From c1990b3e6e196ad41379aa432bf3ccca8a65d9f0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 20 Sep 2026 00:36:50 -0300 Subject: Flatten the 9P control tree and move it out of fs.zig The served tree loses the self/ level: /index /ctl /new /log /screen /listeners /pane//... /os, with /src only in -Dembed-sources=true builds (default off, on for esp32p4). ctl speaks the editor's own language with two lowercase verbs, look TEXT and exec TEXT, plus acme's addr verbs; the new/ factory directory becomes one clone file; cons is gone (exec Msg); name and sel are files; stats report real lengths, modes and mtimes; /log streams pane new/del/rename/save events. The tree code lives in src/ninep/ (tree, pane, ctl, addr, pty, events, screen, sources); fs.zig keeps host access, mounts, resolution and find/grep. Same engine and transports. README (fs-help.txt) and docs rewritten; tests updated and extended. Co-Authored-By: Claude Fable 5.1 --- src/fs.zig | 3594 ++---------------------------------------------------------- 1 file changed, 78 insertions(+), 3516 deletions(-) (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index 4fe32347..7f416440 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -9,6 +9,22 @@ const panes = @import("panes.zig"); const mvzr = @import("mvzr"); const modal = @import("modal.zig"); const look = @import("look.zig"); +pub const tree = @import("ninep/tree.zig"); +const sources_fs = @import("ninep/sources.zig"); +const th = @import("ninep/testing.zig"); + +const Pardes = pardes.Pardes; +const MAX_PANES = pardes.MAX_PANES; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; + +/// The served README; tree.zig answers it. +pub const help = @embedFile("fs-help.txt"); + +/// Host filesystem nodes: the root, and one hashed node per path a client walked to. +pub const os_root: u64 = (1 << 63) + 2; +pub const os_node: u64 = 1 << 62; pub const name_capacity: usize = 255; @@ -18,8 +34,6 @@ pub const sources: []const Source = if (limits.embedded_sources) else &.{}; const source_files = [_]Source{ - .{ .path = "build.zig", .contents = @embedFile("root-build.zig") }, - .{ .path = "build.zig.zon", .contents = @embedFile("root-build.zig.zon") }, .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, @@ -86,101 +100,6 @@ pub const Mount = struct { name: []const u8, dial: []const u8 }; pub const max_mounts = 8; pub const Resolved = struct { path: []const u8, dir: bool = false }; pub const OsPath = struct { node: u64, path: []const u8 }; -pub const archive_node: u64 = 1 << 61; - -pub fn archiveNode(path: []const u8) ?u64 { - if (path.len == 0) return archive_node; - if (path.len >= 4096) return null; - for (sources, 0..) |source, i| { - if (std.mem.eql(u8, source.path, path) or - (source.path.len > path.len and source.path[path.len] == '/' and std.mem.startsWith(u8, source.path, path))) - return archive_node | (@as(u64, i) << 12) | path.len; - } - return null; -} - -fn archiveInfo(node: u64) ?struct { path: []const u8, contents: []const u8, dir: bool } { - if (node == archive_node) return .{ .path = "", .contents = "", .dir = true }; - const index = (node & ~archive_node) >> 12; - if (index >= sources.len) return null; - const source = sources[@intCast(index)]; - const len: usize = @intCast(node & 4095); - if (len > source.path.len) return null; - return .{ .path = source.path[0..len], .contents = source.contents, .dir = len < source.path.len }; -} - -pub fn stageArchive(p: *pardes.Pardes, out: *std.ArrayList(u8), path: []const u8, skip: *u64) void { - var seen: [sources.len][]const u8 = undefined; - var count: usize = 0; - for (sources, 0..) |source, i| { - if (path.len != 0 and - (source.path.len <= path.len or source.path[path.len] != '/' or !std.mem.startsWith(u8, source.path, path))) continue; - const start = if (path.len == 0) 0 else path.len + 1; - const rest = source.path[start..]; - const len = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len; - const name = rest[0..len]; - var duplicate = false; - for (seen[0..count]) |previous| if (std.mem.eql(u8, name, previous)) { - duplicate = true; - break; - }; - if (duplicate) continue; - seen[count] = name; - count += 1; - if (skip.* > 0) { - skip.* -= 1; - continue; - } - const node = archive_node | (@as(u64, i) << 12) | (start + len); - stageDirent(out, p.gpa, node, len < rest.len, name); - } -} - -pub fn archiveHandle(p: *pardes.Pardes, req: Req) Reply { - const info = archiveInfo(req.node) orelse return Reply.fail(req.tag, E.NOENT); - const attr: Reply.Attr = .{ - .node = req.node, - .name = std.fs.path.basename(info.path), - .dir = info.dir, - .size = if (info.dir) 0 else info.contents.len, - .mode = if (info.dir) 0o500 else 0o400, - }; - switch (req.op) { - .getattr => return .{ .tag = req.tag, .attr = attr }, - .open => return .{ .tag = req.tag, .handle = 1 }, - .release => return .{ .tag = req.tag }, - .lookup => { - if (!info.dir) return Reply.fail(req.tag, E.NOTDIR); - if (std.mem.eql(u8, req.data, "..")) { - const parent = std.fs.path.dirname(info.path) orelse ""; - if (parent.len == 0) return handle(p, .{ .tag = req.tag, .op = .getattr, .node = @intFromEnum(SelfFile.root) }); - const node = archiveNode(parent) orelse return Reply.fail(req.tag, E.NOENT); - return archiveHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); - } - if (req.data.len == 0 or std.mem.indexOfAny(u8, req.data, "/\x00") != null) return Reply.fail(req.tag, E.NOENT); - var buf: [4096]u8 = undefined; - const path = if (info.path.len == 0) req.data else std.fmt.bufPrint(&buf, "{s}/{s}", .{ info.path, req.data }) catch return Reply.fail(req.tag, E.NOENT); - const node = archiveNode(path) orelse return Reply.fail(req.tag, E.NOENT); - return archiveHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); - }, - .readdir => { - if (!info.dir) return Reply.fail(req.tag, E.NOTDIR); - const out = p.fs.stage(p.gpa); - var skip = req.off; - stageArchive(p, out, info.path, &skip); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; - }, - .read => { - if (info.dir) return Reply.fail(req.tag, E.PERM); - const off: usize = @intCast(@min(req.off, info.contents.len)); - const bytes = info.contents[off..][0..@min(req.size, info.contents.len - off)]; - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, bytes) catch return Reply.fail(req.tag, E.NOMEM); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(bytes.len) } }; - }, - else => return Reply.fail(req.tag, E.PERM), - } -} fn osPath(p: *pardes.Pardes, node: u64) ?[]const u8 { if (node == os_root) return "/"; @@ -208,7 +127,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { if (req.op == .release) return .{ .tag = req.tag }; const io = std.Io.Threaded.global_single_threaded.io(); const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch return Reply.fail(req.tag, E.NOENT); - const attr: Reply.Attr = .{ .name = if (req.node == os_root) "os" else std.fs.path.basename(path), .node = req.node, .dir = stat.kind == .directory, .size = stat.size, .mode = if (stat.kind == .directory) 0o500 else 0o600 }; + const attr: Reply.Attr = .{ .name = if (req.node == os_root) "os" else std.fs.path.basename(path), .node = req.node, .dir = stat.kind == .directory, .size = stat.size, .mode = if (stat.kind == .directory) 0o755 else 0o644, .mtime = std.math.cast(u32, stat.mtime.toSeconds()) orelse 0 }; switch (req.op) { .getattr => return .{ .tag = req.tag, .attr = attr }, .open => { @@ -218,7 +137,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { .lookup => { if (stat.kind != .directory) return Reply.fail(req.tag, E.NOTDIR); if (req.node == os_root and std.mem.eql(u8, req.data, "..")) - return handle(p, .{ .tag = req.tag, .op = .getattr, .node = namespace_root }); + return tree.handle(p, .{ .tag = req.tag, .op = .getattr, .node = tree.root }); if (req.data.len == 0 or std.mem.indexOfAny(u8, req.data, "/\x00") != null) return Reply.fail(req.tag, E.NOENT); var buf: [4096]u8 = undefined; const joined = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), req.data }) catch return Reply.fail(req.tag, E.NOENT); @@ -244,7 +163,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { continue; } const node = if (std.mem.eql(u8, normalized.path, "/")) os_root else os_node | (std.hash.Wyhash.hash(0, normalized.path) & (os_node - 1)); - stageDirent(out, p.gpa, node, child.kind == .directory, entry.name); + tree.stageDirent(out, p.gpa, node, child.kind == .directory, entry.name); if (out.items.len >= @max(req.size, 512)) break; } return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; @@ -362,10 +281,16 @@ 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/src/fs.zig", "/n/self/src/fs.zig" }) |path| + for ([_][]const u8{ "/virtual/index", "/virtual/screen", "/virtual/README", "/n/self/log" }) |path| try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); - try std.testing.expectError(error.IsDirectory, write(p, "/virtual/src", bytes)); + 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.snapshots) |snapshot| try std.testing.expect(snapshot.node == 0); } @@ -385,8 +310,8 @@ test "direct self reads and writes use the same dot paths as Look" { try std.testing.expectEqualStrings(pane.file.?.content, bytes); var resolved: [4096]u8 = undefined; const canonical = resolve(p, path, "/", &resolved).?; - try std.testing.expectEqual(resolveSelf(p, canonical.path[9..]), resolveSelf(p, path[root.len..])); - try std.testing.expectEqual(@as(?u64, @intFromEnum(SelfFile.root)), resolveSelf(p, "./pane/../../")); + 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); @@ -397,7 +322,7 @@ test "direct self reads and writes use the same dot paths as Look" { @memcpy(overlong[0..9], "/virtual/"); var resolved: [4096]u8 = undefined; try std.testing.expect(resolve(p, &overlong, "/", &resolved) == null); - try std.testing.expect(resolveSelf(p, overlong[9..]) == null); + try std.testing.expect(tree.resolveSelf(p, overlong[9..]) == null); try std.testing.expectError(error.FileNotFound, write(p, &overlong, "")); } @@ -462,8 +387,8 @@ test "bounded reads apply the same limits to self bodies and embedded sources" { contents[contents.len - 1] = '\n'; for ([_][]const u8{ &contents, "" }) |expected| { const pane = try p.setTestFile(expected); - for ([_][]const u8{ "/virtual", "/n/self", "/n/own/self" }) |prefix| { - if (!platform_has_fs and std.mem.eql(u8, prefix, "/n/own/self")) continue; + for ([_][]const u8{ "/virtual", "/n/self", "/n/own" }) |prefix| { + if (!platform_has_fs and std.mem.eql(u8, prefix, "/n/own")) continue; 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); @@ -478,7 +403,7 @@ test "bounded reads apply the same limits to self bodies and embedded sources" { } if (limits.embedded_sources) { const source = findEmbeddedSource("src/look.zig", false).?; - for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig", "/n/own/self/src/look.zig" }) |path| { + for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig", "/n/own/src/look.zig" }) |path| { if (!platform_has_fs and std.mem.startsWith(u8, path, "/n/own/")) continue; const bytes = try readLimit(p, path, source.contents.len); defer gpa.free(bytes); @@ -498,7 +423,7 @@ test "bounded reads count rendered directory paths and unknown self lengths" { defer p.deinit(); p.fs.socket_path = "/tmp/pardes-limited-in-process.sock"; try p.fs.mount(gpa, "own", p.fs.socket_path); - for ([_][]const u8{ "/n", "/virtual", "/n/self", "/n/own", "/n/own/self", "/virtual/listeners" }) |path| { + for ([_][]const u8{ "/n", "/virtual", "/n/self", "/n/own", "/n/own/pane", "/virtual/listeners", "/virtual/README" }) |path| { if (!platform_has_fs and std.mem.startsWith(u8, path, "/n/own")) continue; const expected = try read(p, path); defer gpa.free(expected); @@ -515,10 +440,10 @@ test "bounded reads count rendered directory paths and unknown self lengths" { test "bounded reads release terminal snapshots after success and size refusal" { if (!pardes.terminal_panes) return error.SkipZigTest; const gpa = std.testing.allocator; - const p = try withTerm(gpa); + 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", .{serialOf(p)}); + 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); @@ -626,9 +551,9 @@ 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 = Node.of(pane.serial, .event); - _ = handle(p, .{ .tag = 0, .op = .open, .node = event_node }); - defer _ = handle(p, .{ .tag = 0, .op = .release, .node = event_node }); + 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); @@ -654,11 +579,10 @@ test "same-core mount directories preserve their mount prefix across reads" { try p.fs.mount(gpa, "own", socket_path); const roots = try read(p, "/n/own"); defer gpa.free(roots); - try std.testing.expectEqualStrings("/n/own/os/\n/n/own/self/\n", roots); - const self = try read(p, "/n/own/self"); - defer gpa.free(self); - try std.testing.expect(std.mem.indexOf(u8, self, "/n/own/self/index\n") != null); - try std.testing.expectError(error.NotADirectory, read(p, "/n/own/self/index/..")); + try std.testing.expect(std.mem.startsWith(u8, roots, "/n/own/README\n/n/own/index\n")); + try std.testing.expect(std.mem.indexOf(u8, roots, "/n/own/pane/\n/n/own/os/\n") != null); + try std.testing.expectError(error.NotADirectory, read(p, "/n/own/index/..")); + try std.testing.expectError(error.FileNotFound, read(p, "/n/own/self/index")); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -767,11 +691,11 @@ pub fn resolveOs(path: []const u8, out: *[4096]u8) ?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 (resolveSelf(core, normalized) != 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 (archiveNode(normalized) != null) + if (sources_fs.node(normalized) != null) return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; return null; } @@ -793,7 +717,7 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { } return out.toOwnedSlice(); } - if (std.mem.eql(u8, path, "/virtual")) return readNode(p, @intFromEnum(SelfFile.root), path, limit); + if (std.mem.eql(u8, path, "/virtual")) return readNode(p, tree.root, path, limit); if (std.mem.startsWith(u8, path, "/n/")) { const explicit = path[3..]; const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; @@ -812,7 +736,7 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { return readNode(p, node, path, limit); } if (std.mem.eql(u8, name, "self")) { - const node = resolveSelf(p, remote_path) orelse return error.FileNotFound; + const node = tree.resolveSelf(p, remote_path) orelse return error.FileNotFound; return readNode(p, node, path, limit); } for (p.fs.mounts.items) |mount| { @@ -823,13 +747,13 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { for (p.fs.os_paths.items[saved_paths..]) |temporary| p.gpa.free(temporary.path); p.fs.os_paths.shrinkRetainingCapacity(saved_paths); } - var node = namespace_root; + var node = tree.root; var directory = true; var parts = std.mem.tokenizeScalar(u8, remote_path, '/'); while (parts.next()) |part| { if (!directory) return error.NotADirectory; if (std.mem.eql(u8, part, ".")) continue; - const reply = handle(p, .{ .tag = 0, .op = .lookup, .node = node, .data = part }); + const reply = tree.handle(p, .{ .tag = 0, .op = .lookup, .node = node, .data = part }); if (reply.status != .ok) return error.FileNotFound; node = reply.attr.node; directory = reply.attr.dir; @@ -842,14 +766,14 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { } if (std.mem.startsWith(u8, path, "/virtual/")) { const name = path[9..]; - if (resolveSelf(p, name)) |node| return readNode(p, node, path, limit); + if (tree.resolveSelf(p, name)) |node| return readNode(p, node, path, limit); } return readFileLimit(p.gpa, path, limit); } fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize) ![]u8 { var node = initial_node; - const attr = handle(p, .{ .tag = 0, .op = .getattr, .node = node }); + const attr = tree.handle(p, .{ .tag = 0, .op = .getattr, .node = node }); if (attr.status != .ok) return error.FileNotFound; if (attr.attr.dir) { var out: std.Io.Writer.Allocating = .init(p.gpa); @@ -858,7 +782,7 @@ fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize const max_bytes = @min(limit, limits.max_stream_bytes); const prefix = std.mem.trimEnd(u8, path, "/"); while (true) { - const reply = handle(p, .{ .tag = 0, .op = .readdir, .node = node, .off = index, .size = 8192 }); + const reply = tree.handle(p, .{ .tag = 0, .op = .readdir, .node = node, .off = index, .size = 8192 }); if (reply.status != .ok) return error.ReadFailed; const entries = p.fsPayload(reply); if (entries.len == 0) return out.toOwnedSlice(); @@ -878,15 +802,15 @@ fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize } } if (attr.attr.size > limit) return error.FileTooLarge; - const opened = handle(p, .{ .tag = 0, .op = .open, .node = node }); + const opened = tree.handle(p, .{ .tag = 0, .op = .open, .node = node }); if (opened.status != .ok) return error.OpenFailed; if (opened.attr.node != 0) node = opened.attr.node; - defer _ = handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); while (true) { const want: u32 = @intCast(@min(8192, limit + 1 - out.written().len)); - const reply = handle(p, .{ .tag = 0, .op = .read, .node = node, .handle = opened.handle, .off = out.written().len, .size = want }); + const reply = tree.handle(p, .{ .tag = 0, .op = .read, .node = node, .handle = opened.handle, .off = out.written().len, .size = want }); if (reply.status == .again) return error.NotAFile; if (reply.status != .ok) return error.ReadFailed; const bytes = p.fsPayload(reply); @@ -923,27 +847,27 @@ pub fn write(p: *pardes.Pardes, path: []const u8, bytes: []const u8) !void { } } if (self_path) |name| { - var node = resolveSelf(p, name) orelse return error.FileNotFound; - const attributes = handle(p, .{ .tag = 0, .op = .getattr, .node = node }); + var node = tree.resolveSelf(p, name) orelse return error.FileNotFound; + const attributes = tree.handle(p, .{ .tag = 0, .op = .getattr, .node = node }); if (attributes.status != .ok) return error.FileNotFound; if (attributes.attr.dir) return error.IsDirectory; if (attributes.attr.mode & 0o200 == 0) return error.ReadOnlyFilesystem; - const opened = handle(p, .{ .tag = 0, .op = .open, .node = node }); + const opened = tree.handle(p, .{ .tag = 0, .op = .open, .node = node }); if (opened.status != .ok) return error.OpenFailed; if (opened.attr.node != 0) node = opened.attr.node; - defer _ = handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); var preserved: ?[]u8 = null; defer if (preserved) |copy| p.gpa.free(copy); - const target = Node.target(node); + const target = tree.Node.target(node); if (target != null and target.? == .pane and target.?.pane.file == .body) { preserved = try p.gpa.dupe(u8, bytes); - const trunc = handle(p, .{ .tag = 0, .op = .setattr, .node = node, .truncate = true }); + const trunc = tree.handle(p, .{ .tag = 0, .op = .setattr, .node = node, .truncate = true }); if (trunc.status != .ok) return error.WriteFailed; } const contents = preserved orelse bytes; var off: usize = 0; while (off < contents.len) { - const reply = handle(p, .{ .tag = 0, .op = .write, .node = node, .off = off, .data = contents[off..] }); + const reply = tree.handle(p, .{ .tag = 0, .op = .write, .node = node, .off = off, .data = contents[off..] }); if (reply.status != .ok or reply.written == 0) return error.WriteFailed; off += reply.written; } @@ -964,7 +888,7 @@ fn resolveEmbedded(word: []const u8, cwd: []const u8, scratch: *[4096]u8) ?Sourc return findEmbeddedSource(normalized_word, false); } -fn normalizeVirtualPath(path: []const u8, out: *[4096]u8) ?[]const u8 { +pub fn normalizeVirtualPath(path: []const u8, out: *[4096]u8) ?[]const u8 { if (std.mem.indexOfScalar(u8, path, 0) != null) return null; var len: usize = 0; var parts = std.mem.tokenizeAny(u8, path, "/\\"); @@ -1322,361 +1246,6 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { return buf; } -const Pardes = pardes.Pardes; -const Pane = pardes.Pane; -const MAX_PANES = pardes.MAX_PANES; - -pub const namespace_root: u64 = 1 << 63; -pub const namespace_panes: u64 = namespace_root + 1; -pub const os_root: u64 = namespace_root + 2; -pub const os_node: u64 = 1 << 62; -const factory_base: u64 = namespace_root + 256; -const fs_help = @embedFile("fs-help.txt"); - -pub fn resolveSelf(p: *Pardes, path: []const u8) ?u64 { - var path_buf: [4096]u8 = undefined; - const normalized = normalizeVirtualPath(path, &path_buf) orelse return null; - var parts = std.mem.tokenizeScalar(u8, normalized, '/'); - const first = parts.next() orelse return @intFromEnum(SelfFile.root); - if (!std.mem.eql(u8, first, "pane")) { - const top = topFileNamed(first) orelse return archiveNode(normalized); - if (parts.next()) |name| { - if (top != .new or parts.next() != null) return null; - if (std.mem.eql(u8, name, "README")) return @intFromEnum(SelfFile.README); - const file = paneFileNamed(name) orelse return null; - if (file.inPty()) return null; - return factory_base + @intFromEnum(file); - } - return @intFromEnum(top); - } - const serial = serialNamed(parts.next() orelse return namespace_panes) orelse return null; - const id = p.paneBySerial(serial) orelse return null; - const file = paneFileNamed(parts.next() orelse return Node.of(serial, .dir)) orelse return null; - if (file.inPty() and !p.panes[id].?.isTerminal()) return null; - if (parts.next()) |name| { - if (file != .pty) return null; - const child = ptyFileNamed(name) orelse return null; - if (parts.next() != null) return null; - return Node.of(serial, child); - } - return Node.of(serial, file); -} - -fn namespace(p: *Pardes, req: Req) Reply { - switch (req.op) { - .getattr => return .{ .tag = req.tag, .attr = .{ .node = req.node, .dir = true, .mode = 0o500 } }, - .open => return .{ .tag = req.tag, .handle = 1 }, - .release => return .{ .tag = req.tag }, - .lookup => { - if (std.mem.eql(u8, req.data, "..")) return handle(p, .{ - .tag = req.tag, - .op = .getattr, - .node = if (req.node == namespace_root) namespace_root else @intFromEnum(SelfFile.root), - }); - if (req.node == namespace_root) { - if (std.mem.eql(u8, req.data, "self")) return handle(p, .{ .tag = req.tag, .op = .getattr, .node = @intFromEnum(SelfFile.root) }); - if (std.mem.eql(u8, req.data, "os")) return handle(p, .{ .tag = req.tag, .op = .getattr, .node = os_root }); - } else { - const serial = serialNamed(req.data) orelse return Reply.fail(req.tag, E.NOENT); - if (serial == 0) return Reply.fail(req.tag, E.NOENT); - return handle(p, .{ .tag = req.tag, .op = .getattr, .node = Node.of(serial, .dir) }); - } - return Reply.fail(req.tag, E.NOENT); - }, - .readdir => { - const out = p.fs.stage(p.gpa); - var skip = req.off; - if (req.node == namespace_root) { - if (skip == 0) stageDirent(out, p.gpa, os_root, true, "os") else skip -= 1; - if (skip == 0) stageDirent(out, p.gpa, @intFromEnum(SelfFile.root), true, "self"); - } else { - var last: u32 = 0; - while (nextSerialAfter(p, last)) |serial| { - last = serial; - if (skip > 0) { - skip -= 1; - continue; - } - var buf: [16]u8 = undefined; - const name = std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable; - stageDirent(out, p.gpa, Node.of(serial, .dir), true, name); - } - } - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; - }, - else => return Reply.fail(req.tag, E.PERM), - } -} - -pub const Op = enum(u8) { - lookup, - getattr, - setattr, - open, - read, - write, - release, - readdir, -}; - -pub const Status = enum(u8) { - ok, - again, - err, -}; - -pub const Req = struct { - tag: u64, - op: Op, - node: u64, - handle: u32 = 0, - off: u64 = 0, - size: u32 = 0, - data: []const u8 = &.{}, - truncate: bool = false, - - pub fn changesPane(req: Req) bool { - return switch (req.op) { - .write, .setattr => true, - .lookup => false, - .open => req.node >= factory_base and req.node < factory_base + 16, - .getattr, .read, .release, .readdir => false, - }; - } -}; - -pub const Reply = struct { - tag: u64, - status: Status = .ok, - errno: u16 = 0, - attr: Attr = .{}, - handle: u32 = 0, - payload: Payload = .none, - written: u32 = 0, - - pub const Attr = struct { - name: []const u8 = "", - node: u64 = 0, - dir: bool = false, - size: u64 = 0, - mode: u16 = 0o600, - }; - - pub const Payload = union(enum) { - none, - staged: u32, - region: struct { pane: u8, serial: u32, off: u32, len: u32 }, - }; - - pub fn fail(tag: u64, e: u16) Reply { - return .{ .tag = tag, .status = .err, .errno = e }; - } -}; - -pub const E = struct { - pub const PERM: u16 = 1; - pub const NOENT: u16 = 2; - pub const IO: u16 = 5; - pub const NOMEM: u16 = 12; - pub const NOTDIR: u16 = 20; - pub const INVAL: u16 = 22; - pub const NFILE: u16 = 23; - pub const NOSPC: u16 = 28; - pub const NOSYS: u16 = 38; -}; - -pub const PaneFile = enum(u4) { - dir = 0, - addr, - body, - ctl, - data, - errors, - event, - tag, - xdata, - rdsel, - wrsel, - pty, - pty_ctl, - pty_status, - pty_data, - - pub fn name(f: PaneFile) []const u8 { - return switch (f) { - .dir => ".", - .pty_ctl => "ctl", - .pty_status => "status", - .pty_data => "data", - else => @tagName(f), - }; - } - - pub fn mode(f: PaneFile) u16 { - return switch (f) { - .dir, .pty => 0o500, - .errors, .wrsel, .pty_ctl => 0o200, - .rdsel, .pty_status => 0o400, - else => 0o600, - }; - } - - pub fn isDir(f: PaneFile) bool { - return f == .dir or f == .pty; - } - - pub fn inPty(f: PaneFile) bool { - return switch (f) { - .pty, .pty_ctl, .pty_status, .pty_data => true, - else => false, - }; - } -}; - -pub const SelfFile = enum(u4) { - root = 1, - index = 2, - cons = 3, - new = 4, - screen = 5, - listeners = 6, - README = 7, - - pub fn name(f: SelfFile) []const u8 { - return if (f == .root) "." else @tagName(f); - } - - pub fn mode(f: SelfFile) u16 { - return switch (f) { - .root, .new => 0o500, - .index, .screen, .listeners, .README => 0o400, - .cons => 0o200, - }; - } - - pub fn dir(f: SelfFile) bool { - return f == .root or f == .new; - } -}; - -pub const Node = packed struct(u64) { - file: u4 = 0, - serial: u60 = 0, - - pub fn of(serial: u32, file: PaneFile) u64 { - std.debug.assert(serial != 0); - return @bitCast(Node{ .file = @intFromEnum(file), .serial = serial }); - } - - pub fn target(node: u64) ?Target { - const n: Node = @bitCast(node); - if (n.serial == 0) { - return .{ .top = std.enums.fromInt(SelfFile, n.file) orelse return null }; - } - return .{ .pane = .{ - .serial = std.math.cast(u32, n.serial) orelse return null, - .file = std.enums.fromInt(PaneFile, n.file) orelse return null, - } }; - } -}; - -pub const Target = union(enum) { - top: SelfFile, - pane: struct { serial: u32, file: PaneFile }, -}; - -pub const out_reserve = 4 * 1024; - -pub const queue_cap = 64 * 1024; - -pub const Queue = struct { - buf: std.ArrayList(u8) = .empty, - head: usize = 0, - - pub fn deinit(q: *Queue, gpa: std.mem.Allocator) void { - q.buf.deinit(gpa); - q.head = 0; - } - - pub fn push(q: *Queue, gpa: std.mem.Allocator, record: []const u8) void { - if (record.len > std.math.maxInt(u32)) return; - while (q.buf.items.len - q.head + record.len + 4 > queue_cap) { - if (q.peek() == null) return; - q.pop(); - } - q.compact(); - var head: [4]u8 = undefined; - std.mem.writeInt(u32, &head, @intCast(record.len), .little); - q.buf.appendSlice(gpa, &head) catch return; - q.buf.appendSlice(gpa, record) catch { - q.buf.shrinkRetainingCapacity(q.buf.items.len - 4); - return; - }; - } - - pub fn peek(q: *const Queue) ?[]const u8 { - const rest = q.buf.items[@min(q.head, q.buf.items.len)..]; - if (rest.len < 4) return null; - const len = std.mem.readInt(u32, rest[0..4], .little); - if (rest.len < 4 + len) return null; - return rest[4 .. 4 + len]; - } - - pub fn pop(q: *Queue) void { - const record = q.peek() orelse return; - q.head += 4 + record.len; - if (q.head == q.buf.items.len) { - q.buf.clearRetainingCapacity(); - q.head = 0; - } - } - - pub fn popFront(q: *Queue, n: usize) void { - const record = q.peek() orelse return; - if (n >= record.len) return q.pop(); - q.head += n; - std.mem.writeInt(u32, q.buf.items[q.head..][0..4], @intCast(record.len - n), .little); - } - - fn compact(q: *Queue) void { - if (q.head == 0 or q.head * 2 < q.buf.items.len) return; - const rest = q.buf.items.len - q.head; - std.mem.copyForwards(u8, q.buf.items[0..rest], q.buf.items[q.head..]); - q.buf.shrinkRetainingCapacity(rest); - q.head = 0; - } - - pub fn empty(q: *const Queue) bool { - return q.peek() == null; - } - - pub fn clearAndFree(q: *Queue, gpa: std.mem.Allocator) void { - q.buf.clearAndFree(gpa); - q.head = 0; - } -}; - -pub const PaneState = struct { - addr: Range = .{}, - limit: ?Range = null, - readers: u16 = 0, - events: Queue = .{}, - nomark: bool = false, - noscroll: bool = false, - tag_snap: std.ArrayList(u8) = .empty, - pty_readers: u16 = 0, - pty_out: Queue = .{}, - - pub const Range = struct { q0: u32 = 0, q1: u32 = 0 }; - - fn deinit(pf: *PaneState, gpa: std.mem.Allocator) void { - pf.events.deinit(gpa); - pf.pty_out.deinit(gpa); - pf.tag_snap.deinit(gpa); - pf.* = .{}; - } -}; - pub const Namespace = struct { socket_path: []const u8 = "", tcp_address: ?std.Io.net.IpAddress = null, @@ -1684,11 +1253,20 @@ pub const Namespace = struct { mounts: std.ArrayList(Mount) = .empty, node_name: [16]u8 = undefined, os_paths: std.ArrayList(OsPath) = .empty, - snapshots: [32]struct { node: u64 = 0, bytes: ?[]const u8 = null } = @splat(.{}), + snapshots: [tree.screen.snapshot_slots]tree.screen.Snapshot = @splat(.{}), out: std.ArrayList(u8) = .empty, - panes: [MAX_PANES]PaneState = @splat(.{}), + panes: [MAX_PANES]tree.pane.State = @splat(.{}), listeners: u16 = 0, origin: u8 = 'K', + /// The editor-wide event stream, recorded only while /log is held open. + log: tree.events.Queue = .{}, + log_readers: u16 = 0, + /// What the last ctl command created or touched, answered by reading /ctl. + results: [MAX_PANES]u32 = undefined, + results_len: u8 = 0, + results_valid: bool = false, + /// Process start, the mtime of everything that has no edit time of its own. + started: u32 = 0, pub fn deinit(st: *Namespace, gpa: std.mem.Allocator) void { for (st.mounts.items) |entry| { @@ -1700,6 +1278,7 @@ pub const Namespace = struct { st.os_paths.deinit(gpa); for (st.snapshots) |snapshot| if (snapshot.bytes) |bytes| gpa.free(bytes); for (&st.panes) |*pf| pf.deinit(gpa); + st.log.deinit(gpa); st.out.deinit(gpa); } @@ -1718,7 +1297,7 @@ pub const Namespace = struct { pub fn stage(st: *Namespace, gpa: std.mem.Allocator) *std.ArrayList(u8) { st.out.clearRetainingCapacity(); - st.out.ensureTotalCapacity(gpa, out_reserve) catch {}; + st.out.ensureTotalCapacity(gpa, tree.out_reserve) catch {}; return &st.out; } @@ -1764,3023 +1343,6 @@ pub fn unmount(p: *Pardes, name: []const u8) !void { return error.NotMounted; } -pub const max_record_text = 256; - -pub const Action = enum(u8) { - body_delete = 'D', - tag_delete = 'd', - body_insert = 'I', - tag_insert = 'i', - body_look = 'L', - tag_look = 'l', - body_exec = 'X', - tag_exec = 'x', - - pub fn char(a: Action) u8 { - return @intFromEnum(a); - } - - pub fn fromChar(c: u8) ?Action { - return std.enums.fromInt(Action, c); - } - - pub fn onTag(a: Action) bool { - return @intFromEnum(a) >= 'a'; - } -}; - -pub const flag_builtin: u32 = 1; -pub const flag_expansion: u32 = 2; -pub const flag_filename: u32 = 4; -pub const flag_chorded: u32 = 8; - -pub fn formatRecord( - buf: []u8, - origin: u8, - action: Action, - q0: u32, - q1: u32, - flag: u32, - text: []const u8, -) []const u8 { - const sent = if (text.len >= max_record_text) text[0..0] else text; - return std.fmt.bufPrint(buf, "{c}{c}{d} {d} {d} {d} {s}\n", .{ - origin, - action.char(), - q0, - q1, - flag, - sent.len, - sent, - }) catch buf[0..0]; -} - -pub const Span = struct { at: u32, removed: u32, inserted: u32 }; - -pub fn diffSpan(old: []const u8, new: []const u8) Span { - const both = @min(old.len, new.len); - const stride = 64; - var head: usize = 0; - while (head + stride <= both and - std.mem.eql(u8, old[head..][0..stride], new[head..][0..stride])) head += stride; - while (head < both and old[head] == new[head]) head += 1; - var tail: usize = 0; - const rest = both - head; - while (tail + stride <= rest and std.mem.eql( - u8, - old[old.len - tail - stride ..][0..stride], - new[new.len - tail - stride ..][0..stride], - )) tail += stride; - while (tail < rest 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), - }; -} - -pub fn noteReplace(p: *Pardes, id: usize, on_tag: bool, old: []const u8, new: []const u8) void { - if (!p.fs.scripted(id)) return; - const span = diffSpan(old, new); - if (span.removed == 0 and span.inserted == 0) return; - if (span.removed > 0) _ = noteAction( - p, - id, - if (on_tag) .tag_delete else .body_delete, - span.at, - span.at + span.removed, - 0, - "", - ); - if (span.inserted > 0) _ = noteAction( - p, - id, - if (on_tag) .tag_insert else .body_insert, - span.at, - span.at + span.inserted, - 0, - new[span.at..][0..span.inserted], - ); -} - -pub fn noteAction( - p: *Pardes, - id: usize, - action: Action, - q0: u32, - q1: u32, - flag: u32, - text: []const u8, -) bool { - if (!p.fs.scripted(id)) return false; - var buf: [max_record_text + 64]u8 = undefined; - const record = formatRecord(&buf, p.fs.origin, action, q0, q1, flag, text); - p.fs.panes[id].events.push(p.gpa, record); - return true; -} - -pub fn notePtyOutput(p: *Pardes, id: usize, bytes: []const u8) void { - if (id >= MAX_PANES or bytes.len == 0) return; - const pf = &p.fs.panes[id]; - if (pf.pty_readers == 0) return; - var off: usize = 0; - while (off < bytes.len) { - const n = @min(bytes.len - off, queue_cap / 2); - pf.pty_out.push(p.gpa, bytes[off..][0..n]); - off += n; - } -} - -pub fn handle(p: *Pardes, req: Req) Reply { - if (req.node >= factory_base and req.node < factory_base + 16) { - const file = std.enums.fromInt(PaneFile, req.node - factory_base) orelse return Reply.fail(req.tag, E.NOENT); - if (file == .dir or file.inPty()) return Reply.fail(req.tag, E.NOENT); - // Truncating a factory is harmless: its next open creates an empty pane. - if (req.op == .getattr or (req.op == .setattr and req.truncate)) - return .{ .tag = req.tag, .attr = .{ .node = req.node, .name = file.name(), .mode = file.mode() } }; - if (req.op != .open) return Reply.fail(req.tag, E.PERM); - const serial = newPane(p) orelse return Reply.fail(req.tag, E.NFILE); - const node = Node.of(serial, file); - var reply = handle(p, .{ .tag = req.tag, .op = .open, .node = node }); - reply.attr.node = node; - return reply; - } - if (req.node == namespace_root or req.node == namespace_panes) return namespace(p, req); - if (req.node == os_root or req.node & os_node != 0) return osHandle(p, req); - if (req.node & archive_node != 0) return archiveHandle(p, req); - const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); - if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) { - .pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'), - .top => 'F', - }; - return switch (req.op) { - .lookup => lookup(p, req, target), - .getattr => switch (attrOf(p, target)) { - .ok => |a| .{ .tag = req.tag, .attr = a }, - .missing => Reply.fail(req.tag, E.NOENT), - }, - .setattr => setattr(p, req, target), - .open => open(p, req, target), - .release => release(p, req), - .readdir => readdir(p, req, target), - .read => handleRead(p, req, target), - .write => handleWrite(p, req, target), - }; -} - -const AttrResult = union(enum) { ok: Reply.Attr, missing }; - -fn attrOf(p: *Pardes, target: Target) AttrResult { - switch (target) { - .top => |f| return .{ .ok = .{ - .name = if (f == .root) "self" else f.name(), - .node = @intFromEnum(f), - .dir = f.dir(), - .mode = f.mode(), - .size = topSize(p, f), - } }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return .missing; - if (t.file.inPty() and !p.panes[id].?.isTerminal()) return .missing; - return .{ .ok = .{ - .name = if (t.file == .dir) (std.fmt.bufPrint(&p.fs.node_name, "{d}", .{t.serial}) catch unreachable) else t.file.name(), - .node = Node.of(t.serial, t.file), - .dir = t.file.isDir(), - .mode = t.file.mode(), - .size = paneFileSize(p, id, t.file), - } }; - }, - } -} - -fn topSize(p: *Pardes, f: SelfFile) u64 { - return switch (f) { - .root, .new, .cons, .screen, .listeners => 0, - .index => indexLen(p), - .README => fs_help.len, - }; -} - -fn paneFileSize(p: *Pardes, id: usize, f: PaneFile) u64 { - const pane = p.panes[id] orelse return 0; - return switch (f) { - .body, .data, .xdata => bodyLen(p, pane), - .tag => tagLen(p, pane), - .dir, .addr, .ctl, .errors, .event, .rdsel, .wrsel => 0, - .pty, .pty_ctl, .pty_status, .pty_data => 0, - }; -} - -fn bodyOf(pane: *const Pane) []const u8 { - if (pane.file) |*f| return f.content; - return ""; -} - -fn fileOf(pane: *Pane) ?*panes.File.State { - return if (pane.file) |*f| f else null; -} - -fn tagOf(p: *Pardes, pane: *Pane) []const u8 { - return p.tagText(p.scratch.allocator(), pane) catch ""; -} - -fn dirOf(pane: *Pane) []const u8 { - if (pane.file) |*f| return std.fs.path.dirname(f.path) orelse "/"; - const cwd = pane.cwdSlice(); - return if (cwd.len > 0) cwd else "/"; -} - -fn dirtyOf(pane: *const Pane) bool { - const f = if (pane.file) |*x| x else return false; - if (!panes.Output.fileTraits(f.output).saves) return false; - return f.revision != f.saved_revision; -} - -fn clip(n: usize) u32 { - return std.math.cast(u32, n) orelse std.math.maxInt(u32); -} - -fn cellOf(row: i32, col: i32) modal.Cursor { - return .{ .row = @intCast(@max(0, row)), .col = @intCast(@max(0, col)) }; -} - -fn firstLine(s: []const u8) []const u8 { - return s[0 .. std.mem.indexOfScalar(u8, s, '\n') orelse s.len]; -} - -fn dotOf(pane: *Pane) PaneState.Range { - const text = bodyOf(pane); - const head = modal.offsetAt(text, cellOf(pane.cur_row, pane.cur_col)); - if (!pane.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) }; - const anchor = modal.offsetAt(text, cellOf(pane.vsel.row, pane.vsel.col)); - var hi = @max(head, anchor); - if (hi < text.len) hi = modal.nextGrapheme(text, hi); - return .{ .q0 = clip(@min(head, anchor)), .q1 = clip(hi) }; -} - -fn setDot(pane: *Pane, r: PaneState.Range) void { - const text = bodyOf(pane); - const q0 = @min(@as(usize, r.q0), text.len); - const q1 = @max(q0, @min(@as(usize, r.q1), text.len)); - const a = modal.positionAt(text, q0); - pane.vsel = .{ .active = q1 > q0, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; - const h = modal.positionAt(text, if (q1 > q0) modal.prevGrapheme(text, q1) else q0); - pane.cur_row = @intCast(h.row); - pane.cur_col = @intCast(h.col); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.msel.active = false; - pane.ensureCursorVisible(); -} - -fn showOffset(pane: *Pane, off: usize) void { - const text = bodyOf(pane); - const c = modal.positionAt(text, @min(off, text.len)); - pane.cur_row = @intCast(c.row); - pane.cur_col = @intCast(c.col); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); -} - -fn clampAddr(pf: *PaneState, len: usize) void { - const n = clip(len); - pf.addr.q0 = @min(pf.addr.q0, n); - pf.addr.q1 = @min(pf.addr.q1, n); - if (pf.limit) |*l| { - l.q0 = @min(l.q0, n); - l.q1 = @min(l.q1, n); - } -} - -fn shiftBy(r: PaneState.Range, at: u32, removed: u32, inserted: u32) PaneState.Range { - return .{ .q0 = shiftOne(r.q0, at, removed, inserted), .q1 = shiftOne(r.q1, at, removed, inserted) }; -} - -fn shiftOne(v: u32, at: u32, removed: u32, inserted: u32) u32 { - if (v <= at) return v; - if (v <= at +| removed) return at +| inserted; - return v - removed +| inserted; -} - -fn wholeUtf8(data: []const u8) usize { - var i = data.len; - var back: usize = 0; - while (i > 0 and back < 4) : (back += 1) { - i -= 1; - const c = data[i]; - if (c < 0x80) return data.len; - if (c & 0xC0 == 0xC0) { - const need = std.unicode.utf8ByteSequenceLength(c) catch return data.len; - if (i + need <= data.len or i == 0) return data.len; - return i; - } - } - return data.len; -} - -fn paneFileNamed(name: []const u8) ?PaneFile { - const f = std.meta.stringToEnum(PaneFile, name) orelse return null; - if (f == .dir) return null; - return if (f.inPty() and f != .pty) null else f; -} - -fn ptyFileNamed(name: []const u8) ?PaneFile { - if (std.mem.eql(u8, name, "ctl")) return .pty_ctl; - if (std.mem.eql(u8, name, "status")) return .pty_status; - if (std.mem.eql(u8, name, "data")) return .pty_data; - return null; -} - -fn topFileNamed(name: []const u8) ?SelfFile { - const f = std.meta.stringToEnum(SelfFile, name) orelse return null; - return if (f == .root) null else f; -} - -fn serialNamed(name: []const u8) ?u32 { - if (name.len == 0 or name.len > 10) return null; - for (name) |c| if (c < '0' or c > '9') return null; - return std.fmt.parseInt(u32, name, 10) catch null; -} - -fn nextSerialAfter(p: *Pardes, after: u32) ?u32 { - var best: ?u32 = null; - for (p.panes) |slot| { - const pane = slot orelse continue; - if (pane.serial <= after) continue; - if (best == null or pane.serial < best.?) best = pane.serial; - } - return best; -} - -fn newPane(p: *Pardes) ?u32 { - const slot = p.freeSlot() orelse return null; - p.newScratchBelow(p.active); - const pane = p.panes[slot] orelse return null; - return pane.serial; -} - -fn lookup(p: *Pardes, req: Req, target: Target) Reply { - const name = req.data; - if (std.mem.eql(u8, name, "..")) { - const parent: u64 = switch (target) { - .top => |top| if (top == .root) namespace_root else @intFromEnum(SelfFile.root), - .pane => |t| if (t.file == .pty) Node.of(t.serial, .dir) else namespace_panes, - }; - return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent }); - } - if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) return Reply.fail(req.tag, E.NOENT); - const node: u64 = switch (target) { - .top => |f| switch (f) { - .root => root: { - if (std.mem.eql(u8, name, "pane")) return .{ .tag = req.tag, .attr = .{ .node = namespace_panes, .dir = true, .mode = 0o500 } }; - if (topFileNamed(name)) |t| break :root @intFromEnum(t); - if (archiveNode(name)) |node| return archiveHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); - return Reply.fail(req.tag, E.NOENT); - }, - .new => new: { - if (std.mem.eql(u8, name, "README")) break :new @intFromEnum(SelfFile.README); - const want = paneFileNamed(name) orelse return Reply.fail(req.tag, E.NOENT); - if (want.inPty()) return Reply.fail(req.tag, E.NOENT); - return handle(p, .{ .tag = req.tag, .op = .getattr, .node = factory_base + @intFromEnum(want) }); - }, - else => return Reply.fail(req.tag, E.NOTDIR), - }, - .pane => |t| pane: { - _ = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const f = switch (t.file) { - .dir => paneFileNamed(name), - .pty => ptyFileNamed(name), - else => return Reply.fail(req.tag, E.NOTDIR), - } orelse return Reply.fail(req.tag, E.NOENT); - break :pane Node.of(t.serial, f); - }, - }; - return switch (attrOf(p, Node.target(node) orelse return Reply.fail(req.tag, E.NOENT))) { - .ok => |a| .{ .tag = req.tag, .attr = a }, - .missing => Reply.fail(req.tag, E.NOENT), - }; -} - -pub fn stageDirent(out: *std.ArrayList(u8), gpa: std.mem.Allocator, node: u64, dir: bool, name: []const u8) void { - if (name.len == 0 or name.len > 255) return; - var head: [10]u8 = undefined; - std.mem.writeInt(u64, head[0..8], node, .little); - head[8] = @intFromBool(dir); - head[9] = @intCast(name.len); - out.appendSlice(gpa, &head) catch return; - out.appendSlice(gpa, name) catch return; -} - -fn stagePaneFiles(p: *Pardes, out: *std.ArrayList(u8), serial: u32, terminal: bool, skip: *u64) void { - inline for (comptime std.enums.values(PaneFile)) |f| { - if (comptime f == .dir or (f.inPty() and f != .pty)) continue; - const present = f != .pty or terminal; - if (present) { - if (skip.* > 0) skip.* -= 1 else stageDirent(out, p.gpa, Node.of(serial, f), f.isDir(), f.name()); - } - } -} - -fn stagePtyFiles(p: *Pardes, out: *std.ArrayList(u8), serial: u32, skip: *u64) void { - inline for (comptime std.enums.values(PaneFile)) |f| { - if (comptime !f.inPty() or f == .pty) continue; - if (skip.* > 0) skip.* -= 1 else stageDirent(out, p.gpa, Node.of(serial, f), false, f.name()); - } -} - -fn readdir(p: *Pardes, req: Req, target: Target) Reply { - const out = p.fs.stage(p.gpa); - var skip = req.off; - switch (target) { - .top => |f| switch (f) { - .root => { - inline for (.{ SelfFile.index, SelfFile.cons, SelfFile.new }) |t| { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.name()); - } - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, namespace_panes, true, "pane"); - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(SelfFile.screen), false, "screen"); - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(SelfFile.listeners), false, "listeners"); - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(SelfFile.README), false, "README"); - stageArchive(p, out, "", &skip); - }, - .new => { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(SelfFile.README), false, "README"); - inline for (comptime std.enums.values(PaneFile)) |file| { - if (comptime file == .dir or file.inPty()) continue; - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, factory_base + @intFromEnum(file), false, file.name()); - } - }, - else => return Reply.fail(req.tag, E.NOTDIR), - }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const terminal = p.panes[id].?.isTerminal(); - switch (t.file) { - .dir => stagePaneFiles(p, out, t.serial, terminal, &skip), - .pty => { - if (!terminal) return Reply.fail(req.tag, E.NOENT); - stagePtyFiles(p, out, t.serial, &skip); - }, - else => return Reply.fail(req.tag, E.NOTDIR), - } - }, - } - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; -} - -fn open(p: *Pardes, req: Req, target: Target) Reply { - const snapshot = switch (target) { - .top => |f| f == .screen, - .pane => |t| t.file == .body and if (p.paneBySerial(t.serial)) |id| p.panes[id].?.isTerminal() else false, - }; - if (snapshot) { - for (&p.fs.snapshots, 0..) |*slot, i| { - if (slot.node != 0) continue; - const bytes = if (target == .top) screenSnapshot(p) catch return Reply.fail(req.tag, E.NOMEM) else null; - slot.* = .{ .node = req.node, .bytes = bytes }; - return .{ .tag = req.tag, .handle = @intCast(i + 1) }; - } - return Reply.fail(req.tag, E.NFILE); - } - switch (target) { - .top => {}, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pf = &p.fs.panes[id]; - if (t.file.inPty() and !p.panes[id].?.isTerminal()) return Reply.fail(req.tag, E.NOENT); - switch (t.file) { - .ctl => pf.limit = null, - .addr => { - pf.addr = .{}; - pf.limit = null; - }, - .event => { - pf.readers +|= 1; - p.fs.listeners +|= 1; - }, - .pty_data => pf.pty_readers +|= 1, - else => {}, - } - }, - } - return .{ .tag = req.tag, .handle = 1 }; -} - -fn release(p: *Pardes, req: Req) Reply { - if (req.handle > 0 and req.handle <= p.fs.snapshots.len) { - const snapshot = &p.fs.snapshots[req.handle - 1]; - if (snapshot.node == req.node) { - if (snapshot.bytes) |bytes| p.gpa.free(bytes); - snapshot.* = .{}; - return .{ .tag = req.tag }; - } - } - const target = Node.target(req.node) orelse return .{ .tag = req.tag }; - switch (target) { - .top => {}, - .pane => |t| { - if (t.file != .event and t.file != .pty_data) return .{ .tag = req.tag }; - const id = p.paneBySerial(t.serial) orelse return .{ .tag = req.tag }; - const pf = &p.fs.panes[id]; - if (t.file == .pty_data) { - if (pf.pty_readers == 0) return .{ .tag = req.tag }; - pf.pty_readers -= 1; - if (pf.pty_readers == 0) pf.pty_out.clearAndFree(p.gpa); - return .{ .tag = req.tag }; - } - if (pf.readers == 0) return .{ .tag = req.tag }; - pf.readers -= 1; - p.fs.listeners -|= 1; - if (pf.readers == 0) pf.tag_snap.clearAndFree(p.gpa); - }, - } - return .{ .tag = req.tag }; -} - -fn setattr(p: *Pardes, req: Req, target: Target) Reply { - if (req.truncate) switch (target) { - .pane => |t| switch (t.file) { - .body, .data, .xdata => { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pane = p.panes[id].?; - if (fileOf(pane) != null) { - _ = spliceBody(p, id, pane, 0, bodyOf(pane).len, "") orelse - return Reply.fail(req.tag, E.NOMEM); - p.fs.panes[id].addr = .{}; - setDot(pane, .{}); - } - }, - else => {}, - }, - else => {}, - }; - return switch (attrOf(p, target)) { - .ok => |a| .{ .tag = req.tag, .attr = a }, - .missing => Reply.fail(req.tag, E.NOENT), - }; -} - -fn staged(p: *Pardes, req: Req) Reply { - const out = &p.fs.out; - const off = @min(req.off, out.items.len); - const n = @min(out.items.len - off, req.size); - if (off > 0) std.mem.copyForwards(u8, out.items[0..n], out.items[off..][0..n]); - out.shrinkRetainingCapacity(n); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } }; -} - -fn handleRead(p: *Pardes, req: Req, target: Target) Reply { - switch (target) { - .top => |f| return switch (f) { - .index => readIndex(p, req), - .README => help: { - const off = @min(req.off, fs_help.len); - const bytes = fs_help[off..][0..@min(req.size, fs_help.len - off)]; - p.fs.stage(p.gpa).appendSlice(p.gpa, bytes) catch break :help Reply.fail(req.tag, E.NOMEM); - break :help .{ .tag = req.tag, .payload = .{ .staged = @intCast(bytes.len) } }; - }, - .listeners => listeners: { - var buf: [512]u8 = undefined; - var text = std.Io.Writer.fixed(&buf); - if (p.fs.socket_path.len != 0) - text.print("unix!{s}\n", .{p.fs.socket_path}) catch break :listeners Reply.fail(req.tag, E.IO); - for ([_]?std.Io.net.IpAddress{ p.fs.tcp_address, p.fs.quic_address }, [_][]const u8{ "tcp", "quic" }) |maybe, transport| { - const address = maybe orelse continue; - switch (address) { - .ip4 => |ip| text.print("{s}!{d}.{d}.{d}.{d}!{d}\n", .{ transport, ip.bytes[0], ip.bytes[1], ip.bytes[2], ip.bytes[3], ip.port }) catch - break :listeners Reply.fail(req.tag, E.IO), - .ip6 => |ip| text.print("{s}!{f}!{d}\n", .{ transport, std.Io.net.Ip6Address.Unresolved{ .bytes = ip.bytes, .interface_name = null }, ip.port }) catch - break :listeners Reply.fail(req.tag, E.IO), - } - } - const bytes = text.buffered(); - const off = @min(req.off, bytes.len); - const len = @min(bytes.len - off, req.size); - p.fs.stage(p.gpa).appendSlice(p.gpa, bytes[off..][0..len]) catch break :listeners Reply.fail(req.tag, E.NOMEM); - break :listeners .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; - }, - .screen => readSnapshot(p, req, null), - .cons, .root, .new => Reply.fail(req.tag, E.PERM), - }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pane = p.panes[id].?; - const pf = &p.fs.panes[id]; - if (t.file.inPty() and !pane.isTerminal()) return Reply.fail(req.tag, E.NOENT); - return switch (t.file) { - .addr => readAddr(p, req, pf, pane), - .body => readBody(p, req, id, pane), - .ctl => readCtl(p, req, pane), - .data => readData(req, id, pane, pf, false), - .xdata => readData(req, id, pane, pf, true), - .tag => readTag(p, req, pane), - .event => readQueue(p, req, &pf.events), - .rdsel => readRdsel(req, id, pane), - .pty_status => readPtyStatus(p, req, id, pane), - .pty_data => readPtyData(p, req, pf), - .dir, .errors, .wrsel, .pty, .pty_ctl => Reply.fail(req.tag, E.PERM), - }; - }, - } -} - -fn screenSnapshot(p: *Pardes) ![]u8 { - var arena: std.heap.ArenaAllocator = .init(p.gpa); - defer arena.deinit(); - const surface = try p.render(arena.allocator()); - var styles: std.ArrayList(pardes.CellStyle) = .empty; - var indices: std.ArrayList(usize) = .empty; - for (surface.cells) |cell| { - const style: pardes.CellStyle = if (cell.default) .{} else cell.style; - const index = for (styles.items, 0..) |previous, i| { - if (std.meta.eql(style, previous)) break i; - } else new: { - try styles.append(arena.allocator(), style); - break :new styles.items.len - 1; - }; - try indices.append(arena.allocator(), index); - } - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - const writer = &out.writer; - try writer.print("{{\"cols\":{d},\"rows\":{d},\"cursor\":", .{ surface.cols, surface.rows }); - try std.json.Stringify.value(surface.cursor, .{}, writer); - try writer.writeAll(",\"styles\":"); - try std.json.Stringify.value(styles.items, .{ .emit_strings_as_arrays = true }, writer); - try writer.writeAll(",\"cells\":["); - for (surface.cells, indices.items, 0..) |cell, index, i| { - if (i != 0) try writer.writeByte(','); - try std.json.Stringify.value(.{ if (cell.default) " " else cell.grapheme(), index }, .{}, writer); - } - try writer.writeAll("]}\n"); - return out.toOwnedSlice(); -} - -const ctl_fields = 5 * 12; - -fn stageCtlNumbers(p: *Pardes, out: *std.ArrayList(u8), pane: *Pane) void { - out.print(p.gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} ", .{ - pane.serial, - tagOf(p, pane).len, - bodyOf(pane).len, - @as(u32, 0), - @intFromBool(dirtyOf(pane)), - }) catch {}; -} - -fn readIndex(p: *Pardes, req: Req) Reply { - const out = p.fs.stage(p.gpa); - var last: u32 = 0; - while (nextSerialAfter(p, last)) |s| { - last = s; - const pane = p.panes[p.paneBySerial(s).?].?; - stageCtlNumbers(p, out, pane); - out.appendSlice(p.gpa, firstLine(tagOf(p, pane))) catch {}; - out.append(p.gpa, '\n') catch {}; - } - return staged(p, req); -} - -fn readAddr(p: *Pardes, req: Req, pf: *PaneState, pane: *Pane) Reply { - clampAddr(pf, bodyOf(pane).len); - const out = p.fs.stage(p.gpa); - out.print(p.gpa, "{d:>11} {d:>11} ", .{ pf.addr.q0, pf.addr.q1 }) catch {}; - return staged(p, req); -} - -fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - if (pane.file != null) { - const text = bodyOf(pane); - const off = @min(req.off, text.len); - const n = @min(text.len - off, req.size); - return .{ .tag = req.tag, .payload = .{ .region = .{ - .pane = @intCast(id), - .serial = pane.serial, - .off = clip(off), - .len = clip(n), - } } }; - } - if (req.handle != 0 and pane.isTerminal()) return readSnapshot(p, req, pane); - const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch - return Reply.fail(req.tag, E.NOMEM); - defer p.gpa.free(text); - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM); - return staged(p, req); -} - -fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { - if (req.handle == 0 or req.handle > p.fs.snapshots.len) return Reply.fail(req.tag, E.INVAL); - const snapshot = &p.fs.snapshots[req.handle - 1]; - if (snapshot.node == 0 or snapshot.node != req.node) return Reply.fail(req.tag, E.INVAL); - if (snapshot.bytes == null) { - const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); - snapshot.bytes = panes.Terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); - } - const bytes = snapshot.bytes.?; - const off = @min(req.off, bytes.len); - const len = @min(bytes.len - off, req.size); - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, bytes[off..][0..len]) catch return Reply.fail(req.tag, E.NOMEM); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; -} - -fn fontName(p: *Pardes) []const u8 { - const name = p.settings.font.effective_name.get(); - return if (name.len == 0) "default" else name; -} - -fn stageQuoted(out: *std.ArrayList(u8), gpa: std.mem.Allocator, s: []const u8) void { - const plain = s.len > 0 and for (s) |c| { - if (c <= ' ' or c == '\'') break false; - } else true; - if (plain) { - out.appendSlice(gpa, s) catch {}; - return; - } - out.append(gpa, '\'') catch {}; - for (s) |c| { - if (c == '\'') out.append(gpa, '\'') catch {}; - out.append(gpa, c) catch {}; - } - out.append(gpa, '\'') catch {}; -} - -fn readCtl(p: *Pardes, req: Req, pane: *Pane) Reply { - const out = p.fs.stage(p.gpa); - stageCtlNumbers(p, out, pane); - out.print(p.gpa, "{d:>11} ", .{pane.cols}) catch {}; - stageQuoted(out, p.gpa, fontName(p)); - out.print(p.gpa, " {d:>11} ", .{config.tab_width}) catch {}; - return staged(p, req); -} - -fn readTag(p: *Pardes, req: Req, pane: *Pane) Reply { - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, tagOf(p, pane)) catch {}; - return staged(p, req); -} - -fn readData(req: Req, id: usize, pane: *Pane, pf: *PaneState, stop_at_end: bool) Reply { - const text = bodyOf(pane); - clampAddr(pf, text.len); - const q0: usize = pf.addr.q0; - const hi: usize = if (stop_at_end) @max(q0, @as(usize, pf.addr.q1)) else text.len; - var end = @min(hi, q0 +| req.size); - end = @max(q0, modal.graphemeStart(text, end)); - pf.addr.q0 = clip(end); - if (!stop_at_end) pf.addr.q1 = clip(end); - if (pane.file == null) return .{ .tag = req.tag }; - return .{ .tag = req.tag, .payload = .{ .region = .{ - .pane = @intCast(id), - .serial = pane.serial, - .off = clip(q0), - .len = clip(end - q0), - } } }; -} - -fn readRdsel(req: Req, id: usize, pane: *Pane) Reply { - if (pane.file == null) return .{ .tag = req.tag }; - const text = bodyOf(pane); - const d = dotOf(pane); - const lo = @min(@as(usize, d.q0), text.len); - const hi = @max(lo, @min(@as(usize, d.q1), text.len)); - const off = @min(req.off, hi - lo); - const n = @min(hi - lo - off, req.size); - return .{ .tag = req.tag, .payload = .{ .region = .{ - .pane = @intCast(id), - .serial = pane.serial, - .off = clip(lo + off), - .len = clip(n), - } } }; -} - -fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply { - const record = q.peek() orelse return .{ .tag = req.tag, .status = .again }; - if (req.size < record.len) return Reply.fail(req.tag, E.INVAL); - const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, record) catch return Reply.fail(req.tag, E.NOMEM); - q.pop(); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; -} - -fn readPtyStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - const out = p.fs.stage(p.gpa); - out.print(p.gpa, "{d:>11} {d:>11} {d:>11} ", .{ - pane.cols, - pane.rows, - @intFromBool(p.hostTtyTaken(id)), - }) catch {}; - return staged(p, req); -} - -fn readPtyData(p: *Pardes, req: Req, pf: *PaneState) Reply { - if (pf.pty_out.empty()) return .{ .tag = req.tag, .status = .again }; - const out = p.fs.stage(p.gpa); - while (out.items.len < req.size) { - const chunk = pf.pty_out.peek() orelse break; - const n = @min(chunk.len, req.size - out.items.len); - out.appendSlice(p.gpa, chunk[0..n]) catch break; - pf.pty_out.popFront(n); - } - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; -} - -fn handleWrite(p: *Pardes, req: Req, target: Target) Reply { - switch (target) { - .top => |f| return switch (f) { - .cons => if (appendErrors(p, p.active, req.data)) |took| - .{ .tag = req.tag, .written = @intCast(took) } - else - Reply.fail(req.tag, E.IO), - else => Reply.fail(req.tag, E.PERM), - }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pane = p.panes[id].?; - if (t.file.inPty() and !pane.isTerminal()) return Reply.fail(req.tag, E.NOENT); - return switch (t.file) { - .addr => writeAddr(p, req, id, pane), - .body => writeBody(p, req, id, pane), - .ctl => writeCtl(p, req, t.serial), - .data, .xdata => writeData(p, req, id, pane), - .tag => writeTag(p, req, pane), - .event => writeEvent(p, req, id), - .wrsel => writeWrsel(p, req, id, pane), - .errors => if (appendErrors(p, id, req.data)) |took| - .{ .tag = req.tag, .written = @intCast(took) } - else - Reply.fail(req.tag, E.IO), - .pty_ctl => writePtyCtl(p, req, id), - .pty_data => writePtyData(p, req, id), - .dir, .rdsel, .pty, .pty_status => Reply.fail(req.tag, E.PERM), - }; - }, - } -} - -fn spliceBody(p: *Pardes, id: usize, pane: *Pane, q0: usize, q1: usize, bytes: []const u8) ?usize { - const f = fileOf(pane) orelse return null; - const take = if (bytes.len == 0) 0 else wholeUtf8(bytes); - const lo = @min(q0, f.content.len); - const hi = @max(lo, @min(q1, f.content.len)); - const new = p.gpa.alloc(u8, f.content.len - (hi - lo) + take) catch return null; - @memcpy(new[0..lo], f.content[0..lo]); - @memcpy(new[lo..][0..take], bytes[0..take]); - @memcpy(new[lo + take ..], f.content[hi..]); - if (!p.fs.panes[id].nomark) panes.File.pushUndo(p, pane); - panes.File.setContent(p, f, new); - return take; -} - -fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - if (pane.file == null) { - const take = wholeUtf8(req.data); - p.emitWrite(id, req.data[0..take]); - return .{ .tag = req.tag, .written = @intCast(take) }; - } - const at = bodyOf(pane).len; - const take = spliceBody(p, id, pane, at, at, req.data) orelse - return Reply.fail(req.tag, E.NOMEM); - if (!p.fs.panes[id].noscroll) showOffset(pane, at + take); - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -fn writeTag(p: *Pardes, req: Req, pane: *Pane) Reply { - if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - p.seedTail(pane); - const room = pane.tag_tail.len - pane.tag_tail_len; - if (room == 0) return Reply.fail(req.tag, E.NOSPC); - const take = wholeUtf8(req.data[0..@min(req.data.len, room)]); - @memcpy(pane.tag_tail[pane.tag_tail_len..][0..take], req.data[0..take]); - pane.tag_tail_len += take; - pane.tag_init = true; - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -fn writeData(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); - const pf = &p.fs.panes[id]; - clampAddr(pf, bodyOf(pane).len); - const q0: usize = pf.addr.q0; - const q1: usize = @max(q0, @as(usize, pf.addr.q1)); - const before = dotOf(pane); - const take = spliceBody(p, id, pane, q0, q1, req.data) orelse - return Reply.fail(req.tag, E.NOMEM); - setDot(pane, shiftBy(before, clip(q0), clip(q1 - q0), clip(take))); - pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }; - if (!pf.noscroll) showOffset(pane, q0 + take); - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -fn writeWrsel(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); - const d = dotOf(pane); - const q0: usize = d.q0; - const q1: usize = @max(q0, @as(usize, d.q1)); - const take = spliceBody(p, id, pane, q0, q1, req.data) orelse - return Reply.fail(req.tag, E.NOMEM); - setDot(pane, .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }); - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -fn writeAddr(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - const pf = &p.fs.panes[id]; - const text = bodyOf(pane); - clampAddr(pf, text.len); - const expr = std.mem.trimEnd(u8, req.data, "\n"); - var a: Addr = .{ .text = text, .lim = pf.limit, .expr = expr }; - const r = a.address(pf.addr) orelse return Reply.fail(req.tag, E.INVAL); - if (a.i < expr.len) return Reply.fail(req.tag, E.INVAL); - pf.addr = r; - return .{ .tag = req.tag, .written = @intCast(req.data.len) }; -} - -fn safePattern(pat: []const u8) bool { - var i: usize = 0; - while (i < pat.len) : (i += 1) { - if (pat[i] != '\\') continue; - if (i + 1 >= pat.len) return false; - i += 1; - } - return true; -} - -const Addr = struct { - text: []const u8, - lim: ?PaneState.Range, - expr: []const u8, - i: usize = 0, - depth: u8 = 0, - - const max_depth = 32; - const Size = enum { char, line }; - - fn address(a: *Addr, ar_in: PaneState.Range) ?PaneState.Range { - const start = a.i; - var ar = ar_in; - var r = ar_in; - var dir: u8 = 0; - var size: Size = .line; - var c: u8 = 0; - while (a.i < a.expr.len) { - const prevc = c; - c = a.expr[a.i]; - a.i += 1; - switch (c) { - ',', ';' => { - if (c == ';') ar = r; - if (prevc == 0) r.q0 = 0; // lhs defaults to 0 - if (a.i >= a.expr.len) { - r.q1 = clip(a.text.len); // rhs defaults to $ - } else { - if (a.depth >= max_depth) return null; - a.depth += 1; - const nr = a.address(ar) orelse return null; - a.depth -= 1; - r.q1 = nr.q1; - } - return r; - }, - '+', '-' => { - if (prevc == '+' or prevc == '-') { - const nc = if (a.i < a.expr.len) a.expr[a.i] else 0; - if (nc != '#' and nc != '/' and nc != '?') - r = a.number(r, 1, prevc, .line) orelse return null; - } - dir = c; - }, - '.', '$' => { - if (a.i != start + 1) { - a.i -= 1; - return r; - } - r = if (c == '.') ar else .{ .q0 = clip(a.text.len), .q1 = clip(a.text.len) }; - dir = if (a.i < a.expr.len) '+' else 0; - }, - '#', '0'...'9' => { - var digit = c; - if (c == '#') { - if (a.i >= a.expr.len or a.expr[a.i] < '0' or a.expr[a.i] > '9') { - a.i -= 1; - return r; - } - digit = a.expr[a.i]; - a.i += 1; - size = .char; - } - var n: u64 = digit - '0'; - while (a.i < a.expr.len) : (a.i += 1) { - const d = a.expr[a.i]; - if (d < '0' or d > '9') break; - n = @min(n * 10 + (d - '0'), std.math.maxInt(u32)); - } - r = a.number(r, @intCast(n), dir, size) orelse return null; - dir = 0; - size = .line; - }, - '/', '?' => { - const back = c == '?'; - r = a.regexp(r, a.pattern(c), back) orelse return null; - dir = 0; - size = .line; - }, - else => { - a.i -= 1; - return r; - }, - } - } - if (dir != 0) r = a.number(r, 1, dir, .line) orelse return null; - return r; - } - - fn pattern(a: *Addr, delim: u8) []const u8 { - const s = a.i; - while (a.i < a.expr.len) { - const c = a.expr[a.i]; - if (c == '\n') break; - a.i += 1; - if (c == '\\') { - if (a.i < a.expr.len) a.i += 1; - continue; - } - if (c == delim) return a.expr[s .. a.i - 1]; - } - return a.expr[s..a.i]; - } - - fn number(a: *Addr, r_in: PaneState.Range, n: u32, dir: u8, size: Size) ?PaneState.Range { - var r = r_in; - if (size == .char) { - var off: i64 = n; - if (dir == '+') { - off = @as(i64, r.q1) + n; - } else if (dir == '-') { - if (r.q0 == 0 and n > 0) r.q0 = clip(a.text.len); - off = @as(i64, r.q0) - n; - } - if (off < 0 or off > @as(i64, @intCast(a.text.len))) return null; - const g = clip(modal.graphemeStart(a.text, @intCast(off))); - return .{ .q0 = g, .q1 = g }; - } - var line: i64 = n; - var q0: usize = r.q0; - var q1: usize = r.q1; - switch (dir) { - '-' => { - if (q0 < a.text.len) while (q0 > 0 and a.text[q0 - 1] != '\n') { - q0 -= 1; - }; - q1 = q0; - while (line > 0 and q0 > 0) { - if (a.text[q0 - 1] == '\n') { - line -= 1; - q1 = q0; - } - q0 -= 1; - } - if (line > 1) return null; - while (q0 > 0 and a.text[q0 - 1] != '\n') q0 -= 1; - return .{ .q0 = clip(q0), .q1 = clip(q1) }; - }, - '+' => { - if (q1 > 0) while (q1 < a.text.len and a.text[q1 - 1] != '\n') { - q1 += 1; - }; - q0 = q1; - }, - else => { - q0 = 0; - q1 = 0; - }, - } - while (line > 0 and q1 < a.text.len) { - const ch = a.text[q1]; - q1 += 1; - if (ch == '\n' or q1 == a.text.len) { - line -= 1; - if (line > 0) q0 = q1; - } - } - if (line > 0) return null; - return .{ .q0 = clip(q0), .q1 = clip(q1) }; - } - - fn regexp(a: *Addr, r: PaneState.Range, pat: []const u8, back: bool) ?PaneState.Range { - if (pat.len == 0 or !safePattern(pat)) return null; - const re = mvzr.compile(pat) orelse return null; - if (back) { - const hi = @min(@as(usize, r.q0), a.text.len); - var best: ?mvzr.Match = null; - var at: usize = 0; - while (at < hi) { - const m = re.matchPos(at, a.text[0..hi]) orelse break; - best = m; - at = if (m.end > m.start) m.end else m.end + 1; - } - const m = best orelse return null; - return .{ .q0 = clip(m.start), .q1 = clip(m.end) }; - } - const hi = if (a.lim) |l| @min(@as(usize, l.q1), a.text.len) else a.text.len; - const from = @min(@as(usize, r.q1), hi); - const m = re.match(a.text[from..hi]) orelse return null; - return .{ .q0 = clip(from + m.start), .q1 = clip(from + m.end) }; - } -}; - -const Verb = enum { - @"addr=dot", - clean, - cleartag, - del, - delete, - dirty, - @"dot=addr", - get, - @"limit=addr", - mark, - nomark, - noscroll, - put, - scroll, - show, -}; - -const refused_verbs = [_][]const u8{ "dump", "dumpdir", "font", "lock", "menu", "nomenu", "unlock" }; - -fn verbIs(line: []const u8, word: []const u8) bool { - if (!std.mem.startsWith(u8, line, word)) return false; - return line.len == word.len or line[word.len] == ' '; -} - -fn writeCtl(p: *Pardes, req: Req, serial: u32) Reply { - for ([2]bool{ false, true }) |apply| { - var dirty = if (p.paneBySerial(serial)) |id| dirtyOf(p.panes[id].?) else false; - var it = std.mem.splitScalar(u8, req.data, '\n'); - while (it.next()) |raw| { - const line = std.mem.trim(u8, raw, " \t\r"); - if (line.len == 0) continue; - const live = p.paneBySerial(serial) orelse if (apply) break else return Reply.fail(req.tag, E.NOENT); - const errno = ctlVerb(p, live, line, apply, &dirty); - if (errno != 0) return Reply.fail(req.tag, errno); - } - } - return .{ .tag = req.tag, .written = @intCast(req.data.len) }; -} - -/// Change a buffer's absolute name without writing or renaming a disk file. -/// Tag editing preserves user commands; the 9P name operation resets its tail. -pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) !void { - const pane = p.panes[id] orelse return error.NoPane; - const f = fileOf(pane) orelse return error.NotFile; - if (!std.fs.path.isAbsolute(full) or full.len == 0 or full.len >= 4096) - return error.InvalidName; - for (full) |c| if (c < ' ') return error.InvalidName; - if (std.mem.eql(u8, f.path, full)) return; - const copy = try p.gpa.dupe(u8, full); - p.gpa.free(f.path); - f.path = copy; - if (panes.Output.fileTraits(f.output).saves) { - f.output = null; - pane.clearCwd(); - if (!preserve_tag) { - pane.tag_init = false; - pane.tag_tail_len = 0; - } - f.saved_revision = f.revision -% 1; - f.watch_after_save = localPath(full) != null; - } - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = &.{}; - f.highlight_start = 0; - f.syntax_dirty = true; - f.context_revision = null; - pane.context_rows = 0; - pane.wrap_n = 0; - p.invalidateLookHover(id); - p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); -} - -fn ctlVerb(p: *Pardes, id: usize, line: []const u8, apply: bool, dirty: *bool) u16 { - const pane = p.panes[id] orelse return E.INVAL; - const pf = &p.fs.panes[id]; - - if (verbIs(line, "look")) { - if (line.len <= 5) return E.INVAL; - const word = std.mem.trim(u8, line[5..], " \t"); - if (word.len == 0) return E.INVAL; - for (word) |c| if (c < ' ') return E.INVAL; - if (apply) p.lookAt(id, word); - return 0; - } - if (verbIs(line, "name")) { - if (line.len <= 5) return E.INVAL; - const name = std.mem.trim(u8, line[5..], " \t"); - if (name.len == 0) return E.INVAL; - for (name) |c| if (c <= ' ') return E.INVAL; - const f = fileOf(pane) orelse return 0; - const full = std.fs.path.resolvePosix(p.gpa, &.{ Pardes.paneDir(pane), name }) catch return E.NOMEM; - defer p.gpa.free(full); - if (!std.fs.path.isAbsolute(full) or full.len >= 4096) return E.INVAL; - if (std.mem.eql(u8, f.path, full)) return 0; - if (panes.Output.fileTraits(f.output).saves) dirty.* = true; - if (!apply) return 0; - nameBuffer(p, id, full, false) catch return E.NOMEM; - return 0; - } - for (refused_verbs) |w| if (verbIs(line, w)) return E.INVAL; - - const v = std.meta.stringToEnum(Verb, line) orelse return E.INVAL; - if (v == .del and dirty.*) return E.INVAL; - switch (v) { - .dirty => dirty.* = true, - .clean, .get, .put => dirty.* = false, - else => {}, - } - if (!apply) return 0; - - switch (v) { - .@"addr=dot" => pf.addr = dotOf(pane), - .@"dot=addr" => { - clampAddr(pf, bodyOf(pane).len); - setDot(pane, pf.addr); - }, - .@"limit=addr" => { - clampAddr(pf, bodyOf(pane).len); - pf.limit = pf.addr; - }, - .clean => if (fileOf(pane)) |f| { - f.saved_revision = f.revision; - }, - .dirty => if (fileOf(pane)) |f| { - f.saved_revision = f.revision -% 1; - }, - .cleartag => { - pane.tag_tail_len = 0; - pane.tag_init = true; - }, - .del, .delete => p.removePane(id) catch return E.NOMEM, - .put => { - const serial = pane.serial; - if (fileOf(pane)) |f| { - if (f.output == null) { - p.perform(.{ .save_file = .{ .pane = @intCast(id) } }); - const current = p.paneBySerial(serial) orelse return E.NOENT; - if (dirtyOf(p.panes[current].?)) return E.IO; - } else _ = p.executeBuiltinLine(id, "Save"); - } else _ = p.executeBuiltinLine(id, "Save"); - }, - .get => if (fileOf(pane)) |f| { - if (panes.Output.fileTraits(f.output).saves) { - if (read(p, f.path)) |bytes| { - panes.File.pushUndo(p, pane); - panes.File.setContent(p, f, bytes); - f.saved_revision = f.revision; - } else |err| return switch (err) { - error.FileNotFound => E.NOENT, - else => E.IO, - }; - } - }, - .mark => { - pf.nomark = false; - panes.File.pushUndo(p, pane); - }, - .nomark => pf.nomark = true, - .noscroll => pf.noscroll = true, - .scroll => pf.noscroll = false, - .show => showOffset(pane, dotOf(pane).q0), - } - return 0; -} - -const PtyVerb = enum { winsize, sig, exec }; - -fn ptyDimension(word: []const u8) ?u16 { - if (word.len == 0 or word.len > 5) return null; - for (word) |c| if (c < '0' or c > '9') return null; - const n = std.fmt.parseInt(u16, word, 10) catch return null; - return if (n == 0) null else n; -} - -fn ptySignalNamed(word: []const u8) ?pardes.PtySignal { - if (std.mem.eql(u8, word, "INT")) return .int; - if (std.mem.eql(u8, word, "TERM")) return .term; - if (std.mem.eql(u8, word, "HUP")) return .hup; - if (std.mem.eql(u8, word, "QUIT")) return .quit; - if (std.mem.eql(u8, word, "KILL")) return .kill; - return null; -} - -fn writePtyCtl(p: *Pardes, req: Req, id: usize) Reply { - for ([2]bool{ false, true }) |apply| { - var it = std.mem.splitScalar(u8, req.data, '\n'); - while (it.next()) |raw| { - const line = std.mem.trim(u8, raw, " \t\r"); - if (line.len == 0) continue; - if (!ptyVerb(p, id, line, apply)) return Reply.fail(req.tag, E.INVAL); - } - } - return .{ .tag = req.tag, .written = @intCast(req.data.len) }; -} - -fn ptyVerb(p: *Pardes, id: usize, line: []const u8, apply: bool) bool { - const pane = p.panes[id] orelse return false; - var words = std.mem.tokenizeAny(u8, line, " \t"); - const v = std.meta.stringToEnum(PtyVerb, words.next() orelse return false) orelse return false; - switch (v) { - .winsize => { - const cols = ptyDimension(words.next() orelse return false) orelse return false; - const rows = ptyDimension(words.next() orelse return false) orelse return false; - if (words.next() != null) return false; - if (!apply) return true; - p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); - }, - .sig => { - const which = ptySignalNamed(words.next() orelse return false) orelse return false; - if (words.next() != null) return false; - if (!apply) return true; - p.emit(.{ .signal_pty = .{ .pane = @intCast(id), .sig = which } }); - }, - .exec => { - if (words.next() != null) return false; - if (pane.cwdSlice().len > pardes.effect_path_cap) return false; - if (!apply) return true; - p.emit(.{ .spawn = .{ .pane = @intCast(id), .cwd = .from(pane.cwdSlice()) } }); - }, - } - return true; -} - -fn writePtyData(p: *Pardes, req: Req, id: usize) Reply { - if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - const take = wholeUtf8(req.data); - p.emitWrite(id, req.data[0..take]); - return .{ .tag = req.tag, .written = @intCast(take) }; -} - -const EventRecord = struct { action: Action, q0: u32, q1: u32 }; - -const EventReader = struct { - data: []const u8, - i: usize = 0, - - fn next(er: *EventReader) ?EventRecord { - if (er.i >= er.data.len) return null; - var i = er.i; - if (i + 2 > er.data.len) return null; - i += 1; - const action = Action.fromChar(er.data[i]) orelse return null; - i += 1; - const q0 = scanNumber(er.data, &i) orelse return null; - const q1 = scanNumber(er.data, &i) orelse return null; - while (i < er.data.len and er.data[i] == ' ') i += 1; - if (i >= er.data.len or er.data[i] != '\n') return null; - er.i = i + 1; - return .{ .action = action, .q0 = q0, .q1 = q1 }; - } -}; - -fn scanNumber(data: []const u8, i: *usize) ?u32 { - while (i.* < data.len and data[i.*] == ' ') i.* += 1; - const s = i.*; - var n: u64 = 0; - while (i.* < data.len and data[i.*] >= '0' and data[i.*] <= '9') : (i.* += 1) - n = @min(n * 10 + (data[i.*] - '0'), std.math.maxInt(u32)); - if (i.* == s) return null; - return @intCast(n); -} - -fn writeEvent(p: *Pardes, req: Req, id: usize) Reply { - const pane0 = p.panes[id] orelse return Reply.fail(req.tag, E.NOENT); - const serial = pane0.serial; - { - const body = bodyOf(pane0); - const tag = tagOf(p, pane0); - var check: EventReader = .{ .data = req.data }; - while (check.next()) |r| { - switch (r.action) { - .body_look, .tag_look, .body_exec, .tag_exec => {}, - else => return Reply.fail(req.tag, E.INVAL), - } - const n = if (r.action.onTag()) tag.len else body.len; - if (r.q0 > r.q1 or r.q1 > n) return Reply.fail(req.tag, E.INVAL); - } - if (check.i != req.data.len) return Reply.fail(req.tag, E.INVAL); - } - var run: EventReader = .{ .data = req.data }; - while (run.next()) |r| { - const now = p.paneBySerial(serial) orelse break; - const pane = p.panes[now].?; - const whole = if (r.action.onTag()) tagOf(p, pane) else bodyOf(pane); - const lo = @min(@as(usize, r.q0), whole.len); - const hi = @max(lo, @min(@as(usize, r.q1), whole.len)); - const text = p.scratch.allocator().dupe(u8, whole[lo..hi]) catch continue; - switch (r.action) { - .body_exec, .tag_exec => _ = p.execute(now, text), - .body_look, .tag_look => p.lookAt(now, text), - else => unreachable, - } - } - return .{ .tag = req.tag, .written = @intCast(req.data.len) }; -} - -fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { - if (text.len == 0) return 0; - const pane = p.panes[id] orelse return null; - const dir = dirOf(pane); - for (p.panes, 0..) |slot, i| { - const q = slot orelse continue; - const qf = fileOf(q) orelse continue; - const o = qf.output orelse continue; - if (std.meta.activeTag(o.from) != .errors) continue; - if (!std.mem.eql(u8, std.fs.path.dirname(qf.path) orelse "", dir)) continue; - return spliceBody(p, i, q, qf.content.len, qf.content.len, text); - } - const free = p.freeSlot() orelse return null; - const content = p.gpa.dupe(u8, text) catch return null; - const np = panes.Output.open(p, free, dir, .errors, "", content) catch { - p.gpa.free(content); - return null; - }; - p.placeDoc(id, free, np); - return text.len; -} - -fn indexLen(p: *Pardes) u64 { - var n: u64 = 0; - for (p.panes) |slot| { - const pane = slot orelse continue; - n += ctl_fields + firstLine(tagOf(p, pane)).len + 1; - } - return n; -} - -fn bodyLen(p: *Pardes, pane: *Pane) u64 { - _ = p; - return bodyOf(pane).len; -} - -fn tagLen(p: *Pardes, pane: *Pane) u64 { - return tagOf(p, pane).len; -} - -test "filesystem inspection preserves pending and displayed Look hover" { - const delay = config.look_preview_delay_frames orelse return; - const gpa = std.testing.allocator; - const p = try withFile(gpa, "alpha beta gamma\n"); - defer p.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try p.render(frame.allocator()); - const rect = p.rects[0]; - p.update(.{ .mouse = .{ - .button = .none, - .kind = .motion, - .col = rect.x + config.GUTTER + config.PREFIX_W + 7, - .row = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H, - } }); - try testing.expect(p.look_hover_wait != null); - const body = Node.of(serialOf(p), .body); - const screen = @intFromEnum(SelfFile.screen); - for (0..2) |phase| { - if (phase == 1) { - for (0..delay) |_| p.update(.tick); - try testing.expect(p.look_hover_preview != null); - } - const waiting = p.look_hover_wait; - const preview = p.look_hover_preview; - const requests = [_]Req{ - .{ .tag = 1, .op = .lookup, .node = @intFromEnum(SelfFile.root), .data = "screen" }, - .{ .tag = 1, .op = .lookup, .node = @intFromEnum(SelfFile.new), .data = ".." }, - .{ .tag = 1, .op = .lookup, .node = @intFromEnum(SelfFile.new), .data = "body" }, - .{ .tag = 2, .op = .getattr, .node = body }, - .{ .tag = 3, .op = .open, .node = body }, - .{ .tag = 4, .op = .read, .node = body, .size = 5 }, - .{ .tag = 5, .op = .release, .node = body, .handle = 1 }, - .{ .tag = 6, .op = .readdir, .node = @intFromEnum(SelfFile.root), .size = 4096 }, - .{ .tag = 7, .op = .open, .node = screen }, - .{ .tag = 8, .op = .read, .node = screen, .handle = 1, .size = 32 }, - .{ .tag = 9, .op = .release, .node = screen, .handle = 1 }, - }; - for (requests) |req| { - const answer = call(p, req); - try testing.expectEqual(Status.ok, answer.reply.status); - try testing.expect(std.meta.eql(waiting, p.look_hover_wait)); - try testing.expect(std.meta.eql(preview, p.look_hover_preview)); - try testing.expect(p.raw_hover_intent); - } - } - try testing.expectEqual(Status.ok, wr(p, body, "changed").reply.status); - try testing.expect(p.look_hover_wait == null); - try testing.expect(p.look_hover_preview == null); - try testing.expect(!p.raw_hover_intent); -} - -test "filesystem pane creation and truncation cancel Look hover" { - const requests = [_]Req{ - .{ .tag = 2, .op = .open, .node = factory_base + @intFromEnum(PaneFile.body) }, - .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true }, - }; - for (requests) |request| { - const p = try withFile(testing.allocator, "word\n"); - defer p.deinit(); - p.look_hover_wait = .{ .col = 1, .row = 1, .pane = 0, .serial = serialOf(p) }; - p.raw_hover_intent = true; - var req = request; - if (req.op == .setattr) req.node = Node.of(serialOf(p), .body); - try testing.expectEqual(Status.ok, call(p, req).reply.status); - try testing.expect(p.look_hover_wait == null); - try testing.expect(p.look_hover_preview == null); - try testing.expect(!p.raw_hover_intent); - } -} - -test "terminal body handles keep one history snapshot across fragmented reads" { - const gpa = std.testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const node = Node.of(serialOf(p), .body); - p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } }); - while (p.nextEffect()) |_| {} - const original = try panes.Terminal.screenTextAlloc(p.panes[0].?, gpa); - defer gpa.free(original); - const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqual(Status.ok, opened.reply.status); - const first = call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 3 }); - try testing.expectEqualStrings(original[0..3], first.bytes); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J\x1b[2J\x1b[Hnew output" } }); - while (p.nextEffect()) |_| {} - var offset: usize = 3; - while (offset < original.len) { - const part = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .off = offset, .size = 3 }); - try testing.expectEqualStrings(original[offset..][0..@min(3, original.len - offset)], part.bytes); - offset += part.bytes.len; - } - try testing.expectEqualStrings("", call(p, .{ .tag = 4, .op = .read, .node = node, .handle = opened.reply.handle, .off = original.len, .size = 3 }).bytes); - _ = call(p, .{ .tag = 5, .op = .release, .node = node, .handle = opened.reply.handle }); - const newer = call(p, .{ .tag = 6, .op = .open, .node = node }); - try testing.expectEqualStrings("new output", call(p, .{ .tag = 7, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); - _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = newer.reply.handle }); -} - -test "an empty terminal body snapshot stays empty while output continues" { - const p = try withTerm(std.testing.allocator); - defer p.deinit(); - const node = Node.of(serialOf(p), .body); - const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqualStrings("", call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); - try testing.expect(p.fs.snapshots[opened.reply.handle - 1].bytes != null); - p.update(.{ .output = .{ .pane = 0, .bytes = "new output" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); - _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = opened.reply.handle }); - const newer = call(p, .{ .tag = 5, .op = .open, .node = node }); - try testing.expectEqualStrings("new output", call(p, .{ .tag = 6, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); - _ = call(p, .{ .tag = 7, .op = .release, .node = node, .handle = newer.reply.handle }); -} - -test "terminal body snapshots are lazy bounded and released after the pane closes" { - const gpa = std.testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const node = Node.of(serialOf(p), .body); - var handles: [32]u32 = undefined; - for (&handles) |*opened_handle| { - const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqual(Status.ok, opened.reply.status); - opened_handle.* = opened.reply.handle; - } - for (p.fs.snapshots) |snapshot| { - try testing.expectEqual(node, snapshot.node); - try testing.expect(snapshot.bytes == null); - } - try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = node }).errno()); - const scratch = call(p, .{ .tag = 2, .op = .open, .node = factory_base + @intFromEnum(PaneFile.body) }); - try testing.expectEqual(Status.ok, scratch.reply.status); - const scratch_id = p.paneBySerial(Node.target(scratch.reply.attr.node).?.pane.serial).?; - try testing.expect(p.panes[scratch_id].?.file != null); - _ = call(p, .{ .tag = 2, .op = .release, .node = scratch.reply.attr.node, .handle = scratch.reply.handle }); - p.update(.{ .output = .{ .pane = 0, .bytes = "latest output" } }); - while (p.nextEffect()) |_| {} - var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - p.gpa = failing.allocator(); - const failed = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = handles[0], .size = 32 }); - p.gpa = gpa; - try testing.expectEqual(E.NOMEM, failed.errno()); - try testing.expect(p.fs.snapshots[handles[0] - 1].bytes == null); - const first = call(p, .{ .tag = 4, .op = .read, .node = node, .handle = handles[0], .size = 32 }); - try testing.expectEqualStrings("latest output", first.bytes); - const saved = p.fs.snapshots[handles[0] - 1].bytes.?; - failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - p.gpa = failing.allocator(); - const second = call(p, .{ .tag = 5, .op = .read, .node = node, .handle = handles[0], .off = 7, .size = 32 }); - p.gpa = gpa; - try testing.expectEqualStrings("output", second.bytes); - try testing.expect(!failing.has_induced_failure); - try testing.expectEqual(saved.ptr, p.fs.snapshots[handles[0] - 1].bytes.?.ptr); - const screen = @intFromEnum(SelfFile.screen); - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .read, .node = screen, .handle = handles[0], .size = 32 }).errno()); - _ = call(p, .{ .tag = 7, .op = .release, .node = screen, .handle = handles[0] }); - try testing.expectEqual(node, p.fs.snapshots[handles[0] - 1].node); - try p.removePane(0); - for (handles) |opened_handle| _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = opened_handle }); - for (p.fs.snapshots) |snapshot| { - try testing.expectEqual(@as(u64, 0), snapshot.node); - try testing.expect(snapshot.bytes == null); - } -} - -test "screen snapshots preserve rendered cells and styles until their handle is released" { - const gpa = std.testing.allocator; - const p = try withFile(gpa, "const value = 1;\n"); - defer p.deinit(); - const node = @intFromEnum(SelfFile.screen); - const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqual(Status.ok, opened.reply.status); - const snapshot = p.fs.snapshots[opened.reply.handle - 1].bytes.?; - const original = try gpa.dupe(u8, snapshot); - defer gpa.free(original); - const parsed = try std.json.parseFromSlice(std.json.Value, gpa, original, .{}); - defer parsed.deinit(); - const data = parsed.value.object; - try testing.expectEqual(@as(i64, p.screen_w), data.get("cols").?.integer); - try testing.expectEqual(@as(i64, p.screen_h), data.get("rows").?.integer); - try testing.expectEqual(@as(usize, p.screen_w) * p.screen_h, data.get("cells").?.array.items.len); - try testing.expect(data.get("styles").?.array.items.len > 0); - _ = wr(p, Node.of(serialOf(p), .body), "changed\n"); - const newer = call(p, .{ .tag = 2, .op = .open, .node = node }); - try testing.expectEqual(Status.ok, newer.reply.status); - try testing.expect(!std.mem.eql(u8, original, p.fs.snapshots[newer.reply.handle - 1].bytes.?)); - var off: usize = 0; - while (off < original.len) { - const result = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .off = off, .size = 13 }); - try testing.expectEqual(Status.ok, result.reply.status); - try testing.expectEqualSlices(u8, original[off..][0..@min(13, original.len - off)], result.bytes); - off += result.bytes.len; - } - _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = opened.reply.handle }); - _ = call(p, .{ .tag = 5, .op = .release, .node = node, .handle = newer.reply.handle }); - for (p.fs.snapshots) |slot| try testing.expect(slot.node == 0); -} - -test "screen inspection preserves acknowledged presentation and the next real frame" { - const gpa = testing.allocator; - for (std.enums.values(pardes.layout.Transition)) |transition| { - errdefer std.debug.print("screen inspection during {s}\n", .{@tagName(transition)}); - const control = try withFile(gpa, "const value = 1;\n"); - defer control.deinit(); - const inspected = try withFile(gpa, "const value = 1;\n"); - defer inspected.deinit(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - for ([_]*Pardes{ control, inspected }) |p| { - p.settings.panel_transition = .off; - p.update(.tick); - p.acknowledgePanelPresentation((try p.render(arena.allocator())).panelTracks()); - p.settings.panel_transition = transition; - } - for (0..4) |phase| { - for ([_]*Pardes{ control, inspected }) |p| switch (phase) { - 0 => {}, - 1 => p.update(.{ .command = "New" }), - 2 => { - p.update(.tick); - try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[p.active].?.serial, .body), "changed cells\n").reply.status); - }, - 3 => { - for (0..transition.frames() + 1) |_| p.update(.tick); - p.acknowledgePanelPresentation((try p.render(arena.allocator())).panelTracks()); - p.update(.{ .command = "Del" }); - }, - else => unreachable, - }; - const screen = @intFromEnum(SelfFile.screen); - for (0..2) |_| { - const opened = call(inspected, .{ .tag = 1, .op = .open, .node = screen }); - try testing.expectEqual(Status.ok, opened.reply.status); - const captured = call(inspected, .{ .tag = 2, .op = .read, .node = screen, .handle = opened.reply.handle, .size = 32 }); - try testing.expectEqual(Status.ok, captured.reply.status); - try testing.expect(captured.bytes.len > 0); - try testing.expectEqual(Status.ok, call(inspected, .{ - .tag = 3, - .op = .release, - .node = screen, - .handle = opened.reply.handle, - }).reply.status); - } - const a = &control.presentation; - const b = &inspected.presentation; - try testing.expectEqualDeep(a.shown, b.shown); - try testing.expectEqualDeep(a.shown_tracks, b.shown_tracks); - try testing.expectEqualDeep(a.shown_closing[0..a.shown_closing_len], b.shown_closing[0..b.shown_closing_len]); - try testing.expectEqual(a.pending, b.pending); - try testing.expectEqual(a.acknowledged, b.acknowledged); - try testing.expectEqual(a.previous_valid, b.previous_valid); - try testing.expectEqual(a.previous_cols, b.previous_cols); - try testing.expectEqual(a.previous_rows, b.previous_rows); - try testing.expectEqualDeep(a.previous_layout, b.previous_layout); - try testing.expectEqual(a.previous_cells.len, b.previous_cells.len); - for (a.previous_cells, b.previous_cells) |*expected, *actual| - try testing.expect(expected.visuallyEqual(actual)); - - const expected = try control.render(arena.allocator()); - const actual = try inspected.render(arena.allocator()); - try testing.expectEqual(expected.cols, actual.cols); - try testing.expectEqual(expected.rows, actual.rows); - try testing.expectEqualDeep(expected.cursor, actual.cursor); - try testing.expectEqualDeep(expected.panelTracks(), actual.panelTracks()); - try testing.expectEqualDeep(expected.cell_diffs, actual.cell_diffs); - try testing.expectEqual(expected.previous_cells.len, actual.previous_cells.len); - try testing.expectEqual(expected.cells.len, actual.cells.len); - try testing.expectEqual(@as(usize, 0), expected.nimages); - try testing.expectEqual(@as(usize, 0), actual.nimages); - for (expected.cells, actual.cells) |*left, *right| try testing.expect(left.visuallyEqual(right)); - for (expected.previous_cells, actual.previous_cells) |*left, *right| try testing.expect(left.visuallyEqual(right)); - if (phase == 1 and transition != .off) try testing.expect(expected.panelTracks().len > 0); - if (phase == 1 and transition.needsPreviousGrid()) try testing.expect(expected.hasPanelDiff()); - if (phase == 3 and transition == .vertical) try testing.expect(a.closing_len > 0); - control.acknowledgePanelPresentation(expected.panelTracks()); - inspected.acknowledgePanelPresentation(actual.panelTracks()); - try testing.expectEqualDeep(a.shown, b.shown); - try testing.expectEqualDeep(a.previous_layout, b.previous_layout); - _ = arena.reset(.retain_capacity); - } - } -} - -const testing = std.testing; - -const Answer = struct { - reply: Reply = .{ .tag = 0, .status = .err, .errno = E.IO }, - bytes: []const u8 = "", - saved: bool = false, - watch: ?bool = null, - pty_buf: [256]u8 = undefined, - pty_len: usize = 0, - winsize: ?struct { cols: u16, rows: u16 } = null, - signal: ?pardes.PtySignal = null, - spawned: bool = false, - - fn pty(a: *const Answer) []const u8 { - return a.pty_buf[0..a.pty_len]; - } - - fn errno(a: Answer) u16 { - return if (a.reply.status == .err) a.reply.errno else 0; - } -}; - -fn call(p: *Pardes, req: Req) Answer { - p.update(.{ .fs_req = req }); - var ans: Answer = .{}; - while (p.nextEffect()) |e| switch (e) { - .fs_reply => |r| { - ans.reply = r; - ans.bytes = p.fsPayload(r); - }, - .save_file, .save_text => ans.saved = true, - .watch => |w| ans.watch = w.on, - .write => |w| { - const b = w.bytes.slice(); - const n = @min(b.len, ans.pty_buf.len - ans.pty_len); - @memcpy(ans.pty_buf[ans.pty_len..][0..n], b[0..n]); - ans.pty_len += n; - }, - .resize_pty => |r| ans.winsize = .{ .cols = r.cols, .rows = r.rows }, - .signal_pty => |s| ans.signal = s.sig, - .spawn => ans.spawned = true, - else => {}, - }; - return ans; -} - -fn rd(p: *Pardes, node: u64, off: u64, size: u32) Answer { - return call(p, .{ .tag = 1, .op = .read, .node = node, .off = off, .size = size }); -} - -fn wr(p: *Pardes, node: u64, data: []const u8) Answer { - return call(p, .{ .tag = 2, .op = .write, .node = node, .data = data }); -} - -fn rdir(p: *Pardes, node: u64, skip: u64) Answer { - return call(p, .{ .tag = 4, .op = .readdir, .node = node, .off = skip, .size = 4096 }); -} - -fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer { - return call(p, .{ .tag = 3, .op = .lookup, .node = dir, .data = name }); -} - -fn withFile(gpa: std.mem.Allocator, text: []const u8) !*Pardes { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - errdefer p.deinit(); - while (p.nextEffect()) |_| {} - _ = try p.setTestFile(text); - while (p.nextEffect()) |_| {} - return p; -} - -fn withTerm(gpa: std.mem.Allocator) !*Pardes { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - errdefer p.deinit(); - while (p.nextEffect()) |_| {} - std.debug.assert(p.panes[0].?.isTerminal()); - return p; -} - -fn serialOf(p: *Pardes) u32 { - return p.panes[0].?.serial; -} - -const Dirent = struct { node: u64, dir: bool, name: []const u8 }; - -fn dirents(bytes: []const u8, out: []Dirent) []Dirent { - var n: usize = 0; - var i: usize = 0; - while (i + 10 <= bytes.len and n < out.len) { - const node = std.mem.readInt(u64, bytes[i..][0..8], .little); - const kind = bytes[i + 8]; - const len = bytes[i + 9]; - i += 10; - if (i + len > bytes.len) break; - out[n] = .{ .node = node, .dir = kind == 1, .name = bytes[i .. i + len] }; - i += len; - n += 1; - } - return out[0..n]; -} - -fn nameAt(list: []const Dirent, want: []const u8) ?Dirent { - for (list) |d| if (std.mem.eql(u8, d.name, want)) return d; - return null; -} - -test "listener addresses are readable canonical dials with bounded partial reads" { - const gpa = testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - p.fs.socket_path = "/tmp/a socket.sock"; - p.fs.tcp_address = .{ .ip4 = .loopback(5640) }; - p.fs.quic_address = .{ .ip6 = .loopback(5641) }; - const expected = "unix!/tmp/a socket.sock\ntcp!127.0.0.1!5640\nquic!::1!5641\n"; - for ([_][]const u8{ "/virtual/listeners", "/n/self/listeners" }) |path| { - const bytes = try read(p, path); - defer gpa.free(bytes); - try testing.expectEqualStrings(expected, bytes); - try testing.expectError(error.ReadOnlyFilesystem, write(p, path, "")); - } - const node = @intFromEnum(SelfFile.listeners); - var off: usize = 0; - while (off < expected.len) { - const part = rd(p, node, off, 3); - try testing.expectEqual(Status.ok, part.reply.status); - try testing.expectEqualStrings(expected[off..][0..@min(3, expected.len - off)], part.bytes); - off += part.bytes.len; - } - try testing.expectEqual(@as(usize, 0), rd(p, node, off, 3).bytes.len); -} - -test "readdir lists the root, a pane directory, and new/ without creating anything" { - const gpa = testing.allocator; - const p = try withFile(gpa, "hello\n"); - defer p.deinit(); - const serial = serialOf(p); - var buf: [32]Dirent = undefined; - - const root = rdir(p, @intFromEnum(SelfFile.root), 0); - try testing.expectEqual(Status.ok, root.reply.status); - const top = dirents(root.bytes, &buf); - try testing.expect(top.len >= 5); - try testing.expectEqualStrings("index", top[0].name); - try testing.expectEqualStrings("cons", top[1].name); - try testing.expectEqualStrings("new", top[2].name); - try testing.expect(top[2].dir and !top[0].dir); - try testing.expectEqualStrings("pane", top[3].name); - try testing.expect(top[3].dir); - try testing.expectEqual(namespace_panes, top[3].node); - var idbuf: [16]u8 = undefined; - try testing.expect(nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); - try testing.expect(nameAt(top, "src") != null); - - const rest = rdir(p, @intFromEnum(SelfFile.root), 3); - try testing.expectEqual(top.len - 3, dirents(rest.bytes, &buf).len); - const eof = rdir(p, @intFromEnum(SelfFile.root), 99); - try testing.expectEqual(Status.ok, eof.reply.status); - try testing.expectEqual(@as(usize, 0), eof.bytes.len); - - const dir = rdir(p, Node.of(serial, .dir), 0); - const files = dirents(dir.bytes, &buf); - try testing.expectEqual(@as(usize, 10), files.len); - try testing.expect(nameAt(files, "addr") != null); - try testing.expect(nameAt(files, "xdata") != null); - try testing.expect(nameAt(files, ".") == null); - try testing.expectEqual(Node.of(serial, .body), nameAt(files, "body").?.node); - - const before = p.next_serial; - const new = rdir(p, @intFromEnum(SelfFile.new), 0); - try testing.expectEqual(Status.ok, new.reply.status); - const factories = dirents(new.bytes, &buf); - try testing.expectEqual(@as(usize, 11), factories.len); - try testing.expect(nameAt(factories, "README") != null); - for (factories) |entry| { - const inspected = look_up(p, @intFromEnum(SelfFile.new), entry.name); - try testing.expectEqual(Status.ok, inspected.reply.status); - try testing.expectEqual(entry.node, inspected.reply.attr.node); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = entry.node }).reply.status); - } - try testing.expectEqual(before, p.next_serial); - - try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .body), 0).errno()); -} - -test "lookup resolves top files, pane serials and pane files" { - const gpa = testing.allocator; - const p = try withFile(gpa, "hello\n"); - defer p.deinit(); - const serial = serialOf(p); - const root = @intFromEnum(SelfFile.root); - - try testing.expectEqual(@as(u64, @intFromEnum(SelfFile.index)), look_up(p, root, "index").reply.attr.node); - try testing.expect(look_up(p, root, "new").reply.attr.dir); - try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno()); - - var idbuf: [16]u8 = undefined; - const serial_name = try std.fmt.bufPrint(&idbuf, "{d}", .{serial}); - try testing.expectEqual(E.NOENT, look_up(p, root, serial_name).errno()); - const dir = look_up(p, namespace_panes, serial_name); - try testing.expectEqual(Node.of(serial, .dir), dir.reply.attr.node); - try testing.expect(dir.reply.attr.dir); - try testing.expectEqual(E.NOENT, look_up(p, namespace_panes, "99999").errno()); - - const body = look_up(p, Node.of(serial, .dir), "body"); - try testing.expectEqual(Node.of(serial, .body), body.reply.attr.node); - const stat = call(p, .{ .tag = 4, .op = .getattr, .node = Node.of(serial, .body) }); - try testing.expectEqual(body.reply.attr.size, stat.reply.attr.size); - try testing.expectEqual(@as(u64, "hello\n".len), stat.reply.attr.size); - try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .dir), "editout").errno()); - try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .body), "x").errno()); -} - -test "new/ lookup is inert and each open creates a distinct pane" { - const gpa = testing.allocator; - const p = try withFile(gpa, "first\n"); - defer p.deinit(); - const before = serialOf(p); - - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(SelfFile.new), "bogus").errno()); - try testing.expectEqual(before, p.next_serial); - - const a = look_up(p, @intFromEnum(SelfFile.new), "body"); - try testing.expectEqual(Status.ok, a.reply.status); - try testing.expectEqual(before, p.next_serial); - const opened = call(p, .{ .tag = 1, .op = .open, .node = a.reply.attr.node }); - try testing.expectEqual(Status.ok, opened.reply.status); - const made: Node = @bitCast(opened.reply.attr.node); - try testing.expect(made.serial != before); - try testing.expectEqual(@intFromEnum(PaneFile.body), made.file); - - _ = wr(p, opened.reply.attr.node, "hi"); - const second = call(p, .{ .tag = 2, .op = .open, .node = a.reply.attr.node }); - try testing.expectEqual(Status.ok, second.reply.status); - try testing.expect(second.reply.attr.node != opened.reply.attr.node); - const id = p.paneBySerial(@intCast(made.serial)).?; - try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content); -} - -test "index prints winctlprint's five fields then the tag" { - const gpa = testing.allocator; - const p = try withFile(gpa, "hello\nthere\n"); - defer p.deinit(); - const pane = p.panes[0].?; - - const a = rd(p, @intFromEnum(SelfFile.index), 0, 4096); - try testing.expectEqual(Status.ok, a.reply.status); - var got: [512]u8 = undefined; - @memcpy(got[0..a.bytes.len], a.bytes); - const line = got[0..a.bytes.len]; - - const tag = try gpa.dupe(u8, tagOf(p, pane)); - defer gpa.free(tag); - var want: std.ArrayList(u8) = .empty; - defer want.deinit(gpa); - try want.print(gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {s}\n", .{ - pane.serial, tag.len, @as(usize, "hello\nthere\n".len), 0, 0, firstLine(tag), - }); - try testing.expectEqualStrings(want.items, line); - try testing.expectEqual(@as(usize, 60), std.mem.indexOf(u8, line, firstLine(tag)).?); - - const mid = rd(p, @intFromEnum(SelfFile.index), 60, 5); - try testing.expectEqualStrings(firstLine(tag)[0..5], mid.bytes); - - pane.file.?.saved_revision = pane.file.?.revision -% 1; - const dirty = rd(p, @intFromEnum(SelfFile.index), 48, 12); - try testing.expectEqualStrings(" 1 ", dirty.bytes); -} - -test "ctl read is index's five fields plus width in cells, font and tab width" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const pane = p.panes[0].?; - - const a = rd(p, Node.of(pane.serial, .ctl), 0, 4096); - try testing.expectEqual(Status.ok, a.reply.status); - var want: std.ArrayList(u8) = .empty; - defer want.deinit(gpa); - try want.print(gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {s} {d:>11} ", .{ - pane.serial, tagOf(p, pane).len, @as(usize, 2), 0, 0, pane.cols, "default", config.tab_width, - }); - try testing.expectEqualStrings(want.items, a.bytes); - - var quoted: std.ArrayList(u8) = .empty; - defer quoted.deinit(gpa); - stageQuoted("ed, gpa, "DejaVu Sans Mono"); - try testing.expectEqualStrings("'DejaVu Sans Mono'", quoted.items); - quoted.clearRetainingCapacity(); - stageQuoted("ed, gpa, "it's"); - try testing.expectEqualStrings("'it''s'", quoted.items); -} - -test "body reads at any offset and writes append" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const body = Node.of(serial, .body); - - try testing.expectEqualStrings("one\ntwo\n", rd(p, body, 0, 100).bytes); - try testing.expectEqualStrings("two\n", rd(p, body, 4, 100).bytes); - try testing.expectEqualStrings("wo", rd(p, body, 5, 2).bytes); - try testing.expectEqualStrings("", rd(p, body, 999, 2).bytes); - try testing.expect(rd(p, body, 0, 100).bytes.ptr == p.panes[0].?.file.?.content.ptr); - - const w = call(p, .{ .tag = 5, .op = .write, .node = body, .off = 0, .data = "three\n" }); - try testing.expectEqual(@as(u32, 6), w.reply.written); - try testing.expectEqualStrings("one\ntwo\nthree\n", p.panes[0].?.file.?.content); - - const short = wr(p, body, "a\xC3"); - try testing.expectEqual(@as(u32, 1), short.reply.written); - try testing.expectEqualStrings("one\ntwo\nthree\na", p.panes[0].?.file.?.content); -} - -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 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.isTerminal()); - - const a = wr(p, Node.of(pane.serial, .body), "ls -l\r"); - try testing.expectEqual(@as(u32, 6), a.reply.written); - try testing.expectEqualStrings("ls -l\r", a.pty()); - - const r = rd(p, Node.of(pane.serial, .body), 0, 64); - try testing.expectEqual(Status.ok, r.reply.status); -} - -test "tag reads the whole tag and writes append to the editable tail" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const pane = p.panes[0].?; - const node = Node.of(pane.serial, .tag); - - const whole = rd(p, node, 0, 4096); - try testing.expect(std.mem.startsWith(u8, whole.bytes, "/test.txt")); - try testing.expect(std.mem.indexOf(u8, whole.bytes, "Del") != null); - - const before = rd(p, node, 0, 4096).bytes.len; - const w = wr(p, node, " Mine"); - try testing.expectEqual(@as(u32, 5), w.reply.written); - try testing.expect(std.mem.endsWith(u8, pane.tag_tail[0..pane.tag_tail_len], " Mine")); - const after = rd(p, node, 0, 4096); - try testing.expectEqual(before + 5, after.bytes.len); - try testing.expect(std.mem.endsWith(u8, after.bytes, " Mine")); - - pane.tag_tail_len = pane.tag_tail.len; - try testing.expectEqual(E.NOSPC, wr(p, node, "x").errno()); -} - -test "the address language, form by form" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\nthree\n"); - defer p.deinit(); - const serial = serialOf(p); - const addr = Node.of(serial, .addr); - - const Case = struct { expr: []const u8, q0: u32, q1: u32 }; - for ([_]Case{ - .{ .expr = "#0", .q0 = 0, .q1 = 0 }, - .{ .expr = "#5", .q0 = 5, .q1 = 5 }, - .{ .expr = "0", .q0 = 0, .q1 = 0 }, - .{ .expr = "1", .q0 = 0, .q1 = 4 }, - .{ .expr = "2", .q0 = 4, .q1 = 8 }, - .{ .expr = "$", .q0 = 14, .q1 = 14 }, - .{ .expr = ",", .q0 = 0, .q1 = 14 }, - .{ .expr = "1,2", .q0 = 0, .q1 = 8 }, - .{ .expr = "#1,#4", .q0 = 1, .q1 = 4 }, - .{ .expr = "2+1", .q0 = 8, .q1 = 14 }, - .{ .expr = "$-1", .q0 = 8, .q1 = 14 }, - .{ .expr = "/two/", .q0 = 4, .q1 = 7 }, - .{ .expr = "/t.o/", .q0 = 4, .q1 = 7 }, - .{ .expr = "1\n", .q0 = 0, .q1 = 4 }, - }) |c| { - _ = wr(p, addr, "#0"); - const w = wr(p, addr, c.expr); - try testing.expectEqual(Status.ok, w.reply.status); - const got = rd(p, addr, 0, 64); - var want: [32]u8 = undefined; - try testing.expectEqualStrings( - try std.fmt.bufPrint(&want, "{d:>11} {d:>11} ", .{ c.q0, c.q1 }), - got.bytes, - ); - } - - _ = wr(p, addr, "1"); - _ = wr(p, addr, "."); - try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 4), p.fs.panes[0].addr.q1); - - _ = wr(p, addr, "$"); - _ = wr(p, addr, "?o?"); - try testing.expectEqual(@as(u32, 6), p.fs.panes[0].addr.q0); // the `o` in "two" - try testing.expectEqual(@as(u32, 7), p.fs.panes[0].addr.q1); - - _ = wr(p, addr, "1"); - _ = wr(p, Node.of(serial, .ctl), "limit=addr\n"); - _ = wr(p, addr, "#0"); - try testing.expectEqual(E.INVAL, wr(p, addr, "/three/").errno()); - _ = wr(p, Node.of(serial, .ctl), "clean\n"); - _ = call(p, .{ .tag = 6, .op = .open, .node = Node.of(serial, .ctl) }); - try testing.expect(p.fs.panes[0].limit == null); - _ = wr(p, addr, "#0"); - try testing.expectEqual(Status.ok, wr(p, addr, "/three/").reply.status); - - for ([_][]const u8{ "zzz", "#", "//", "/nomatch/", "1 2", "99", "/a\\" }) |bad| { - _ = wr(p, addr, "#0"); - try testing.expectEqual(E.INVAL, wr(p, addr, bad).errno()); - } - - const nested = "," ** 4096; - _ = wr(p, addr, "#0"); - try testing.expectEqual(E.INVAL, wr(p, addr, nested).errno()); -} - -test "data and xdata read from addr, move it, and write through it" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const addr = Node.of(serial, .addr); - const data = Node.of(serial, .data); - const xdata = Node.of(serial, .xdata); - - _ = wr(p, addr, "#0"); - try testing.expectEqualStrings("one", rd(p, data, 0, 3).bytes); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); - - _ = wr(p, addr, "1"); - try testing.expectEqualStrings("one\n", rd(p, xdata, 0, 100).bytes); - _ = wr(p, addr, "1"); - try testing.expectEqualStrings("one\ntwo\n", rd(p, data, 0, 100).bytes); - - _ = wr(p, addr, "1"); - const w = wr(p, data, "ONE\n"); - try testing.expectEqual(@as(u32, 4), w.reply.written); - try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); - try testing.expectEqual(@as(u32, 4), p.fs.panes[0].addr.q0); -} - -test "data never splits a grapheme, in either direction" { - const gpa = testing.allocator; - const p = try withFile(gpa, "\u{00e9}x\n"); - defer p.deinit(); - const serial = serialOf(p); - _ = wr(p, Node.of(serial, .addr), "#0"); - try testing.expectEqualStrings("", rd(p, Node.of(serial, .data), 0, 1).bytes); - _ = wr(p, Node.of(serial, .addr), "#0"); - try testing.expectEqualStrings("\u{00e9}", rd(p, Node.of(serial, .data), 0, 2).bytes); - - _ = wr(p, Node.of(serial, .addr), "#0"); - try testing.expectEqual(@as(u32, 1), wr(p, Node.of(serial, .data), "a\xC3").reply.written); -} - -test "rdsel reads the selection and wrsel replaces it" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const ctl = Node.of(serial, .ctl); - - _ = wr(p, Node.of(serial, .addr), "#0,#3"); - try testing.expectEqual(Status.ok, wr(p, ctl, "dot=addr\n").reply.status); - try testing.expectEqualStrings("one", rd(p, Node.of(serial, .rdsel), 0, 100).bytes); - - _ = wr(p, ctl, "addr=dot\n"); - try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); - - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .wrsel), "ONE").reply.status); - try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); - _ = wr(p, Node.of(serial, .wrsel), "!"); - try testing.expectEqualStrings("ONE!\ntwo\n", p.panes[0].?.file.?.content); -} - -test "every ctl verb, and every refusal" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - const ctl = Node.of(serial, .ctl); - const pane = p.panes[0].?; - const pf = &p.fs.panes[0]; - - try testing.expectEqual(Status.ok, wr(p, ctl, "nomark\nnoscroll\ndirty\n").reply.status); - try testing.expect(pf.nomark and pf.noscroll and dirtyOf(pane)); - try testing.expectEqual(Status.ok, wr(p, ctl, "mark\nscroll\nclean\n").reply.status); - try testing.expect(!pf.nomark and !pf.noscroll and !dirtyOf(pane)); - - _ = wr(p, ctl, "cleartag\n"); - try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); - - _ = wr(p, Node.of(serial, .addr), "2"); - _ = wr(p, ctl, "limit=addr\n"); - try testing.expectEqual(@as(u32, 4), pf.limit.?.q0); - _ = wr(p, ctl, "dot=addr\nshow\n"); - try testing.expectEqual(@as(i32, 1), pane.cur_row); - - try testing.expectEqual(Status.ok, wr(p, ctl, "name /tmp/renamed.txt\n").reply.status); - try testing.expectEqualStrings("/tmp/renamed.txt", pane.file.?.path); - try testing.expectEqual(E.INVAL, wr(p, ctl, "name two words\n").errno()); - try testing.expectEqual(E.INVAL, wr(p, ctl, "name\n").errno()); - try testing.expectEqualStrings("/tmp/renamed.txt", pane.file.?.path); - - try testing.expectEqual(Status.ok, wr(p, ctl, "put\n").reply.status); - try testing.expectEqualStrings(pane.file.?.content, p.fallback.get("/tmp/renamed.txt").?); - - for ([_][]const u8{ - "menu", "nomenu", "dump echo hi", "dumpdir /tmp", "font Go Mono", "lock", "unlock", "bogus", "DEL", - }) |bad| try testing.expectEqual(E.INVAL, wr(p, ctl, bad).errno()); - - try testing.expect(!dirtyOf(pane)); - try testing.expectEqual(E.INVAL, wr(p, ctl, "dirty\nbogus\n").errno()); - try testing.expect(!dirtyOf(pane)); -} - -test "ctl look opens spaced paths and locations without editing the source pane" { - if (!platform_has_fs) return error.SkipZigTest; - const gpa = testing.allocator; - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "two words.zig", .data = "first\nsecond\nthird\n" }); - var path_buf: [4096]u8 = undefined; - const path = path_buf[0..try tmp.dir.realPathFile(testing.io, "two words.zig", &path_buf)]; - const p = try withFile(gpa, "source stays intact\n"); - defer p.deinit(); - const source = p.panes[0].?; - const ctl = Node.of(source.serial, .ctl); - const revision = source.file.?.revision; - const undo_len = source.file.?.history.undo_len; - source.cur_col = 3; - var command: [4200]u8 = undefined; - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&command, "look {s}:2:3\n", .{path})).reply.status); - const opened = p.panes[p.active].?; - try testing.expect(opened != source); - try testing.expectEqualStrings(path, opened.file.?.path); - try testing.expectEqualStrings("first\nsecond\nthird\n", opened.file.?.content); - try testing.expectEqual(@as(i32, 1), opened.cur_row); - try testing.expectEqual(@as(i32, 2), opened.cur_col); - try testing.expectEqualStrings("source stays intact\n", source.file.?.content); - try testing.expectEqual(revision, source.file.?.revision); - try testing.expectEqual(undo_len, source.file.?.history.undo_len); - try testing.expectEqual(@as(i32, 3), source.cur_col); - - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&command, "look {s}:3:2\n", .{path})).reply.status); - try testing.expect(p.panes[p.active].? == opened); - try testing.expectEqual(@as(i32, 2), opened.cur_row); - try testing.expectEqual(@as(i32, 1), opened.cur_col); -} - -test "ctl look validates the whole batch before opening virtual files" { - const gpa = testing.allocator; - const p = try withFile(gpa, "source\n"); - defer p.deinit(); - const source = p.panes[0].?; - const ctl = Node.of(source.serial, .ctl); - const serial = p.next_serial; - for ([_][]const u8{ - "look", "look \t", "look /virtual/index\x00ignored", "look /virtual/index\nbogus\n", - }) |invalid| { - try testing.expectEqual(E.INVAL, wr(p, ctl, invalid).errno()); - try testing.expectEqual(serial, p.next_serial); - try testing.expectEqual(@as(usize, 0), p.active); - try testing.expectEqualStrings("source\n", source.file.?.content); - } - try testing.expectEqual(Status.ok, wr(p, ctl, "look /n/self/index\n").reply.status); - const opened = p.panes[p.active].?; - try testing.expectEqualStrings("/virtual/index", opened.file.?.path); - try testing.expect(std.mem.indexOf(u8, opened.file.?.content, "/test.txt") != null); - try testing.expectEqualStrings("source\n", source.file.?.content); -} - -test "ctl name promotes a scratch without changing its body or undo history" { - const gpa = testing.allocator; - const p = try withFile(gpa, "opener\n"); - defer p.deinit(); - _ = call(p, .{ .tag = 1, .op = .open, .node = factory_base + @intFromEnum(PaneFile.ctl) }); - const pane = p.panes[p.active].?; - const ctl = Node.of(pane.serial, .ctl); - const body = Node.of(pane.serial, .body); - _ = wr(p, body, "scratch "); - _ = wr(p, body, "work\n"); - const undo_len = pane.file.?.history.undo_len; - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "renamed.zig", .data = "existing target\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; - var path_buffer: [4096]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buffer, "{s}/renamed.zig", .{directory}); - var command: [4104]u8 = undefined; - const renamed = wr(p, ctl, try std.fmt.bufPrint(&command, "name {s}\n", .{path})); - try testing.expectEqual(Status.ok, renamed.reply.status); - try testing.expectEqual(false, renamed.watch.?); - try testing.expectEqualStrings("scratch work\n", pane.file.?.content); - try testing.expectEqual(undo_len, pane.file.?.history.undo_len); - try testing.expect(pane.file.?.output == null and dirtyOf(pane)); - try testing.expect(pane.file.?.watch_after_save); - const target = try readFile(gpa, path); - defer gpa.free(target); - try testing.expectEqualStrings("existing target\n", target); - const saved = wr(p, ctl, "put\n"); - try testing.expectEqual(Status.ok, saved.reply.status); - try testing.expectEqual(true, saved.watch.?); - try testing.expect(!dirtyOf(pane) and !pane.file.?.watch_after_save); - try testing.expectEqualStrings("scratch work\n", p.fallback.get(path).?); -} - -test "ctl name refreshes cached syntax for unchanged contents" { - if (!pardes.syntax.enabled) return error.SkipZigTest; - pardes.syntax.start(testing.allocator); - defer pardes.syntax.stop(); - const p = try withFile(testing.allocator, "fn check() void {}\n"); - defer p.deinit(); - const pane = p.panes[0].?; - panes.File.refreshHighlights(p); - try testing.expectEqual(@as(usize, 0), pane.file.?.highlights.len); - try testing.expectEqual(Status.ok, wr(p, Node.of(pane.serial, .ctl), "name renamed.zig\n").reply.status); - panes.File.refreshHighlights(p); - try testing.expect(pane.file.?.highlights.len >= 2); - try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]); - try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]); - try testing.expectEqualStrings("fn check() void {}\n", pane.file.?.content); -} - -test "ctl relative names use the file directory and can name a new target" { - const gpa = testing.allocator; - const p = try withFile(gpa, "retained body\n"); - defer p.deinit(); - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "note.txt", .data = "from pane directory\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; - const pane = p.panes[0].?; - const ctl = Node.of(pane.serial, .ctl); - var command: [4140]u8 = undefined; - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&command, "name {s}/old.txt\n", .{directory})).reply.status); - try testing.expectEqual(Status.ok, wr(p, ctl, "name child/../note.txt\nget\n").reply.status); - try testing.expectEqualStrings("from pane directory\n", pane.file.?.content); - try testing.expectEqualStrings(directory, Pardes.paneDir(pane)); - try testing.expectEqual(Status.ok, wr(p, ctl, "name ./created.txt\nput\n").reply.status); - try testing.expect(!dirtyOf(pane)); - var expected_buf: [4096]u8 = undefined; - const expected = try std.fmt.bufPrint(&expected_buf, "{s}/created.txt", .{directory}); - try testing.expectEqualStrings(expected, pane.file.?.path); - try testing.expectEqualStrings(pane.file.?.content, p.fallback.get(expected).?); -} - -test "ctl relative names follow inherited scratch and virtual directories" { - const p = try withFile(testing.allocator, "source body\n"); - defer p.deinit(); - const source = p.panes[0].?; - try testing.expectEqual(Status.ok, wr(p, Node.of(source.serial, .ctl), "name /project/src/source.zig\n").reply.status); - _ = call(p, .{ .tag = 1, .op = .open, .node = factory_base + @intFromEnum(PaneFile.ctl) }); - const scratch = p.panes[p.active].?; - const ctl = Node.of(scratch.serial, .ctl); - try testing.expectEqualStrings("/project/src", Pardes.paneDir(scratch)); - try testing.expectEqual(Status.ok, wr(p, ctl, "name ../out/./notes.txt\n").reply.status); - try testing.expectEqualStrings("/project/out/notes.txt", scratch.file.?.path); - try testing.expectEqualStrings("/project/out", Pardes.paneDir(scratch)); - var command: [256]u8 = undefined; - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&command, "name /virtual/pane/{d}/./body\nget\n", .{source.serial})).reply.status); - try testing.expectEqualStrings(source.file.?.content, scratch.file.?.content); - const unchanged = wr(p, ctl, "name ./body\n"); - try testing.expectEqual(Status.ok, unchanged.reply.status); - try testing.expect(unchanged.watch == null); - try testing.expect(!dirtyOf(scratch)); - try testing.expect(!scratch.file.?.watch_after_save); -} - -test "ctl get reloads the pane from disk and del honours a dirty body" { - const gpa = testing.allocator; - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "note.txt", .data = "from disk\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; - var path_buf: [4096]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/note.txt", .{directory}); - - const p = try withFile(gpa, "in memory\n"); - defer p.deinit(); - const serial = serialOf(p); - const ctl = Node.of(serial, .ctl); - const pane = p.panes[0].?; - - var name: [std.fs.max_path_bytes + 8]u8 = undefined; - _ = wr(p, ctl, try std.fmt.bufPrint(&name, "name {s}\n", .{path})); - try testing.expectEqual(Status.ok, wr(p, ctl, "get\n").reply.status); - try testing.expectEqualStrings("from disk\n", pane.file.?.content); - try testing.expect(!dirtyOf(pane)); - try testing.expect(pane.file.?.history.undo_len > 0); - - _ = wr(p, ctl, "dirty\n"); - try testing.expectEqual(E.INVAL, wr(p, ctl, "del\n").errno()); - try testing.expect(p.paneBySerial(serial) != null); - _ = call(p, .{ .tag = 1, .op = .open, .node = factory_base + @intFromEnum(PaneFile.body) }); - try testing.expectEqual(Status.ok, wr(p, ctl, "delete\n").reply.status); - try testing.expect(p.paneBySerial(serial) == null); -} - -test "ctl get reports missing files without losing dirty contents or applying del" { - const p = try withFile(testing.allocator, "unsaved contents\n"); - defer p.deinit(); - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(testing.io, &directory_buf)]; - var name: [4140]u8 = undefined; - const ctl = Node.of(serialOf(p), .ctl); - try testing.expectEqual(Status.ok, wr(p, ctl, try std.fmt.bufPrint(&name, "name {s}/missing.txt\ndirty\n", .{directory})).reply.status); - try testing.expectEqual(E.NOENT, wr(p, ctl, "get\ndel\n").errno()); - const pane = p.panes[0].?; - try testing.expectEqualStrings("unsaved contents\n", pane.file.?.content); - try testing.expect(dirtyOf(pane)); -} - -test "ctl put waits for one host write and stops before del when saving fails" { - const Refusing = struct { - p: *Pardes, - calls: usize = 0, - - fn writeFile(ctx: ?*anyopaque, id: u8, _: []const u8, _: []const u8) void { - const self: *@This() = @ptrCast(@alignCast(ctx.?)); - self.calls += 1; - self.p.saveFailed(id, "save", error.PermissionDenied); - } - }; - const p = try withFile(testing.allocator, "retained contents\n"); - defer p.deinit(); - var refusing: Refusing = .{ .p = p }; - p.host = .{ .ctx = &refusing, .vtable = &.{ .write_file = Refusing.writeFile } }; - const serial = serialOf(p); - const ctl = Node.of(serial, .ctl); - for ([_][]const u8{ "clean\n", "dirty\n" }, 0..) |initial, i| { - _ = wr(p, ctl, initial); - const result = wr(p, ctl, "put\ndel\n"); - try testing.expectEqual(E.IO, result.errno()); - try testing.expect(!result.saved); - try testing.expectEqual(i + 1, refusing.calls); - const pane = p.panes[p.paneBySerial(serial).?].?; - try testing.expect(dirtyOf(pane)); - try testing.expectEqualStrings("retained contents\n", pane.file.?.content); - } -} - -test "self directories walk to their namespace parents" { - const p = try withFile(testing.allocator, "contents\n"); - defer p.deinit(); - const root = @intFromEnum(SelfFile.root); - for ([_]struct { node: u64, parent: u64 }{ - .{ .node = root, .parent = namespace_root }, - .{ .node = @intFromEnum(SelfFile.new), .parent = root }, - .{ .node = namespace_panes, .parent = root }, - .{ .node = Node.of(serialOf(p), .dir), .parent = namespace_panes }, - }) |case| { - const result = look_up(p, case.node, ".."); - try testing.expectEqual(Status.ok, result.reply.status); - try testing.expectEqual(case.parent, result.reply.attr.node); - } -} - -test "errors and cons append to one +Errors buffer per directory" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const serial = serialOf(p); - - const live = for (p.panes) |slot| { - if (slot) |q| if (q.file) |f| if (f.output) |o| if (std.meta.activeTag(o.from) == .errors) break q; - } else null; - try testing.expect(live == null); - - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .errors), "boom\n").reply.status); - _ = wr(p, @intFromEnum(SelfFile.cons), "again\n"); - - var found: usize = 0; - for (p.panes) |slot| { - const q = slot orelse continue; - const f = q.file orelse continue; - const o = f.output orelse continue; - if (std.meta.activeTag(o.from) != .errors) continue; - found += 1; - try testing.expectEqualStrings("boom\nagain\n", f.content); - try testing.expectEqualStrings("/+Errors", f.path); - } - try testing.expectEqual(@as(usize, 1), found); -} - -test "setattr truncation empties the body and answers fresh attributes" { - const gpa = testing.allocator; - const p = try withFile(gpa, "one\ntwo\n"); - defer p.deinit(); - const serial = serialOf(p); - - const a = call(p, .{ .tag = 7, .op = .setattr, .node = Node.of(serial, .body), .truncate = true }); - try testing.expectEqual(Status.ok, a.reply.status); - try testing.expectEqual(@as(u64, 0), a.reply.attr.size); - try testing.expectEqualStrings("", p.panes[0].?.file.?.content); - - _ = wr(p, Node.of(serial, .body), "new text\n"); - try testing.expectEqualStrings("new text\n", p.panes[0].?.file.?.content); - - const noop = call(p, .{ .tag = 8, .op = .setattr, .node = Node.of(serial, .body) }); - try testing.expectEqual(@as(u64, 9), noop.reply.attr.size); -} - -test "event records are acme's bytes, one per read, and .again when empty" { - const gpa = testing.allocator; - const p = try withFile(gpa, "Msg fs-ran\n"); - defer p.deinit(); - const serial = serialOf(p); - const event = Node.of(serial, .event); - - _ = noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "sg "); - try testing.expect(p.fs.panes[0].events.empty()); - - const h = call(p, .{ .tag = 10, .op = .open, .node = event }); - try testing.expect(h.reply.handle != 0); - try testing.expectEqual(@as(u16, 1), p.fs.listeners); - - try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); - - p.fs.origin = 'M'; - _ = noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "ell"); - _ = noteAction(p, 0, .body_delete, 0, 3, 0, ""); - try testing.expectEqualStrings("MX1 4 1 3 ell\n", rd(p, event, 0, 4096).bytes); - try testing.expectEqualStrings("MD0 3 0 0 \n", rd(p, event, 0, 4096).bytes); - try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); - - _ = noteAction(p, 0, .body_look, 0, 3, flag_filename, "one"); - try testing.expectEqual(E.INVAL, rd(p, event, 0, 4).errno()); - try testing.expectEqualStrings("ML0 3 4 3 one\n", rd(p, event, 0, 4096).bytes); - - const big = "z" ** max_record_text; - _ = noteAction(p, 0, .body_exec, 0, max_record_text, 0, big); - try testing.expectEqualStrings("MX0 256 0 0 \n", rd(p, event, 0, 4096).bytes); - - _ = call(p, .{ .tag = 11, .op = .release, .node = event, .handle = h.reply.handle }); - 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"); - defer p.deinit(); - const serial = serialOf(p); - const event = Node.of(serial, .event); - _ = call(p, .{ .tag = 40, .op = .open, .node = event }); - var store: [4096]u8 = undefined; - var slots: [16][]const u8 = undefined; - _ = drainEvents(p, event, &store, &slots); - - _ = wr(p, Node.of(serial, .body), "three\n"); - const body_recs = drainEvents(p, event, &store, &slots); - try testing.expect(body_recs.len >= 1); - try testing.expectEqualStrings("EI8 14 0 6 three\n\n", body_recs[0]); - for (body_recs[1..]) |r| { - try testing.expectEqual(@as(u8, 'E'), r[0]); - try testing.expect(Action.fromChar(r[1]).?.onTag()); - } - - _ = wr(p, Node.of(serial, .addr), "1"); - _ = wr(p, Node.of(serial, .data), "ONE\n"); - const data_recs = drainEvents(p, event, &store, &slots); - try testing.expectEqual(@as(usize, 2), data_recs.len); - try testing.expectEqualStrings("FD0 3 0 0 \n", data_recs[0]); - try testing.expectEqualStrings("FI0 3 0 3 ONE\n", data_recs[1]); - try testing.expectEqual(Status.again, rd(p, event, 0, 4096).reply.status); -} - -test "two event readers each count once, and the second closing leaves the first" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const event = Node.of(serialOf(p), .event); - - _ = call(p, .{ .tag = 12, .op = .open, .node = event }); - _ = call(p, .{ .tag = 13, .op = .open, .node = event }); - try testing.expectEqual(@as(u16, 2), p.fs.panes[0].readers); - try testing.expectEqual(@as(u16, 2), p.fs.listeners); - - _ = call(p, .{ .tag = 14, .op = .release, .node = event }); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].readers); - try testing.expect(p.fs.scripted(0)); - - _ = call(p, .{ .tag = 15, .op = .release, .node = Node.of(serialOf(p), .body) }); - try testing.expectEqual(@as(u16, 1), p.fs.listeners); - - _ = call(p, .{ .tag = 16, .op = .release, .node = event }); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); - try testing.expect(!p.fs.scripted(0)); - _ = call(p, .{ .tag = 17, .op = .release, .node = event }); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); -} - -test "a pane deleted while its event file is open leaves no suppression behind" { - const gpa = testing.allocator; - const p = try withFile(gpa, "x\n"); - defer p.deinit(); - const serial = serialOf(p); - const event = Node.of(serial, .event); - _ = call(p, .{ .tag = 1, .op = .open, .node = factory_base + @intFromEnum(PaneFile.body) }); - - const a = call(p, .{ .tag = 18, .op = .open, .node = event }); - const b = call(p, .{ .tag = 19, .op = .open, .node = event }); - try testing.expectEqual(@as(u16, 2), p.fs.listeners); - - _ = wr(p, Node.of(serial, .ctl), "delete\n"); - try testing.expect(p.paneBySerial(serial) == null); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); - - _ = call(p, .{ .tag = 20, .op = .release, .node = event, .handle = a.reply.handle }); - _ = call(p, .{ .tag = 21, .op = .release, .node = event, .handle = b.reply.handle }); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); - - try testing.expectEqual(E.NOENT, rd(p, event, 0, 64).errno()); - try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .body), 0, 64).errno()); - try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .ctl), "clean\n").errno()); - try testing.expectEqual(E.NOENT, call(p, .{ .tag = 22, .op = .open, .node = event }).errno()); -} - -test "writing an event record back performs the action it names" { - const gpa = testing.allocator; - const p = try withFile(gpa, "Msg fs-ran\n"); - defer p.deinit(); - const serial = serialOf(p); - const event = Node.of(serial, .event); - const pane = p.panes[0].?; - - const w = wr(p, event, "FX0 10\n"); - try testing.expectEqual(Status.ok, w.reply.status); - try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]); - - pane.msg_len = 0; - try testing.expectEqual(Status.ok, wr(p, event, "FX0 10\nFX0 10\n").reply.status); - try testing.expectEqualStrings("fs-ran", pane.msg[0..pane.msg_len]); - - pane.msg_len = 0; - for ([_][]const u8{ - "FX0 10\nFQ0 1\n", // unknown type character - "FX0 999\n", // out of range - "FX0 10", // no newline - "FX5 1\n", // q0 > q1 - "FD0 3\n", // a report, not a request - "F\n", - }) |bad| { - try testing.expectEqual(E.INVAL, wr(p, event, bad).errno()); - try testing.expectEqual(@as(usize, 0), pane.msg_len); - } - - _ = call(p, .{ .tag = 23, .op = .open, .node = event }); - p.fs.origin = 'K'; - _ = wr(p, event, "KX0 10\n"); - try testing.expectEqual(@as(u8, 'F'), p.fs.origin); -} - -test "a pane that is not a terminal has no pty/ at all" { - const gpa = testing.allocator; - const p = try withFile(gpa, "hello\n"); - defer p.deinit(); - const serial = serialOf(p); - const dir = Node.of(serial, .dir); - - try testing.expectEqual(E.NOENT, look_up(p, dir, "pty").errno()); - try testing.expectEqual(E.NOENT, call(p, .{ - .tag = 1, - .op = .getattr, - .node = Node.of(serial, .pty), - }).errno()); - try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .pty_status), 0, 256).errno()); - try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .pty_ctl), "winsize 80 24\n").errno()); - try testing.expectEqual(E.NOENT, rdir(p, Node.of(serial, .pty), 0).errno()); - try testing.expectEqual(E.NOENT, call(p, .{ - .tag = 2, - .op = .open, - .node = Node.of(serial, .pty_data), - }).errno()); - try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); - - var buf: [32]Dirent = undefined; - const files = dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 10), files.len); - try testing.expect(nameAt(files, "pty") == null); - - try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno()); - try testing.expectEqual(E.NOENT, look_up(p, dir, "status").errno()); - - const before = p.next_serial; - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(SelfFile.new), "pty").errno()); - try testing.expectEqual(before, p.next_serial); -} - -test "a terminal pane's pty/ holds exactly ctl, status and data" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const serial = serialOf(p); - const dir = Node.of(serial, .dir); - - const pty = look_up(p, dir, "pty"); - try testing.expectEqual(Node.of(serial, .pty), pty.reply.attr.node); - try testing.expect(pty.reply.attr.dir); - try testing.expectEqual(@as(u16, 0o500), pty.reply.attr.mode); - - var buf: [32]Dirent = undefined; - const files = dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 11), files.len); - try testing.expect(nameAt(files, "pty").?.dir); - - const inside = dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf); - try testing.expectEqual(@as(usize, 3), inside.len); - try testing.expectEqualStrings("ctl", inside[0].name); - try testing.expectEqualStrings("status", inside[1].name); - try testing.expectEqualStrings("data", inside[2].name); - for (inside) |d| try testing.expect(!d.dir); - try testing.expectEqual(Node.of(serial, .pty_data), inside[2].node); - - const ctl = look_up(p, Node.of(serial, .pty), "ctl"); - try testing.expectEqual(Node.of(serial, .pty_ctl), ctl.reply.attr.node); - try testing.expectEqual(@as(u16, 0o200), ctl.reply.attr.mode); - try testing.expectEqual(@as(u16, 0o400), look_up(p, Node.of(serial, .pty), "status").reply.attr.mode); - try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "body").errno()); - try testing.expectEqual(E.NOENT, look_up(p, Node.of(serial, .pty), "pty").errno()); - - try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .pty_ctl), "x").errno()); - try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .pty_ctl), 0).errno()); - try testing.expectEqual(E.PERM, rd(p, Node.of(serial, .pty), 0, 16).errno()); - try testing.expectEqual(E.PERM, rd(p, Node.of(serial, .pty_ctl), 0, 16).errno()); - try testing.expectEqual(E.PERM, wr(p, Node.of(serial, .pty_status), "x").errno()); -} - -test "every pty/ctl verb, and every refusal" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const ctl = Node.of(serialOf(p), .pty_ctl); - - const pane = p.panes[0].?; - const cols = pane.cols; - const rows = pane.rows; - const ws = wr(p, ctl, "winsize 132 44\n"); - try testing.expectEqual(@as(u32, "winsize 132 44\n".len), ws.reply.written); - try testing.expectEqual(@as(u16, 132), ws.winsize.?.cols); - try testing.expectEqual(@as(u16, 44), ws.winsize.?.rows); - try testing.expectEqual(cols, pane.cols); - try testing.expectEqual(rows, pane.rows); - - for ([_]struct { line: []const u8, want: pardes.PtySignal }{ - .{ .line = "sig INT", .want = .int }, - .{ .line = "sig TERM", .want = .term }, - .{ .line = "sig HUP", .want = .hup }, - .{ .line = "sig QUIT", .want = .quit }, - .{ .line = "sig KILL", .want = .kill }, - }) |c| { - const a = wr(p, ctl, c.line); - try testing.expectEqual(Status.ok, a.reply.status); - try testing.expectEqual(c.want, a.signal.?); - } - - const ex = wr(p, ctl, "exec\n"); - try testing.expectEqual(Status.ok, ex.reply.status); - try testing.expect(ex.spawned); - - const both = wr(p, ctl, "winsize 100 30\nsig TERM"); - try testing.expectEqual(@as(u16, 100), both.winsize.?.cols); - try testing.expectEqual(pardes.PtySignal.term, both.signal.?); - - for ([_][]const u8{ - "winsize", // no arguments - "winsize 80", // one argument - "winsize 80 24 extra", // three - "winsize 0 24", // zero is "unknown", never a width - "winsize 80 0", - "winsize -1 24", // not a decimal - "winsize 999999 24", // wider than a u16 - "sig", // no name - "sig INT TERM", // two - "sig SIGINT", - "sig int", // lower case - "sig 9", // a number is one platform's number - "sig USR1", // a real signal, deliberately not offered - "exec /bin/sh", // the effect carries no argv; refused, never ignored - "raw", - "cooked", - "winsize 80 24\nbogus", // a good verb beside a bad one - "bogus\nwinsize 80 24", - "name x", // a `ctl` verb; the two files share no vocabulary - "del", - }) |bad| { - const a = wr(p, ctl, bad); - try testing.expectEqual(E.INVAL, a.errno()); - try testing.expect(a.winsize == null); - try testing.expect(a.signal == null); - try testing.expect(!a.spawned); - } - - const spaced = wr(p, ctl, "\n winsize 90 20 \n\n"); - try testing.expectEqual(Status.ok, spaced.reply.status); - try testing.expectEqual(@as(u16, 90), spaced.winsize.?.cols); - try testing.expectEqual(Status.ok, wr(p, ctl, "").reply.status); -} - -const FakeTty = struct { - taken: bool, - - const vtable: pardes.Host.VTable = .{ .tty_taken = answer }; - - fn answer(ctx: ?*anyopaque, pane: u8) bool { - _ = pane; - const f: *FakeTty = @ptrCast(@alignCast(ctx.?)); - return f.taken; - } -}; - -test "owned cwd pty exec rejects long paths before applying its batch" { - const p = try withTerm(testing.allocator); - defer p.deinit(); - const pane = p.panes[0].?; - const ctl = Node.of(pane.serial, .pty_ctl); - var path: [1025]u8 = @splat('d'); - path[0] = '/'; - p.setCwd(0, &path); - for ([_][]const u8{ "exec\n", "winsize 100 30\nexec\n", "sig TERM\nexec\n" }) |command| { - const result = wr(p, ctl, command); - try testing.expectEqual(E.INVAL, result.errno()); - try testing.expect(!result.spawned); - try testing.expect(result.signal == null and result.winsize == null); - } - try testing.expectEqualStrings(&path, pane.cwdSlice()); - p.setCwd(0, path[0..pardes.effect_path_cap]); - const accepted = wr(p, ctl, "exec\n"); - try testing.expectEqual(Status.ok, accepted.reply.status); - try testing.expect(accepted.spawned); -} - -test "owned cwd name promotion releases the former directory" { - const p = try withTerm(testing.allocator); - defer p.deinit(); - p.newScratchBelow(0); - const id = p.active; - const pane = p.panes[id].?; - try pane.setOwnedCwd("/old/directory"); - const result = wr(p, Node.of(pane.serial, .ctl), "name saved.txt\n"); - try testing.expectEqual(Status.ok, result.reply.status); - try testing.expect(pane.cwd == .none); - try testing.expect(pane.file.?.output == null); - try testing.expectEqualStrings("/old/directory/saved.txt", pane.file.?.path); - try testing.expectEqualStrings("/old/directory", Pardes.paneDir(pane)); -} - -test "pty/status reports the grid and who holds the tty" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const pane = p.panes[0].?; - const status = Node.of(pane.serial, .pty_status); - - const a = rd(p, status, 0, 256); - try testing.expectEqual(Status.ok, a.reply.status); - var want: [64]u8 = undefined; - const whole = try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11} ", .{ pane.cols, pane.rows, 0 }); - try testing.expectEqualStrings(whole, a.bytes); - try testing.expectEqual(@as(usize, 3 * 12), a.bytes.len); - try testing.expectEqualStrings(whole[12..], rd(p, status, 12, 256).bytes); - - var probe: FakeTty = .{ .taken = true }; - p.host = .{ .ctx = &probe, .vtable = &FakeTty.vtable }; - const held = rd(p, status, 0, 256); - try testing.expectEqualStrings( - try std.fmt.bufPrint(&want, "{d:>11} {d:>11} {d:>11} ", .{ pane.cols, pane.rows, 1 }), - held.bytes, - ); -} - -test "pty/data writes at the shell and reads the raw stream" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const serial = serialOf(p); - const data = Node.of(serial, .pty_data); - - const w = call(p, .{ .tag = 2, .op = .write, .node = data, .off = 999, .data = "ls -l\r" }); - try testing.expectEqual(@as(u32, 6), w.reply.written); - try testing.expectEqualStrings("ls -l\r", w.pty()); - try testing.expectEqual(@as(u32, 1), wr(p, data, "a\xC3").reply.written); - try testing.expectEqual(@as(u32, 0), wr(p, data, "").reply.written); - - try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); - - p.update(.{ .output = .{ .pane = 0, .bytes = "unwatched" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.items.len); - try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); - - _ = call(p, .{ .tag = 5, .op = .open, .node = data }); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers); - try testing.expectEqual(@as(u16, 0), p.fs.listeners); - try testing.expect(!p.fs.scripted(0)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "hello" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("hello", rd(p, data, 0, 64).bytes); - try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); - - p.update(.{ .output = .{ .pane = 0, .bytes = "abcdef" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("ab", rd(p, data, 0, 2).bytes); - try testing.expectEqualStrings("cd", rd(p, data, 0, 2).bytes); - p.update(.{ .output = .{ .pane = 0, .bytes = "ghi" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("efghi", rd(p, data, 0, 64).bytes); - - p.update(.{ .output = .{ .pane = 0, .bytes = "orphan" } }); - while (p.nextEffect()) |_| {} - _ = call(p, .{ .tag = 6, .op = .release, .node = data }); - try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); - try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.capacity); - try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); - - _ = call(p, .{ .tag = 7, .op = .open, .node = data }); - _ = call(p, .{ .tag = 8, .op = .open, .node = data }); - _ = call(p, .{ .tag = 9, .op = .release, .node = data }); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers); - p.update(.{ .output = .{ .pane = 0, .bytes = "still" } }); - while (p.nextEffect()) |_| {} - try testing.expectEqualStrings("still", rd(p, data, 0, 64).bytes); -} - -test "the pty queue drops the oldest at its cap" { - const gpa = testing.allocator; - const p = try withTerm(gpa); - defer p.deinit(); - const data = Node.of(serialOf(p), .pty_data); - _ = call(p, .{ .tag = 5, .op = .open, .node = data }); - - const oldest: [4096]u8 = @splat('A'); - const rest: [4096]u8 = @splat('B'); - notePtyOutput(p, 0, &oldest); - for (0..queue_cap / rest.len + 4) |_| notePtyOutput(p, 0, &rest); - const q = &p.fs.panes[0].pty_out; - try testing.expect(q.buf.items.len - q.head <= queue_cap); - - var seen: usize = 0; - while (true) { - const a = rd(p, data, 0, 1 << 16); - if (a.reply.status == .again) break; - try testing.expect(std.mem.indexOfScalar(u8, a.bytes, 'A') == null); - if (a.bytes.len == 0) break; - seen += a.bytes.len; - } - try testing.expect(seen > 0 and seen <= queue_cap); +test { + _ = tree; } -- cgit v1.3 From 9070942b29bd10dddcdecdb0e88ba0fb40608467 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 21 Sep 2026 20:07:43 -0300 Subject: Plan 9 idiom for the control filesystem, and the regressions a624a56 left The 9P tree stops being a command language wearing a filesystem. /new created a pane as a side effect of a *read*; it is now Tcreate in /pane, with Tremove to close, which cloud9's engine has always supported and the editor never declared: tree.zig now says `features = .{ .create = true, .remove = true }`. Eleven pane ctl verbs become files that can be read as well as written -- dot, limit, dirty, mark, scroll, look, exec -- leaving ctl with `get`, the one verb no file would say better. Root /ctl splits into a read-only /status and the /look and /exec files whose write IS the click. stat carries real sizes where it used to answer 0, and qid versions track a pane's revision, so a client can poll for change without re-reading the body. Commit a624a56 moved raw-tty keys to an early-return branch that knew only Ctrl-B and bare Escape, and in the same edit deleted the paste branch below it. That cost Shift-Escape (the unconditional way out of tty mode) and both paste chords: Ctrl-V and Ctrl-Shift-V reached the child as keystrokes, so an agent CLI running in a pane took Ctrl-V for its image-paste binding and answered "No image found in clipboard". Both are restored, with tests. Nested detection was not subtly broken but deleted: 60367d8 removed nested.zig's process-ancestry walk and left "am I inside pardes" derived from PARDES_FORWARD_LOOK, which read "0" both for --nested and for "the listener did not come up". PARDES_PID now answers that question on its own, checked with kill(pid, 0); PARDES_9P and PARDES_PANE answer how to reach it; the flag is gone. The posted-9P registry also self-heals now -- a session that aborts cannot unlink its own socket, so posting sweeps entries whose target refuses a connection, symlinks only and on a definite ECONNREFUSED only. Elsewhere: tty scrolling is sticky-bottom, following new output only from the last row, with typing and entering raw mode snapping back to live; the boot layouts are a Boot enum instead of a chain of ifs, and the bare tty startup (Boot.tty, which main.zig names) opens an empty text pane under the shell while tests keep Boot.tty_shell; builtins announce themselves on the message row under a Verbose setting that is on by default; Config prints each setting the way you would type it back, so WindowOpacity 70 rather than "WindowOpacity: 70%"; LocationsConfig opens its window only when called bare; every tagline puts the word that closes the thing last, and a column now outlives its panes -- closing the last one leaves an empty pane, and only Delcol, newly on the column tagline, takes the column away. Co-Authored-By: Claude Opus 5 (1M context) --- .agents/skills/pardes-9p/SKILL.md | 271 +++++++++++++++++++------------- docs/cloud9.md | 11 ++ docs/config.md | 18 ++- docs/design.typ | 31 ++-- docs/fs.md | 120 +++++++++----- docs/v9fs.md | 2 +- features.txt | 48 ++++++ src/9p_io.zig | 290 +++++++++++++++++++++++++++++++--- src/builtins.zig | 15 +- src/config.zig | 187 +++++++++++----------- src/fs-help.txt | 42 ++--- src/fs.zig | 11 +- src/host_io.zig | 3 + src/main.zig | 71 +++++++-- src/ninep/addr.zig | 16 +- src/ninep/ctl.zig | 319 ++++++++++++++++---------------------- src/ninep/events.zig | 15 +- src/ninep/pane.zig | 241 ++++++++++++++++++++++++---- src/ninep/pty.zig | 9 +- src/ninep/screen.zig | 25 ++- src/ninep/testing.zig | 29 +++- src/ninep/tree.zig | 207 ++++++++++++++++--------- src/panes.zig | 14 +- src/pardes.zig | 294 +++++++++++++++++++++++++++++------ src/tty/tty.zig | 31 ++++ src/tutor.txt | 21 +-- test/appearance_gallery.py | 14 +- test/column_tags.py | 4 +- test/e2e_harness.zig | 2 +- test/font_size.py | 6 +- test/fs.py | 134 +++++++++------- test/fs_bench.zig | 4 +- test/fs_namespace.zig | 15 +- test/fs_soak.py | 8 +- test/look_placement.py | 6 +- test/ninep.py | 19 +++ test/output.zig | 32 ++-- test/panes.zig | 76 ++++++++- test/pdf.zig | 2 +- test/tag_cleanup.py | 2 +- test/ui_review.py | 12 +- test/v9fs.py | 35 +++-- test/window_opacity.py | 2 +- 43 files changed, 1898 insertions(+), 816 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 09dee666..2cea4d4a 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -1,23 +1,127 @@ --- name: pardes-9p -description: Inspect and drive a running Pardes editor over 9P, or exercise its panes, builtins, terminal input and rendered output in an isolated session. Use for Pardes interaction, plugin development and end-to-end debugging through its control filesystem. +description: Inspect and drive a running Pardes editor through its control filesystem, or exercise its panes, builtins, terminal input and rendered output in an isolated session. Use for Pardes interaction, plugin development and end-to-end debugging. --- # Pardes over 9P -Use the existing [Python client](../../../test/ninep.py) for ad hoc interaction -and functional tests. Do not build another wire client. Project tooling stays -in Zig. Run the examples from the repository root; paths below are relative to -that root unless linked. +Pardes is driven by reading and writing files. Prefer ordinary file tools over +a mount; reach for the Python client only when nothing is mounted, or when the +work needs a fid held open. Do not build another wire client: project tooling +stays in Zig. Run the examples from the repository root; paths below are +relative to that root unless linked. -## Connect and identify panes +## Find the session through the mount -Every native session opens a Unix socket. Inside a pane, `PARDES_9P` names the -socket and `PARDES_PANE` is that pane's serial. Outside Pardes, find -`pardes-9p-*.sock` under `$XDG_RUNTIME_DIR`, or `~/.local/state/pardes` when -that variable is unset. Select the intended session explicitly; do not assume -the newest socket is the right one. Names come from `--9p=name`, the detached -session name, or the process ID. +This machine keeps a FUSE mount of every posted session under `/mnt/9p`: +`/mnt/9p/pardes//` is one session's served root. Inside a pane, +`$PARDES_9P` is that session's socket (`/run/user/1000/pardes-9p-.sock`), +so its pid is the directory to use, and `$PARDES_PANE` is the calling pane's +serial: + +```sh +m=/mnt/9p/pardes/$(basename "$PARDES_9P" .sock | sed 's/^pardes-9p-//') +cat "$m/index" +cat "$m/pane/$PARDES_PANE/body" +``` + +Entries for dead sessions stay listed and answer `Input/output error` on any +access, so name the session you mean rather than globbing or taking the newest. +`cat "$m/index"` is the cheapest liveness check, and `cat "$m/status"` reports +the `pid`, `version` and `panes` of a session new enough to serve it. + +`/mnt/9p/pardes` is the registry of posted sessions, mounted once for the +machine. It is not the per-pane kernel mount the `Tty9p` builtin makes, which +gives one pane's shell `$PARDES_MOUNT`; see [docs/v9fs.md](../../../docs/v9fs.md) +for that. Either mountpoint serves the same tree. + +A running session serves whatever binary started it. If a listing does not +match this document, that session predates the change; restart it. + +## The tree, and what to do with it + +``` +$m/README the served guide, worth reading first +$m/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name +$m/status pid, version, panes +$m/look write a line = a right click on it at the active pane +$m/exec write a line = a middle click: an editor command word, or a shell line +$m/log one record per read: new|del|rename|save ; reads park +$m/screen the rendered screen as JSON, frozen per open +$m/listeners this session's dial addresses +$m/pane/ mkdir opens a pane; rmdir closes it +$m/os/ the host filesystem +``` + +The first field of an index row is a stable pane serial, not a slot or row +number. A row is `serial kind dirty name`, so `row.split(maxsplit=3)` keeps a +name with spaces intact. Re-read the index after anything that might open, +reuse or close a pane. + +```sh +cat "$m/index" # which panes exist +mkdir "$m/pane/x"; n=$(awk 'END{print $1}' "$m/index") # open one, take its serial +printf 'text\n' > "$m/pane/$n/body" # append +cat "$m/pane/$n/tag" # what its tagline offers +echo notes.txt > "$m/pane/$n/name" # rename the buffer +echo Save > "$m/pane/$n/exec" # save it +echo "/etc/hosts:3" > "$m/look"; cat "$m/look" # open a file, see where it landed +rmdir "$m/pane/$n" # close it, dirty or not +``` + +The name `mkdir` asks for is ignored: a pane is named by the serial the editor +gives it, and because `/index` is ordered by serial its last row is the pane +just made. Nothing else in the tree can be created or removed, and no read +creates anything, so `ls`, `stat` and `find` over the whole tree are inert. + +`look` and `exec` are the editor's two clicks, one per line of a write, at the +active pane from the root and at that pane from `$m/pane//look` and +`$m/pane//exec`. Reading any of them answers the serials the last command +made, or the pane it focused or acted on. A command that fails is reported in +the editor, not as a write error, so inspect the resulting pane, index, message +or screen; only a malformed line fails the write itself. + +## Edit through addresses, dot and the flag files + +For a file or scratch pane, with `pane=$m/pane/`: + +| Operation | Shell | Python client | +|---|---|---| +| Read text | `cat $pane/body` | `client.read(pane + '/body')` | +| Append text | `echo text >> $pane/body` | `client.write(pane + '/body', b'text\n')` | +| Replace all text | `echo text > $pane/body` | `client.write(pane + '/body', b'text\n', truncate=True)` | +| Address a byte range | `echo '#0,#2' > $pane/addr` | `client.write(pane + '/addr', b'#0,#2')` | +| Replace that range | `echo 'pub fn' > $pane/data` | `client.write(pane + '/data', b'pub fn')` | +| Read the selection | `cat $pane/dot` (offsets), `cat $pane/sel` (text) | the same two reads | +| Select the addressed range | `cp $pane/addr $pane/dot` | `client.write(pane + '/dot', client.read(pane + '/addr'))` | +| Reload from disk | `echo get > $pane/ctl` | `client.write(pane + '/ctl', b'get\n')` | +| Close it | `rmdir $pane` | `client.remove(pane)` | + +`addr`, `dot` and `limit` each read the pair of offsets they also accept, which +is why copying one onto another is all that acme's `addr=dot`, `dot=addr` and +`limit=addr` ever were; a write may also be an address expression (`#0,#5`, +`/pattern/`, `2+1`). Moving `dot` scrolls the pane to it. `limit` bounds a +search and reads empty until set; truncate it to lift it. + +`dirty`, `mark` and `scroll` read `0` or `1` and take `0` or `1`: whether the +buffer differs from its file, whether a write pushes an undo point, and whether +a write scrolls. Truncating `tag` clears the part of the tag you may edit. + +Address state belongs to the pane, not to a client: opening `addr` resets it, +so two clients addressing the same pane will interfere. `$pane/ctl` reads +acme's window status line — serial, tag length, body length, a reserved zero, +the dirty flag, the width in cells, the font and the tab width — and takes the +one verb `get`. + +Terminal panes have no file: writing their `body` sends child input, and +truncation does not erase terminal history. + +## The Python client, for what a shell cannot express + +Use the existing [Python client](../../../test/ninep.py) when there is no +mount, or when the work needs a fid held open across several operations — +`log`, `event` and `pty/data` are consuming queues whose reads park, and shell +redirection cannot hold one open. ```sh PYTHONPATH=test python3 -B - "$PARDES_9P" <<'PY' @@ -25,103 +129,56 @@ import sys from ninep import Client with Client(sys.argv[1]) as client: - print(client.read('/self/index').decode(), end='') - print(client.read('/self/listeners').decode(), end='') + print(client.read('/index').decode(), end='') + print(client.read('/listeners').decode(), end='') PY ``` -`Client` takes a raw Unix socket path, or `(numeric_ip, port)` for TCP; it -does not parse Pardes dial strings or implement QUIC. It negotiates 9P2000, -uses a five-second socket timeout, and closes on leaving `with`. - -The first field of each index row is a stable pane serial, not a slot or row -number. The tag starts after five numeric fields; use `row.split(maxsplit=5)` -to preserve spaces. Inspect `/self/pane//tag`, `body`, or directory -entries before choosing a target. Re-read the index after actions that might -open, reuse or close panes. - -Wire paths start with `/self` or `/os`. `/n/self`, `/n/os`, `/n/peer` and -`/virtual` belong to editor Look paths, not the server root. For example, -Look `/virtual/src/pardes.zig` corresponds to reading `/self/src/pardes.zig`. - -## Edit, Look and execute - -For a file or scratch pane, with a connected `client` and a confirmed -`serial`, let `pane = f'/self/pane/{serial}'`. Terminal body writes instead -send child input; truncation does not erase terminal history. - -| Operation | Client call | -|---|---| -| Read text | `client.read(pane + '/body')` | -| Append text | `client.write(pane + '/body', b'text\n')` | -| Replace all text | `client.write(pane + '/body', b'text\n', truncate=True)` | -| Select a byte range | `client.write(pane + '/addr', b'#0,#2')` | -| Replace that range | `client.write(pane + '/data', b'pub fn')` | -| Show the addressed selection | `client.write(pane + '/ctl', b'dot=addr\n')` | -| Look from this pane | `client.write(pane + '/ctl', b'look /virtual/src/pardes.zig:10\n')` | -| Save | `client.write(pane + '/ctl', b'put\n')` | -| Reload | `client.write(pane + '/ctl', b'get\n')` | -| Close, refusing dirty text | `client.write(pane + '/ctl', b'del\n')` | - -`delete` force-closes, discarding unsaved text. `get` replaces edits with file -contents. Use those only when that loss is intended. Reading `/self/new/ctl` -creates a scratch pane and returns its serial as the first field; it is not -an observational read. - -`ctl` is not a builtin interpreter. Execute builtins through a body Exec event -on an owned scratch pane: - -```python -from fs import new_pane, execute - -control = new_pane(client, b'') -execute(client, control, 'Msg 9p-ready') -``` - -`execute` overwrites that pane's body with the command, then writes -`MX0 \n` to its `event` file. Keep the control pane separate -from user text. The same helper can run `Mini path`, `Mount peer dial`, and -`Unmount peer`; commands resolve relative to the control pane's directory. -A successful event write acknowledges dispatch, not completion: inspect the -resulting pane, message or screen for success. +`Client` takes a raw Unix socket path, or `(numeric_ip, port)` for TCP; it does +not parse Pardes dial strings or implement QUIC. It negotiates 9P2000, uses a +five-second socket timeout, and closes on leaving `with`. Its paths are the +served root: `/index`, `/pane/2/body`, `/os/...`. `/n/self`, `/n/os`, `/n/peer` +and `/virtual` are editor Look paths, not server paths — Look +`/virtual/src/pardes.zig` corresponds to reading `/src/pardes.zig`. -Opening `addr` resets its range. To inspect the current selection, open -`addr` first, write `addr=dot\n` to `ctl`, then use `read_fid` on that already -open handle. Do not replace that last step with `client.read`, which reopens -and resets it. Address state is shared by the pane, not private to a client. +For live terminal output or plugin events, use `open` / `read_fid` / `close`, +not the read-until-EOF helper. `pty/data` captures output while held open; it +is not a history replay. Both files are shared, consuming queues, not +per-client broadcasts, so a slow reader loses older data. Holding `event` open +intercepts that pane's Look and Exec clicks, so it is not a passive logger: for +Look/Exec records whose offsets identify the intended text, forward the short +record ` \n`, not the whole report with flags and text. +Expansion and chord reports need explicit handling, and terminal-body events +can carry text only in the report, which a short writeback cannot reproduce. +Read the event implementation before building an interceptor. Close handles in +`finally`, and disconnect after a socket timeout. The service shares four +connection slots and 32 screen/terminal-history snapshot handles. + +A file's qid version is the pane's revision for `body`, `data` and `xdata`, so +`stat` sees an edit land without reading the text; it stays zero elsewhere. +Stat sizes are real, and for `log`, `event` and `pty/data` report the length of +the record a read would answer — zero when nothing is waiting. ## Terminal input and screen observations Only terminal panes have `pty/`. Write keystroke bytes to `pty/data`, not `body`: `client.write(pane + '/pty/data', b'printf hello\r')` submits a shell -command. For an interactive application, send its actual input bytes; -`b'\x03'` is Ctrl-C, and Ctrl-U is `b'\x15'` where that application supports it. -These inputs go to the child terminal, not Pardes editor key bindings. +command. For an interactive application, send its actual input bytes; `b'\x03'` +is Ctrl-C, and Ctrl-U is `b'\x15'` where that application supports it. These go +to the child terminal, not to Pardes key bindings. `pty/ctl` takes `winsize C R`, +`sig INT` and `exec`, one per line. -`client.screen()` returns `cols`, `rows`, `cursor`, `styles`, and row-major +`client.screen()` returns `cols`, `rows`, `cursor`, `styles` and row-major `cells` of `[grapheme, style_index]`. Reconstruct rows using `cols`; resolve -each cell's style through `styles` when checking highlighting. Compare colors -and attributes, not just style-table indices or flattened text. +each cell's style through `styles` when checking highlighting, and compare +colors and attributes rather than style-table indices or flattened text. -Each screen open freezes one frame. A terminal `body` freezes history on its -first read. `client.read` and `client.screen` reopen each time; use repeated -calls for fresh observations. Do not poll a stale handle. Poll a specific -condition with a deadline and a short delay, rather than a fixed long sleep. -For large histories, measure whole-body reads separately from screen polling; -9P write-to-observation timing includes RPC, rendering and polling overhead. - -For live terminal output or plugin events, use `open` / `read_fid` / `close`, -not the read-until-EOF helper. `pty/data` captures output while held open; -it is not a history replay. Both files are shared, consuming queues, not -per-client broadcasts; slow readers can lose older data. Holding `event` open -intercepts Look/Exec clicks, so it is not a passive logger. For Look/Exec -records whose offsets identify the intended file/tag text, forward the short -record ` \n`, not the entire report with flags and text. -Expansion/chord reports need explicit handling; terminal-body events can have -empty ranges with text carried only in the report, so short writeback cannot -reproduce them. Read the event implementation before building an interceptor. -Close handles in `finally`; disconnect after a socket timeout. The service -shares four connection slots and 32 screen/terminal-history snapshot handles. +Each screen open freezes one frame, and a terminal `body` freezes its history +on its first read. `client.read` and `client.screen` reopen each time, so +repeat the call for a fresh observation rather than polling a stale handle. +Poll a specific condition with a deadline and a short delay, not a fixed long +sleep. For large histories, measure whole-body reads separately from screen +polling; write-to-observation timing includes RPC, rendering and polling. ## Exercise an isolated session @@ -140,22 +197,23 @@ binary = str(Path(sys.argv[1]).resolve()) with tempfile.TemporaryDirectory(prefix='pardes-9p-skill-') as directory: with session(binary, Path(directory), 'skill') as (client, address): serial = new_pane(client, b'fn main() void {}\n') - pane = f'/self/pane/{serial}' - client.write(pane + '/ctl', b'name probe.zig\n') + pane = f'/pane/{serial}' + client.write(pane + '/name', b'probe.zig\n') client.write(pane + '/addr', b'#0,#2') client.write(pane + '/data', b'pub fn') assert client.read(pane + '/body') == b'pub fn main() void {}\n' - control = new_pane(client, b'') - execute(client, control, 'Msg 9p-ready') + execute(client, serial, 'Msg 9p-ready') frame = client.screen() assert '9p-ready' in ''.join(cell[0] for cell in frame['cells']) print('9P edit, builtin and screen checks passed') PY ``` -For terminal tests, use `session(..., tty=True)` and read +`new_pane` is `mkdir` plus a read of the index; `execute` writes one line to a +pane's `exec`. Both are in `test/fs.py`. For terminal tests, use +`session(..., tty=True)` and read [test/agent_session.py](../../../test/agent_session.py) for bounded interactive -driving. Its readiness text and history threshold are application-specific; +driving; its readiness text and history threshold are application-specific, and session cleanup alone does not guarantee arbitrary grandchildren have exited. Use [test/snapshot.zig](../../../test/snapshot.zig) when editor key/mouse input or an independent terminal-rendering comparison matters; 9P screen inspection @@ -163,6 +221,7 @@ alone does not test physical input routing or the host renderer. Read [docs/fs.md](../../../docs/fs.md) for runtime mounts, TCP/QUIC listeners, Plan9port and Linux v9fs compatibility. Unix is always available; network -listeners are opt-in and grant full session/OS-file access. Use isolated -loopback listeners for tests. For less common control verbs or event details, -read their implementation and tests in [src/fs.zig](../../../src/fs.zig). +listeners are opt-in and grant full session and OS-file access, so use isolated +loopback listeners for tests. For event details or anything this page leaves +open, read the implementation and its tests in +[src/ninep/](../../../src/ninep/). diff --git a/docs/cloud9.md b/docs/cloud9.md index 79fda717..d030db1d 100644 --- a/docs/cloud9.md +++ b/docs/cloud9.md @@ -54,6 +54,17 @@ way a private `ZMX_DIR` does for zmx. Stopping unposts, and only while the entry is still ours, so a name another editor has since claimed is never unlinked. +An exit that cannot run any code of its own — an aborted test, a kill, a +crash — leaves its entry and its socket behind, so posting first sweeps the +group: every entry that is a symlink and whose socket answers a connect with +a definite ECONNREFUSED is unlinked, along with the socket it points at when +a `stat` agrees that is a socket of ours. Anything that is not a symlink is +somebody else's, and any other answer — connected, busy, refused permission, +a surprise — counts as live, because uncertainty belongs to the server that +owns the socket rather than to the sweeper. That is `cloud9.post.Probe`'s +classification, repeated in `src/9p_io.zig` only because `post.probe` is raw +Linux syscalls and pardes also builds for darwin. + **Consuming.** Nothing. `9ns --mntgen` mounts the whole registry at `/mnt/9p`, and an interactive fish already self-wraps in one, so a pardes started from a terminal sees every posted service as ordinary files — diff --git a/docs/config.md b/docs/config.md index a55aef1c..04b0fd82 100644 --- a/docs/config.md +++ b/docs/config.md @@ -111,6 +111,10 @@ Workspace, column and pane command text can be edited directly; see `ColumnTags` toggles the column command row in both GUI and TTY; it is on by default. Add `ColumnTags` to startup configuration to reclaim that row on a compact screen. Hiding it preserves your custom column commands. +`Verbose` toggles the message-row announcement every builtin makes of its own +name before it runs; it is on by default, and the builtins that own the message +row themselves (`Msg`) never announce. Turning it off leaves the row to the +messages a builtin chooses to write. `SyntaxBold` toggles bold syntax keywords; it is off by default. These settings are shared by GUI and TTY, and `Config` reports their current states. Like `Colors` and `Wrap`, these commands take no argument and invert @@ -334,10 +338,16 @@ The installed `pardes-v9fs` helper lives beside the editor; development builds can set `PARDES_V9FS_HELPER` to its absolute path. See [v9fs.md](v9fs.md). Ctrl-B switches between raw TTY and editor mode. Plain Escape at a detected -shell prompt hops back to the previous pane. Other keys, including Ctrl-O, Ctrl-W, -paste shortcuts, and modified Escape belong -to the child. Use `Mode` in the pane tag to return to editor -mode in place. Desktop paste events still feed the terminal. +shell prompt hops back to the previous pane. Other keys, including Ctrl-O, +Ctrl-W and modified Escape, belong to the child. Use `Mode` in the pane tag to +return to editor mode in place. Desktop paste events still feed the terminal. + +The paste chords are the exception the window keeps. Ctrl-V types the yank +register at the program, and Ctrl-Shift-V asks the desktop for its clipboard +and types that; both go through the program's bracketed paste when it has +asked for one. Neither reaches the child as a keystroke, so an application +that would otherwise answer Ctrl-V by reading the system clipboard itself +never gets the chance to read the wrong thing. `Font` and `FontSel` exist ONLY in the SDL GUI and native macOS builds — a terminal's font belongs to its emulator and a browser's to the page — so a diff --git a/docs/design.typ b/docs/design.typ index 4c8956ba..f8f0b05c 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -1492,15 +1492,20 @@ same thread as editing. == Nested Look -Pane shells inherit `PARDES_9P`, `PARDES_PANE` (the pane serial), and -`PARDES_FORWARD_LOOK`. A child launch resolves its OS-relative argument in -the child's working directory, then writes `look ` to the parent's -`self/pane//ctl`. Explicit `/virtual` and `/n` paths resolve in the -parent. The ordinary filesystem update performs layout and drains host effects. - -`--nested` starts a separate editor and disables forwarding from its direct -pane shells. Its 9P socket remains available for control and plugins. There is -no executable-name discovery or separate Look listener. +Pane shells inherit `PARDES_PID` (the editor's process id), `PARDES_9P` and +`PARDES_PANE` (the pane serial). The first answers whether the shell is inside +a pardes at all, the other two answer how to reach it, and they are separate +because a session whose listener never came up still owns its children. A child +launch that finds a live `PARDES_PID` and no way to reach it says so instead of +starting a second editor. Otherwise it resolves its OS-relative argument in the +child's working directory, then writes `look ` to the parent's +`pane//ctl`. Explicit `/virtual` and `/n` paths resolve in the parent. +The ordinary filesystem update performs layout and drains host effects. + +`--nested` starts a separate editor and withholds `PARDES_PID` from its direct +pane shells, which is the whole of the opt-out. Its 9P socket remains available +for control and plugins, so those shells still get `PARDES_9P` and +`PARDES_PANE`. There is no executable-name discovery or separate Look listener. Detached frontends use `pardes-detached-.sock` in the same runtime directory. The shared Unix socket conventions live in `src/9p_io.zig`. @@ -1928,9 +1933,11 @@ arrives bracketed, as one `paste` event. staged edits: Enter commits a new buffer save target, Escape cancels, and no disk rename or write happens until explicit Save. Terminal cwd and image/PDF status stay generated. Save leads the tail of every pane holding text of its own: -`Save Tty Del Collapse` for a file or an output buffer, -`Save Tty Del Togglettymode Filter Collapse` for a terminal, and `Tty Del Collapse` -for an image. PDFs use `Tty Del PdfSections PdfTint Collapse`, without tint status text. +`Save Tty Collapse Del` for a file or an output buffer, +`Tty Save Mode Filter Collapse Del` for a terminal, and `Tty Collapse Del` +for an image. PDFs use `Tty PdfSections PdfTint Collapse Del`, without tint status text. +The word that closes the thing is last on every tagline, so overshooting the +click before it cannot destroy anything. `Collapse` toggles a pane between its tagline alone and its expanded height; hidden body contents and running terminals are retained. An unsaved file has `*` after its name; an image tag diff --git a/docs/fs.md b/docs/fs.md index 55ffdc9c..0bcc0313 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -1,14 +1,19 @@ # Filesystem Every native session serves 9P2000 on a Unix socket. Pane shells receive -`PARDES_9P` (socket path) and `PARDES_PANE` (pane serial). The socket is +`PARDES_PID` (the editor's process id), `PARDES_9P` (socket path) and +`PARDES_PANE` (pane serial). The socket is `$XDG_RUNTIME_DIR/pardes-9p-.sock`, or lives under `~/.local/state/pardes` when XDG_RUNTIME_DIR is unset. Detached sessions use their session name; `--9p=` overrides it. A `pardes ` launched from a pane forwards Look to that pane over 9P. -`--nested` opens a separate editor and disables forwarding from its pane shells; -its 9P service stays available. +`PARDES_PID` alone says the shell is inside pardes; `PARDES_9P` and +`PARDES_PANE` say how to reach it, and a launch that has the first without the +other two refuses rather than opening a second editor. `--nested` opens a +separate editor and withholds `PARDES_PID` from its pane shells, so a pardes +started in one of them runs a session of its own; its 9P service stays +available. Look resolves the OS filesystem first, then the editor's virtual filesystem. Explicit paths bypass that search: @@ -68,53 +73,79 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. ``` /README this guide, also src/fs-help.txt /index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name -/ctl write: one command per line; read: the serials the last command made or touched -/new reading it creates one empty pane and answers "\n" (the /net/tcp/clone idiom) +/status pid, version and pane count +/look write a line: a right click on it at the active pane; read: the serials it touched +/exec write a line: a middle click; read the same serials /log one line per editor event: new|del|rename|save ; reads park /screen rendered screen JSON; frozen per open handle /listeners the session's dial addresses -/pane// name body tag ctl addr data xdata sel errors event, plus pty/{ctl,status,data} +/pane/ create a directory here to open a pane; remove one to close it +/pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll + errors event look exec, plus pty/{ctl,status,data} on terminals /os/ the host filesystem /src/ the editor's embedded sources, only when built with -Dembed-sources=true ``` -Nothing in the tree is created by list, stat, walk or read, except that -reading `/new` makes a pane; that is its whole purpose, so a recursive read -of the tree makes one pane per open of it. - -`/ctl` and `/pane//ctl` take the editor's own command language, two verbs: - -- `look TEXT` is a right click on `TEXT`: a path opens a file, `file:12` jumps - to a line, a directory opens a shell there, a URL opens in the browser. From - `/ctl` the look happens at the active pane; from a pane's `ctl` at that pane. -- `exec TEXT` is a middle click: a command word from `src/builtins.zig` - (`Save`, `Del`, `New`, `Newcol`, `Mount NAME DIAL`, `Unmount NAME`, `Dump`, - `Restore`, `Msg TEXT`, `Find`, `Grep`, `Tty`, ...), or anything else, which - runs in the pane's terminal. - -Both verbs are lowercase; the words after `exec` are the editor's capitalized -commands. A pane's `ctl` also keeps acme's addr verbs (`addr=dot`, `dot=addr`, -`limit=addr`, `clean`, `dirty`, `cleartag`, `get`, `mark`, `nomark`, -`noscroll`, `scroll`, `show`). Every line of a write is checked before any -line runs; a malformed line fails the write with EINVAL. A command that fails -inside the editor is reported on the message row, not as a write error. - -After a write to either `ctl`, reading `/ctl` answers the serials of the panes -the command created, or, when it created none, the pane a look focused or the -pane an exec acted on (even one it closed), one per line. Before any command it answers `pid`, `version` and `panes` lines. +Nothing in the tree is created by list, stat, walk or read. A pane is opened +by Tcreate in `/pane` (`mkdir`) and closed by Tremove on `/pane/` (`rmdir`), +which is the only create and the only remove the tree serves. The name a +create asks for is ignored, since a pane is named by the serial the editor +gives it: the Rcreate qid names the new directory, and because `/index` is +ordered by serial its last line is the pane just made. + +`/look` and `/exec` are the editor's two clicks, one per line of a write: + +- a line written to `look` is a right click on it: a path opens a file, + `file:12` jumps to a line, a directory opens a shell there, a URL opens in + the browser. +- a line written to `exec` is a middle click: a command word from + `src/builtins.zig` (`Save`, `Del`, `New`, `Newcol`, `Mount NAME DIAL`, + `Unmount NAME`, `Dump`, `Restore`, `Msg TEXT`, `Find`, `Grep`, `Tty`, ...), + or anything else, which runs in the pane's terminal. + +The root's pair clicks at the active pane and `/pane//look` and +`/pane//exec` at that pane. Blank lines are skipped, and every other line +is checked before any of them runs, so a control character fails the whole +write with EINVAL; a command that fails inside the editor is reported on the +message row, not as a write error. Reading any of these files answers the +serials of the panes the last command created, or, when it created none, the +pane a look focused or the pane an exec acted on (even one it closed), one +per line. `/pane//name` reads the pane's file name (a terminal's directory) and writing it renames the buffer; a relative name resolves against the pane's -directory. `sel` reads the editor selection and writing it replaces the -selection. `body` appends on write and replaces on truncating open. `addr` -selects a range and `data` or `xdata` read or replace it. `errors` appends to -the directory's `+Errors` pane. Holding `event` open redirects the pane's Look -and Exec clicks to that client; writing a record back performs the action. - -Stats report real lengths for `index`, `ctl`, `name`, `body`, `tag` and `sel`, -modes 0644/0666 (0444 for read-only files, 0222 for write-only), the pane's -last edit time or the process start as mtime, and stable qids. Directory -entries carry no sizes; stat the entry. +directory. `body` appends on write and replaces on truncating open. `sel` +reads the selected text and writing it replaces the selection. `errors` +appends to the directory's `+Errors` pane. Holding `event` open redirects the +pane's Look and Exec clicks to that client; writing a record back performs the +action. `ctl` reads acme's window status line — serial, tag length, body +length, a reserved zero, the dirty flag, the width in cells, the font and the +tab width — and takes one verb, `get`, which reloads the buffer from the name +it carries. + +The three range files `addr`, `dot` and `limit` each read the pair of offsets +they also accept, so copying one onto another is all that acme's `addr=dot`, +`dot=addr` and `limit=addr` ever were. A write is either that pair or an +address expression (`#0,#5`, `/pattern/`, `2+1`); `addr` selects what `data` +and `xdata` read or replace, `dot` is the editor's own selection and moving it +scrolls the pane into view, and `limit` bounds a search and reads empty until +it is set. Truncating a range file empties it; truncating `limit` lifts it. + +The three flag files `dirty`, `mark` and `scroll` read `0` or `1` and take +`0` or `1`: whether the buffer differs from its file, whether a write pushes +an undo point (writing `1` pushes one now), and whether a write scrolls the +pane. Truncating `tag` clears the part of the tag you may edit. + +Stats report real lengths for `index`, `status`, `look`, `exec`, `listeners`, +`name`, `body`, `tag`, `sel`, `ctl`, the range files and the flag files, and +for `log`, `event` and `pty/data` the length of the record a read would +answer, which is zero when nothing is waiting. Modes are 0644/0666 (0444 for +read-only files, 0222 for write-only); mtime is the pane's last edit or the +process start. The qid version of `body`, `data` and `xdata` is the pane's +revision, so a stat sees an edit land without reading the text; every other +file leaves it zero rather than promise a version it cannot keep. Directory +entries carry no sizes, and neither does `/screen`, which has no length until +an open renders its frame; stat the entry. `/log` records `new`, `del`, `rename` and `save` while at least one client holds it open; a read parks until a record arrives. `/screen` returns JSON with @@ -132,8 +163,10 @@ enables the option by default, so the device can serve its own source. This is a control filesystem, not a complete POSIX export. Native filenames may contain up to 255 bytes. Existing regular OS files support read, write, -and truncation to zero; protocol create, remove, rename, and other metadata -changes are refused. Ownership and permissions under `/os` are synthetic. +and truncation to zero; under `/os` protocol create, remove, rename and other +metadata changes are refused, as is every create and remove in the control +tree but the pane directories. Ownership and permissions under `/os` are +synthetic. Zero-length truncation accepts the accompanying `mtime` hint sent by Linux v9fs; the hint is not stored. Standalone timestamp changes remain refused. @@ -148,7 +181,8 @@ for Unix and TCP, a poll loop for QUIC, and the 9P client for mounts); `zig build fs-test` drives real sessions using the independent Python client in `test/ninep.py`; `zig build fs-discovery-test` checks that browsing creates -nothing and that `new`, `ctl`, `name`, `sel` and `log` behave. `zig build +nothing, that a pane create and remove work, and that `look`, `exec`, `name`, +`sel` and `log` behave. `zig build 9p-test` checks the two engine configurations' budgets (the engine's own tests are cloud9's `zig build test`); `zig build fs-bench` measures filesystem transactions in the core. diff --git a/docs/v9fs.md b/docs/v9fs.md index 6cb4e998..8cc97ff9 100644 --- a/docs/v9fs.md +++ b/docs/v9fs.md @@ -12,7 +12,7 @@ ls "$PARDES_MOUNT/pane" cat "$PARDES_MOUNT/index" cat "$PARDES_MOUNT/README" cat "$PARDES_MOUNT/pane/$PARDES_PANE/body" -echo 'exec Msg hello' > "$PARDES_MOUNT/ctl" +echo 'Msg hello' > "$PARDES_MOUNT/exec" ``` The mount belongs to that pane's subprocess tree. Other panes and the editor diff --git a/features.txt b/features.txt index 3bfc6967..bee079a7 100644 --- a/features.txt +++ b/features.txt @@ -20,3 +20,51 @@ on tty mode the mouse selection works but the pardes selection on that pane shou between tty panes without changing the pardes semantics or adding anything extra, just neat tricks like this. Still, you might need to come up with something to decrease the number of movements/interactions needed to do simple things like copy and pasting text from a terminal to another. + +The 9p protocol needs to be simplified and made plan9 idiomatic. Stop leaning on ctl verbs: a name should be the operation. The filesystem should carry more +in stat metadata (real sizes, mtimes, qid versions so a client can poll for change cheaply) and use the real 9P operations for what is currently a ctl verb or a +magic read. cloud9's engine already exposes fs.Features{create, remove, wstat} and the editor backend simply never declared them, so /new creating a pane on +*read* becomes a Tcreate in /pane, del becomes Tremove, cleartag becomes a truncating write to tag, and clean/dirty, scroll/noscroll, mark/nomark and +addr=dot/dot=addr/limit=addr become their own files. What is left of ctl should be only the verbs with no file analog. + +shift-esc stopped leaving raw tty mode on the sdl backend. Commit a624a56 moved raw tty keys to an early-return branch that only knew ctrl-B and bare Esc, so +shift-esc was forwarded to the child instead. It is the unconditional way out of tty mode and should stay that way. + +On tty mode scrolling should work and not always move the focus down to follow a new line. The terminal only moves down to follow new output when the last line +is already at the bottom, like most terminals and editors. Typing and entering raw mode snap back to live output, so nobody types blind. + +The different kinds of layout pardes can initialize (tty mode, file mode, the classic three-shell boot, and the others that already exist) should be an explicit +enum rather than a chain of ifs over tty_only/shells/file/missing. That part of the code needs to be more explicit. The bare tty startup should always start with +an empty text pane at the bottom, not focused. + +Nested pardes detection stopped working. Spawning a subprocess should export an env variable holding the pardes pid, so a child can see it and call a Look on the +parent through the 9p mount instead of starting a second session; whether 9p is mounted is another env variable the child can check. + +Builtins should call Msg with the builtin name when they are called, minus a few exceptions like Msg itself. This is gated on a verbose config that is on by +default and can be turned off. + +The sr.ht upstream has a macos update pushed to it. Pull it, merge it into the tip here as its own change, then look at what the macos backend gained and port +those features to the sdl backend wherever it makes sense. + +Config options should print symmetrically with the way they are set: instead of showing transparency with a colon and a percent sign it should read like +`Etcetera 70`, exactly what you would type to set it, and the same for every other setting. LocationsConfig should only open an output window with the current +config when it is called with no arguments. + +Closing the last pane in a column should not delete the column: it should leave a new empty pane there instead. A column closes only when it is closed explicitly, +so if there is no builtin for that, add a Delcol that sits on the column tagline by default. And in every tagline the builtin that kills or closes the thing should +come last, which does not look like the case for panes right now. + +Pasting regressed on the terminal: inside agent sessions text is being pasted as an image and simply does not work. Reproduce it first, then fix it. + +The 9p skill documentation should teach interacting with a running pardes through the /mnt/9p mount with ordinary file tools — cat, echo, ls — as the normal +ad-hoc path, and fall back to the python client only when nothing is mounted. + +Dead sessions are never removed from the posted-9P registry, which is a bug. A session that aborts or is killed leaves both its socket in $XDG_RUNTIME_DIR and its +symlink under the registry directory, so /mnt/9p/pardes lists entries that give Input/output error on access. postToRegistry only ever replaces its own name's +entry; nothing sweeps the rest. Posting should sweep the service directory and unlink every entry whose target refuses a connection, and the dangling socket with +it. cloud9 already classifies a refused connect as stale (post.zig Probe), and 9p_io.zig already has `alive`, which treats uncertainty as live -- that is the right +bias, so only a definite refusal reaps. + +After all of the above, do an optimization pass on startup time for the gui and tty platforms: measure first, then optimize. build.zig already has a `perf` step +(gesture latency and bounded terminal stress, with --json and a --base baseline to compare against), so a startup measurement belongs there rather than in a new +harness, and the baseline files are how a regression gets caught later. diff --git a/src/9p_io.zig b/src/9p_io.zig index 4f7c2e97..3d019e0d 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -596,7 +596,7 @@ pub const Listener = struct { } for (l.control) |fd| { setCloexec(fd); - setNonblock(fd); + _ = setNonblock(fd); } l.arm(); l.watcher = try std.Thread.spawn(.{}, watchQuic, .{l}); @@ -671,6 +671,7 @@ pub const Listener = struct { log.warn("registry post skipped: cannot create {s}", .{svc}); return; } + sweepRegistry(l.io, svc); var entry_buf: [sun_path_len:0]u8 = undefined; const entry = std.fmt.bufPrintSentinel(&entry_buf, "{s}/{s}", .{ svc, name }, 0) catch { log.warn("registry post skipped: name too long: {s}", .{name}); @@ -679,15 +680,15 @@ pub const Listener = struct { const target = l.path_buf[0..l.path_len]; // Replace only what is provably not live: our own entry, or a - // dead predecessor's symlink. `isListening` treats uncertainty - // as live, so it is only asked about an entry that *is* a - // symlink; anything else is left strictly alone and the - // symlink below simply fails. + // dead predecessor's symlink. `probe` treats uncertainty as + // live, so it is only asked about an entry that *is* a symlink; + // anything else is left strictly alone and the symlink below + // simply fails. var link_buf: [sun_path_len]u8 = undefined; const n = libc.readlink(entry, &link_buf, link_buf.len); if (n >= 0) { const had = link_buf[0..@intCast(n)]; - if (!std.mem.eql(u8, had, target) and alive(entry)) { + if (!std.mem.eql(u8, had, target) and probe(entry) == .live) { log.warn("registry entry pardes/{s} is live; not re-posted", .{name}); return; } @@ -842,12 +843,129 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, named: []const u8, fallback: [ const alive = transport.isListening; -fn setNonblock(fd: c_int) void { +/// What is at a socket path, in cloud9's three answers (`post.Probe`). +/// Asked here with libc rather than through `cloud9.post.probe`, whose +/// raw Linux syscalls darwin cannot compile, but the classification is +/// that file's and must not become a second opinion: the one definite +/// refusal is `.stale`, nothing at the path at all is `.none`, and +/// everything else — connected, busy, refused permission, a surprise — +/// is `.live`. Uncertainty belongs to the server that owns the socket, +/// never to a sweeper deciding what to delete. +const Probe = enum { none, stale, live }; + +/// `SOCK.STREAM`, and the kernel's own non-blocking bit where there is +/// one. Darwin's `SOCK.NONBLOCK` is a Zig shim for `std.posix.socket` +/// to unpack, not an ABI value, so handing it to the raw libc call +/// would ask a kernel that has never heard of it; there it is an +/// `fcntl` instead. +const probe_socket_kind: c_uint = libc.SOCK.STREAM | (if (darwin) 0 else libc.SOCK.NONBLOCK); + +fn probe(path: [:0]const u8) Probe { + if (path.len + 1 > sun_path_len) return .live; // cannot ask; assume occupied + var addr: libc.sockaddr.un = .{ .path = @splat(0) }; + @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]); + const fd = libc.socket(libc.AF.UNIX, probe_socket_kind, 0); + if (fd < 0) return .live; + defer _ = libc.close(fd); + + // Non-blocking is the whole safety of this function, so it is read + // back rather than assumed: a BLOCKING connect to a live server + // whose backlog is full parks in the kernel with no timeout to end + // it — measured, it simply never returns — and a sweep that parks + // takes the editor's startup with it. An fd that cannot be proven + // non-blocking is never connected at all, which lands on `.live`, + // the answer that deletes nothing. + if (comptime darwin) _ = setNonblock(fd); + if (!isNonblocking(fd)) return .live; + + if (libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) == 0) return .live; + // cloud9's `post.probe` mapping, answer for answer. The connection + // is never wanted: EAGAIN (a full Unix backlog) and EINPROGRESS say + // somebody is listening, which is all that was asked, and the fd + // closes without ever waiting for it to become writable. + return switch (libc.errno(-1)) { + .AGAIN, .INPROGRESS, .PERM, .ACCES => .live, + .CONNREFUSED => .stale, + .NOENT, .NOTDIR => .none, + else => .live, + }; +} + +/// Reaps the registry entries whose editor is gone, once per post. +/// +/// A clean exit unposts itself (`unpostFromRegistry`), so everything +/// left behind comes from an exit that could not: an aborted test, a +/// kill, a crash. No code in the dead process can ever run, so the cure +/// has to be somebody else's readdir, and the next editor to start is +/// the somebody. It is only ever a symlink that is followed or +/// unlinked, because that is the only thing `postToRegistry` makes and +/// anything else under a name belongs to whoever put it there; and only +/// a definite refusal counts as gone. The socket a stale entry points +/// at goes too, but not before a stat agrees it is a socket of ours: a +/// plain file answers a connect with the same refusal. +fn sweepRegistry(io: std.Io, svc: [:0]const u8) void { + if (comptime !supported) return; + + // The names are staged before anything is unlinked, so the sweep + // never asks a directory to keep reading while it is being edited. + var names: [4096]u8 = undefined; + var staged: usize = 0; + { + const dir = std.Io.Dir.openDirAbsolute(io, svc, .{ .iterate = true }) catch return; + defer dir.close(io); + var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; + var reader: std.Io.Dir.Reader = .init(dir, &read_buf); + while (true) { + const listed = (reader.next(io) catch break) orelse break; + if (listed.name.len == 0 or listed.name.len > 255) continue; + if (staged + 1 + listed.name.len > names.len) break; + names[staged] = @intCast(listed.name.len); + @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); + staged += 1 + listed.name.len; + } + } + + var reaped: usize = 0; + var i: usize = 0; + while (i < staged) { + const name = names[i + 1 ..][0..names[i]]; + i += 1 + name.len; + var entry_buf: [sun_path_len:0]u8 = undefined; + const entry = std.fmt.bufPrintSentinel(&entry_buf, "{s}/{s}", .{ svc, name }, 0) catch continue; + const facts = statNoFollow(entry) orelse continue; + if (facts.mode & 0o170000 != 0o120000) continue; // not a symlink: not ours to judge + const state = probe(entry); + if (state == .live) continue; + var link_buf: [sun_path_len]u8 = undefined; + const n = libc.readlink(entry, &link_buf, link_buf.len); + if (libc.unlink(entry) != 0) continue; + reaped += 1; + // A relative target would resolve against this editor's working + // directory, which says nothing about what the entry named. + if (state != .stale or n <= 0 or link_buf[0] != '/') continue; + var target_buf: [sun_path_len:0]u8 = undefined; + const target = std.fmt.bufPrintSentinel(&target_buf, "{s}", .{link_buf[0..@intCast(n)]}, 0) catch continue; + const t = statNoFollow(target) orelse continue; + if (t.mode & 0o170000 == 0o140000 and t.uid == libc.getuid()) _ = libc.unlink(target); + } + if (reaped != 0) log.info("reaped {d} stale registry entries under {s}", .{ reaped, svc }); +} + +/// Whether it worked, because `probe` is not allowed to find out the +/// hard way: a caller that needs the guarantee has to be able to check. +fn setNonblock(fd: c_int) bool { const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0)); - if (flags < 0) return; + if (flags < 0) return false; var o: libc.O = @bitCast(@as(u32, @bitCast(flags))); o.NONBLOCK = true; - _ = libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(o))))); + return libc.fcntl(fd, libc.F.SETFL, @as(c_int, @bitCast(@as(u32, @bitCast(o))))) >= 0; +} + +fn isNonblocking(fd: c_int) bool { + const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0)); + if (flags < 0) return false; + const o: libc.O = @bitCast(@as(u32, @bitCast(flags))); + return o.NONBLOCK; } const testing = std.testing; @@ -866,6 +984,108 @@ test "a name that is not one path component is no address at all" { try testing.expect(socketPath(&buf, "/run", "a\x00b") == 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; + + var paths: [5][sun_path_len:0]u8 = undefined; + const live_sock = try std.fmt.bufPrintSentinel(&paths[0], "{s}/live.sock", .{svc}, 0); + const dead_sock = try std.fmt.bufPrintSentinel(&paths[1], "{s}/dead.sock", .{svc}, 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); + defer { + for ([_][:0]const u8{ live_sock, dead_sock, live, dead, stranger }) |p| _ = libc.unlink(p); + _ = libc.rmdir(svc); + } + + 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)); + + // Bound and then dropped: the file stays, and nobody answers it — + // exactly what an aborted test leaves behind. + const abandoned = bindSocket(dead_sock); + try testing.expect(abandoned >= 0); + _ = libc.close(abandoned); + + try testing.expectEqual(@as(c_int, 0), libc.symlink(live_sock, live)); + try testing.expectEqual(@as(c_int, 0), libc.symlink(dead_sock, dead)); + // 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 = "" }); + + // The guarantee itself, asserted rather than inferred from the fact + // that the test finished: if a probe socket ever stops being + // non-blocking the connect below parks instead of failing, and a + // parked test costs whoever is building far more than a red one. + const checking = libc.socket(libc.AF.UNIX, probe_socket_kind, 0); + try testing.expect(checking >= 0); + if (comptime darwin) try testing.expect(setNonblock(checking)); + try testing.expect(isNonblocking(checking)); + _ = libc.close(checking); + + // The listener's backlog is filled before anything is asked, because + // a full backlog is the one place a blocking connect parks forever + // (`unix_wait_for_peer`, no timeout) and a sweep that only answers + // while nobody is queued is the sweep that hangs a build. Nothing + // below accepts any of these, so the queue stays full throughout. + var queued: [8]c_int = @splat(-1); + defer for (queued) |fd| { + if (fd >= 0) _ = libc.close(fd); + }; + for (&queued) |*slot| { + const fd = libc.socket(libc.AF.UNIX, probe_socket_kind, 0); + if (fd < 0) break; + if (comptime darwin) _ = setNonblock(fd); + var addr: libc.sockaddr.un = .{ .path = @splat(0) }; + @memcpy(addr.path[0 .. live_sock.len + 1], live_sock[0 .. live_sock.len + 1]); + _ = libc.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))); + slot.* = fd; + } + + const started = transport.nowMs(); + try testing.expectEqual(Probe.live, probe(live)); + try testing.expectEqual(Probe.stale, probe(dead)); + + sweepRegistry(testing.io, svc); + + // Promptly, and not "eventually": a blocking probe never comes back + // at all, so any wall-clock bound at all is the assertion that + // matters. A second is several thousand times what three connects + // and a readdir cost. + try testing.expect(transport.nowMs() - started < 1000); + + try testing.expect(statNoFollow(dead) == null); + try testing.expect(statNoFollow(dead_sock) == null); + try testing.expect(statNoFollow(live) != null); + try testing.expect(statNoFollow(live_sock) != null); + try testing.expect(statNoFollow(stranger) != 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 "one connection's buffers are sized from the one msize constant" { try testing.expect(msize >= ninep.min_msize); try testing.expectEqual(@as(u32, msize), Runner.msize); @@ -1102,24 +1322,41 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes) ?*Listene return listener; } -pub fn exportPaneEnv(listener: ?*const Listener, serial: u32, forward_look: bool) void { - _ = unsetenv("PARDES_FORWARD_LOOK"); +/// 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. +pub fn exportPaneEnv(listener: ?*const Listener, serial: u32, adopts: bool) void { + var announced = false; + if (adopts) announcing: { + var buf: [16]u8 = undefined; + const text = std.fmt.bufPrintSentinel(&buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}, 0) catch + break :announcing; + announced = setenv("PARDES_PID", text, 1) == 0; + } + if (!announced) _ = unsetenv("PARDES_PID"); + if (listener) |l| exporting: { var sock: [sun_path_len]u8 = undefined; const path = std.fmt.bufPrintSentinel(&sock, "{s}", .{l.path()}, 0) catch break :exporting; var buf: [16]u8 = undefined; const id = std.fmt.bufPrintSentinel(&buf, "{d}", .{serial}, 0) catch break :exporting; if (setenv("PARDES_9P", path, 1) != 0) break :exporting; - if (setenv("PARDES_PANE", id, 1) != 0) break :exporting; - if (setenv("PARDES_FORWARD_LOOK", if (forward_look) "1" else "0", 1) == 0) return; + if (setenv("PARDES_PANE", id, 1) == 0) return; } _ = unsetenv("PARDES_9P"); _ = unsetenv("PARDES_PANE"); - _ = setenv("PARDES_FORWARD_LOOK", "0", 1); } -test "9P shell environment preserves identity when nested Look forwarding is disabled" { - const names = [_][*:0]const u8{ "XDG_RUNTIME_DIR", "HOME", "PARDES_9P", "PARDES_PANE", "PARDES_FORWARD_LOOK" }; +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.dupeZ(u8, std.mem.span(old)); @@ -1146,17 +1383,32 @@ test "9P shell environment preserves identity when nested Look forwarding is dis const path = "/tmp/pardes-example.sock"; @memcpy(listener.path_buf[0..path.len], path); listener.path_len = path.len; + var own: [16]u8 = undefined; + const own_pid = try std.fmt.bufPrint(&own, "{d}", .{@as(u32, @intCast(libc.getpid()))}); + + // 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. exportPaneEnv(listener, 7, false); try testing.expectEqualStrings(path, std.mem.span(libc.getenv("PARDES_9P").?)); try testing.expectEqualStrings("7", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expectEqualStrings("0", std.mem.span(libc.getenv("PARDES_FORWARD_LOOK").?)); + try testing.expect(libc.getenv("PARDES_PID") == null); + exportPaneEnv(listener, 8, true); try testing.expectEqualStrings("8", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expectEqualStrings("1", std.mem.span(libc.getenv("PARDES_FORWARD_LOOK").?)); + try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + + // 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. + exportPaneEnv(null, 0, true); + try testing.expect(libc.getenv("PARDES_9P") == null); + try testing.expect(libc.getenv("PARDES_PANE") == null); + try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + exportPaneEnv(null, 0, false); try testing.expect(libc.getenv("PARDES_9P") == null); try testing.expect(libc.getenv("PARDES_PANE") == null); - try testing.expectEqualStrings("0", std.mem.span(libc.getenv("PARDES_FORWARD_LOOK").?)); + try testing.expect(libc.getenv("PARDES_PID") == null); } pub const Client = struct { diff --git a/src/builtins.zig b/src/builtins.zig index 39d70e5d..aa2b2d6d 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -137,6 +137,14 @@ pub const registry = struct { unreachable; } + /// Does this builtin say its own name on the message row before it runs? + /// The ones that own that row themselves declare `quiet` and do not. + pub fn announces(b: Builtin()) bool { + inline for (manualBuiltinList(), 0..) |T, i| + if (@intFromEnum(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); + return true; // a setting builtin changes something invisible; say so + } + pub fn dispatch(b: Builtin(), c: Ctx) void { inline for (manualBuiltinList(), 0..) |T, i| if (@intFromEnum(b) == i) return T.run(c); @@ -259,6 +267,7 @@ pub const Unmount = struct { pub const Msg = struct { pub const takes_arg = true; + pub const quiet = true; // it IS the message row pub fn run(c: Ctx) void { if (c.arg) |text| c.p.setMessage(c.id, text) @@ -542,11 +551,15 @@ pub const LocationsConfig = struct { pub const output: OutputTraits = .{ .name = "+LocationsConfig" }; pub fn run(c: Ctx) void { - const next = c.p.locations_config.parse(c.arg orelse "") catch |err| { + const argument = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const next = c.p.locations_config.parse(argument) catch |err| { c.p.reportError(c.id, "LocationsConfig", err); return; }; c.p.locations_config = next; + // Bare, it is a question, and the window is the answer. With arguments + // it is a setting, and a setting that opens a window is noise. + if (argument.len != 0) return; report(c) catch |err| c.p.reportError(c.id, "LocationsConfig", err); } diff --git a/src/config.zig b/src/config.zig index 440549b3..3169b20c 100644 --- a/src/config.zig +++ b/src/config.zig @@ -71,6 +71,7 @@ pub const leader_path = paths: { .FocusTint = null, .ColumnTags = null, .SyntaxBold = null, + .Verbose = null, .TreeContextTagStyle = null, .Wrap = "tw", .Tagbottom = "tb", @@ -224,10 +225,10 @@ pub const tty_filter_min_contrast: f64 = 1.5; pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill"; -pub const pane_builtins_str = "Tty Del Collapse"; -pub const pdf_pane_builtins_str = "Tty Del PdfSections PdfTint Collapse"; -pub const file_pane_builtins_str = "Save Tty Del Collapse"; -pub const terminal_pane_builtins_str = "Tty Save Del Mode Filter Collapse"; +pub const pane_builtins_str = "Tty Collapse Del"; +pub const pdf_pane_builtins_str = "Tty PdfSections PdfTint Collapse Del"; +pub const file_pane_builtins_str = "Save Tty Collapse Del"; +pub const terminal_pane_builtins_str = "Tty Save Mode Filter Collapse Del"; // Each mode badge is one codepoint. pub const tag_normal = " "; @@ -540,6 +541,8 @@ pub const Runtime = struct { focus_tint: bool = true, column_tags: bool = true, syntax_bold: bool = false, + /// Builtins announce themselves on the message row. + verbose: bool = true, window_opacity: u8 = 100, window_blur: u8 = 0, window_opacity_pending: bool = true, @@ -637,7 +640,7 @@ pub const Runtime = struct { pub const Capability = std.meta.FieldEnum(Capabilities); - pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, column_tags, syntax_bold }; + pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, column_tags, syntax_bold, verbose }; pub const Scene = std.meta.FieldEnum(layout.SceneEffect); pub const Action = union(enum) { @@ -682,6 +685,7 @@ pub const Runtime = struct { .{ .word = "FocusTint", .action = .{ .toggle = .focus_tint } }, .{ .word = "ColumnTags", .action = .{ .toggle = .column_tags } }, .{ .word = "SyntaxBold", .action = .{ .toggle = .syntax_bold } }, + .{ .word = "Verbose", .action = .{ .toggle = .verbose } }, .{ .word = "Theme", .action = .theme }, .{ .word = "Shell", .action = .shell }, .{ .word = "Font", .action = .font, .availability = .font_picker }, @@ -761,15 +765,10 @@ pub const Runtime = struct { pub fn apply(state: *Runtime, setting: Setting, argument: ?[]const u8) bool { switch (setting.action) { + // Every toggle names a bool field of its own, so one line covers + // all of them and a new toggle needs no arm here. .toggle => |field| switch (field) { - .colors => state.colors = !state.colors, - .wrap => state.wrap = !state.wrap, - .tree_context_tag_style => state.tree_context_tag_style = !state.tree_context_tag_style, - .tag_bottom => state.tag_bottom = !state.tag_bottom, - .debug => state.debug = !state.debug, - .focus_tint => state.focus_tint = !state.focus_tint, - .column_tags => state.column_tags = !state.column_tags, - .syntax_bold => state.syntax_bold = !state.syntax_bold, + inline else => |f| @field(state, @tagName(f)) = !@field(state, @tagName(f)), }, .shell => { const value = std.mem.trim(u8, argument orelse return false, " \t\r\n"); @@ -835,46 +834,42 @@ pub const Runtime = struct { return findAction(.{ .transition = transition }).?.word; } + /// Each line reads as the command that would set it: the word, then the + /// value you would type after it. No colons, no units — `WindowOpacity 70` + /// is both what Config prints and what you write back. pub fn writeReport(out: *std.Io.Writer, context: ReportContext) !void { const state = context.state; var wrote_transition = false; for (settings) |setting| switch (setting.action) { .toggle => |field| { const value = switch (field) { - .colors => state.colors, - .wrap => state.wrap, - .tree_context_tag_style => state.tree_context_tag_style, - .tag_bottom => state.tag_bottom, - .debug => state.debug, - .focus_tint => state.focus_tint, - .column_tags => state.column_tags, - .syntax_bold => state.syntax_bold, + inline else => |f| @field(state, @tagName(f)), }; - try out.print("{s}: {s}\n", .{ setting.word, onOff(value) }); + try out.print("{s} {s}\n", .{ setting.word, onOff(value) }); }, - .theme => try out.print("{s}: {s}\n", .{ setting.word, context.theme_name }), + .theme => try out.print("{s} {s}\n", .{ setting.word, context.theme_name }), .window_opacity => { if (setting.enabled(context.capabilities)) - try out.print("{s}: {d}%{s}\n", .{ + try out.print("{s} {d}{s}\n", .{ setting.word, state.window_opacity, if (state.window_opacity_pending) " (pending)" else "", }) else - try out.print("{s}: unsupported\n", .{setting.word}); + try out.print("{s} unsupported\n", .{setting.word}); }, .window_blur => { if (setting.enabled(context.capabilities)) - try out.print("{s}: {d}%\n", .{ setting.word, state.window_blur }) + try out.print("{s} {d}\n", .{ setting.word, state.window_blur }) else - try out.print("{s}: unsupported\n", .{setting.word}); + try out.print("{s} unsupported\n", .{setting.word}); }, .shell => { const chosen = state.shell.requested.get(); try out.print( - "{s} requested (new panes): {s}{s}\n" ++ - "{s} effective (last spawn): {s}\n" ++ - "{s} pending: {s}\n", + "{s} requested (new panes) {s}{s}\n" ++ + "{s} effective (last spawn) {s}\n" ++ + "{s} pending {s}\n", .{ setting.word, if (chosen.len == 0) context.compiled_default_shell else chosen, @@ -887,18 +882,18 @@ pub const Runtime = struct { ); }, .font => if (!setting.enabled(context.capabilities)) - try out.print("{s}: unsupported\n", .{setting.word}) + try out.print("{s} unsupported\n", .{setting.word}) else { if (state.font.requested_size_hundredths == 0) - try out.print("{s} requested size: unchanged\n", .{setting.word}) + try out.print("{s} requested size unchanged\n", .{setting.word}) else - try out.print("{s} requested size: {d}.{d:0>2}\n", .{ setting.word, state.font.requested_size_hundredths / 100, state.font.requested_size_hundredths % 100 }); + try out.print("{s} requested size {d}.{d:0>2}\n", .{ setting.word, state.font.requested_size_hundredths / 100, state.font.requested_size_hundredths % 100 }); try out.print( - "{s} requested: {s}\n" ++ - "{s} requested path: {s}\n" ++ - "{s} effective: {s}\n" ++ - "{s} pending: {s}\n" ++ - "{s} effective size: {d}.{d:0>2} {s}\n", + "{s} requested {s}\n" ++ + "{s} requested path {s}\n" ++ + "{s} effective {s}\n" ++ + "{s} pending {s}\n" ++ + "{s} effective size {d}.{d:0>2} {s}\n", .{ setting.word, shown(state.font.requested_name.get()), @@ -916,28 +911,28 @@ pub const Runtime = struct { ); }, .tagline_size => if (!context.capabilities.tagline_font_size) - try out.print("{s}: unsupported\n", .{setting.word}) + try out.print("{s} unsupported\n", .{setting.word}) else if (!setting.enabled(context.capabilities)) - try out.print("{s}: {d}% (build-time only)\n", .{ setting.word, state.font.tagline_percent }) + try out.print("{s} {d} (build-time only)\n", .{ setting.word, state.font.tagline_percent }) else - try out.print("{s}: {d}%\n", .{ setting.word, state.font.tagline_percent }), + try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), .transition => { if (wrote_transition) continue; wrote_transition = true; if (!setting.enabled(context.capabilities)) - try out.writeAll("Panel transition: unsupported\n") + try out.writeAll("Panel transition unsupported\n") else - try out.print("Panel transition: {s}\n", .{transitionSettingName(state.panel_transition)}); + try out.print("Panel transition {s}\n", .{transitionSettingName(state.panel_transition)}); }, .scene => |effect| { if (!setting.enabled(context.capabilities)) { - try out.print("{s}: unsupported\n", .{setting.word}); + try out.print("{s} unsupported\n", .{setting.word}); continue; } const enabled = switch (effect) { inline else => |field| @field(state.scene_effects, @tagName(field)), }; - try out.print("{s}: {s}\n", .{ setting.word, onOff(enabled) }); + try out.print("{s} {s}\n", .{ setting.word, onOff(enabled) }); }, }; @@ -1073,7 +1068,8 @@ pub const Runtime = struct { test "Config report observes every simple setting and all live context" { var state: Runtime = .{}; - var storage: [4096]u8 = undefined; + // Every setting, every context line: the report outgrows 4K. + var storage: [8192]u8 = undefined; const context: ReportContext = .{ .startup_config_path = "/tmp/pardes/init", .platform = "gui", @@ -1112,37 +1108,38 @@ pub const Runtime = struct { const report = storage[0..out.end]; const expected = switch (setting.action) { .toggle => |field| switch (field) { - .colors => "Colors: off\n", - .wrap => "Wrap: off\n", - .tree_context_tag_style => "TreeContextTagStyle: off\n", - .tag_bottom => "Tagbottom: on\n", - .debug => "Debug: on\n", - .focus_tint => "FocusTint: off\n", - .column_tags => "ColumnTags: off\n", - .syntax_bold => "SyntaxBold: on\n", + .colors => "Colors off\n", + .wrap => "Wrap off\n", + .tree_context_tag_style => "TreeContextTagStyle off\n", + .tag_bottom => "Tagbottom on\n", + .debug => "Debug on\n", + .focus_tint => "FocusTint off\n", + .column_tags => "ColumnTags off\n", + .syntax_bold => "SyntaxBold on\n", + .verbose => "Verbose off\n", }, - .shell => "Shell requested (new panes): fish\n", - .tagline_size => "TaglineSize: 73%\n", - .window_opacity => "WindowOpacity: 85% (pending)\n", - .window_blur => "WindowBlur: 40%\n", + .shell => "Shell requested (new panes) fish\n", + .tagline_size => "TaglineSize 73\n", + .window_opacity => "WindowOpacity 85 (pending)\n", + .window_blur => "WindowBlur 40\n", .transition => |transition| switch (transition) { .off => unreachable, - .slide => "Panel transition: PanelSlide\n", - .zoom => "Panel transition: PanelZoom\n", - .dissolve => "Panel transition: PanelDissolve\n", - .ascii => "Panel transition: PanelAscii\n", - .vertical => "Panel transition: PanelVertical\n", - .edges => "Panel transition: PanelEdges\n", - .fall => "Panel transition: PanelFall\n", - .wave => "Panel transition: PanelWave\n", - .curtain => "Panel transition: PanelCurtain\n", - .scramble => "Panel transition: PanelScramble\n", - .typewriter => "Panel transition: PanelType\n", + .slide => "Panel transition PanelSlide\n", + .zoom => "Panel transition PanelZoom\n", + .dissolve => "Panel transition PanelDissolve\n", + .ascii => "Panel transition PanelAscii\n", + .vertical => "Panel transition PanelVertical\n", + .edges => "Panel transition PanelEdges\n", + .fall => "Panel transition PanelFall\n", + .wave => "Panel transition PanelWave\n", + .curtain => "Panel transition PanelCurtain\n", + .scramble => "Panel transition PanelScramble\n", + .typewriter => "Panel transition PanelType\n", }, .scene => |effect| switch (effect) { - .crt => "Crt: on\n", - .ripple => "Ripple: on\n", - .glitch => "Glitch: on\n", + .crt => "Crt on\n", + .ripple => "Ripple on\n", + .glitch => "Glitch on\n", }, .theme, .font => unreachable, }; @@ -1163,15 +1160,15 @@ pub const Runtime = struct { try writeReport(&out, context); const report = storage[0..out.end]; for ([_][]const u8{ - "Theme: acme\n", - "WindowOpacity: 85%\n", - "Font requested size: 18.50\n", - "Font requested: Wanted Mono\n", - "Font requested path: /fonts/wanted.ttf\n", - "Font effective: Effective Mono\n", - "Font pending: on\n", - "Font effective size: 13.75 points\n", - "TaglineSize: 82%\n", + "Theme acme\n", + "WindowOpacity 85\n", + "Font requested size 18.50\n", + "Font requested Wanted Mono\n", + "Font requested path /fonts/wanted.ttf\n", + "Font effective Effective Mono\n", + "Font pending on\n", + "Font effective size 13.75 points\n", + "TaglineSize 82\n", "Startup config: /tmp/pardes/init\n", "Platform: gui\n", "Compiled default shell: /bin/sh\n", @@ -1197,23 +1194,23 @@ pub const Runtime = struct { out = .fixed(&storage); try writeReport(&out, defaults_context); const defaults_report = storage[0..out.end]; - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowOpacity: unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowOpacity unsupported\n") != null); try std.testing.expect(!find("WindowOpacity").?.enabled(defaults_context.capabilities)); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowBlur: unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowBlur unsupported\n") != null); try std.testing.expect(!find("WindowBlur").?.enabled(defaults_context.capabilities)); try std.testing.expect(find("WindowOpacity").?.enabled(context.capabilities)); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell requested (new panes): /bin/sh (default)\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell effective (last spawn): (none)\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell pending: on\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell requested (new panes) /bin/sh (default)\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell effective (last spawn) (none)\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell pending on\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Startup config: no per-user config path\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "GUI shader source:") == null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font requested:") == null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Panel transition: off\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Crt: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Ripple: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Glitch: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "TaglineSize: unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font requested") == null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Panel transition off\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Crt unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Ripple unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Glitch unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "TaglineSize unsupported\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Look hover delay: off\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Native images: off\n") != null); @@ -1223,8 +1220,8 @@ pub const Runtime = struct { out = .fixed(&storage); try writeReport(&out, defaults_context); const web_report = storage[0..out.end]; - try std.testing.expect(std.mem.indexOf(u8, web_report, "Panel transition: unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, web_report, "TaglineSize: 100% (build-time only)\n") != null); + try std.testing.expect(std.mem.indexOf(u8, web_report, "Panel transition unsupported\n") != null); + try std.testing.expect(std.mem.indexOf(u8, web_report, "TaglineSize 100 (build-time only)\n") != null); } }; diff --git a/src/fs-help.txt b/src/fs-help.txt index a0a84b28..1e5d64c2 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -2,41 +2,43 @@ Pardes control filesystem ========================= README this guide index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name -ctl write commands; read the serials the last command made or touched -new reading it creates one empty pane and answers its serial +status pid, version and pane count +look write a line: a right click on it at the active pane; read: the serials it touched +exec write a line: a middle click, an editor command word or a shell line; read the same log one line per editor event (new/del/rename/save ); reads wait screen rendered screen as JSON, frozen from open to close listeners the session's dial addresses -pane// name body tag ctl addr data xdata sel errors event, and pty/ for terminals +pane/ mkdir makes a pane, rmdir closes it +pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll + errors event look exec, and pty/ for terminals os/ the host filesystem src/ the editor's own sources, only in a -Dembed-sources=true build -Commands, on /ctl (applied at the active pane) or on pane//ctl (at that pane): - look TEXT a right click: open a file, a file:12 location, a directory, a URL - exec TEXT a middle click: an editor command word (Save Del New Newcol Mount Unmount - Dump Restore Msg Find Grep Tty ...), or a shell command for the pane's terminal Below, $m is the mount point (PARDES_MOUNT in a Tty9p shell; 9ns and 9p work too): cat $m/index which panes exist - n=$(cat $m/new) make a pane, remember its serial - echo 'look /etc/hosts:3' > $m/ctl; cat $m/ctl open a file, see the pane it went to - printf 'text\n' > $m/pane/$n/body append to a pane (>| truncates first) + mkdir $m/pane/x; n=$(awk 'END{print $1}' $m/index) make a pane, take its serial + echo /etc/hosts:3 > $m/look; cat $m/look open a file, see the pane it went to + printf 'text\n' > $m/pane/$n/body append to a pane (>| truncates first) cat $m/pane/$n/name; echo notes.txt > $m/pane/$n/name read, then rename - echo 'exec Save' > $m/pane/$n/ctl save it (exec Del closes it) - echo 'exec Msg hello' > $m/ctl show text in the editor + echo Save > $m/pane/$n/exec save it; rmdir $m/pane/$n closes it + echo 'Msg hello' > $m/exec show text in the editor echo '#0,#5' > $m/pane/$n/addr; echo NEW > $m/pane/$n/data replace bytes 0..5 - echo 'dot=addr' > $m/pane/$n/ctl; cat $m/pane/$n/sel select the range, read it + cp $m/pane/$n/addr $m/pane/$n/dot; cat $m/pane/$n/sel select the range, read it + cat $m/pane/$n/dirty; echo 0 > $m/pane/$n/dirty is it modified? say it is not cat $m/log block until a pane is made, renamed, saved or closed cat $m/pane/$n/event hold it open to own that pane's clicks - echo 'exec' > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT + echo exec > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT Pitfalls, one each: - Every open of new makes another pane, so `cat $m/new` twice makes two. - ls, stat and find create nothing; reading log, event or pty/data blocks until something happens. - exec Del closes a pane even when it is dirty; index shows the dirty flag first. - look and exec are lowercase verbs; the words after exec are the editor's capitalized commands. - ctl also takes acme's addr verbs (addr=dot dot=addr limit=addr clean dirty get show ...), one per line. + Only mkdir in pane/ makes a pane; ls, stat, find and every read create nothing. + Panes are named by the serial the editor gives them, not by the name mkdir asked for. + rmdir closes a pane even when it is dirty; index and pane//dirty show the flag. + addr, dot and limit read the same pair of offsets they take, so cp between them works. + dirty, mark and scroll read "0" or "1" and take "0" or "1"; truncating limit lifts it. Writing body appends; open it with truncation to replace; writes are whole UTF-8 sequences. + Truncating tag clears the part you may edit; truncating dot or addr empties it. A terminal's body is a history snapshot frozen per open; pty/data is the live stream. screen is frozen per open handle as well; reopen it for a fresh frame. - A command that fails is reported in the editor, not as a write error; a malformed line fails the write. + A failing command is reported in the editor, not as a write error; a bad line fails the write. + pane//ctl reads acme's window status line and takes one verb, get, which reloads from disk. diff --git a/src/fs.zig b/src/fs.zig index 7f416440..7cb08980 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -260,12 +260,13 @@ test "unmount refuses pane paths inherited directories and queued save targets" } gpa.free(pane.file.?.path); pane.file.?.path = try gpa.dupe(u8, "/n/peer2/file"); - const shell = try p.newShell(1, "/n/peer/dir"); - p.setCwd(1, "/n/peer/dir"); + 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(1, "/"); + 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")); @@ -1261,10 +1262,10 @@ pub const Namespace = struct { /// The editor-wide event stream, recorded only while /log is held open. log: tree.events.Queue = .{}, log_readers: u16 = 0, - /// What the last ctl command created or touched, answered by reading /ctl. + /// What the last look or exec created or touched, answered by reading + /// either of those files. results: [MAX_PANES]u32 = undefined, results_len: u8 = 0, - results_valid: bool = false, /// Process start, the mtime of everything that has no edit time of its own. started: u32 = 0, diff --git a/src/host_io.zig b/src/host_io.zig index 212c23b4..fb09fcc7 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -874,6 +874,9 @@ pub fn forkShell( if (fs == null) return error.SessionSocketRequired; break :blk try @import("linux/v9fs.zig").helperPath(&helper_buf); } else null; + // The last argument is whether this session takes its children's Looks — + // every session does but a `--nested` one, and a fork with no core at all + // (the tests below) is nobody's parent. ninep_io.exportPaneEnv( fs, if (core) |c| (if (c.panes[pane]) |pn| pn.serial else 0) else 0, diff --git a/src/main.zig b/src/main.zig index 4b1910bd..1cbdf24c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -112,6 +112,16 @@ const nested_text = \\ ; +/// $PARDES_PID named a live editor, so this shell IS inside one, but the Look +/// never got there. Saying so beats quietly opening the second editor that +/// $PARDES_PID exists to prevent. +const unreachable_text = + \\pardes: this shell is inside pardes, but that session did not take the + \\file. Check that it is still running, or pass --nested to start a second + \\editor in here anyway. + \\ +; + // The browser runtime calls a C main (exported below); everything else keeps // the std.process.Init entry. pub const main = if (is_emscripten) webMain else nativeMain; @@ -260,6 +270,10 @@ fn nativeMain(init: std.process.Init) !void { } } opts.tty_only = explicit_tty or session_only; + // The real bare-tty startup wants the editor half present from the first + // frame, so it names that layout; a core booted for a test names none and + // gets the raw shell by itself. + if (opts.tty_only) opts.boot = .tty; opts.mounts = mounts[0..mounts_len]; if (detach != null and attach != null) badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); @@ -272,31 +286,60 @@ fn nativeMain(init: std.process.Init) !void { if (opts.mounts.len != 0 and attach != null) badArgs(init.io, "--mount configures a session's own core, and --attach has none of its own", .{}); if (!new_session and !opts.nested and detach == null and attach == null) forwarding: { - const enabled = std.c.getenv("PARDES_FORWARD_LOOK") orelse break :forwarding; - if (!std.mem.eql(u8, std.mem.span(enabled), "1")) break :forwarding; - const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :forwarding); - ninep_io.Client.validateDial(dial) catch break :forwarding; - const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse break :forwarding); - for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :forwarding; - const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :forwarding; - if (serial == 0) break :forwarding; - var ctl_buf: [64]u8 = undefined; - const ctl = try std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}); + // Am I inside a pardes at all? That is $PARDES_PID and nothing else — + // one variable, exported by every session that means to take its + // children's Looks, so a session that could not open a socket is still + // recognisably the session this shell is inside. A pid naming no live + // process is a shell that outlived its editor (a daemon started from a + // pane, a stale environment carried into a new terminal), which is not + // nested at all. + const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding); + const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding; + if (pid <= 0 or std.c.kill(pid, @enumFromInt(0)) != 0) break :forwarding; + + // Can I reach it? That is the other two, and it is a separate answer. + const Parent = struct { dial: []const u8, serial: u32 }; + const found: ?Parent = reaching: { + const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :reaching null); + ninep_io.Client.validateDial(dial) catch break :reaching null; + const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse break :reaching null); + for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :reaching null; + const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :reaching null; + if (serial == 0) break :reaching null; + break :reaching .{ .dial = dial, .serial = serial }; + }; + const parent = found orelse { + try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); + std.process.exit(1); + }; + // The pane's `look` file: one line, and the line is the clicked text + // itself, which is what a right click in that pane would have been. + var look_buf: [64]u8 = undefined; + const look = try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); const word = positional orelse { var tag_buf: [64]u8 = undefined; - const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{serial}); - const contents = ninep_io.Client.read(arena, dial, tag, tag) catch break :forwarding; + const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); + const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch { + try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); + std.process.exit(1); + }; arena.free(contents); try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); std.process.exit(1); }; + // A word this launch cannot turn into a path is an argument problem + // rather than a nesting one: fall through and let the session that + // starts report it, the way `pardes typo` outside pardes does. if (std.mem.indexOfAny(u8, word, "\r\n") != null) break :forwarding; const target = @import("look.zig").parsePathLine(word); var realbuf: [4096]u8 = undefined; const path = if (pardes.filesystem.isVirtual(target.path)) target.path else (pardes.filesystem.resolveOs(target.path, &realbuf) orelse break :forwarding).path; var command_buf: [8192]u8 = undefined; - const command = std.fmt.bufPrint(&command_buf, "look {s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; - ninep_io.Client.write(arena, dial, ctl, command) catch break :forwarding; + const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch break :forwarding; + ninep_io.Client.write(arena, parent.dial, look, command) catch { + try std.Io.File.stderr().writeStreamingAll(init.io, unreachable_text); + std.process.exit(1); + }; return; } if (positional) |a| { diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index f7642b9e..566e2364 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -255,17 +255,25 @@ test "the address language, form by form" { try testing.expectEqual(@as(u32, 6), p.fs.panes[0].addr.q0); // the `o` in "two" try testing.expectEqual(@as(u32, 7), p.fs.panes[0].addr.q1); + // limit is its own file: copying addr onto it bounds the search, and + // truncating it lifts the bound again. + const limit = Node.of(serial, .limit); _ = th.wr(p, addr, "1"); - _ = th.wr(p, Node.of(serial, .ctl), "limit=addr\n"); + try testing.expectEqualStrings("", th.rd(p, limit, 0, 64).bytes); + var copied: [64]u8 = undefined; + const pair = th.rd(p, addr, 0, 64).bytes; + @memcpy(copied[0..pair.len], pair); + _ = th.wr(p, limit, copied[0..pair.len]); + try testing.expectEqual(@as(u32, 4), p.fs.panes[0].limit.?.q1); + try testing.expectEqualStrings(" 0 4 ", th.rd(p, limit, 0, 64).bytes); _ = th.wr(p, addr, "#0"); try testing.expectEqual(E.INVAL, th.wr(p, addr, "/three/").errno()); - _ = th.wr(p, Node.of(serial, .ctl), "clean\n"); - _ = th.call(p, .{ .tag = 6, .op = .open, .node = Node.of(serial, .ctl) }); + _ = th.call(p, .{ .tag = 6, .op = .setattr, .node = limit, .truncate = true }); try testing.expect(p.fs.panes[0].limit == null); _ = th.wr(p, addr, "#0"); try testing.expectEqual(Status.ok, th.wr(p, addr, "/three/").reply.status); - for ([_][]const u8{ "zzz", "#", "//", "/nomatch/", "1 2", "99", "/a\\" }) |bad| { + for ([_][]const u8{ "zzz", "#", "//", "/nomatch/", "1 2 3", "99", "/a\\" }) |bad| { _ = th.wr(p, addr, "#0"); try testing.expectEqual(E.INVAL, th.wr(p, addr, bad).errno()); } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index d61ebf75..c213ece5 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1,6 +1,9 @@ -//! The two ctl files. `look TEXT` is a right click and `exec TEXT` a middle -//! click in the editor's own command language; a pane's ctl adds the addr -//! verbs. Reading /ctl answers the serials the last command made or touched. +//! The command files and the status they answer. Writing a line to `look` is +//! a right click on it and writing one to `exec` a middle click, at the +//! active pane from the root and at that pane from /pane//; reading either +//! answers the serials the last command made or touched. /status reports the +//! editor, and a pane's ctl its acme status line and the one verb, `get`, +//! that no file of its own would say any better. const std = @import("std"); const pardes = @import("../pardes.zig"); const panes = @import("../panes.zig"); @@ -16,36 +19,6 @@ const Req = tree.Req; const Reply = tree.Reply; const E = tree.E; -const Verb = enum { - @"addr=dot", - clean, - cleartag, - dirty, - @"dot=addr", - get, - @"limit=addr", - mark, - nomark, - noscroll, - scroll, - show, -}; - -fn verbIs(line: []const u8, word: []const u8) bool { - if (!std.mem.startsWith(u8, line, word)) return false; - return line.len == word.len or line[word.len] == ' ' or line[word.len] == '\t'; -} - -/// The text after `look` or `exec`, or null when the line is not that verb. -/// Control characters other than tab are refused. -fn textAfter(line: []const u8, verb: []const u8) ?[]const u8 { - if (!verbIs(line, verb)) return null; - const text = std.mem.trim(u8, line[verb.len..], " \t"); - if (text.len == 0) return ""; - for (text) |c| if (c < ' ' and c != '\t') return ""; - return text; -} - // ---- which panes a command made or touched ---- const Serials = struct { @@ -96,37 +69,49 @@ fn run(p: *Pardes, id: usize, exec: bool, text: []const u8) void { noteResult(p, if (exec) context else activeSerial(p) orelse return); } -fn beginResults(p: *Pardes) void { - p.fs.results_len = 0; - p.fs.results_valid = true; -} - -// ---- /ctl ---- +// ---- look and exec ---- -pub fn writeRoot(p: *Pardes, req: Req) Reply { +/// One command per line, checked whole before any line runs: a line is the +/// clicked text itself, so it may not be empty or carry control characters. +/// A null `serial` clicks at whichever pane is active as each line runs, +/// which is what the root's own look and exec mean; a serial stays put. +pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool) Reply { for ([2]bool{ false, true }) |apply| { - if (apply) beginResults(p); + if (apply) p.fs.results_len = 0; var it = std.mem.splitScalar(u8, req.data, '\n'); while (it.next()) |raw| { - const line = std.mem.trim(u8, raw, " \t\r"); - if (line.len == 0) continue; - const exec = verbIs(line, "exec"); - const text = textAfter(line, if (exec) "exec" else "look") orelse return Reply.fail(req.tag, E.INVAL); - if (text.len == 0) return Reply.fail(req.tag, E.INVAL); + const text = std.mem.trim(u8, raw, " \t\r"); + if (text.len == 0) continue; + for (text) |c| if (c < ' ' and c != '\t') return Reply.fail(req.tag, E.INVAL); if (!apply) continue; - if (p.panes[p.active] == null) return Reply.fail(req.tag, E.NOENT); - run(p, p.active, exec, text); + const id = if (serial) |s| p.paneBySerial(s) orelse break else p.active; + if (p.panes[id] == null) return Reply.fail(req.tag, E.NOENT); + run(p, id, exec, text); } } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } -pub fn rootText(p: *Pardes, buf: []u8) []const u8 { - var w = std.Io.Writer.fixed(buf); - if (p.fs.results_valid) { - for (p.fs.results[0..p.fs.results_len]) |serial| w.print("{d}\n", .{serial}) catch break; - return w.buffered(); +pub fn resultsLen(p: *Pardes) u64 { + var n: u64 = 0; + for (p.fs.results[0..p.fs.results_len]) |serial| { + var digits: [16]u8 = undefined; + n += (std.fmt.bufPrint(&digits, "{d}\n", .{serial}) catch unreachable).len; } + return n; +} + +pub fn readResults(p: *Pardes, req: Req) Reply { + const out = p.fs.stage(p.gpa); + for (p.fs.results[0..p.fs.results_len]) |serial| + out.print(p.gpa, "{d}\n", .{serial}) catch return Reply.fail(req.tag, E.NOMEM); + return tree.stagedReply(p, req); +} + +// ---- /status ---- + +fn statusText(p: *Pardes, buf: []u8) []const u8 { + var w = std.Io.Writer.fixed(buf); var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); const pid: u32 = if (comptime pardes.hosted) @intCast(std.c.getpid()) else 0; @@ -134,13 +119,17 @@ pub fn rootText(p: *Pardes, buf: []u8) []const u8 { return w.buffered(); } -pub const root_text_cap = @max(MAX_PANES * 11, 64 + pardes.version.len); +pub const status_text_cap = 64 + pardes.version.len; + +pub fn statusLen(p: *Pardes) u64 { + var buf: [status_text_cap]u8 = undefined; + return statusText(p, &buf).len; +} -pub fn readRoot(p: *Pardes, req: Req) Reply { - var buf: [root_text_cap]u8 = undefined; - const text = rootText(p, &buf); +pub fn readStatus(p: *Pardes, req: Req) Reply { + var buf: [status_text_cap]u8 = undefined; const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM); + out.appendSlice(p.gpa, statusText(p, &buf)) catch return Reply.fail(req.tag, E.NOMEM); return tree.stagedReply(p, req); } @@ -190,74 +179,35 @@ pub fn readPane(p: *Pardes, req: Req, pane: *Pane) Reply { return tree.stagedReply(p, req); } -pub fn writePane(p: *Pardes, req: Req, serial: u32) Reply { - for ([2]bool{ false, true }) |apply| { - if (apply) beginResults(p); - var it = std.mem.splitScalar(u8, req.data, '\n'); - while (it.next()) |raw| { - const line = std.mem.trim(u8, raw, " \t\r"); - if (line.len == 0) continue; - const live = p.paneBySerial(serial) orelse if (apply) break else return Reply.fail(req.tag, E.NOENT); - const errno = paneVerb(p, live, line, apply); - if (errno != 0) return Reply.fail(req.tag, errno); - } +/// `get` is the one thing here that no file of the pane's own would say: it +/// reloads the buffer from the name it carries, wherever that name resolves. +/// Repeating it in one write would only reload the same bytes, so it runs once. +pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { + var asked = false; + var it = std.mem.splitScalar(u8, req.data, '\n'); + while (it.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0) continue; + if (!std.mem.eql(u8, line, "get")) return Reply.fail(req.tag, E.INVAL); + asked = true; + } + if (asked) { + const errno = get(p, pane); + if (errno != 0) return Reply.fail(req.tag, errno); } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } -fn paneVerb(p: *Pardes, id: usize, line: []const u8, apply: bool) u16 { - const pane = p.panes[id] orelse return E.INVAL; - const pf = &p.fs.panes[id]; - - for ([_]bool{ false, true }) |exec| if (textAfter(line, if (exec) "exec" else "look")) |text| { - if (text.len == 0) return E.INVAL; - if (apply) run(p, id, exec, text); - return 0; +fn get(p: *Pardes, pane: *Pane) u16 { + const f = pane_files.fileOf(pane) orelse return 0; + if (!panes.Output.fileTraits(f.output).saves) return 0; + const bytes = fs.read(p, f.path) catch |err| return switch (err) { + error.FileNotFound => E.NOENT, + else => E.IO, }; - const v = std.meta.stringToEnum(Verb, line) orelse return E.INVAL; - if (!apply) return 0; - - switch (v) { - .@"addr=dot" => pf.addr = pane_files.dotOf(pane), - .@"dot=addr" => { - pane_files.clampAddr(pf, pane_files.bodyOf(pane).len); - pane_files.setDot(pane, pf.addr); - }, - .@"limit=addr" => { - pane_files.clampAddr(pf, pane_files.bodyOf(pane).len); - pf.limit = pf.addr; - }, - .clean => if (pane_files.fileOf(pane)) |f| { - f.saved_revision = f.revision; - }, - .dirty => if (pane_files.fileOf(pane)) |f| { - f.saved_revision = f.revision -% 1; - }, - .cleartag => { - pane.tag_tail_len = 0; - pane.tag_init = true; - }, - .get => if (pane_files.fileOf(pane)) |f| { - if (panes.Output.fileTraits(f.output).saves) { - if (fs.read(p, f.path)) |bytes| { - panes.File.pushUndo(p, pane); - panes.File.setContent(p, f, bytes); - f.saved_revision = f.revision; - } else |err| return switch (err) { - error.FileNotFound => E.NOENT, - else => E.IO, - }; - } - }, - .mark => { - pf.nomark = false; - panes.File.pushUndo(p, pane); - }, - .nomark => pf.nomark = true, - .noscroll => pf.noscroll = true, - .scroll => pf.noscroll = false, - .show => pane_files.showOffset(pane, pane_files.dotOf(pane).q0), - } + panes.File.pushUndo(p, pane); + panes.File.setContent(p, f, bytes); + f.saved_revision = f.revision; return 0; } @@ -272,7 +222,9 @@ const withFile = th.withFile; const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; -const root_ctl = @intFromEnum(tree.TopFile.ctl); +const root_status = @intFromEnum(tree.TopFile.status); +const root_look = @intFromEnum(tree.TopFile.look); +const root_exec = @intFromEnum(tree.TopFile.exec); test "pane ctl read is index's five fields plus width in cells, font and tab width" { const gpa = testing.allocator; @@ -299,37 +251,18 @@ test "pane ctl read is index's five fields plus width in cells, font and tab wid try testing.expectEqualStrings("'it''s'", w.buffered()); } -test "every pane ctl verb, and every refusal" { +test "the pane ctl takes get, and nothing that a file of its own now answers" { const gpa = testing.allocator; const p = try withFile(gpa, "one\ntwo\n"); defer p.deinit(); - const serial = serialOf(p); - const ctl_node = Node.of(serial, .ctl); - const pane = p.panes[0].?; - const pf = &p.fs.panes[0]; - - try testing.expectEqual(Status.ok, wr(p, ctl_node, "nomark\nnoscroll\ndirty\n").reply.status); - try testing.expect(pf.nomark and pf.noscroll and pane_files.dirtyOf(pane)); - try testing.expectEqual(Status.ok, wr(p, ctl_node, "mark\nscroll\nclean\n").reply.status); - try testing.expect(!pf.nomark and !pf.noscroll and !pane_files.dirtyOf(pane)); - - _ = wr(p, ctl_node, "cleartag\n"); - try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); - - _ = wr(p, Node.of(serial, .addr), "2"); - _ = wr(p, ctl_node, "limit=addr\n"); - try testing.expectEqual(@as(u32, 4), pf.limit.?.q0); - _ = wr(p, ctl_node, "dot=addr\nshow\n"); - try testing.expectEqual(@as(i32, 1), pane.cur_row); - + const ctl_node = Node.of(serialOf(p), .ctl); for ([_][]const u8{ - "menu", "nomenu", "dump echo hi", "dumpdir /tmp", "font Go Mono", "lock", "unlock", "bogus", "DEL", - "name x.txt", "put", "del", "delete", "Look x", "Exec Save", + "menu", "nomenu", "dump echo hi", "font Go Mono", "lock", "bogus", "DEL", + "name x.txt", "put", "del", "delete", "Look x", "Exec Save", "clean", + "dirty", "cleartag", "dot=addr", "addr=dot", "show", "mark", "nomark", + "scroll", "limit=addr", "get x", "look /tmp", "exec Del", }) |bad| try testing.expectEqual(E.INVAL, wr(p, ctl_node, bad).errno()); - - try testing.expect(!pane_files.dirtyOf(pane)); - try testing.expectEqual(E.INVAL, wr(p, ctl_node, "dirty\nbogus\n").errno()); - try testing.expect(!pane_files.dirtyOf(pane)); + try testing.expect(p.paneBySerial(serialOf(p)) != null); } test "exec runs a builtin at the pane and records the pane it acted on" { @@ -338,61 +271,69 @@ test "exec runs a builtin at the pane and records the pane it acted on" { defer p.deinit(); const serial = serialOf(p); const pane = p.panes[0].?; - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec Msg from ctl\n").reply.status); - try testing.expectEqualStrings("from ctl", pane.msg[0..pane.msg_len]); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "Msg from exec\n").reply.status); + try testing.expectEqualStrings("from exec", pane.msg[0..pane.msg_len]); var expected: [16]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{serial}), rd(p, root_ctl, 0, 4096).bytes); + const own = try std.fmt.bufPrint(&expected, "{d}\n", .{serial}); + try testing.expectEqualStrings(own, rd(p, root_exec, 0, 4096).bytes); + // Either command file reads back what the last one did. + try testing.expectEqualStrings(own, rd(p, Node.of(serial, .look), 0, 4096).bytes); + try testing.expectEqual(@as(u64, own.len), call(p, .{ .tag = 1, .op = .getattr, .node = root_exec }).reply.attr.size); - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec New\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "New\n").reply.status); const made = p.panes[p.active].?; try testing.expect(made.serial != serial); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_ctl, 0, 4096).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_exec, 0, 4096).bytes); - try testing.expectEqual(Status.ok, wr(p, Node.of(made.serial, .ctl), "exec Del\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(made.serial, .exec), "Del\n").reply.status); try testing.expect(p.paneBySerial(made.serial) == null); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_ctl, 0, 4096).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_exec, 0, 4096).bytes); } -test "the root ctl reads editor status until a command runs and validates whole batches" { +test "status reads the editor, and look and exec validate whole batches" { const gpa = testing.allocator; const p = try withFile(gpa, "Msg root\n"); defer p.deinit(); - const status = rd(p, root_ctl, 0, 4096); + const status = rd(p, root_status, 0, 4096); try testing.expectEqual(Status.ok, status.reply.status); var lines = std.mem.tokenizeScalar(u8, status.bytes, '\n'); try testing.expect(std.mem.startsWith(u8, lines.next().?, "pid ")); var expected: [64]u8 = undefined; try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "version {s}", .{pardes.version}), lines.next().?); - try testing.expectEqualStrings("panes 1", lines.next().?); + var live: usize = 0; + for (p.panes) |slot| live += @intFromBool(slot != null); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "panes {d}", .{live}), lines.next().?); try testing.expect(lines.next() == null); - const stat = call(p, .{ .tag = 1, .op = .getattr, .node = root_ctl }); + const stat = call(p, .{ .tag = 1, .op = .getattr, .node = root_status }); try testing.expectEqual(@as(u64, status.bytes.len), stat.reply.attr.size); - try testing.expectEqual(@as(u16, 0o666), stat.reply.attr.mode); + try testing.expectEqual(@as(u16, 0o444), stat.reply.attr.mode); + try testing.expectEqual(E.PERM, wr(p, root_status, "anything\n").errno()); + try testing.expectEqualStrings("", rd(p, root_exec, 0, 4096).bytes); const serial = p.next_serial; - for ([_][]const u8{ "look", "exec", "look \t", "Look /virtual/index", "exec Msg a\x00b", "exec Msg x\nbogus\n", "name x", "put" }) |invalid| { - try testing.expectEqual(E.INVAL, wr(p, root_ctl, invalid).errno()); + for ([_][]const u8{ "Msg a\x00b", "Msg x\nMsg \x01y\n" }) |invalid| { + try testing.expectEqual(E.INVAL, wr(p, root_exec, invalid).errno()); try testing.expectEqual(serial, p.next_serial); } - try testing.expectEqualStrings(status.bytes, rd(p, root_ctl, 0, 4096).bytes); + // An empty write is a no-op, not a command. + try testing.expectEqual(Status.ok, wr(p, root_exec, "\n \n").reply.status); + try testing.expectEqualStrings("", rd(p, root_exec, 0, 4096).bytes); + try testing.expectEqualStrings(status.bytes, rd(p, root_status, 0, 4096).bytes); const pane = p.panes[0].?; - try testing.expectEqual(Status.ok, wr(p, root_ctl, "exec Msg hello there\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, root_exec, "Msg hello there\n").reply.status); try testing.expectEqualStrings("hello there", pane.msg[0..pane.msg_len]); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{pane.serial}), rd(p, root_ctl, 0, 4096).bytes); - - try testing.expectEqual(Status.ok, wr(p, root_ctl, "look /virtual/index\nexec New\n").reply.status); - var made: [MAX_PANES]u32 = undefined; - var n: usize = 0; - for (p.panes) |slot| if (slot) |q| if (q.serial != pane.serial) { - made[n] = q.serial; - n += 1; - }; - try testing.expectEqual(@as(usize, 2), n); - const listed = rd(p, root_ctl, 0, 4096); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n{d}\n", .{ @min(made[0], made[1]), @max(made[0], made[1]) }), listed.bytes); - const opened = p.panes[p.paneBySerial(@min(made[0], made[1])).?].?; + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{pane.serial}), rd(p, root_exec, 0, 4096).bytes); + + try testing.expectEqual(Status.ok, wr(p, root_look, "/virtual/index\n").reply.status); + const opened = p.panes[p.active].?; try testing.expectEqualStrings("/virtual/index", opened.file.?.path); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_look, 0, 4096).bytes); + + try testing.expectEqual(Status.ok, wr(p, root_exec, "New\n").reply.status); + const made = p.panes[p.active].?; + try testing.expect(made.serial != opened.serial); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{made.serial}), rd(p, root_exec, 0, 4096).bytes); } test "look opens spaced paths and locations without editing the source pane" { @@ -406,12 +347,12 @@ test "look opens spaced paths and locations without editing the source pane" { const p = try withFile(gpa, "source stays intact\n"); defer p.deinit(); const source = p.panes[0].?; - const ctl_node = Node.of(source.serial, .ctl); + const look_node = Node.of(source.serial, .look); const revision = source.file.?.revision; const undo_len = source.file.?.history.undo_len; source.cur_col = 3; - var command: [4200]u8 = undefined; - try testing.expectEqual(Status.ok, wr(p, ctl_node, try std.fmt.bufPrint(&command, "look {s}:2:3\n", .{path})).reply.status); + var clicked: [4200]u8 = undefined; + try testing.expectEqual(Status.ok, wr(p, look_node, try std.fmt.bufPrint(&clicked, "{s}:2:3\n", .{path})).reply.status); const opened = p.panes[p.active].?; try testing.expect(opened != source); try testing.expectEqualStrings(path, opened.file.?.path); @@ -423,14 +364,14 @@ test "look opens spaced paths and locations without editing the source pane" { try testing.expectEqual(undo_len, source.file.?.history.undo_len); try testing.expectEqual(@as(i32, 3), source.cur_col); var expected: [16]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_ctl, 0, 4096).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_look, 0, 4096).bytes); p.active = 0; - try testing.expectEqual(Status.ok, wr(p, root_ctl, try std.fmt.bufPrint(&command, "look {s}:3:2\n", .{path})).reply.status); + try testing.expectEqual(Status.ok, wr(p, root_look, try std.fmt.bufPrint(&clicked, "{s}:3:2\n", .{path})).reply.status); try testing.expect(p.panes[p.active].? == opened); try testing.expectEqual(@as(i32, 2), opened.cur_row); try testing.expectEqual(@as(i32, 1), opened.cur_col); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_ctl, 0, 4096).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_look, 0, 4096).bytes); } test "look validates the whole batch before opening virtual files" { @@ -438,17 +379,17 @@ test "look validates the whole batch before opening virtual files" { const p = try withFile(gpa, "source\n"); defer p.deinit(); const source = p.panes[0].?; - const ctl_node = Node.of(source.serial, .ctl); + const look_node = Node.of(source.serial, .look); const serial = p.next_serial; for ([_][]const u8{ - "look", "look \t", "look /virtual/index\x00ignored", "look /virtual/index\nbogus\n", + "/virtual/index\x00ignored", "/virtual/index\n/virtual/\x01index\n", }) |invalid| { - try testing.expectEqual(E.INVAL, wr(p, ctl_node, invalid).errno()); + try testing.expectEqual(E.INVAL, wr(p, look_node, invalid).errno()); try testing.expectEqual(serial, p.next_serial); try testing.expectEqual(@as(usize, 0), p.active); try testing.expectEqualStrings("source\n", source.file.?.content); } - try testing.expectEqual(Status.ok, wr(p, ctl_node, "look /n/self/index\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, look_node, "/n/self/index\n").reply.status); const opened = p.panes[p.active].?; try testing.expectEqualStrings("/virtual/index", opened.file.?.path); try testing.expect(std.mem.indexOf(u8, opened.file.?.content, "/test.txt") != null); @@ -480,7 +421,7 @@ test "get reloads the pane from disk and reports a missing file without losing d _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&name, "{s}/missing.txt\n", .{directory})); _ = wr(p, Node.of(serial, .body), "unsaved\n"); - try testing.expectEqual(E.NOENT, wr(p, ctl_node, "get\nexec Del\n").errno()); + try testing.expectEqual(E.NOENT, wr(p, ctl_node, "get\n").errno()); try testing.expect(p.paneBySerial(serial) != null); try testing.expectEqualStrings("from disk\nunsaved\n", pane.file.?.content); try testing.expect(pane_files.dirtyOf(pane)); @@ -494,7 +435,7 @@ test "exec Save writes the named file through the host" { const pane = p.panes[0].?; try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/renamed.txt\n").reply.status); try testing.expect(pane_files.dirtyOf(pane)); - const saved = wr(p, Node.of(serial, .ctl), "exec Save\n"); + const saved = wr(p, Node.of(serial, .exec), "Save\n"); try testing.expectEqual(Status.ok, saved.reply.status); try testing.expect(saved.saved); p.perform(.{ .save_file = .{ .pane = 0 } }); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index fb49e41b..bd53bcd9 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -89,6 +89,13 @@ pub const Queue = struct { } }; +/// What the next read would answer, which is the size a stat reports: a +/// client can see there is something waiting without parking on it. +pub fn pending(q: *const Queue) u64 { + const record = q.peek() orelse return 0; + return record.len; +} + /// One record per read; `.again` parks the read until a record arrives. pub fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply { const record = q.peek() orelse return .{ .tag = req.tag, .status = .again }; @@ -461,7 +468,7 @@ test "a pane deleted while its event file is open leaves no suppression behind" const b = call(p, .{ .tag = 19, .op = .open, .node = event }); try testing.expectEqual(@as(u16, 2), p.fs.listeners); - _ = wr(p, Node.of(serial, .ctl), "exec Del\n"); + _ = wr(p, Node.of(serial, .exec), "Del\n"); try testing.expect(p.paneBySerial(serial) == null); try testing.expectEqual(@as(u16, 0), p.fs.listeners); @@ -471,7 +478,7 @@ test "a pane deleted while its event file is open leaves no suppression behind" try testing.expectEqual(E.NOENT, rd(p, event, 0, 64).errno()); try testing.expectEqual(E.NOENT, rd(p, Node.of(serial, .body), 0, 64).errno()); - try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .ctl), "clean\n").errno()); + try testing.expectEqual(E.NOENT, wr(p, Node.of(serial, .dirty), "0\n").errno()); try testing.expectEqual(E.NOENT, call(p, .{ .tag = 22, .op = .open, .node = event }).errno()); } @@ -535,7 +542,7 @@ test "the log parks until a pane is created, renamed, saved or deleted" { try std.fmt.bufPrint(&expected, "rename {d} /tmp/logged.txt\n", .{serial}), rd(p, log, 0, 4096).bytes, ); - const saving = wr(p, Node.of(serial, .ctl), "exec Save\n"); + const saving = wr(p, Node.of(serial, .exec), "Save\n"); try testing.expectEqual(Status.ok, saving.reply.status); try testing.expect(saving.saved); p.perform(.{ .save_file = .{ .pane = @intCast(id) } }); @@ -543,7 +550,7 @@ test "the log parks until a pane is created, renamed, saved or deleted" { try std.fmt.bufPrint(&expected, "save {d} /tmp/logged.txt\n", .{serial}), rd(p, log, 0, 4096).bytes, ); - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "exec Del\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "Del\n").reply.status); try testing.expectEqualStrings( try std.fmt.bufPrint(&expected, "del {d} /tmp/logged.txt\n", .{serial}), rd(p, log, 0, 4096).bytes, diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index b37ae645..42c0c48e 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1,5 +1,6 @@ -//! The files under /pane//: name, body, tag, ctl, addr, data, xdata, -//! sel, errors and event. Terminal panes add pty/ (pty.zig). +//! The files under /pane//: name, body, tag, ctl, the three range +//! files addr, dot and limit, data, xdata, sel, the three flag files dirty, +//! mark and scroll, errors, event, look and exec. Terminals add pty/ (pty.zig). const std = @import("std"); const pardes = @import("../pardes.zig"); const panes = @import("../panes.zig"); @@ -187,10 +188,15 @@ pub fn spliceBody(p: *Pardes, id: usize, pane: *Pane, q0: usize, q1: usize, byte return take; } -// ---- sizes reported by stat ---- +// ---- what stat reports ---- + +/// A range file's text: acme's addr format, two right-aligned offsets, so +/// that copying one range file onto another is the whole of `dot=addr`. +pub const range_len: u64 = 24; pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pane = p.panes[id] orelse return 0; + const pf = &p.fs.panes[id]; return switch (f) { .body, .data, .xdata => bodyOf(pane).len, .tag => tagOf(p, pane).len, @@ -203,7 +209,24 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const d = dotOf(pane); break :sel @max(d.q0, d.q1) - d.q0; }, - .dir, .addr, .errors, .event, .pty, .pty_ctl, .pty_status, .pty_data => 0, + .addr, .dot => range_len, + .limit => if (pf.limit == null) 0 else range_len, + .dirty, .mark, .scroll => 2, + .look, .exec => ctl.resultsLen(p), + .event => events.pending(&pf.events), + .pty_status => pty.status_len, + .pty_data => events.pending(&pf.pty_out), + .dir, .errors, .pty, .pty_ctl => 0, + }; +} + +/// The qid version, which a client polls to watch a file for change. Only +/// the pane's text can promise one: its revision counts every edit, and +/// nothing else here changes in step with it. +pub fn versionOf(pane: *const Pane, f: PaneFile) u32 { + return switch (f) { + .body, .data, .xdata => if (pane.file) |*file| file.revision else 0, + else => 0, }; } @@ -246,13 +269,17 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .ctl => ctl.readPane(p, req, pane), .addr => addr: { clampAddr(pf, bodyOf(pane).len); - const out = p.fs.stage(p.gpa); - out.print(p.gpa, "{d:>11} {d:>11} ", .{ pf.addr.q0, pf.addr.q1 }) catch {}; - break :addr tree.stagedReply(p, req); + break :addr readRange(p, req, pf.addr); }, + .dot => readRange(p, req, dotOf(pane)), + .limit => readRange(p, req, pf.limit), .data => readData(req, id, pane, pf, false), .xdata => readData(req, id, pane, pf, true), .sel => readSel(req, id, pane), + .dirty => readFlag(p, req, dirtyOf(pane)), + .mark => readFlag(p, req, !pf.nomark), + .scroll => readFlag(p, req, !pf.noscroll), + .look, .exec => ctl.readResults(p, req), .event => events.readQueue(p, req, &pf.events), .pty_status => pty.readStatus(p, req, id, pane), .pty_data => pty.readData(p, req, pf), @@ -260,6 +287,20 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply }; } +/// An unset limit reads empty, which is how a client tells it from one that +/// happens to bound nothing. +fn readRange(p: *Pardes, req: Req, r: ?State.Range) Reply { + const out = p.fs.stage(p.gpa); + if (r) |range| out.print(p.gpa, "{d:>11} {d:>11} ", .{ range.q0, range.q1 }) catch {}; + return tree.stagedReply(p, req); +} + +fn readFlag(p: *Pardes, req: Req, on: bool) Reply { + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, if (on) "1\n" else "0\n") catch {}; + return tree.stagedReply(p, req); +} + fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (pane.file != null) { const text = bodyOf(pane); @@ -322,10 +363,12 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .name => writeName(p, req, id, pane), .body => writeBody(p, req, id, pane), .tag => writeTag(p, req, pane), - .ctl => ctl.writePane(p, req, pane.serial), - .addr => writeAddr(p, req, id, pane), + .ctl => ctl.writePane(p, req, pane), + .addr, .dot, .limit => writeRange(p, req, id, pane, file), .data, .xdata => writeData(p, req, id, pane), .sel => writeSel(p, req, id, pane), + .dirty, .mark, .scroll => writeFlag(p, req, id, pane, file), + .look, .exec => ctl.command(p, req, pane.serial, file == .exec), .event => events.writeEvent(p, req, id), .errors => if (appendErrors(p, id, req.data)) |took| .{ .tag = req.tag, .written = @intCast(took) } @@ -389,15 +432,68 @@ fn writeSel(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } -fn writeAddr(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { +/// The pair of offsets a range file reads back, so that copying `addr` onto +/// `dot` or `limit` does what acme spelled `dot=addr` and `limit=addr`. +fn pairOf(text: []const u8) ?State.Range { + var it = std.mem.tokenizeAny(u8, text, " \t"); + const q0 = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null; + const q1 = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null; + if (it.next() != null) return null; + return .{ .q0 = q0, .q1 = @max(q0, q1) }; +} + +/// A range file takes an address expression, or that pair of offsets. +fn rangeOf(pf: *State, text: []const u8, data: []const u8) ?State.Range { + const expr = std.mem.trimEnd(u8, data, "\n"); + if (pairOf(expr)) |r| { + const n = clip(text.len); + return .{ .q0 = @min(r.q0, n), .q1 = @min(r.q1, n) }; + } + var a: addressing.Addr = .{ .text = text, .lim = pf.limit, .expr = expr }; + const r = a.address(pf.addr) orelse return null; + return if (a.i < expr.len) null else r; +} + +fn writeRange(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { const pf = &p.fs.panes[id]; const text = bodyOf(pane); clampAddr(pf, text.len); - const expr = std.mem.trimEnd(u8, req.data, "\n"); - var a: addressing.Addr = .{ .text = text, .lim = pf.limit, .expr = expr }; - const r = a.address(pf.addr) orelse return Reply.fail(req.tag, E.INVAL); - if (a.i < expr.len) return Reply.fail(req.tag, E.INVAL); - pf.addr = r; + const r = rangeOf(pf, text, req.data) orelse return Reply.fail(req.tag, E.INVAL); + switch (file) { + .addr => pf.addr = r, + .limit => pf.limit = r, + // Setting dot scrolls to it, which is the whole of acme's `show`. + .dot => { + if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); + setDot(pane, r); + }, + else => unreachable, + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +fn flagOf(data: []const u8) ?bool { + const word = std.mem.trim(u8, data, " \t\r\n"); + if (std.mem.eql(u8, word, "1")) return true; + if (std.mem.eql(u8, word, "0")) return false; + return null; +} + +fn writeFlag(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { + const on = flagOf(req.data) orelse return Reply.fail(req.tag, E.INVAL); + const pf = &p.fs.panes[id]; + switch (file) { + .dirty => { + const f = fileOf(pane) orelse return Reply.fail(req.tag, E.INVAL); + f.saved_revision = if (on) f.revision -% 1 else f.revision; + }, + .mark => { + pf.nomark = !on; + if (on) panes.File.pushUndo(p, pane); + }, + .scroll => pf.noscroll = !on, + else => unreachable, + } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } @@ -475,14 +571,24 @@ pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { return text.len; } -/// Truncation empties a body; every other setattr just answers fresh attributes. +/// Truncation empties whatever the file holds: the body, the tag's editable +/// tail (acme's `cleartag`), a range. Every other setattr just answers fresh +/// attributes. pub fn truncate(p: *Pardes, id: usize, pane: *Pane, file: PaneFile) tree.Status { + const pf = &p.fs.panes[id]; switch (file) { .body, .data, .xdata => if (fileOf(pane) != null) { _ = spliceBody(p, id, pane, 0, bodyOf(pane).len, "") orelse return .err; - p.fs.panes[id].addr = .{}; + pf.addr = .{}; setDot(pane, .{}); }, + .tag => { + pane.tag_tail_len = 0; + pane.tag_init = true; + }, + .addr => pf.addr = .{}, + .limit => pf.limit = null, + .dot => if (fileOf(pane) != null) setDot(pane, .{}), else => {}, } return .ok; @@ -509,15 +615,19 @@ test "index lists serial kind dirty flag and name and stat reports its length" { const a = rd(p, index, 0, 4096); try testing.expectEqual(Status.ok, a.reply.status); var want: [64]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d} text 0 /test.txt\n", .{pane.serial}), a.bytes); + const clean_row = try std.fmt.bufPrint(&want, "{d} text 0 /test.txt\n", .{pane.serial}); + try testing.expect(std.mem.indexOf(u8, a.bytes, clean_row) != null); + const at = std.mem.indexOf(u8, a.bytes, clean_row).?; const stat = call(p, .{ .tag = 1, .op = .getattr, .node = index }); try testing.expectEqual(@as(u64, a.bytes.len), stat.reply.attr.size); try testing.expectEqual(@as(u16, 0o444), stat.reply.attr.mode); pane.file.?.saved_revision = pane.file.?.revision -% 1; - try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d} text 1 /test.txt\n", .{pane.serial}), rd(p, index, 0, 4096).bytes); - const mid = rd(p, index, 2, 4); - try testing.expectEqualStrings("text", mid.bytes); + var dirty_want: [64]u8 = undefined; + const dirty_row = try std.fmt.bufPrint(&dirty_want, "{d} text 1 /test.txt\n", .{pane.serial}); + try testing.expect(std.mem.indexOf(u8, rd(p, index, 0, 4096).bytes, dirty_row) != null); + const kind = at + std.mem.indexOfScalar(u8, clean_row, ' ').? + 1; + try testing.expectEqualStrings("text", rd(p, index, kind, 4).bytes); const serial = try th.newPane(p); const both = rd(p, index, 0, 4096); @@ -533,10 +643,11 @@ test "a terminal is listed as term with its directory as name" { const pane = p.panes[0].?; p.setCwd(0, "/work/dir"); var want: [64]u8 = undefined; - try testing.expectEqualStrings( - try std.fmt.bufPrint(&want, "{d} term 0 /work/dir\n", .{pane.serial}), + try testing.expect(std.mem.indexOf( + u8, rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, - ); + try std.fmt.bufPrint(&want, "{d} term 0 /work/dir\n", .{pane.serial}), + ) != null); try testing.expectEqualStrings("/work/dir\n", rd(p, Node.of(pane.serial, .name), 0, 4096).bytes); try testing.expectEqual(E.PERM, wr(p, Node.of(pane.serial, .name), "/elsewhere\n").errno()); } @@ -566,6 +677,13 @@ test "body reads at any offset and writes append" { try testing.expectEqual(@as(u64, "one\ntwo\nthree\na".len), stat.reply.attr.size); try testing.expectEqual(@as(u16, 0o666), stat.reply.attr.mode); try testing.expect(stat.reply.attr.mtime >= p.fs.started); + + // The qid version is the pane's revision, so a stat sees an edit land. + try testing.expectEqual(p.panes[0].?.file.?.revision, stat.reply.attr.version); + _ = wr(p, body, "more\n"); + const later = call(p, .{ .tag = 7, .op = .getattr, .node = body }); + try testing.expect(later.reply.attr.version != stat.reply.attr.version); + try testing.expectEqual(@as(u32, 0), call(p, .{ .tag = 8, .op = .getattr, .node = Node.of(serial, .tag) }).reply.attr.version); } test "a body write to a terminal pane types at its shell" { @@ -653,18 +771,29 @@ test "sel reads the selection and writing sel replaces it" { const p = try withFile(gpa, "one\ntwo\n"); defer p.deinit(); const serial = serialOf(p); - const ctl_node = Node.of(serial, .ctl); + const addr_node = Node.of(serial, .addr); + const dot = Node.of(serial, .dot); const sel = Node.of(serial, .sel); - _ = wr(p, Node.of(serial, .addr), "#0,#3"); - try testing.expectEqual(Status.ok, wr(p, ctl_node, "dot=addr\n").reply.status); + // Copying addr onto dot is the whole of acme's `dot=addr`, and back again + // of `addr=dot`; each range file reads exactly what the other takes. + _ = wr(p, addr_node, "#0,#3"); + try testing.expectEqual(Status.ok, wr(p, dot, " 0 3 ").reply.status); + try testing.expectEqualStrings(" 0 3 ", rd(p, dot, 0, 100).bytes); + try testing.expectEqual(range_len, call(p, .{ .tag = 1, .op = .getattr, .node = dot }).reply.attr.size); try testing.expectEqualStrings("one", rd(p, sel, 0, 100).bytes); try testing.expectEqual(@as(u64, 3), call(p, .{ .tag = 1, .op = .getattr, .node = sel }).reply.attr.size); - _ = wr(p, ctl_node, "addr=dot\n"); + _ = wr(p, addr_node, "#0"); + _ = wr(p, addr_node, " 0 3 "); try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); + // A truncation empties dot; an address expression addresses it. + _ = call(p, .{ .tag = 9, .op = .setattr, .node = dot, .truncate = true }); + try testing.expectEqualStrings("", rd(p, sel, 0, 100).bytes); + try testing.expectEqual(Status.ok, wr(p, dot, "#0,#3").reply.status); + try testing.expectEqual(Status.ok, wr(p, sel, "ONE").reply.status); try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); _ = wr(p, sel, "!"); @@ -672,6 +801,62 @@ test "sel reads the selection and writing sel replaces it" { try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 2, .op = .getattr, .node = sel }).reply.attr.size); } +test "the flag files read and write the state acme kept behind ctl verbs" { + const gpa = testing.allocator; + const p = try withFile(gpa, "one\ntwo\n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[0].?; + const pf = &p.fs.panes[0]; + const dirty = Node.of(serial, .dirty); + const mark = Node.of(serial, .mark); + const scroll = Node.of(serial, .scroll); + + for ([_]u64{ dirty, mark, scroll }) |node| { + try testing.expectEqual(@as(u64, 2), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size); + for ([_][]const u8{ "", "yes", "2", "0 1", "true" }) |bad| + try testing.expectEqual(E.INVAL, wr(p, node, bad).errno()); + } + + try testing.expectEqualStrings("0\n", rd(p, dirty, 0, 8).bytes); + try testing.expectEqualStrings("1\n", rd(p, mark, 0, 8).bytes); + try testing.expectEqualStrings("1\n", rd(p, scroll, 0, 8).bytes); + + try testing.expectEqual(Status.ok, wr(p, dirty, "1\n").reply.status); + try testing.expect(dirtyOf(pane)); + try testing.expectEqualStrings("1\n", rd(p, dirty, 0, 8).bytes); + _ = wr(p, dirty, "0"); + try testing.expect(!dirtyOf(pane)); + + _ = wr(p, mark, "0"); + _ = wr(p, scroll, "0"); + try testing.expect(pf.nomark and pf.noscroll); + try testing.expectEqualStrings("0\n", rd(p, mark, 0, 8).bytes); + try testing.expectEqualStrings("0\n", rd(p, scroll, 0, 8).bytes); + _ = wr(p, mark, "1"); + _ = wr(p, scroll, "1"); + try testing.expect(!pf.nomark and !pf.noscroll); + + // A terminal has no file, so its dirty flag is readable but not writable. + const term = try th.withTerm(gpa); + defer term.deinit(); + try testing.expectEqualStrings("0\n", rd(term, Node.of(serialOf(term), .dirty), 0, 8).bytes); + try testing.expectEqual(E.INVAL, wr(term, Node.of(serialOf(term), .dirty), "1").errno()); +} + +test "truncating the tag clears its editable tail" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const pane = p.panes[0].?; + const tag = Node.of(pane.serial, .tag); + _ = wr(p, tag, " Mine"); + try testing.expect(pane.tag_tail_len > 0); + const cleared = call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true }); + try testing.expectEqual(Status.ok, cleared.reply.status); + try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); + try testing.expect(std.mem.indexOf(u8, rd(p, tag, 0, 4096).bytes, " Mine") == null); +} + test "name reads the file name and writing it promotes a scratch without touching its body" { const gpa = testing.allocator; const p = try withFile(gpa, "opener\n"); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index e6696b85..1b71a8d3 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -76,6 +76,9 @@ fn verb(p: *Pardes, id: usize, line: []const u8, apply: bool) bool { return true; } +/// Three right-aligned fields: cols, rows and whether the host holds the tty. +pub const status_len: u64 = 36; + pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { const out = p.fs.stage(p.gpa); out.print(p.gpa, "{d:>11} {d:>11} {d:>11} ", .{ @@ -146,7 +149,7 @@ test "a pane that is not a terminal has no pty/ at all" { var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 10), files.len); + try testing.expectEqual(@as(usize, 17), files.len); try testing.expect(th.nameAt(files, "pty") == null); try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno()); @@ -167,7 +170,7 @@ test "a terminal pane's pty/ holds exactly ctl, status and data" { var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 11), files.len); + try testing.expectEqual(@as(usize, 18), files.len); try testing.expect(th.nameAt(files, "pty").?.dir); const inside = th.dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf); @@ -247,7 +250,7 @@ test "every pty/ctl verb, and every refusal" { "cooked", "winsize 80 24\nbogus", // a good verb beside a bad one "bogus\nwinsize 80 24", - "look x", // a `ctl` verb; the two files share no vocabulary + "look x", // a pane command; pty/ctl shares none of that vocabulary "exec Del", }) |bad| { const a = wr(p, ctl, bad); diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 5b68b34c..2684aa41 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -83,22 +83,33 @@ pub fn releaseSnapshot(p: *Pardes, req: Req) bool { return true; } -pub fn readListeners(p: *Pardes, req: Req) Reply { - var buf: [512]u8 = undefined; - var text = std.Io.Writer.fixed(&buf); +const listeners_cap = 512; + +fn listenersText(p: *Pardes, buf: []u8) []const u8 { + var text = std.Io.Writer.fixed(buf); if (p.fs.socket_path.len != 0) - text.print("unix!{s}\n", .{p.fs.socket_path}) catch return Reply.fail(req.tag, E.IO); + text.print("unix!{s}\n", .{p.fs.socket_path}) catch return text.buffered(); for ([_]?std.Io.net.IpAddress{ p.fs.tcp_address, p.fs.quic_address }, [_][]const u8{ "tcp", "quic" }) |maybe, transport| { const address = maybe orelse continue; switch (address) { .ip4 => |ip| text.print("{s}!{d}.{d}.{d}.{d}!{d}\n", .{ transport, ip.bytes[0], ip.bytes[1], ip.bytes[2], ip.bytes[3], ip.port }) catch - return Reply.fail(req.tag, E.IO), + return text.buffered(), .ip6 => |ip| text.print("{s}!{f}!{d}\n", .{ transport, std.Io.net.Ip6Address.Unresolved{ .bytes = ip.bytes, .interface_name = null }, ip.port }) catch - return Reply.fail(req.tag, E.IO), + return text.buffered(), } } + return text.buffered(); +} + +pub fn listenersLen(p: *Pardes) u64 { + var buf: [listeners_cap]u8 = undefined; + return listenersText(p, &buf).len; +} + +pub fn readListeners(p: *Pardes, req: Req) Reply { + var buf: [listeners_cap]u8 = undefined; const out = p.fs.stage(p.gpa); - out.appendSlice(p.gpa, text.buffered()) catch return Reply.fail(req.tag, E.NOMEM); + out.appendSlice(p.gpa, listenersText(p, &buf)) catch return Reply.fail(req.tag, E.NOMEM); return tree.stagedReply(p, req); } diff --git a/src/ninep/testing.zig b/src/ninep/testing.zig index ba26cb38..ad1d84e4 100644 --- a/src/ninep/testing.zig +++ b/src/ninep/testing.zig @@ -69,13 +69,30 @@ pub fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer { return call(p, .{ .tag = 3, .op = .lookup, .node = dir, .data = name }); } -/// Opens /new once, as a client would, and returns the pane it made. +/// Creates a pane in /pane, as a client's mkdir does, and returns its serial. pub fn newPane(p: *Pardes) !u32 { - const new = @intFromEnum(tree.TopFile.new); - const opened = call(p, .{ .tag = 9, .op = .open, .node = new }); - if (opened.reply.status != .ok or opened.reply.handle == 0) return error.NoPane; - _ = call(p, .{ .tag = 9, .op = .release, .node = new, .handle = opened.reply.handle }); - return opened.reply.handle; + const made = mkdir(p, "scratch"); + if (made.reply.status != .ok) return error.NoPane; + const target = tree.Node.target(made.reply.attr.node) orelse return error.NoPane; + return switch (target) { + .pane => |t| t.serial, + .top => error.NoPane, + }; +} + +pub fn mkdir(p: *Pardes, name: []const u8) Answer { + return call(p, .{ + .tag = 9, + .op = .open, + .node = @intFromEnum(tree.TopFile.pane), + .data = name, + .create = true, + .perm = 0x8000_0000 | 0o755, + }); +} + +pub fn rmdir(p: *Pardes, node: u64) Answer { + return call(p, .{ .tag = 9, .op = .release, .node = node, .remove = true }); } pub fn withFile(gpa: std.mem.Allocator, text: []const u8) !*Pardes { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 56c3112d..46609649 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -4,8 +4,10 @@ //! extended here with the editor's reply payload; fs.zig keeps host access //! and mounts. //! -//! /README /index /ctl /new /log /screen /listeners -//! /pane//{name,body,tag,ctl,addr,data,xdata,sel,errors,event,pty/} +//! /README /index /status /look /exec /log /screen /listeners +//! /pane/ mkdir makes a pane, rmdir closes it +//! /pane//{name,body,tag,ctl,addr,dot,limit,data,xdata,sel, +//! dirty,mark,scroll,errors,event,look,exec,pty/} //! /os/... the host filesystem /src/... embedded sources (opt-in) const std = @import("std"); const cloud9 = @import("cloud9"); @@ -47,11 +49,16 @@ pub const Payload = union(enum) { pub const Reply = cloud9.fs.ReplyWith(Payload); +/// Tcreate opens a pane and Tremove closes one; nothing else in the tree is +/// created or destroyed by the protocol, and wstat stays a truncation. +pub const features: cloud9.fs.Features = .{ .create = true, .remove = true }; + pub fn changesPane(req: Req) bool { return switch (req.op) { .write, .setattr => true, - .open => req.node == @intFromEnum(TopFile.new), - .lookup, .getattr, .read, .release, .readdir => false, + .open => req.create, + .release => req.remove, + .lookup, .getattr, .read, .readdir => false, }; } @@ -63,8 +70,9 @@ pub const TopFile = enum(u4) { root = 1, README, index, - ctl, - new, + status, + look, + exec, log, screen, listeners, @@ -77,8 +85,8 @@ pub const TopFile = enum(u4) { pub fn mode(f: TopFile) u16 { return switch (f) { .root, .pane => 0o755, - .ctl => 0o666, - .README, .index, .new, .log, .screen, .listeners => 0o444, + .look, .exec => 0o666, + .README, .index, .status, .log, .screen, .listeners => 0o444, }; } @@ -89,18 +97,26 @@ pub const TopFile = enum(u4) { pub const root: u64 = @intFromEnum(TopFile.root); -pub const PaneFile = enum(u4) { +/// Declaration order is readdir order. +pub const PaneFile = enum(u5) { dir = 0, name, body, tag, ctl, addr, + dot, + limit, data, xdata, sel, + dirty, + mark, + scroll, errors, event, + look, + exec, pty, pty_ctl, pty_status, @@ -138,8 +154,8 @@ pub const PaneFile = enum(u4) { }; pub const Node = packed struct(u64) { - file: u4 = 0, - serial: u60 = 0, + file: u5 = 0, + serial: u59 = 0, pub fn of(serial: u32, file: PaneFile) u64 { std.debug.assert(serial != 0); @@ -240,8 +256,13 @@ pub fn stagedReply(p: *Pardes, req: Req) Reply { // ---- dispatch ---- pub fn handle(p: *Pardes, req: Req) Reply { - if (req.node == fs.os_root or req.node & fs.os_node != 0) return fs.osHandle(p, req); - if (req.node & sources.archive_node != 0) return sources.handle(p, req); + const host = req.node == fs.os_root or req.node & fs.os_node != 0; + const archive = req.node & sources.archive_node != 0; + // Only /pane is created in and removed from. The host tree and the + // embedded sources say so, rather than quietly doing nothing. + if ((host or archive) and (req.create or req.remove)) return Reply.fail(req.tag, E.PERM); + if (host) return fs.osHandle(p, req); + if (archive) return sources.handle(p, req); const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) { .pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'), @@ -280,6 +301,7 @@ fn attrOf(p: *Pardes, target: Target) ?Reply.Attr { .mode = t.file.mode(), .size = pane.fileSize(p, id, t.file), .mtime = pane.mtimeOf(p, pn), + .version = pane.versionOf(pn, t.file), }; }, } @@ -292,13 +314,14 @@ fn attrReply(p: *Pardes, tag: u64, target: Target) Reply { fn topSize(p: *Pardes, f: TopFile) u64 { return switch (f) { - .root, .pane, .new, .log, .screen, .listeners => 0, + // ponytail: /screen has no length until an open renders its frame. + .root, .pane, .screen => 0, .index => pane.indexLen(p), .README => fs.help.len, - .ctl => ctl: { - var buf: [ctl.root_text_cap]u8 = undefined; - break :ctl ctl.rootText(p, &buf).len; - }, + .status => ctl.statusLen(p), + .look, .exec => ctl.resultsLen(p), + .log => events.pending(&p.fs.log), + .listeners => screen.listenersLen(p), }; } @@ -366,7 +389,7 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { switch (target) { .top => |f| switch (f) { .root => { - inline for (.{ TopFile.README, TopFile.index, TopFile.ctl, TopFile.new, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.pane }) |t| { + inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.look, TopFile.exec, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.pane }) |t| { if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); @@ -403,21 +426,27 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; } -fn newPane(p: *Pardes) ?u32 { - const slot = p.freeSlot() orelse return null; +/// Tcreate in /pane opens a pane, the way mkdir opens a directory. The name +/// asked for is ignored: a pane is named by the serial the editor gives it, +/// which the reply carries back and /index lists last. +fn create(p: *Pardes, req: Req, target: Target) Reply { + switch (target) { + .top => |f| if (f != .pane) return Reply.fail(req.tag, E.PERM), + .pane => return Reply.fail(req.tag, E.PERM), + } + if (req.perm & cloud9.dmdir == 0) return Reply.fail(req.tag, E.PERM); + const slot = p.freeSlot() orelse return Reply.fail(req.tag, E.NFILE); p.newScratchBelow(p.active); - const pn = p.panes[slot] orelse return null; - return pn.serial; + const made = p.panes[slot] orelse return Reply.fail(req.tag, E.NFILE); + const attr = attrOf(p, .{ .pane = .{ .serial = made.serial, .file = .dir } }) orelse + return Reply.fail(req.tag, E.NFILE); + return .{ .tag = req.tag, .handle = 1, .attr = attr }; } fn open(p: *Pardes, req: Req, target: Target) Reply { + if (req.create) return create(p, req, target); switch (target) { .top => |f| switch (f) { - // The clone idiom: each open makes one empty pane; reads answer its serial. - .new => { - const serial = newPane(p) orelse return Reply.fail(req.tag, E.NFILE); - return .{ .tag = req.tag, .handle = serial }; - }, .screen => return screen.openSnapshot(p, req, true), .log => p.fs.log_readers +|= 1, else => {}, @@ -429,11 +458,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); switch (t.file) { .body => if (pn.isTerminal()) return screen.openSnapshot(p, req, false), - .ctl => pf.limit = null, - .addr => { - pf.addr = .{}; - pf.limit = null; - }, + .addr => pf.addr = .{}, .event => { pf.readers +|= 1; p.fs.listeners +|= 1; @@ -446,7 +471,27 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { return .{ .tag = req.tag, .handle = 1 }; } +/// Tremove closes a pane. Nothing else in the tree can be removed, and this +/// is also where an ORCLOSE open lands, so every node is checked here. +fn remove(p: *Pardes, req: Req) Reply { + const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); + const t = switch (target) { + .pane => |t| t, + .top => return Reply.fail(req.tag, E.PERM), + }; + if (t.file != .dir) return Reply.fail(req.tag, E.PERM); + const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); + p.removePane(id) catch return Reply.fail(req.tag, E.IO); + return .{ .tag = req.tag }; +} + fn release(p: *Pardes, req: Req) Reply { + // The handle's bookkeeping runs whether or not the removal is allowed. + const done = releaseHandle(p, req); + return if (req.remove) remove(p, req) else done; +} + +fn releaseHandle(p: *Pardes, req: Req) Reply { if (screen.releaseSnapshot(p, req)) return .{ .tag = req.tag }; const target = Node.target(req.node) orelse return .{ .tag = req.tag }; switch (target) { @@ -502,12 +547,8 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { } break :index stagedReply(p, req); }, - .ctl => ctl.readRoot(p, req), - .new => new: { - if (req.handle == 0) break :new Reply.fail(req.tag, E.INVAL); - p.fs.stage(p.gpa).print(p.gpa, "{d}\n", .{req.handle}) catch break :new Reply.fail(req.tag, E.NOMEM); - break :new stagedReply(p, req); - }, + .status => ctl.readStatus(p, req), + .look, .exec => ctl.readResults(p, req), .log => events.readQueue(p, req, &p.fs.log), .screen => screen.readSnapshot(p, req, null), .listeners => screen.readListeners(p, req), @@ -525,7 +566,7 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { fn write(p: *Pardes, req: Req, target: Target) Reply { switch (target) { .top => |f| return switch (f) { - .ctl => ctl.writeRoot(p, req), + .look, .exec => ctl.command(p, req, null, f == .exec), else => Reply.fail(req.tag, E.PERM), }, .pane => |t| { @@ -587,8 +628,8 @@ test "filesystem inspection preserves pending and displayed Look hover" { const preview = p.look_hover_preview; const requests = [_]Req{ .{ .tag = 1, .op = .lookup, .node = root, .data = "screen" }, - .{ .tag = 1, .op = .lookup, .node = root, .data = "new" }, - .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 1, .op = .lookup, .node = root, .data = "status" }, + .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.pane) }, .{ .tag = 2, .op = .getattr, .node = body }, .{ .tag = 3, .op = .open, .node = body }, .{ .tag = 4, .op = .read, .node = body, .size = 5 }, @@ -614,7 +655,7 @@ test "filesystem inspection preserves pending and displayed Look hover" { test "filesystem pane creation and truncation cancel Look hover" { const requests = [_]Req{ - .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.pane), .data = "x", .create = true, .perm = cloud9.dmdir | 0o755 }, .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true }, }; for (requests) |request| { @@ -644,13 +685,13 @@ test "readdir lists the root and a pane directory without creating anything" { var top_bytes: [4096]u8 = undefined; @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); - try testing.expect(top.len >= 9); - for ([_][]const u8{ "README", "index", "ctl", "new", "log", "screen", "listeners", "pane", "os" }, 0..) |name, i| { + try testing.expect(top.len >= 10); + for ([_][]const u8{ "README", "index", "status", "look", "exec", "log", "screen", "listeners", "pane", "os" }, 0..) |name, i| { try testing.expectEqualStrings(name, top[i].name); - try testing.expectEqual(i >= 7, top[i].dir); + try testing.expectEqual(i >= 8, top[i].dir); } - try testing.expectEqual(@intFromEnum(TopFile.pane), top[7].node); - try testing.expectEqual(fs.os_root, top[8].node); + try testing.expectEqual(@intFromEnum(TopFile.pane), top[8].node); + try testing.expectEqual(fs.os_root, top[9].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); try testing.expect(th.nameAt(top, "self") == null); @@ -674,13 +715,18 @@ test "readdir lists the root and a pane directory without creating anything" { } const panes_dir = rdir(p, @intFromEnum(TopFile.pane), 0); const listed = th.dirents(panes_dir.bytes, &buf); - try testing.expectEqual(@as(usize, 1), listed.len); - try testing.expectEqual(Node.of(serial, .dir), listed[0].node); + var idname: [16]u8 = undefined; + const own = th.nameAt(listed, try std.fmt.bufPrint(&idname, "{d}", .{serial})).?; + try testing.expectEqual(Node.of(serial, .dir), own.node); + try testing.expect(own.dir); const dir = rdir(p, Node.of(serial, .dir), 0); const files = th.dirents(dir.bytes, &buf); - try testing.expectEqual(@as(usize, 10), files.len); - for ([_][]const u8{ "name", "body", "tag", "ctl", "addr", "data", "xdata", "sel", "errors", "event" }, 0..) |name, i| + try testing.expectEqual(@as(usize, 17), files.len); + for ([_][]const u8{ + "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", + "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", + }, 0..) |name, i| try testing.expectEqualStrings(name, files[i].name); try testing.expect(th.nameAt(files, ".") == null); try testing.expect(th.nameAt(files, "rdsel") == null); @@ -703,8 +749,10 @@ test "lookup resolves top files, pane serials and pane files" { const serial = serialOf(p); try testing.expectEqual(@as(u64, @intFromEnum(TopFile.index)), look_up(p, root, "index").reply.attr.node); - try testing.expect(!look_up(p, root, "new").reply.attr.dir); - try testing.expectEqual(@as(u16, 0o444), look_up(p, root, "new").reply.attr.mode); + try testing.expect(!look_up(p, root, "status").reply.attr.dir); + try testing.expectEqual(@as(u16, 0o444), look_up(p, root, "status").reply.attr.mode); + try testing.expectEqual(@as(u16, 0o666), look_up(p, root, "look").reply.attr.mode); + try testing.expectEqual(E.NOENT, look_up(p, root, "new").errno()); try testing.expect(look_up(p, root, "pane").reply.attr.dir); try testing.expect(look_up(p, root, "os").reply.attr.dir); try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno()); @@ -732,38 +780,46 @@ test "lookup resolves top files, pane serials and pane files" { try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serial, .body), "x").errno()); } -test "each open of new creates exactly one pane whose serial the read answers" { +test "creating in the pane directory opens a pane and removing one closes it" { const gpa = testing.allocator; const p = try withFile(gpa, "first\n"); defer p.deinit(); const before = p.next_serial; - const new = @intFromEnum(TopFile.new); + const panes_dir = @intFromEnum(TopFile.pane); - try testing.expectEqual(Status.ok, look_up(p, root, "new").reply.status); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = new }).reply.status); + // Browsing /pane creates nothing; only a create does. + try testing.expectEqual(Status.ok, rdir(p, panes_dir, 0).reply.status); try testing.expectEqual(before, p.next_serial); - const opened = call(p, .{ .tag = 1, .op = .open, .node = new }); - try testing.expectEqual(Status.ok, opened.reply.status); + const made = th.mkdir(p, "scratch"); + try testing.expectEqual(Status.ok, made.reply.status); try testing.expectEqual(before + 1, p.next_serial); - try testing.expectEqual(before + 1, opened.reply.handle); - try testing.expectEqual(@as(u64, 0), opened.reply.attr.node); + const serial = before + 1; + try testing.expectEqual(Node.of(serial, .dir), made.reply.attr.node); + try testing.expect(made.reply.attr.dir); var expected: [16]u8 = undefined; - const line = try std.fmt.bufPrint(&expected, "{d}\n", .{opened.reply.handle}); - try testing.expectEqualStrings(line, call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .size = 64 }).bytes); - try testing.expectEqualStrings(line[1..], call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .off = 1, .size = 64 }).bytes); - try testing.expectEqualStrings("", call(p, .{ .tag = 2, .op = .read, .node = new, .handle = opened.reply.handle, .off = line.len, .size = 64 }).bytes); - try testing.expectEqual(before + 1, p.next_serial); - _ = call(p, .{ .tag = 3, .op = .release, .node = new, .handle = opened.reply.handle }); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}", .{serial}), made.reply.attr.name); - const id = p.paneBySerial(opened.reply.handle).?; + const id = p.paneBySerial(serial).?; try testing.expectEqualStrings("", p.panes[id].?.file.?.content); - _ = wr(p, Node.of(opened.reply.handle, .body), "hi"); - const second = call(p, .{ .tag = 4, .op = .open, .node = new }); + _ = wr(p, Node.of(serial, .body), "hi"); + const second = th.mkdir(p, "another"); try testing.expectEqual(Status.ok, second.reply.status); - try testing.expect(second.reply.handle != opened.reply.handle); + try testing.expect(second.reply.attr.node != made.reply.attr.node); try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content); - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 5, .op = .read, .node = new, .size = 64 }).errno()); + + // A plain file, and a create anywhere else, are refused. + try testing.expectEqual(E.PERM, call(p, .{ .tag = 1, .op = .open, .node = panes_dir, .data = "f", .create = true, .perm = 0o666 }).errno()); + try testing.expectEqual(E.PERM, call(p, .{ .tag = 1, .op = .open, .node = root, .data = "d", .create = true, .perm = cloud9.dmdir | 0o755 }).errno()); + try testing.expectEqual(E.PERM, call(p, .{ .tag = 1, .op = .open, .node = Node.of(serial, .dir), .data = "d", .create = true, .perm = cloud9.dmdir | 0o755 }).errno()); + + // Tremove closes the pane it names, and nothing else in the tree. + try testing.expectEqual(E.PERM, th.rmdir(p, Node.of(serial, .body)).errno()); + try testing.expectEqual(E.PERM, th.rmdir(p, @intFromEnum(TopFile.index)).errno()); + try testing.expect(p.paneBySerial(serial) != null); + try testing.expectEqual(Status.ok, th.rmdir(p, Node.of(serial, .dir)).reply.status); + try testing.expect(p.paneBySerial(serial) == null); + try testing.expectEqual(E.NOENT, th.rmdir(p, Node.of(serial, .dir)).errno()); } test "directories walk to their parents" { @@ -791,14 +847,15 @@ test "editor paths resolve to the same nodes the wire serves" { try testing.expectEqual(root, resolveSelf(p, "").?); try testing.expectEqual(root, resolveSelf(p, "/./pane/../").?); try testing.expectEqual(@intFromEnum(TopFile.index), resolveSelf(p, "index").?); - try testing.expectEqual(@intFromEnum(TopFile.new), resolveSelf(p, "new").?); + try testing.expectEqual(@intFromEnum(TopFile.status), resolveSelf(p, "status").?); + try testing.expect(resolveSelf(p, "new") == null); try testing.expectEqual(@intFromEnum(TopFile.pane), resolveSelf(p, "pane").?); try testing.expectEqual(Node.of(serial, .dir), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}", .{serial})).?); try testing.expectEqual(Node.of(serial, .sel), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/sel", .{serial})).?); try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/pty/ctl", .{serial})) == null); try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/rdsel", .{serial})) == null); try testing.expect(resolveSelf(p, "self/index") == null); - try testing.expect(resolveSelf(p, "new/ctl") == null); + try testing.expect(resolveSelf(p, "status/ctl") == null); try testing.expect(resolveSelf(p, "cons") == null); try testing.expect(resolveSelf(p, "pane/0") == null); } diff --git a/src/panes.zig b/src/panes.zig index edd7038f..9a6802d0 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -6273,6 +6273,13 @@ pub const Terminal = struct { state.vt.screens.active.scroll(.{ .delta_row = delta }); } + /// Is the viewport already showing the last row of output? + pub fn atBottom(pane: *const Pane) bool { + if (comptime !enabled) return true; + const sb = scrollbar(pane); + return sb.offset + sb.len >= sb.total; + } + /// Snap the viewport back onto live output. pub fn followOutput(pane: *Pane) void { if (comptime !enabled) return; @@ -6559,10 +6566,14 @@ pub const Terminal = struct { const has_positions = pane.ovl != null or pane.cur_pinned or pane.vsel.active or pane.msel.active or pane.nsel > 0 or pane.append_at != null or pane.look_at != null or pane.ed_undo_len > 0 or pane.ed_redo_len > 0 or pointerRowCount(pane) > 0; + // Sticky bottom, as every other terminal does it: output drags the + // viewport down only when the viewport was already on the last row, so + // a reader scrolled back into the scrollback stays where they scrolled. + const at_bottom = atBottom(pane); if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); p.shell_rows.markStale(pane); const body_mode = if (pane.tag_edit) pane.tag_mode else pane.mode; - if (body_mode == .tty) followOutput(pane); + if (body_mode == .tty and at_bottom) followOutput(pane); } const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; @@ -6890,6 +6901,7 @@ pub const Terminal = struct { }; pane.mode = .tty; + followOutput(pane); // entering raw mode is a request for the live shell pane.msel.active = false; pane.vsel.active = false; pane.nsel = 0; diff --git a/src/pardes.zig b/src/pardes.zig index ed71102e..c66688f5 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -295,6 +295,12 @@ const pre_collapse_pdf_pane_tail = " Tty Del PdfSections PdfTint"; const pre_collapse_terminal_pane_tail = " Save Tty Del Togglettymode Filter"; const pre_tty_first_terminal_pane_tail = " Save Tty Del Togglettymode Filter Collapse"; const pre_mode_terminal_pane_tail = " Tty Save Del Togglettymode Filter Collapse"; +// ...and the defaults from before the closing word moved to the end of every +// tagline, where a click cannot land on it by overshooting the one before. +const pre_close_last_pane_tail = " Tty Collapse Del"; +const pre_close_last_file_pane_tail = " Save Tty Del Collapse"; +const pre_close_last_pdf_pane_tail = " Tty Del PdfSections PdfTint Collapse"; +const pre_close_last_terminal_pane_tail = " Tty Save Del Mode Filter Collapse"; const Builtin = builtins.registry.Builtin(); @@ -1078,7 +1084,7 @@ test "Collapse builtin keeps content and restores the pane from its default tag" const height = p.rects[0].h; const revision = pane.file.?.revision; for ([_][]const u8{ pane_tail, file_pane_tail, pdf_pane_tail, terminal_pane_tail }) |tail| - try std.testing.expect(std.mem.endsWith(u8, tail, " Collapse")); + try std.testing.expect(std.mem.endsWith(u8, tail, " Collapse Del")); try std.testing.expect(p.executeBuiltinLine(0, "Collapse")); p.sync(); @@ -1115,6 +1121,8 @@ test "LocationsConfig command reports partial updates and survives restore" { try std.testing.expectEqual(expected, p.locations_config); try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig context:2 unknown:on")); try std.testing.expectEqual(expected, p.locations_config); + // Setting it is silent; asking bare is what opens the window. + try std.testing.expect(p.executeBuiltinLine(0, "LocationsConfig")); var reports: usize = 0; for (p.panes) |slot| { const pane = slot orelse continue; @@ -1409,7 +1417,7 @@ test "legacy default tag tails upgrade while custom tails remain owned" { }); p.restoreTail(file, file_old); try std.testing.expect(!file.tag_init); - try std.testing.expectEqualStrings(" Save Tty Del Collapse", Pardes.curTail(file)); + try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(file)); const file_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Mine Del", .{ try p.tagPrefix(file), @@ -1430,7 +1438,7 @@ test "legacy default tag tails upgrade while custom tails remain owned" { try std.testing.expectEqualStrings(" New Del", Pardes.curTail(file)); const image_doc = try panes.Image.create(p, 1, "/tmp/legacy image.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Del Collapse", Pardes.curTail(image_doc)); + try std.testing.expectEqualStrings(" Tty Collapse Del", Pardes.curTail(image_doc)); p.restoreDumpTail(image_doc, .{ .kind = .image, .tag = "img /tmp/legacy image.ppm Keep Del", @@ -1576,7 +1584,7 @@ test "pane defaults keep creation of scratch panes in column tags" { var words = std.mem.tokenizeScalar(u8, tag, ' '); while (words.next()) |word| try std.testing.expect(!std.mem.eql(u8, word, "New")); } - try std.testing.expectEqualStrings("New Tty Find Grep Joincol", p.columnTag(0)); + try std.testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", p.columnTag(0)); const terminal = p.panes[0].?; p.restoreTailAt(terminal, pre_column_terminal_pane_tail, "", .terminal); try std.testing.expect(!terminal.tag_init); @@ -2441,13 +2449,13 @@ test "Save reaches every tagline with text behind it and no other" { }); p.restoreTail(out, scratch_dumped); try std.testing.expect(!out.tag_init); - try std.testing.expectEqualStrings(" Save Tty Del Collapse", Pardes.curTail(out)); + try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(out)); // An image's bytes on disk already are what they are: nothing of the // pane's own is unwritten, so the word is absent and inert. const img_id = p.freeSlot().?; const img = try panes.Image.create(p, img_id, "/tmp/pardes-tag.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Del Collapse", Pardes.curTail(img)); + try std.testing.expectEqualStrings(" Tty Collapse Del", Pardes.curTail(img)); try std.testing.expect(p.executeBuiltinLine(img_id, "Save")); try std.testing.expect(img.prompt != .save); var buf: [256]u8 = undefined; @@ -5818,8 +5826,42 @@ test "repeated non-dyadic column splits preserve every unrelated boundary" { pub const Rect = layout.Rect; +/// The session layouts `init` can put on screen. One name each, so choosing +/// between them reads as a choice instead of a chain of ifs over four options. +pub const Boot = enum { + /// the document named on the command line, or the pane explaining why not + document, + /// a Look that found nothing: reported, not opened + missing, + /// the firmware's boot buffer, the only pane a board has + embedded, + /// the bare tty startup: one shell in raw tty mode, with an empty text + /// pane under it so the editor half is there before you want it + tty, + /// that raw shell by itself, which is all a core booted for a test wants + tty_shell, + /// acme's boot: two columns, the left one split in two + classic, + /// one greeted shell + shell, + + pub fn of(opts: Options) Boot { + if (opts.boot) |named| return named; + if (opts.file != null) return .document; + if (opts.missing != null) return .missing; + if (comptime platform == .esp32p4) return .embedded; + if (opts.tty_only) return .tty_shell; + // ponytail: 1 and 3 are the only shell counts anyone asked for + return if (opts.shells >= 3) .classic else .shell; + } +}; + pub const Options = struct { tty_only: bool = false, + /// The layout to boot, when a host means one outright rather than leaving + /// it to be read off the options below. `--tty` names `.tty`; a core + /// booted for a test names nothing and gets `.tty_shell`. + boot: ?Boot = null, /// initial shell panes: 1 (default) or 3 for the classic two-column boot. /// A `file` outranks this — see there. shells: u8 = 1, @@ -6035,6 +6077,11 @@ pub const Pardes = struct { pipe_wait: ?PendingPipe = null, fs: filesystem.Namespace = .{}, + boot: Boot = .shell, + /// Builtins announce themselves on the message row. Off while startup + /// configuration is applied: those lines are nobody clicking, and should + /// not leave the row holding the name of the last one. + announce: bool = true, // Reject overflow: evicting an older effect would reorder a byte stream. effects: [limits.effect_cap]Effect = undefined, @@ -6114,7 +6161,10 @@ pub const Pardes = struct { for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial); p.opts.mounts = &.{}; p.opts.ninep_identity = .{}; - if (opts.file) |path| { + p.boot = Boot.of(opts); + switch (p.boot) { + .document => { + const path = opts.file.?; const opened = initial_doc: { if (comptime pdf_enabled) if (look.isPdfPath(path)) break :initial_doc panes.Pdf.openPane(p, 0, path, opts.file_line); @@ -6137,10 +6187,10 @@ pub const Pardes = struct { errdefer gpa.free(content); _ = try panes.Output.open(p, 0, std.fs.path.dirname(path) orelse "/", .errors, "", content); } - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } else if (opts.missing) |missing| { + p.oneColumn(); + }, + .missing => { + const missing = opts.missing.?; const content = try std.fmt.allocPrint( gpa, "file or directory not found\n\n\t{s}\n", @@ -6148,24 +6198,26 @@ pub const Pardes = struct { ); errdefer gpa.free(content); _ = try panes.Output.open(p, 0, missing.dir, .errors, "", content); - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } else if (comptime platform == .esp32p4) { + p.oneColumn(); + }, + .embedded => { const content = try p.gpa.dupe(u8, boot_buffer); errdefer p.gpa.free(content); _ = try panes.Output.open(p, 0, "", .{ .cmd = .New }, "", content); - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } else if (opts.tty_only) { + p.oneColumn(); + }, + .tty, .tty_shell => { _ = try p.newShell(0, ""); p.panes[0].?.mode = .tty; - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; - } else if (opts.shells >= 3) { - // classic layout: two columns, the left one split in two. + p.oneColumn(); + // A bare tty is still an editor: it opens with somewhere to put + // text under the shell. The shell keeps the keyboard. + if (p.boot == .tty) { + p.newScratchBelow(0); + p.active = 0; + } + }, + .classic => { _ = try p.newShell(0, ""); _ = try p.newShell(1, ""); _ = try p.newShell(2, ""); @@ -6176,13 +6228,12 @@ pub const Pardes = struct { p.col_panes[0][1] = 1; p.col_n[1] = 1; p.col_panes[1][0] = 2; - } else { - // ponytail: 1 and 3 are the only boot layouts; anything else acts as 1 + }, + .shell => { _ = try p.newShell(0, ""); p.panes[0].?.greet = true; - p.ncol = 1; - p.col_n[0] = 1; - p.col_panes[0][0] = 0; + p.oneColumn(); + }, } p.sync(); p.applyStartupConfig(); @@ -6195,6 +6246,13 @@ pub const Pardes = struct { return p; } + /// The layout every single-pane boot starts from. + fn oneColumn(p: *Pardes) void { + p.ncol = 1; + p.col_n[0] = 1; + p.col_panes[0][0] = 0; + } + pub fn deinit(p: *Pardes) void { p.cancelLookHover(); for (0..MAX_PANES) |id| p.dropPendingWrite(id); @@ -6268,7 +6326,7 @@ pub const Pardes = struct { } pub fn columnTag(p: *const Pardes, c: usize) []const u8 { - return p.col_tags[c].slice("New Tty Find Grep Joincol"); + return p.col_tags[c].slice("New Tty Find Grep Joincol Delcol"); } fn headerText(p: *Pardes) []const u8 { @@ -6413,6 +6471,17 @@ pub const Pardes = struct { return np; } + /// The empty pane that stands in for one that closed, keeping its column + /// alive and its directory. Unlike `newScratch` it inherits nothing: the + /// pane it replaces is on its way out. + fn newScratchIn(p: *Pardes, free: usize, dir: []const u8) !*Pane { + const content = try p.gpa.dupe(u8, ""); + errdefer p.gpa.free(content); + const np = try panes.Output.open(p, free, dir, .{ .cmd = .New }, "", content); + np.cur_pinned = true; + return np; + } + /// New: a scratch below the calling pane, in its column. pub fn newScratchBelow(p: *Pardes, from_id: usize) void { const free = p.freeSlot() orelse return; @@ -8237,8 +8306,23 @@ pub const Pardes = struct { p.ctrl_w_pending = false; if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) return p.toggleTty(p.active); + // Shift-Escape is the unconditional way out, even mid-application; + // bare Escape only leaves at a shell prompt. + if (hit(key, config.tty_toggle_alt)) + return p.runBuiltin(.Last, p.active, "", null); if (key.cp == Key.escape and !key.ctrl and !key.alt and !key.shift and p.takesCommandLine(p.active)) return p.runBuiltin(.Last, p.active, "", null); + panes.Terminal.followOutput(pane); // typing snaps back to live output + // Paste stays the window's, the one exception to forwarding a raw + // tty's keys: Ctrl-V types the register at the program and + // Ctrl-Shift-V asks the desktop for its clipboard first. Forwarded, + // they reach an application that reads the clipboard on its own + // account instead — a coding agent goes there hunting for an image. + // A host that folds Shift into the letter says the same thing. + if (key.ctrl and !key.alt and (key.cp == 'v' or key.cp == 'V')) { + if (key.shift or key.cp == 'V') return p.clipRequest(p.active, .after); + return p.typeToTty(p.active, pane, p.yank orelse return); + } return panes.Terminal.forwardKey(p, p.active, key); } if (p.leader_on) return p.leaderKey(key); @@ -12499,6 +12583,8 @@ pub const Pardes = struct { } fn applyStartupConfig(p: *Pardes) void { + p.announce = false; + defer p.announce = true; var lines = std.mem.splitScalar(u8, p.opts.startup_config orelse return, '\n'); while (lines.next()) |line| _ = p.executeBuiltinLine(p.active, line); } @@ -12506,6 +12592,11 @@ pub const Pardes = struct { fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8) void { if (!p.multiOnce()) return; // a builtin is per-keystroke, never per-cursor const pane = p.panes[id] orelse return; + // A builtin says its own name before it runs, so a tagline click is + // legible even when what it did is invisible. Whatever the builtin + // then says for itself replaces the announcement. + if (p.announce and p.settings.verbose and builtins.registry.announces(b)) + p.setMessage(id, @tagName(b)); const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg }; builtins.registry.dispatch(b, c); } @@ -12887,11 +12978,13 @@ pub const Pardes = struct { const rest = saved_tag[pfx.len..]; const said = std.mem.trimStart(u8, rest, " "); const defaults: []const []const u8 = switch (class) { - .generic => &.{ pdf_pane_tail, pane_tail, pre_collapse_pdf_pane_tail, pre_collapse_pane_tail, pre_column_pdf_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, - .file => &.{ context_pane_tail, file_pane_tail, pre_collapse_file_pane_tail, pre_column_file_pane_tail, prev_file_pane_tail, legacy_file_pane_tail }, + .generic => &.{ pdf_pane_tail, pane_tail, pre_close_last_pdf_pane_tail, pre_close_last_pane_tail, pre_collapse_pdf_pane_tail, pre_collapse_pane_tail, pre_column_pdf_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, + .file => &.{ context_pane_tail, file_pane_tail, pre_close_last_file_pane_tail, pre_collapse_file_pane_tail, pre_column_file_pane_tail, prev_file_pane_tail, legacy_file_pane_tail }, .output => &.{ locations_pane_tail, file_pane_tail, + pre_close_last_file_pane_tail, + pre_close_last_pane_tail, prev_file_pane_tail, legacy_file_pane_tail, pane_tail, @@ -12902,7 +12995,7 @@ pub const Pardes = struct { pre_collapse_file_pane_tail, pre_collapse_pane_tail, }, - .terminal => &.{ terminal_pane_tail, pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail, pre_column_terminal_pane_tail, pre_tty_terminal_pane_tail, prev_terminal_pane_tail, legacy_terminal_pane_tail, pane_tail, pre_collapse_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, + .terminal => &.{ terminal_pane_tail, pre_close_last_terminal_pane_tail, pre_close_last_pane_tail, pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail, pre_column_terminal_pane_tail, pre_tty_terminal_pane_tail, prev_terminal_pane_tail, legacy_terminal_pane_tail, pane_tail, pre_collapse_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, }; for (defaults) |default| if (std.mem.eql(u8, said, std.mem.trimStart(u8, default, " "))) return; @@ -12912,11 +13005,34 @@ pub const Pardes = struct { pub fn removePane(p: *Pardes, id: usize) !void { const pane = p.panes[id] orelse return; + // A column outlives its panes. Closing the last one leaves an empty + // pane standing in its place and in its directory; only Delcol ever + // takes a column away. + const place = layout.findPane(p, id); + const last_in_column = if (place) |f| p.col_n[f.col] == 1 else false; + var dir_buf: [limits.host_path_cap]u8 = undefined; + var dir: []const u8 = ""; + if (last_in_column) { + const had = paneDir(pane); + const n = @min(had.len, dir_buf.len); + @memcpy(dir_buf[0..n], had[0..n]); + dir = dir_buf[0..n]; + } + // Before anything is torn down, so a failure here changes nothing. try p.deinitPane(pane); + // ...and after it, so the stand-in inherits none of the closing pane. + const heir: ?usize = heir: { + if (!last_in_column) break :heir null; + const f = place.?; + const free = p.freeSlot() orelse break :heir null; + _ = p.newScratchIn(free, dir) catch break :heir null; + layout.insert(p, f.col, f.idx + 1, free); + break :heir free; + }; layout.absorbVWeight(p, id); layout.removePane(p, id); p.panes[id] = null; - if (p.active == id) p.active = p.prevFocus(id) orelse { + if (p.active == id) p.active = heir orelse p.prevFocus(id) orelse { p.quit = true; p.emit(.quit); return; @@ -14408,6 +14524,75 @@ test "Esc back into a tty leaves its view at the prompt" { try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset); } +test "the bare tty startup opens a text pane under the shell, unfocused" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .boot = .tty }); + defer p.deinit(); + try std.testing.expectEqual(Boot.tty, p.boot); + + // One column, shell on top in raw mode, an empty text pane under it. + try std.testing.expectEqual(@as(usize, 1), p.ncol); + try std.testing.expectEqual(@as(usize, 2), p.col_n[0]); + const shell = p.panes[p.col_panes[0][0]].?; + const scratch = p.panes[p.col_panes[0][1]].?; + try std.testing.expect(shell.isTerminal()); + try std.testing.expectEqual(Pane.Mode.tty, shell.mode); + try std.testing.expect(!scratch.isTerminal()); + try std.testing.expectEqualStrings("", scratch.file.?.content); + + // ...and the shell keeps the keyboard. + try std.testing.expectEqual(p.col_panes[0][0], p.active); + + // Unnamed, it is the bare shell every test asks for. + const plain = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer plain.deinit(); + try std.testing.expectEqual(Boot.tty_shell, plain.boot); + try std.testing.expectEqual(@as(usize, 1), plain.col_n[0]); +} + +test "tty output follows only from the bottom" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); + p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc + const shell = p.active; + const sp = p.panes[shell].?; + p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); + try std.testing.expectEqual(Pane.Mode.tty, sp.mode); + + for (0..60) |i| { + var buf: [32]u8 = undefined; + p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); + } + p.sync(); + const bottom = panes.Terminal.scrollbar(sp).offset; + try std.testing.expect(bottom > 0); + + // Scrolled back, the reader stays put however much the shell prints. + sp.scrollBy(-10); + p.sync(); + const parked = panes.Terminal.scrollbar(sp).offset; + try std.testing.expect(parked < bottom); + for (60..70) |i| { + var buf: [32]u8 = undefined; + p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); + } + p.sync(); + try std.testing.expectEqual(parked, panes.Terminal.scrollbar(sp).offset); + + // Typing snaps back to live output, so nobody types blind. + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + p.sync(); + try std.testing.expect(panes.Terminal.scrollbar(sp).offset > parked); + + // ...and from there output follows again. + const live = panes.Terminal.scrollbar(sp).offset; + p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = "tail\r\n" } }); + p.sync(); + try std.testing.expect(panes.Terminal.scrollbar(sp).offset > live); +} + test "Esc back into a file leaves its view where it was" { if (platform == .web) return; const gpa = std.testing.allocator; @@ -14461,15 +14646,23 @@ test "raw tty Escape only leaves at a shell prompt" { const pane = p.panes[shell].?; var buf: [256]u8 = undefined; _ = drainWrites(p, &buf); - for ([_]Key{ - .{ .cp = Key.escape, .shift = true }, - }) |key| { - p.update(.{ .key = key }); - try std.testing.expectEqual(shell, p.active); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); - try std.testing.expect(drainWrites(p, &buf).len > 0); - } - p.update(.{ .key = .{ .cp = Key.escape } }); + + // Ordinary keys reach the child; Shift-Escape is the one unconditional way + // out and sends it nothing. + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + try std.testing.expectEqual(shell, p.active); + try std.testing.expect(drainWrites(p, &buf).len > 0); + + p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("", drainWrites(p, &buf)); + try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + + p.update(.{ .key = .{ .cp = Key.escape } }); // back into the shell + try std.testing.expectEqual(shell, p.active); + _ = drainWrites(p, &buf); + + p.update(.{ .key = .{ .cp = Key.escape } }); // bare Escape leaves at a prompt try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expectEqualStrings("", drainWrites(p, &buf)); try std.testing.expectEqual(Pane.Mode.tty, pane.mode); @@ -14620,9 +14813,10 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { defer p.deinit(); var buf: [256]u8 = undefined; _ = drainWrites(p, &buf); - p.setYank("must not be pasted"); + p.setYank("register text"); for ('a'..'z' + 1) |letter| { if (letter == p.opts.tty_toggle) continue; // editor/TTY mode shortcut + if (letter == 'v') continue; // the window's paste, asserted just below p.update(.{ .key = .{ .cp = @intCast(letter), .ctrl = true } }); const expected = [_]u8{@intCast(letter - 'a' + 1)}; // The terminal encoder distinguishes Ctrl-I/M from Tab/Return. @@ -14636,15 +14830,21 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { try std.testing.expectEqual(Pane.Mode.tty, p.panes[0].?.mode); try std.testing.expect(!p.ctrl_w_pending and p.clip_pending == null); } - p.update(.{ .key = .{ .cp = 'v', .ctrl = true, .shift = true } }); - try std.testing.expectEqualStrings("\x1b[118;6u", drainWrites(p, &buf)); + // ...and the two paste chords are the exception: Ctrl-V types the register + // at the program, Ctrl-Shift-V asks the desktop first and types nothing yet. + p.update(.{ .key = .{ .cp = 'v', .ctrl = true } }); + try std.testing.expectEqualStrings("register text", drainWrites(p, &buf)); try std.testing.expect(p.clip_pending == null); + p.update(.{ .key = .{ .cp = 'v', .ctrl = true, .shift = true } }); + try std.testing.expectEqualStrings("", drainWrites(p, &buf)); + try std.testing.expect(p.clip_pending != null); + const unopened = p.freeSlot(); // whatever the boot layout already used for ([_]u8{ 'n', 'c' }) |letter| { p.update(.{ .key = .{ .cp = letter, .alt = true } }); const expected = [_]u8{ 0x1b, letter }; try std.testing.expectEqualStrings(&expected, drainWrites(p, &buf)); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expect(p.panes[1] == null); + try std.testing.expectEqual(unopened, p.freeSlot()); } p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1b[A", drainWrites(p, &buf)); diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 23b7c09b..a1917ba9 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -71,6 +71,21 @@ fn inputReader(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) void { loop.postEvent(.quit) catch {}; } +/// How long a lone ESC waits for the rest of a sequence before it counts as +/// the Escape key. Long enough for the remainder of a real sequence to arrive +/// even over a slow link, short enough that nobody sees the delay. +const escape_hold_ms = 25; + +/// Is there more input right behind what we have already read? Only a real +/// terminal has an fd to ask; the test readers hand their parts over whole, so +/// for them the answer is always no. +fn morePending(tty: anytype) bool { + const Reader = @typeInfo(@TypeOf(tty)).pointer.child; + if (!@hasField(Reader, "fd") or @FieldType(Reader, "fd") != std.Io.File) return false; + var fds = [_]std.posix.pollfd{.{ .fd = tty.fd.handle, .events = std.posix.POLL.IN, .revents = 0 }}; + return (std.posix.poll(&fds, escape_hold_ms) catch return false) > 0; +} + fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { try loop.postEvent(.{ .winsize = try tty.getWinsize() }); var parser: vaxis.Parser = .{}; @@ -101,6 +116,22 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { } carried = end - consumed; std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]); + // A lone ESC opens most sequences and is also the Escape key, so the + // parser holds it for a remainder that a keypress never sends: the + // press would only land when the NEXT key arrived. Wait a beat, and + // when nothing follows it was the key. A terminal speaking the kitty + // protocol never reaches here — it spells Escape out in full. + if (carried == 1 and buf[0] == 0x1b and !morePending(tty)) { + carried = 0; + try vaxis.loop.handleEventGeneric( + loop, + loop.vaxis, + cache, + @TypeOf(Command.value), + @as(vaxis.Event, .{ .key_press = .{ .codepoint = vaxis.Key.escape } }), + loop.vaxis.opts.system_clipboard_allocator, + ); + } } } diff --git a/src/tutor.txt b/src/tutor.txt index 394a48a3..adf4ae3a 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -160,8 +160,10 @@ RAW INPUT Ctrl-b switches to editor mode. Other keys go to the child, - including Ctrl-o, Ctrl-w, Ctrl-V, Ctrl-Shift-V, Alt shortcuts, and - modified Escape. Plain Esc at a detected shell prompt hops + including Ctrl-o, Ctrl-w, Alt shortcuts, and + modified Escape. The two paste chords are the exception: Ctrl-V + types the yank register at the program and Ctrl-Shift-V types the + desktop clipboard. Plain Esc at a detected shell prompt hops to the previous pane. While a program owns the terminal, Esc goes to that program too. Use the Togglettymode tag to leave raw input in place. Desktop paste events still feed the child. @@ -387,15 +389,15 @@ typed pardes the 9P socket opens by default - A directory per pane holding `name`, `body`, `tag`, `ctl`, `addr`, - `data`, `sel`, `event`, `pty/` and the rest, plus `index`, `ctl`, - `new` and `log` at the root. Every pane shell receives `$PARDES_9P` - (the socket) and `$PARDES_PANE` (its serial). Use a 9P client: + A directory per pane holding `name`, `body`, `tag`, `addr`, `dot`, + `data`, `sel`, `dirty`, `event`, `pty/` and the rest, plus `index`, + `status`, `look`, `exec` and `log` at the root. Every pane shell + receives `$PARDES_9P` (the socket) and `$PARDES_PANE` (its serial): /pane//body /index - /new reading it makes a pane, answers its serial - /ctl `look FILE:12` and `exec Save`, as the mouse does + /pane mkdir here makes a pane, rmdir closes it + /look /exec `FILE:12` and `Save`, as the mouse does A terminal pane also has `pty/`: @@ -446,7 +448,8 @@ typed Esc goes to the program — except at a shell PROMPT, where it hops to the previous pane Ctrl-b switches to editor mode - All other keys belong to the child, including Ctrl-V + Ctrl-V types the register, Ctrl-Shift-V the clipboard + All other keys belong to the child DETACHED pardes --detach[=name] the core, no terminal pardes --attach[=name] a frontend for it diff --git a/test/appearance_gallery.py b/test/appearance_gallery.py index 0fa12136..48c0ea1b 100644 --- a/test/appearance_gallery.py +++ b/test/appearance_gallery.py @@ -82,7 +82,7 @@ def run(args): right = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'right column missing') client.write(f'/pane/{right}/name', f'{root / "Review"}\n'.encode()) client.write(f'/pane/{right}/body', PREFERENCE_NOTES if args.theme_selector else NOTES, truncate=True) - client.write(f'/pane/{right}/ctl', b'clean\n') + client.write(f'/pane/{right}/dirty', b'0\n') before = set(panes(client)) command(client, right, 'Tty') terminal = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'terminal missing') @@ -94,12 +94,12 @@ def run(args): command(client, right, 'Config') pane = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'Config output missing') text = client.read(f'/pane/{pane}/body').decode() - client.write(f'/pane/{pane}/ctl', b'exec Del\n') + client.write(f'/pane/{pane}/exec', b'Del\n') return text settings = config_report() - require('Font effective size: 18.00 pixels' in settings, 'configured font size not applied: ' + settings) - require('TaglineSize: 80' in settings, 'configured tag size missing') + require('Font effective size 18.00 pixels' in settings, 'configured font size not applied: ' + settings) + require('TaglineSize 80' in settings, 'configured tag size missing') (root / 'effective-config.txt').write_text(settings) report['font_effective_pixels'] = 18 report['tagline_percent'] = 80 @@ -135,7 +135,7 @@ def run(args): command(client, right, 'Theme ' + theme) if args.theme_selector: # Keep both quiet active gutter ink and vivid comments in view. - client.write(f'/pane/{source}/ctl', f'look {source_path}:117\n'.encode()) + client.write(f'/pane/{source}/look', f'{source_path}:117\n'.encode()) take_frame('classic-' + theme) if args.theme_selector: frame = client.screen() @@ -171,14 +171,14 @@ def run(args): 'ThemeSel did not open at native first entry') take_frame('theme-selector') report['native_themes_first'] = True - client.write(f'/pane/{selector}/ctl', b'exec Del\n') + client.write(f'/pane/{selector}/exec', b'Del\n') command(client, terminal, 'Collapse') for pet in (() if args.skip_pets else ('cat', 'frog', 'off')): command(client, right, 'Pet ' + pet) settings = config_report() require('Pet: ' + pet + '\n' in settings, 'pet setting not applied') # Returning focus to the source closes all transient report state. - client.write(f'/pane/{source}/ctl', f'look {source_path}:1\n'.encode()) + client.write(f'/pane/{source}/look', f'{source_path}:1\n'.encode()) take_frame('pet-' + pet) if pet != 'off': frame = client.screen() diff --git a/test/column_tags.py b/test/column_tags.py index 80b623bd..fe3a8699 100644 --- a/test/column_tags.py +++ b/test/column_tags.py @@ -143,7 +143,7 @@ def run(args): client.write(f'/pane/{right}/name', f'{right_name}\n'.encode()) right_body = b'// Column-local scratch\nfn main() {\n let ready = true;\n}\n' client.write(f'/pane/{right}/body', right_body) - client.write(f'/pane/{right}/ctl', b'clean\n') + client.write(f'/pane/{right}/dirty', b'0\n') require(wait_for(lambda: locate(client, 'New Tty', row=1, minimum_col=75)), 'right column tag missing') require(locate(client, 'New Tty', row=1, minimum_col=75) == (75, 1), 'right column tag retains an inset') @@ -173,7 +173,7 @@ def run(args): extra = require(wait_for(lambda: new_serial(client, before)), 'right-column New did not create a pane') client.write(f'/pane/{extra}/body', b'RIGHT-COLUMN-NEW\n') require(wait_for(lambda: locate(client, 'RIGHT-COLUMN-NEW', minimum_col=75)), 'right-column command targeted another column') - client.write(f'/pane/{extra}/ctl', b'exec Del\n') + client.write(f'/pane/{extra}/exec', b'Del\n') checks.append('middle-click New targets the inactive right column') # An owned short-path file makes its complete tag visible. Pane-tag diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index f7f380df..5a181b78 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -92,7 +92,7 @@ pub const Harness = struct { const ws = posix.winsize{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; const pid = forkpty(&master, null, null, &ws); if (pid == 0) { - for ([_][*:0]const u8{ "PARDES_9P", "PARDES_PANE", "PARDES_FORWARD_LOOK" }) |name| + for ([_][*:0]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE" }) |name| if (unsetenv(name) != 0) _exit(126); _ = execvp(exe, argv.ptr); _exit(127); diff --git a/test/font_size.py b/test/font_size.py index 3a0a9a28..b7104099 100644 --- a/test/font_size.py +++ b/test/font_size.py @@ -30,16 +30,16 @@ def run(args): for serial, tag in panes(client).items(): if '/+Config ' in tag: body = client.read(f'/pane/{serial}/body').decode() - if f'Font effective size: {size:.2f} pixels' in body: + if f'Font effective size {size:.2f} pixels' in body: return body return None return require(wait_for(ready), f'Font did not become {size} pixels') initial = report(18) - require('Font requested size: 18.00' in initial, 'startup size suffix ignored') + require('Font requested size 18.00' in initial, 'startup size suffix ignored') require(args.font in initial, 'requested font missing') execute(client, control, f'Font {args.font}:20.5') - require('Font requested size: 20.50' in report(20.5), 'fractional size ignored') + require('Font requested size 20.50' in report(20.5), 'fractional size ignored') execute(client, control, f'Font {args.font}') report(20.5) # no suffix preserves current size execute(client, control, f'Font {args.font}:900') diff --git a/test/fs.py b/test/fs.py index 819a78d6..c3ffa440 100644 --- a/test/fs.py +++ b/test/fs.py @@ -100,8 +100,15 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False assert not reader.is_alive(), 'terminal reader did not stop' +def newest(client): + """The newest pane's serial: /index is ordered by serial.""" + return int(client.read('/index').splitlines()[-1].split()[0]) + + def new_pane(client, contents): - serial = int(client.read('/new').split()[0]) + """mkdir in /pane; the editor names the directory after the new serial.""" + client.mkdir('/pane', 'scratch') + serial = newest(client) if contents: client.write(f'/pane/{serial}/body', contents) return serial @@ -110,18 +117,18 @@ def new_pane(client, contents): def look(client, path, source=None): """A right click on `path` from a pane (a fresh scratch by default).""" serial = source if source is not None else new_pane(client, b'') - client.write(f'/pane/{serial}/ctl', f'look {path}\n'.encode()) - results = [int(row) for row in client.read('/ctl').split()] + client.write(f'/pane/{serial}/look', f'{path}\n'.encode()) + results = [int(row) for row in client.read('/look').split()] assert len(results) == 1 and results[0] != serial, (path, results) return results[0] def execute(client, serial, command): """A middle click on `command` from a pane.""" - client.write(f'/pane/{serial}/ctl', f'exec {command}\n'.encode()) + client.write(f'/pane/{serial}/exec', f'{command}\n'.encode()) -def walk_tree(client, path='/', skip=('/new', '/log', '/os', '/screen')): +def walk_tree(client, path='/', skip=('/log', '/os', '/screen')): """Stat every entry below `path`, as `find` does, without opening anything.""" seen = [] for name in client.list(path): @@ -138,18 +145,21 @@ def discovery(binary, embedded=False): root = Path(directory) with session(binary, root, 'discovery') as (client, _): top = client.list('/') - assert top[:9] == ['README', 'index', 'ctl', 'new', 'log', 'screen', 'listeners', 'pane', 'os'], top - assert 'self' not in top and 'cons' not in top, top + assert top[:10] == ['README', 'index', 'status', 'look', 'exec', 'log', 'screen', + 'listeners', 'pane', 'os'], top + assert 'self' not in top and 'cons' not in top and 'new' not in top, top assert ('src' in top) == embedded, (top, embedded) before = client.read('/index') guide = client.read('/README') - assert guide.count(b'\n') <= 45 and b'exec Msg' in guide and b'/new' in guide, guide + assert guide.count(b'\n') <= 45 and b'Msg hello' in guide and b'mkdir' in guide, guide assert client.stat('/README')['length'] == len(guide) # ls/stat/find over the whole tree, without opening, creates nothing. seen = walk_tree(client) names = {path for path, _ in seen} - assert {'/index', '/ctl', '/new', '/log', '/pane/1', '/pane/1/body', '/pane/1/name', - '/pane/1/sel', '/pane/1/ctl', '/pane/1/tag', '/pane/1/event'} <= names, sorted(names) + assert {'/index', '/status', '/look', '/exec', '/log', '/pane/1', '/pane/1/body', + '/pane/1/name', '/pane/1/sel', '/pane/1/ctl', '/pane/1/tag', '/pane/1/event', + '/pane/1/dot', '/pane/1/limit', '/pane/1/dirty', '/pane/1/mark', + '/pane/1/scroll', '/pane/1/look', '/pane/1/exec'} <= names, sorted(names) assert '/pane/1/pty' not in names, 'the fixture file pane grew a pty/' assert not any(name.startswith('/self') or name.endswith('/rdsel') or name.endswith('/wrsel') for name in names), sorted(names) @@ -159,18 +169,28 @@ def discovery(binary, embedded=False): assert client.read('/index') == before, 'browsing created a pane' assert client.stat('/index')['length'] == len(before) > 0 index = client.stat('/index') - assert index['mode'] == 0o444 and client.stat('/ctl')['mode'] == 0o666 + assert index['mode'] == 0o444 and client.stat('/status')['mode'] == 0o444 + assert client.stat('/exec')['mode'] == 0o666 assert client.stat('/pane/1/body')['mode'] == 0o666 and client.stat('/pane')['mode'] == 0o755 + # A range file reads the pair it takes; a flag file reads 0 or 1. + assert client.stat('/pane/1/addr')['length'] == 24 + assert client.stat('/pane/1/limit')['length'] == 0 + assert client.read('/pane/1/dirty') == b'0\n' + assert client.read('/pane/1/scroll') == b'1\n' fixture = int(before.split()[0]) assert before.split()[1:3] == [b'text', b'0'] and before.endswith(b'/discovery.txt\n'), before - # Before any command, /ctl reports the editor. - status = dict(line.split(maxsplit=1) for line in client.read('/ctl').decode().splitlines()) - assert int(status['pid']) > 0 and status['version'] and int(status['panes']) == 1, status - # /new: one pane per open, its serial is the file's content. + # /status reports the editor; /exec has nothing to report yet. + status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) + assert int(status['pid']) > 0 and status['version'] and int(status['panes']) >= 1, status + assert client.read('/exec') == b'' + # mkdir makes a pane, named by the serial the editor gives it. log = client.open('/log') - first = int(client.read('/new').split()[0]) - second = int(client.read('/new').split()[0]) + client.mkdir('/pane', 'one') + first = newest(client) + client.mkdir('/pane', 'two') + second = newest(client) assert first != second and first != fixture, (first, second) + assert 'one' not in client.list('/pane') and 'two' not in client.list('/pane') assert client.read_fid(log) == f'new {first} {root}/+New\n'.encode() assert client.read_fid(log) == f'new {second} {root}/+New\n'.encode() assert set(client.list('/pane')) == {str(fixture), str(first), str(second)} @@ -186,51 +206,63 @@ def discovery(binary, embedded=False): assert client.read(f'/pane/{first}/name') == f'{root}/notes.txt\n'.encode() assert client.read_fid(log) == f'rename {first} {root}/notes.txt\n'.encode() assert client.stat(f'/pane/{first}/name')['length'] == len(f'{root}/notes.txt\n') + # Copying addr onto dot selects that range; sel reads and replaces it. client.write(f'/pane/{first}/addr', b'#0,#5') - client.write(f'/pane/{first}/ctl', b'dot=addr\n') + client.write(f'/pane/{first}/dot', client.read(f'/pane/{first}/addr')) + assert client.read(f'/pane/{first}/dot') == client.read(f'/pane/{first}/addr') assert client.read(f'/pane/{first}/sel') == b'first' assert client.stat(f'/pane/{first}/sel')['length'] == 5 client.write(f'/pane/{first}/sel', b'FIRST') assert client.read(f'/pane/{first}/body') == b'FIRST pane' assert client.read(f'/pane/{first}/sel') == b'' - # exec Msg shows text; exec Save writes the named file; exec Del closes. - client.write(f'/pane/{first}/ctl', b'exec Msg hello from 9P\n') + # exec Msg shows text; exec Save writes the named file; rmdir closes. + client.write(f'/pane/{first}/exec', b'Msg hello from 9P\n') assert 'hello from 9P' in ''.join(cell[0] for cell in client.screen()['cells']) - client.write(f'/pane/{first}/ctl', b'exec Save\n') + assert client.read(f'/pane/{first}/dirty') == b'1\n' + client.write(f'/pane/{first}/exec', b'Save\n') assert (root / 'notes.txt').read_bytes() == b'FIRST pane' assert client.read_fid(log) == f'save {first} {root}/notes.txt\n'.encode() - assert client.read('/ctl') == f'{first}\n'.encode() - client.write('/ctl', b'exec Del\n') + assert client.read('/exec') == f'{first}\n'.encode() + assert client.read(f'/pane/{first}/dirty') == b'0\n' + client.remove(f'/pane/{second}') assert client.read_fid(log) == f'del {second} {root}/+New\n'.encode() assert str(second) not in client.list('/pane') - # look through /ctl opens a file; the serial reads back. + # look opens a file; the serial reads back. (root / 'opened.txt').write_bytes(b'one\ntwo\nthree\n') - client.write('/ctl', f'look {root}/opened.txt:2\n'.encode()) - opened = int(client.read('/ctl')) + client.write('/look', f'{root}/opened.txt:2\n'.encode()) + opened = int(client.read('/look')) assert opened not in (fixture, first, second), opened assert client.read(f'/pane/{opened}/body') == b'one\ntwo\nthree\n' assert client.read(f'/pane/{opened}/name') == f'{root}/opened.txt\n'.encode() assert client.read_fid(log) == f'new {opened} {root}/opened.txt\n'.encode() - client.write(f'/pane/{first}/ctl', f'look {root}/opened.txt:3\n'.encode()) - assert client.read('/ctl') == f'{opened}\n'.encode(), 'a repeated look targets the open pane' - assert set(client.list('/pane')) == {str(fixture), str(first), str(opened)} + client.write(f'/pane/{first}/look', f'{root}/opened.txt:3\n'.encode()) + assert client.read('/look') == f'{opened}\n'.encode(), 'a repeated look targets the open pane' + assert {str(fixture), str(first), str(opened)} <= set(client.list('/pane')) # Writing an event record back still performs the action it names. client.write(f'/pane/{first}/body', b'Msg via event', truncate=True) client.write(f'/pane/{first}/event', b'FX0 13\n') assert 'via event' in ''.join(cell[0] for cell in client.screen()['cells']) - for bad in [b'Look x\n', b'Exec Msg x\n', b'put\n', b'name x\n', b'del\n']: + # A command line may not carry control characters, and nothing else + # in the tree may be created or removed. + refused = [lambda: client.write('/exec', b'Msg a\x00b'), + lambda: client.write('/status', b'anything\n'), + lambda: client.mkdir('/', 'x'), + lambda: client.create('/pane', 'plain-file'), + lambda: client.remove('/pane/1/body'), + lambda: client.remove('/index')] + for index, attempt in enumerate(refused): try: - client.write('/ctl', bad) + attempt() except OSError: pass else: - raise AssertionError(f'{bad!r} was accepted') + raise AssertionError(f'refusal {index} was accepted') client.close(log) if embedded: assert client.read('/src/pardes.zig').startswith(b'const std') assert client.stat('/src/pardes.zig')['mode'] == 0o444 assert b'pub const Pardes' in client.read(f'/pane/{look(client, "/virtual/src/pardes.zig")}/body') - print('9P discovery: listing/stat/find are inert; new, ctl, name, sel and log behave') + print('9P discovery: listing/stat/find are inert; create, remove, look, exec, name, sel and log behave') def test(binary, quic=False): @@ -266,7 +298,7 @@ def test(binary, quic=False): assert not (root / 'pardes-9p-renamed.sock').exists() assert named.read('/pane/1/body') == b'initial\n' with session(binary, root, 'first') as (client, address): - assert {'pane', 'index', 'new', 'ctl', 'log', 'os'} <= set(client.list('/')) + assert {'pane', 'index', 'status', 'look', 'exec', 'log', 'os'} <= set(client.list('/')) assert 'self' not in client.list('/') assert client.read('/pane/1/body') == b'initial\n' assert client.read('/os' + str(root / 'first.txt')) == b'initial\n' @@ -346,7 +378,7 @@ def test(binary, quic=False): opened = look(remote, '/n/peer/pane/' + str(serial) + '/body') assert remote.read(f'/pane/{opened}/body') == b'replaced\nevent\n' remote.write(f'/pane/{opened}/body', b'saved to peer\n', truncate=True) - remote.write(f'/pane/{opened}/ctl', b'exec Save\n') + remote.write(f'/pane/{opened}/exec', b'Save\n') assert client.read(body) == b'saved to peer\n' large = b'mounted file contents\n' * 60000 @@ -356,7 +388,7 @@ def test(binary, quic=False): assert remote.read(f'/pane/{opened}/body') == large edited = large[:-3] + b'edited\n' remote.write(f'/pane/{opened}/body', edited, truncate=True) - remote.write(f'/pane/{opened}/ctl', b'exec Save\n') + remote.write(f'/pane/{opened}/exec', b'Save\n') assert large_path.read_bytes() == edited assert client.read('/os' + str(large_path)) == edited @@ -368,12 +400,12 @@ def test(binary, quic=False): execute(remote, control, 'Mount peer ' + str(own_address)) execute(remote, control, 'Unmount peer') remote.write(f'/pane/{opened}/body', b'runtime mounted Save\n', truncate=True) - remote.write(f'/pane/{opened}/ctl', b'exec Save\n') + remote.write(f'/pane/{opened}/exec', b'Save\n') assert client.read('/pane/1/body') == b'runtime mounted Save\n' assert remote.read('/pane/1/body') == b'initial\n' roots = look(remote, '/n', source=control) assert b'/n/peer/\n' in remote.read(f'/pane/{roots}/body') - remote.write(f'/pane/{opened}/ctl', b'exec Del\n') + remote.write(f'/pane/{opened}/exec', b'Del\n') execute(remote, control, 'Unmount peer') remote.write(f'/pane/{roots}/ctl', b'get\n') assert remote.read(f'/pane/{roots}/body') == b'/n/os/\n/n/self/\n' @@ -385,7 +417,7 @@ def test(binary, quic=False): file='/n/peer/pane/1/body:1') as (remote, _): assert remote.read('/pane/1/body') == b'runtime mounted Save\n' - client.write(f'/pane/{serial}/ctl', b'exec Del\n') + client.write(f'/pane/{serial}/exec', b'Del\n') assert str(serial) not in client.list('/pane') for tty in [False, True]: @@ -424,7 +456,7 @@ def test(binary, quic=False): file_id, control_id = restored_ids contents = restored.read(f'/pane/{file_id}/body') assert contents == b'dumped state\n', (contents, saved.read_text(), restored.read('/index')) - assert restored.read(f'/pane/{control_id}/body') == b'', 'commands ran through ctl, not the body' + assert restored.read(f'/pane/{control_id}/body') == b'', 'commands ran through exec, not the body' assert restored.screen()['cols'] == 80 opened = look(restored, '/n/own/os' + str(root / (name + '.txt')), source=control_id) assert restored.read(f'/pane/{opened}/body') == b'initial\n' @@ -451,14 +483,12 @@ def test(binary, quic=False): assert client.read(f'/pane/{opened}/body') == expected assert client.read('/pane/1/body') == b'initial\n' if selected is not None: - addr = client.open(f'/pane/{opened}/addr') - client.write(f'/pane/{opened}/ctl', b'addr=dot\n') - actual = list(map(int, client.read_fid(addr).split())) - client.close(addr) + # The selection is dot; reading it takes no command at all. + actual = list(map(int, client.read(f'/pane/{opened}/dot').split())) assert actual == selected, (word, actual, selected) addr = client.open('/pane/1/addr', 2) - ctl = client.open('/pane/1/ctl', 1) - for fid, text in [(addr, b'#0,#3'), (ctl, b'limit=addr\n'), (addr, b'#0')]: + limit = client.open('/pane/1/limit', 2) + for fid, text in [(addr, b'#0,#3'), (limit, b'#0,#3'), (addr, b'#0')]: client.rpc(118, struct.pack(' req.size) return error.IncorrectReply; - const names = [_][]const u8{ "README", "index", "ctl", "new", "log", "screen", "listeners", "pane", "os" }; - const nodes = [_]u64{ @intFromEnum(ctlfs.TopFile.README), @intFromEnum(ctlfs.TopFile.index), @intFromEnum(ctlfs.TopFile.ctl), @intFromEnum(ctlfs.TopFile.new), @intFromEnum(ctlfs.TopFile.log), @intFromEnum(ctlfs.TopFile.screen), @intFromEnum(ctlfs.TopFile.listeners), @intFromEnum(ctlfs.TopFile.pane), filesystem.os_root }; + const names = [_][]const u8{ "README", "index", "status", "look", "exec", "log", "screen", "listeners", "pane", "os" }; + const nodes = [_]u64{ @intFromEnum(ctlfs.TopFile.README), @intFromEnum(ctlfs.TopFile.index), @intFromEnum(ctlfs.TopFile.status), @intFromEnum(ctlfs.TopFile.look), @intFromEnum(ctlfs.TopFile.exec), @intFromEnum(ctlfs.TopFile.log), @intFromEnum(ctlfs.TopFile.screen), @intFromEnum(ctlfs.TopFile.listeners), @intFromEnum(ctlfs.TopFile.pane), filesystem.os_root }; var off: usize = 0; var entry: usize = 0; while (off < bytes.len) : (entry += 1) { diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index 8b6f245e..3eba6639 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -245,22 +245,17 @@ test "virtual file opens do not request OS watches" { while (p.nextEffect()) |effect| if (effect == .watch) return error.VirtualFileWatch; } -test "Look at the clone file reserves its own pane and failed opens release it" { +test "Look at a virtual file opens one pane and failed opens release their slot" { const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); - p.lookAt(0, "/virtual/new"); - var control_count: usize = 0; - var scratch_count: usize = 0; + p.lookAt(0, "/virtual/index"); + var opened: usize = 0; for (p.panes) |slot| { const pane = slot orelse continue; const file = pane.file orelse continue; - if (std.mem.eql(u8, file.path, "/virtual/new")) control_count += 1; - if (file.output) |output| if (output.from == .cmd and output.from.cmd == .New) { - scratch_count += 1; - }; + if (std.mem.eql(u8, file.path, "/virtual/index")) opened += 1; } - try std.testing.expectEqual(@as(usize, 1), control_count); - try std.testing.expectEqual(@as(usize, 1), scratch_count); + try std.testing.expectEqual(@as(usize, 1), opened); const free = p.freeSlot().?; try std.testing.expectError(error.FileNotFound, pardes.panes.File.open(p, free, "/n/self/does-not-exist", 0)); try std.testing.expect(p.panes[free] == null); diff --git a/test/fs_soak.py b/test/fs_soak.py index 5569a7c7..a62f03e6 100644 --- a/test/fs_soak.py +++ b/test/fs_soak.py @@ -145,7 +145,7 @@ def run(args): client.write(base + '/body', body, truncate=True) path = root / f'pane-{slot}-0.zig' client.write(base + '/name', f'{path}\n'.encode()) - client.write(base + '/ctl', b'exec Save\n') + client.write(base + '/exec', b'Save\n') panes.append({'serial': serial, 'body': body, 'path': path, 'variant': 0}) emit(kind='start', seed=args.seed, session_pid=pid, transport=args.transport, host='tty' if args.tty else 'detached', @@ -187,7 +187,7 @@ def run(args): pane['variant'] ^= 1 pane['path'] = root / f'pane-{slot}-{pane["variant"]}.zig' client.write(base + '/name', f'{pane["path"]}\n'.encode()) - client.write(base + '/ctl', b'exec Save\n') + client.write(base + '/exec', b'Save\n') check_bytes(pane['path'].read_bytes(), pane['body'], 'saved file') check_bytes(client.read('/os' + str(pane['path'])), pane['body'], 'OS mount') elif operation == 'reload': @@ -196,13 +196,13 @@ def run(args): client.write(base + '/ctl', b'get\n') elif operation == 'cycle': old_serial = pane['serial'] - client.write(base + '/ctl', b'exec Del\n') + client.remove(base) pane['body'] = payload(rng) pane['serial'] = new_pane(client, pane['body']) assert pane['serial'] != old_serial base = f'/pane/{pane["serial"]}' client.write(base + '/name', f'{pane["path"]}\n'.encode()) - client.write(base + '/ctl', b'exec Save\n') + client.write(base + '/exec', b'Save\n') elif operation == 'reconnect': client.socket.close() client = Client(address) diff --git a/test/look_placement.py b/test/look_placement.py index 1341e776..8a31157f 100644 --- a/test/look_placement.py +++ b/test/look_placement.py @@ -74,7 +74,7 @@ def run_case(args, root, source_index): require('pty' in client.list(pane), 'fixture contains an existing document') marker = f'LP_{index}' markers[serial] = marker - client.write(pane + '/ctl', b'cleartag\n') + client.write(pane + '/tag', b'', truncate=True) client.write(pane + '/tag', f' {marker} Tty Del Collapse'.encode()) # Establish non-pristine shells and a stable prompt before measuring. client.write(pane + '/pty/data', f"printf 'ready-{index}\\n'\r".encode()) @@ -89,7 +89,7 @@ def run_case(args, root, source_index): require(before[serials[0]][:2] == (0, 2) and before[serials[1]][0] == 0 and before[serials[1]][1] > 2 and before[serials[2]][:2] == (75, 2), f'unexpected initial classic layout: {before}') - client.write(f'/pane/{source}/ctl', f'look {target}\n'.encode()) + client.write(f'/pane/{source}/look', f'{target}\n'.encode()) opened = require(wait_for(lambda: next((serial for serial in panes(client) if serial not in serials), None)), 'Look did not open the first document') @@ -113,7 +113,7 @@ def run_case(args, root, source_index): f'Look changed unrelated terminal {serial} rendered text') require(client.read(f'/pane/{opened}/body') == contents, 'opened document contents differ') - client.write(f'/pane/{source}/ctl', f'look {target}:2\n'.encode()) + client.write(f'/pane/{source}/look', f'{target}:2\n'.encode()) require(list(panes(client)) == serials + [opened], 'repeated Look created a duplicate pane') require(wait_for(lambda: geometry(client, markers)[1] == after), 'repeated Look changed layout') diff --git a/test/ninep.py b/test/ninep.py index 6c625951..ac4e146b 100644 --- a/test/ninep.py +++ b/test/ninep.py @@ -97,6 +97,25 @@ class Client: def close(self, fid): self.rpc(120, struct.pack(' |w| { + const bytes = w.bytes.slice(); + if (n + bytes.len > buf.len) break; + @memcpy(buf[n..][0..bytes.len], bytes); + n += bytes.len; + }, + else => {}, + }; + return buf[0..n]; + } + + // Raw tty mode forwards nearly every key to the child; the two paste + // chords are the exception, and forwarding them instead is what broke + // pasting into a terminal pane. An application that gets Ctrl-V rather + // than the text goes and reads the desktop clipboard on its own account, + // and a coding agent reading it is looking for an image, not for words. + test "raw tty paste chords type at the program instead of reaching it as keys" { + if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + for ([_]bool{ false, true }) |bracketed| { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + const pane = p.panes[0].?; + try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + if (bracketed) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); + try std.testing.expectEqual(bracketed, panes.Terminal.bracketedPaste(pane)); + p.yank = try p.gpa.dupe(u8, "one\ntwo"); // what a `y` anywhere left behind + var buf: [256]u8 = undefined; + _ = childInput(p, &buf); + + // Ctrl-V types the register straight at the program, asking the + // desktop for nothing. Under DECSET 2004 the program's own fences + // carry it, which is what stops readline RUNNING a multi-line paste. + p.update(.{ .key = .{ .cp = 'v', .ctrl = true } }); + try std.testing.expectEqualStrings( + if (bracketed) "\x1b[200~one\ntwo\x1b[201~" else "one\rtwo", + childInput(p, &buf), + ); + try std.testing.expect(p.clip_pending == null); + + // Ctrl-Shift-V is the other store: it ASKS, types nothing yet, and + // the answer lands at the program rather than in an edit buffer. A + // host that folds the Shift into the letter says the same thing. + for ([_]Key{ + .{ .cp = 'v', .ctrl = true, .shift = true }, + .{ .cp = 'V', .ctrl = true }, + }) |chord| { + p.update(.{ .key = chord }); + try std.testing.expect(p.clip_pending != null); + try std.testing.expectEqualStrings("", childInput(p, &buf)); + p.update(.{ .paste = "from-desktop" }); + try std.testing.expect(p.clip_pending == null); + try std.testing.expectEqualStrings( + if (bracketed) "\x1b[200~from-desktop\x1b[201~" else "from-desktop", + childInput(p, &buf), + ); + } + // ...and neither chord put the clipboard in the register on its way. + try std.testing.expectEqualStrings("one\ntwo", p.yank orelse ""); + } + } }; const ClickCursorTests = struct { @@ -1616,7 +1682,7 @@ test "generated output refuses every pipe prompt before seeding the tag" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const content = try p.gpa.dupe(u8, "generated\n"); - const pane = try panes.Output.open(p, 1, "/", .{ .cmd = .Help }, "", content); + const pane = try panes.Output.open(p, p.freeSlot().?, "/", .{ .cmd = .Help }, "", content); p.active = 1; for ([_]Key{ .{ .cp = '|' }, .{ .cp = '|', .alt = true }, .{ .cp = '!' }, .{ .cp = '!', .alt = true } }) |key| { p.update(.{ .key = key }); @@ -1825,14 +1891,14 @@ test "file history construction failures preserve existing panes" { defer if (incoming) |bytes| p.gpa.free(bytes); failing.fail_index = failing.alloc_index + failure; const result = switch (case) { - .open => panes.File.open(p, 1, path, 0), + .open => panes.File.open(p, p.freeSlot().?, path, 0), .restore => panes.File.restore(p, 1, .{ .kind = .file, .tag = "", .body = "", .file = .{ .path = "/restored.zig", .content = "restored\n" }, }), - .output => panes.Output.open(p, 1, "/", .{ .cmd = .Help }, "", incoming.?), + .output => panes.Output.open(p, p.freeSlot().?, "/", .{ .cmd = .Help }, "", incoming.?), .tutor => p.openTutorView(1), .replace => p.setTestFile("replacement\n"), }; @@ -1900,14 +1966,14 @@ test "file history owns bounded snapshot storage without per-edit bookkeeping al try std.testing.expectEqual(@as(usize, 0), history.redo_len); } -test "file history allocation precedes a filesystem read with side effects" { +test "file history allocation precedes reading the served tree" { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); const original = p.panes[0].?; const serial = p.next_serial; failing.fail_index = failing.alloc_index + 2; - try std.testing.expectError(error.OutOfMemory, panes.File.open(p, 1, "/n/self/new", 0)); + try std.testing.expectError(error.OutOfMemory, panes.File.open(p, p.freeSlot().?, "/n/self/index", 0)); try std.testing.expect(failing.has_induced_failure); try std.testing.expectEqual(original, p.panes[0].?); try std.testing.expectEqual(serial, p.next_serial); diff --git a/test/pdf.zig b/test/pdf.zig index beeb0b40..930cc5c0 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -1253,7 +1253,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { try std.testing.expectEqual(PdfTintMode.filtered, pv.tint); const initial_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.startsWith(u8, initial_tag, pv.path)); - try std.testing.expect(std.mem.endsWith(u8, initial_tag, " PdfSections PdfTint Collapse")); + try std.testing.expect(std.mem.endsWith(u8, initial_tag, " PdfSections PdfTint Collapse Del")); try std.testing.expect(std.mem.indexOf(u8, initial_tag, "filtered") == null); try std.testing.expect(pardes.test_api.runBuiltin( diff --git a/test/tag_cleanup.py b/test/tag_cleanup.py index 7b7d8bbf..ae0a0e66 100644 --- a/test/tag_cleanup.py +++ b/test/tag_cleanup.py @@ -36,7 +36,7 @@ def run(args): before = set(panes(client)) execute(client, control, 'Tty') tty = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'terminal missing') - client.write(f'/pane/{control}/ctl', b'exec Del\n') # owned command-only scratch + client.write(f'/pane/{control}/exec', b'Del\n') # owned command-only scratch def tag_position(): frame = client.screen() diff --git a/test/ui_review.py b/test/ui_review.py index 2b6faa29..a1cdcdeb 100644 --- a/test/ui_review.py +++ b/test/ui_review.py @@ -43,7 +43,7 @@ def command(client, serial, text): current = client.read(tag) start = current.rfind(text.encode()) client.write(f'/pane/{serial}/event', f'Mx{start} {start + len(text.encode())}\n'.encode()) - client.write(f'/pane/{serial}/ctl', b'cleartag\n') + client.write(f'/pane/{serial}/tag', b'', truncate=True) client.write(tag, before[tail_start:]) def new_output(client, before): @@ -111,7 +111,7 @@ def run(args): capture(client, root, '02-find', not args.tty) if find_pane: (root / 'find-results.txt').write_bytes(client.read(f'/pane/{find_pane}/body')) - client.write(f'/pane/{find_pane}/ctl', b'exec Del\n') + client.write(f'/pane/{find_pane}/exec', b'Del\n') before = panes(client) command(client, source, 'Grep CrdsValueLabel') grep_pane = require(wait_for(lambda: new_output(client, before)), 'Grep did not return results') @@ -140,10 +140,10 @@ def run(args): (root / 'symbols-results.txt').write_bytes(client.read(f'/pane/{symbols}/body')) capture(client, root, '05-symbols', not args.tty) if symbols: - client.write(f'/pane/{symbols}/ctl', b'exec Del\n') + client.write(f'/pane/{symbols}/exec', b'Del\n') offset = original.index(b'CrdsValue {') client.write(f'/pane/{source}/addr', f'#{offset},#{offset}'.encode()) - client.write(f'/pane/{source}/ctl', b'dot=addr\nshow\n') + client.write(f'/pane/{source}/dot', client.read(f'/pane/{source}/addr')) before = panes(client) command(client, source, 'Hover') hover = wait_for(lambda: new_output(client, before), args.lsp_wait) @@ -154,7 +154,7 @@ def run(args): # Look focuses the source without changing it; gd then travels through # the host's real input parser, unlike tag builtin dispatch above. line = original[:original.index(b'impl Sanitize for CrdsValue')].count(b'\n') + 1 - client.write(f'/pane/{source}/ctl', f'look {source_path}:{line}:19\n'.encode()) + client.write(f'/pane/{source}/look', f'{source_path}:{line}:19\n'.encode()) os.write(terminal_handle['input_fd'], b'gd') time.sleep(1) capture(client, root, '07-definition', not args.tty) @@ -166,7 +166,7 @@ def run(args): report['lsp'] = info.decode() capture(client, root, '08-lsp-info', not args.tty) if lsp: - client.write(f'/pane/{lsp}/ctl', b'exec Del\n') + client.write(f'/pane/{lsp}/exec', b'Del\n') for theme in args.themes: command(client, source, 'Theme ' + theme) capture(client, root, 'theme-' + theme, not args.tty) diff --git a/test/v9fs.py b/test/v9fs.py index 16916d0b..fa35388f 100644 --- a/test/v9fs.py +++ b/test/v9fs.py @@ -43,8 +43,8 @@ def worker(mountpoint, socket, uid, gid, original_namespace): assert not any(field.startswith(('shared:', 'master:')) for field in mounted[0].split()[6:]) tree = mountpoint - assert {'os', 'index', 'pane', 'new', 'ctl', 'log', 'screen', 'README'} <= set(os.listdir(tree)) - assert 'self' not in os.listdir(tree) + assert {'os', 'index', 'pane', 'status', 'look', 'exec', 'log', 'screen', 'README'} <= set(os.listdir(tree)) + assert 'self' not in os.listdir(tree) and 'new' not in os.listdir(tree) # A direct connection provides independent evidence for VFS reads/writes. with Client(socket) as client: assert (tree / 'index').read_bytes() == client.read('/index') @@ -52,14 +52,31 @@ def worker(mountpoint, socket, uid, gid, original_namespace): before = client.read('/index') subprocess.run(['ls', '-l', str(tree), str(tree / 'pane' / '1')], check=True, capture_output=True, timeout=5) - subprocess.run(['find', str(tree / 'pane'), str(tree / 'new'), '-ls'], check=True, capture_output=True, timeout=5) + subprocess.run(['find', str(tree / 'pane'), '-ls'], check=True, capture_output=True, timeout=5) assert (tree / 'README').read_bytes() == client.read('/README') - assert (tree / 'new').stat().st_size == 0 assert client.read('/index') == before, 'browsing created panes' - serial = int((tree / 'new').read_bytes().split()[0]) - another = int((tree / 'new').read_bytes().split()[0]) - assert serial != another, 'cached factory reused a pane' - client.write(f'/pane/{another}/ctl', b'exec Del\n') + # mkdir through the kernel mount opens a pane. The editor names it + # after its serial, not after the name asked for, so the kernel's own + # revalidation of that name may fail; the index is the answer. + def serials(): + return {int(row.split()[0]) for row in (tree / 'index').read_bytes().splitlines()} + + def mkpane(name): + known = serials() + try: + (tree / 'pane' / name).mkdir() + except FileNotFoundError: + pass + made = serials() - known + assert len(made) == 1, (name, made) + return made.pop() + + serial = mkpane('kernel-made') + another = mkpane('kernel-made-again') + assert serial != another, 'a second mkdir reused a pane' + assert not (tree / 'pane' / 'kernel-made').exists() + (tree / 'pane' / str(another)).rmdir() + assert another not in serials() pane = tree / 'pane' / str(serial) wire = f'/pane/{serial}' assert str(serial) in os.listdir(tree / 'pane') @@ -101,7 +118,7 @@ def worker(mountpoint, socket, uid, gid, original_namespace): # Reading OS files through the exported tree does not recurse through # the mount: the core still lives in the supervisor's namespace. assert (mountpoint / 'os' / str(socket.parent).lstrip('/') / 'kernel.txt').read_bytes() == b'initial\n' - write_existing(pane / 'ctl', b'exec Del\n') + (tree / 'pane' / str(serial)).rmdir() assert serial not in [int(row.split()[0]) for row in (tree / 'index').read_bytes().splitlines()] print('v9fs: namespace isolation, privilege drop, inherited mount, directory refresh, ' diff --git a/test/window_opacity.py b/test/window_opacity.py index b9529373..a576b1bd 100644 --- a/test/window_opacity.py +++ b/test/window_opacity.py @@ -60,7 +60,7 @@ def run(args): pane = require(wait_for(lambda: next((serial for serial in panes(client) if serial not in before), None)), builtin + ' output missing') text = client.read(f'/pane/{pane}/body').decode() - client.write(f'/pane/{pane}/ctl', b'exec Del\n') + client.write(f'/pane/{pane}/exec', b'Del\n') return text help_text = output('Help') -- cgit v1.3 From 760448928186382da4ef9d942af1a2b7546ef54c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 22 Sep 2026 01:24:56 -0300 Subject: Refuse a session's own mount, and paint notices as a tagline band Opening a path inside this editor's own 9P tree hung the session outright, and it is easy to do by accident: a file manager whose $EDITOR is pardes, or a Look at anything under /mnt/9p/pardes//. The realpath, the stat and the read all leave through the mount and come back as 9P requests only this editor's loop can answer, while that loop is blocked making them. The filesystem then stops answering anybody, which is what made it look frozen rather than slow. The answer has to come from the NAME, before any syscall, because the syscall is the thing that never returns: the listener notes the name it is posted under and `resolveOs` refuses a path containing `/pardes//`, with `readLimit` refusing it too for anything that gets past resolution. Another session's mount stays perfectly usable, and `/n/self/...` is the way to reach your own tree -- the editor serves it from memory without leaving the process. Reproduced before and after: the 9P write that never returned now returns, the editor stays responsive, and it spends four CPU ticks doing it. The transient lines also now look like what they were modelled on. They carried the context band's bookkeeping -- one list, rows reserved the way sticky headers reserve them -- but still painted as ordinary body text, so a message read as a stray line at the bottom of the pane rather than as part of its chrome. They take the tagline font and the tagline's own colours now, verified on a running editor: the announcement lands with font_role=tagline. Two tests the features never had: a builtin announcing itself, reaching the notice list, being overridden by Msg's own text and silenced by Verbose; and the own-mount guard, including that a session with no listener refuses nothing. Co-Authored-By: Claude Opus 5 (1M context) --- .agents/skills/pardes-9p/SKILL.md | 4 ++++ docs/fs.md | 10 ++++++++ src/9p_io.zig | 3 +++ src/fs.zig | 49 +++++++++++++++++++++++++++++++++++++++ src/pardes.zig | 42 +++++++++++++++++++++++++++++---- 5 files changed, 104 insertions(+), 4 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index aa856953..b776e407 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -69,6 +69,10 @@ echo "/etc/hosts:3" > "$m/look"; cat "$m/look" # open a file, see where it land rmdir "$m/pane/$n" # close it, dirty or not ``` +Do not open a session's own mount from inside that session -- a Look at +`$m/anything` in the editor that serves `$m` would deadlock it, so such paths +are refused. Use `/n/self/...` from inside; `$m/...` is for everyone else. + **Opening** `$m/pane/new` is what makes a pane, and reading the open file answers its serial — `/net/tcp/clone`'s mechanism. Each open makes another one, two reads of the same open file answer the same serial, and closing it leaves diff --git a/docs/fs.md b/docs/fs.md index d1ed2b73..6d2891e0 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -106,6 +106,16 @@ at the cost of acme's one-step `new/body`. Nothing in the tree is created by list, stat, walk or read; only that one open. Every other name in `/pane` is a serial. +A session cannot open its own tree through a mount. Looking at +`/mnt/9p/pardes//anything` from inside that very editor used to hang it +outright: the realpath, the stat and the read all leave through the mount and +come back as 9P requests only that editor's loop can answer, while the loop is +blocked making them, and the filesystem then stops answering anybody. Such a +path is now refused by name before any syscall runs, because the syscall is the +thing that never returns. Address your own tree as `/n/self/...`, which the +editor serves from memory without leaving the process. Another session's mount +is perfectly fine to open. + `/look` and `/exec` are the editor's two clicks, one per line of a write: - a line written to `look` is a right click on it: a path opens a file, diff --git a/src/9p_io.zig b/src/9p_io.zig index 7f0134ed..08deae7a 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1358,6 +1358,9 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes) ?*Listene return null; }; core.fs.socket_path = listener.path(); + // So the editor can recognise its own tree by name and refuse to walk into + // it through the mount, which would deadlock the loop that serves it. + pardes.filesystem.noteOwnSocket(listener.path()); core.fs.tcp_address = listener.tcp_address; core.fs.quic_address = listener.quic_address; return listener; diff --git a/src/fs.zig b/src/fs.zig index 7cb08980..5c75eb72 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -681,8 +681,56 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 return null; } +/// The name this session is posted under, taken from its socket path. +var own_name_buf: [64]u8 = undefined; +var own_name_len: usize = 0; + +pub fn noteOwnSocket(socket_path: []const u8) void { + own_name_len = 0; + const base = std.fs.path.basename(socket_path); + const head = "pardes-9p-"; + const tail = ".sock"; + if (!std.mem.startsWith(u8, base, head) or !std.mem.endsWith(u8, base, tail)) return; + const name = base[head.len .. base.len - tail.len]; + if (name.len == 0 or name.len > own_name_buf.len) return; + @memcpy(own_name_buf[0..name.len], name); + own_name_len = name.len; +} + +/// Is this path inside this editor's OWN 9P tree, as a mount presents it? +/// +/// Touching one from inside the editor deadlocks the session outright: the +/// realpath, the stat and the read all leave through the mount and come back +/// as 9P requests that only the editor's loop can answer, while that loop is +/// blocked making them. The filesystem then stops answering anybody. So the +/// answer has to come from the NAME, before any syscall -- the syscall is the +/// thing that never returns. Look at `/n/self/...` instead, which the editor +/// serves from memory without leaving the process. +pub fn isOwnMount(path: []const u8) bool { + if (own_name_len == 0) return false; + var buf: [own_name_buf.len + 16]u8 = undefined; + const needle = std.fmt.bufPrint(&buf, "/pardes/{s}/", .{own_name_buf[0..own_name_len]}) catch return false; + return std.mem.indexOf(u8, path, needle) != null; +} + +test "a path inside this session's own mount is refused before any syscall" { + noteOwnSocket("/run/user/1000/pardes-9p-demo.sock"); + defer own_name_len = 0; + try std.testing.expect(isOwnMount("/mnt/9p/pardes/demo/index")); + try std.testing.expect(isOwnMount("/mnt/9p/pardes/demo/pane/new")); + try std.testing.expect(!isOwnMount("/mnt/9p/pardes/other/index")); + try std.testing.expect(!isOwnMount("/home/goblin/src/pardes/demo.zig")); + var out: [4096]u8 = undefined; + try std.testing.expect(resolveOs("/mnt/9p/pardes/demo/index", &out) == null); + + // A session with no listener has no name, so nothing is refused. + noteOwnSocket("/tmp/not-a-pardes-socket"); + try std.testing.expect(!isOwnMount("/mnt/9p/pardes/demo/index")); +} + pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { if (comptime !platform_has_fs) return null; + if (isOwnMount(path)) return null; var z: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null; const resolved = realpath(path_z, out) orelse return null; @@ -706,6 +754,7 @@ pub fn read(p: *pardes.Pardes, path: []const u8) ![]u8 { } pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { + if (isOwnMount(path)) return error.OwnMount; const limit = @min(max_bytes, limits.max_file_bytes); if (std.mem.eql(u8, std.mem.trimEnd(u8, path, "/"), "/n")) { var out: std.Io.Writer.Allocating = .init(p.gpa); diff --git a/src/pardes.zig b/src/pardes.zig index 5c6d2422..ec743bc6 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -13387,7 +13387,7 @@ pub const Pardes = struct { s.previous_tag_layers = &.{}; s.cell_diffs = &.{}; const chrome = p.chromeTheme(); - const th = p.theme(); // the message row paints in the editor's colours + const th = p.theme(); // Separators have their own role; a scrollbar need not frame the page. s.fill(0, 0, s.cols, s.rows, .{ .bg = .{ .rgb = chrome.border } }); @@ -13407,9 +13407,14 @@ pub const Pardes = struct { const r = p.rects[id]; const tx = r.x + config.GUTTER; const tw = r.w - config.GUTTER; + // Painted the way the sticky context headers above them are: the + // tagline font and the tagline's own colours, so a notice reads as + // a band belonging to the pane rather than as a line of body text + // that happens to sit at the bottom of it. const msg_style: CellStyle = .{ - .fg = if (th.fg) |c| .{ .rgb = c } else .default, - .bg = if (th.bg) |c| .{ .rgb = c } else .default, + .fg = .{ .rgb = chrome.tag_fg }, + .bg = .{ .rgb = chrome.tag_bg }, + .font_role = .tagline, }; // The stack sits directly above the tagline, one line to a row, in // the order collectNotices chose. A single notice therefore lands @@ -13417,7 +13422,7 @@ pub const Pardes = struct { const bottom = if (p.settings.tag_bottom) r.y + r.h - 1 - BOX_H else r.y + r.h - 1; for (pane.notices.slice(), 0..) |kind, i| { const row = bottom - @as(u16, @intCast(pane.notices.len - 1 - i)); - s.fill(tx, row, tw, 1, .{ .bg = msg_style.bg }); + s.fill(tx, row, tw, 1, .{ .bg = msg_style.bg, .font_role = .tagline }); switch (kind) { .message => _ = s.print(tx, row, tw, pane.msg[0..pane.msg_len], msg_style), .leader => { @@ -14634,6 +14639,35 @@ test "Esc back into a tty leaves its view at the prompt" { try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset); } +test "a builtin announces itself on the message row, and Verbose silences it" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = p.panes[p.active].?; + + p.sync(); + try std.testing.expect(p.settings.verbose); + // Wrap, not Collapse: a builtin that folds its own pane away leaves no row + // for its announcement, which is correct and not what this is testing. + try std.testing.expect(p.executeBuiltinLine(p.active, "Wrap")); + try std.testing.expectEqualStrings("Wrap", pane.msg[0..pane.msg_len]); + + // The notice list is what the paint pass reads, so the announcement has to + // reach it, not just the buffer. + p.collectNotices(pane, p.rects[p.active], p.active); + try std.testing.expect(pane.notices.len > 0); + try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[0]); + + // Msg owns the row itself, so it does not announce over its own text. + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); + try std.testing.expectEqualStrings("hello", pane.msg[0..pane.msg_len]); + + pane.msg_len = 0; + p.settings.verbose = false; + try std.testing.expect(p.executeBuiltinLine(p.active, "Wrap")); + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); +} + test "closing the last pane in a column leaves an empty one in its place" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 24 }); -- cgit v1.3 From 43b9d696f9e25ad7589527b91a74666e71ff0472 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 22 Sep 2026 02:21:03 -0300 Subject: Notices become tagline bands at the top of the body A message, a leader chord and a prompt used to share one row of body text at the bottom of a pane, wearing the tagline font and nothing else about a tagline. Now each one is a TagLayer of its own, emitted through the same renderHeaderLayer the pane and column tags go through, so it gets the tagline height, the small-font metrics, the band offset and the border for free -- none of which a body-grid row can have by changing its font role. The text is right aligned. The prompt stays on the canonical grid because it owns a cursor, and a cursor has to sit on a real cell. The body starts BELOW the bands rather than under them, the way tree-sitter context rows already worked. Pane.body_offset is how many rows they took and Pardes.bodyTop(pane, rect) is the one place that answers "where does the body begin" -- replacing fifteen copies of `if (tag_bottom) r.y else r.y + BOX_H` spread across the paint, hit-test, scroll, PDF and image paths, which is what let the bands and the text under them come adrift. Every notice is painted on the grid as well, because the grid is what a terminal client draws and a band it cannot see is a message it never gets; the GUI skips grid cells a tag layer covers, so nothing is drawn twice. Three bugs the bands exposed, fixed here: - a prompt band flush with the right edge put its caret one column past the pane, which the detached wire refuses -- so every frame was dropped for as long as the prompt was open. The band now reserves that column. - a click on a band mapped to Sel row 0, which is the TAG row: clicking chrome expanded a word out of the tagline and ran it as a builtin. - a watched file reloading under the editor changed the core without going through update, so needs_frame was never set and the reload was never drawn. Pardes.invalidate() is the name for that, and the file and theme reloads call it. A session can now drive its own 9P namespace instead of being refused one: ownMountSuffix answers what a path names inside this editors own tree and resolve, readLimit and write serve it from memory rather than making the syscall that never returns. The match is anchored to whole components under the registrys 9p/pardes/, because a bare /pardes/ anywhere in a string would claim ~/src/pardes//README -- and, before write learned the same trick, write the trees bytes over the real file. readFileLimit and writeFile refuse instead, having no core to answer from. A toggle setting SETS when given `on` or `off` and only flips when it is bare, so the report LocationsConfig prints can be fed back as configuration and mean what it says. Snapshots: 97/98, from 0/98. The goldens were several commits stale and 17 scripts had stopped running; `config ` is a new script command that appends to the per-script startup config, so a script that clicks body coordinates pins `Verbose off` instead of counting the rows an announcement moves. nested-optout is left failing on purpose: two levels of nesting prepend vaxis F3 codepoints to typed lines, which is a real bug and is written down in docs/divergences.md with a repro. Co-Authored-By: Claude Opus 5 (1M context) --- docs/divergences.md | 38 +- features.txt | 30 + src/config.zig | 48 +- src/detached/client.zig | 26 +- src/detached/wire.zig | 7 +- src/file_watch.zig | 2 + src/fs.zig | 124 +++- src/gui/gui.zig | 25 +- src/panes.zig | 42 +- src/pardes.zig | 328 +++++++-- src/tag_layer.zig | 6 +- test/e2e_harness.zig | 12 + test/fs.py | 6 +- test/output.zig | 4 +- test/panes.zig | 32 +- test/snapshot.zig | 8 +- test/snapshots/argv.golden | 33 +- test/snapshots/badutf.golden | 8 +- test/snapshots/boot.golden | 64 +- test/snapshots/builtins.golden | 27 +- test/snapshots/builtins.snap | 19 +- test/snapshots/chordcut.golden | 115 +-- test/snapshots/cmdword.golden | 16 +- test/snapshots/cmdword.snap | 4 + test/snapshots/collapse.golden | 79 +- test/snapshots/cornerdrag-left.golden | 32 +- test/snapshots/cornerdrag.golden | 48 +- test/snapshots/cursorline.golden | 72 +- test/snapshots/doccol.golden | 10 +- test/snapshots/doccol.snap | 4 + test/snapshots/dump.golden | 13 +- test/snapshots/edit.golden | 66 +- test/snapshots/exec-bigdrag.golden | 6 +- test/snapshots/exec-bigdrag.snap | 4 + test/snapshots/exec.golden | 39 +- test/snapshots/exec.snap | 2 +- test/snapshots/fileedit.golden | 8 +- test/snapshots/filewatch.golden | 33 +- test/snapshots/filewatch.snap | 4 + test/snapshots/find.golden | 177 +++-- test/snapshots/fsearch.golden | 161 ++-- test/snapshots/fsearch.snap | 9 +- test/snapshots/ghostty-mid.golden | 6 +- test/snapshots/grep.golden | 35 +- test/snapshots/grep.snap | 9 +- test/snapshots/hscroll.golden | 24 +- test/snapshots/images.golden | 132 ++-- test/snapshots/jumps.golden | 217 ++++-- test/snapshots/layout-close.golden | 29 +- test/snapshots/layout-open.golden | 20 +- test/snapshots/leader.golden | 81 +-- test/snapshots/load.golden | 66 +- test/snapshots/logquiet.golden | 4 +- test/snapshots/look-center.golden | 38 +- test/snapshots/look-dir.golden | 14 +- test/snapshots/look-file-1col.golden | 8 +- test/snapshots/look-file.golden | 74 +- test/snapshots/lookloaded.golden | 28 +- test/snapshots/lookpanes.golden | 114 +-- test/snapshots/lookpanes.snap | 4 + test/snapshots/lookrange.golden | 179 +++-- test/snapshots/lookrange.snap | 8 +- test/snapshots/lsp-client-edit.golden | 44 +- test/snapshots/lsp-client.golden | 40 +- test/snapshots/lsp-rename.golden | 29 +- test/snapshots/lsp.golden | 56 +- test/snapshots/lspcomplete.golden | 28 +- test/snapshots/lspcompletemoved.golden | 4 +- test/snapshots/lspdebug.golden | 4 +- test/snapshots/lspdebug.snap | 7 + test/snapshots/lsprelpath.golden | 162 +++-- test/snapshots/markup.golden | 104 +-- test/snapshots/mini.golden | 234 +++--- test/snapshots/modal.golden | 86 +-- test/snapshots/msg.golden | 93 ++- test/snapshots/multicursor.golden | 82 +-- test/snapshots/nested.golden | 69 +- test/snapshots/ninep.golden | 288 ++++---- test/snapshots/pipe.golden | 20 +- test/snapshots/psearch.golden | 140 ++-- test/snapshots/reflow.golden | 12 +- test/snapshots/respawn.golden | 10 +- test/snapshots/respawn.snap | 2 +- test/snapshots/restore.golden | 6 +- test/snapshots/rsearch.golden | 42 +- test/snapshots/rsearch.snap | 11 +- test/snapshots/savepane.golden | 20 +- test/snapshots/scroll.golden | 66 +- test/snapshots/scrolloff.golden | 4 +- test/snapshots/selarg.golden | 6 +- test/snapshots/selregex.golden | 121 ++-- test/snapshots/shellset.golden | 12 +- test/snapshots/shrinktag.golden | 12 +- test/snapshots/splitparent.golden | 26 +- test/snapshots/stepgrain.golden | 131 ++-- test/snapshots/syntax.golden | 183 ++--- test/snapshots/tag.golden | 23 +- test/snapshots/tagalign.golden | 32 +- test/snapshots/tagalign2col.golden | 21 +- test/snapshots/tagbottom.golden | 36 +- test/snapshots/tagbottom.snap | 15 +- test/snapshots/tagbottomimage.golden | 126 ++-- test/snapshots/tagbottomshort.golden | 40 +- test/snapshots/tagcmd.golden | 30 +- test/snapshots/tagnav.golden | 101 +-- test/snapshots/tagpath.golden | 84 +-- test/snapshots/theme.golden | 1248 ++++++++++++++++---------------- test/snapshots/themesel.golden | 1194 +++++++++++++++--------------- test/snapshots/tinywin.golden | 94 ++- test/snapshots/topbarexec.golden | 27 +- test/snapshots/tty.golden | 33 +- test/snapshots/ttyclick.golden | 10 +- test/snapshots/ttyedit.golden | 10 +- test/snapshots/ttyfollow.golden | 10 +- test/snapshots/ttyhelp.golden | 37 +- test/snapshots/ttyhelp.snap | 5 +- test/snapshots/ttylook.golden | 79 +- test/snapshots/ttyonly.golden | 81 ++- test/snapshots/ttypaste.golden | 6 +- test/snapshots/ttyprompt.golden | 10 +- test/snapshots/ttytaken.golden | 22 +- test/snapshots/tutor.golden | 8 +- test/snapshots/wheeldrift.golden | 16 +- test/snapshots/winch.golden | 12 +- test/snapshots/windownav.golden | 63 +- test/snapshots/windowops.golden | 108 +-- test/snapshots/wrap.golden | 36 +- test/snapshots/yankpaste.golden | 4 +- 128 files changed, 4912 insertions(+), 3744 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/divergences.md b/docs/divergences.md index fada830c..6679d962 100644 --- a/docs/divergences.md +++ b/docs/divergences.md @@ -43,17 +43,41 @@ there, deliberately, because that box serves a public site. ## Known-failing on `main`, not caused by the 9P work -* **`zig build fs-test`** fails on a syntax-highlighting assertion — the - word `fn` is expected bold and comes back unstyled: +* **`zig build snap` fails `nested-optout`, and the cause is a real bug.** + At the SECOND level of nesting -- a pardes whose shell runs a pardes whose + shell runs a command -- two U+E016 codepoints are prepended to whatever is + typed. U+E016 is 57366, which is vaxis's private-use spelling of **F3** + (`Key.zig`, "kitty encodes these keys directly in the private use area"), so + something in the chain is decoding a capability-query REPLY as a key and + forwarding it to the shell as text. bash then sees + `$'\356\200\226\356\200\226echo'` and answers `command not found`; with a + path it answers `No such file or directory` for a path that exists and runs + perfectly from the same shell a moment later. + + Minimal repro, in a snapshot script: ``` - AssertionError: ('fn', [{'fg': {'rgb': [201, 176, 228]}, ..., 'bold': False}, ...]) + dirmk innerdir + file innerdir/deeper.txt deepest-marker\n + start 31 100 + wait 8000 $ + stable 700 20000 + text (cd innerdir && $(readlink /proc/$PPID/exe) --nested) + key enter + wait 20000 cwd/innerdir + stable 700 20000 + text E=$(readlink /proc/$PPID/exe); "$E" deeper.txt + key enter + settle 5000 + stable 700 10000 + snap probe ``` - Verified by restoring `main`'s own `src/9p_io.zig`, `build.zig` and - `build.zig.zon` and re-running: it fails identically. The editor line - (`rruwvuzm`) has substantial `src/syntax.zig` changes and may well be the - fix in progress. + `bash: E=/home/.../pardes: No such file or directory` -- bash did not even + parse the assignment, because the line does not start where it looks like it + starts. `--nested` is exactly the flag meant to opt a child out of this, so + the fix belongs next to the key-forwarding path in `panes.Terminal.forwardKey` + and whatever answers terminal capability queries on a nested stdin. * **pardes does not start headless.** `pardes --9p=` with no terminal exits 1 from the argument-forwarding path; the installed build fails diff --git a/features.txt b/features.txt index eeadba39..d035648a 100644 --- a/features.txt +++ b/features.txt @@ -167,3 +167,33 @@ Found by adversarial review and NOT fixed, because they are upstream or macOS-on frontend. Fixing it means a new header variant, i.e. a protocol change. - A shell that outlives its editor keeps PARDES_PID; if that pid is reused, `pardes ` now exits 1 instead of falling back to starting an editor. Exiting 1 only when the socket itself refused would keep the old behaviour. + +Notices are tagline bands at the TOP of the body now, not a row of body text at the bottom. Each message or leader prefix is emitted through the same +renderHeaderLayer the pane and column tags use, as a TagLayer of the new `.notice` kind, so it gets the tagline's height, its small-font metrics, its band +offset and its border for free -- none of which a body-grid row can have just by wearing a tagline font. The text is right aligned. The prompt stays on the +canonical grid because it owns a cursor, which has to sit on a real cell. + +The body starts BELOW the bands rather than under them: Pane.body_offset is the number of rows they take, and every painter and hit test derives the body's +first row from Pardes.bodyTop(pane, rect). That replaced fifteen copies of `if (tag_bottom) r.y else r.y + BOX_H` scattered across the paint and pointer paths, +which is what let the bands and the text they sit over come adrift in the first place. renderBodyLayer zeroes the offset around its own render, because it +paints into a surface of its own that carries no bands. + +Every notice is ALSO painted on the canonical grid, because the grid is what a terminal client draws and a band it cannot see is a message it never gets. The +GUI skips grid cells a tag layer covers, so nothing is drawn twice there. + +Snapshot suite: 97/98. The goldens were several commits stale (Delcol on the column tagline, the closing word moved last in every +tagline, the bare-tty boot's empty pane, stacked Locations rows, the notice bands) and 17 scripts had stopped running at all. Fixed +by making the scripts say what they mean rather than by loosening them: `config ` is a new snapshot-script command that appends +to the per-script startup config, so a script that clicks body coordinates can pin `Verbose off` instead of counting the rows an +announcement band moves; `@word` column specs replace counted columns where a tagline word has moved; and two grids grew because a +pane tag is wider now than its `Del` could fit in. + +Found by that pass and fixed: a watched file reloading under the editor changed the core WITHOUT going through `update`, so +`needs_frame` was never set and the reload was never drawn. `Pardes.invalidate()` is the name for "something changed me from +outside the event loop"; `reloadWatchedFile` and the theme reload call it. + +Also from it: a toggle setting now SETS when given `on` or `off` and only flips when it is bare, so `writeReport`'s `Verbose on` +means what it says when fed back as configuration -- the symmetry the report was asked for, on the input side too. + +Left failing, deliberately: `nested-optout`. See docs/divergences.md -- two levels of nesting prepend U+E016 (vaxis's F3) to typed +lines, which is a real bug in the key-forwarding path and not a stale expectation. diff --git a/src/config.zig b/src/config.zig index 81fefd2c..98bbf3f4 100644 --- a/src/config.zig +++ b/src/config.zig @@ -677,7 +677,9 @@ pub const Runtime = struct { pub fn takesArg(setting: Setting) bool { return switch (setting.action) { - .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur => true, + // A toggle flips when it is a bare tagline word and SETS when + // it is given `on` or `off`, so the report is configuration. + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .toggle => true, else => false, }; } @@ -781,9 +783,23 @@ pub const Runtime = struct { pub fn apply(state: *Runtime, setting: Setting, argument: ?[]const u8) bool { switch (setting.action) { // Every toggle names a bool field of its own, so one line covers - // all of them and a new toggle needs no arm here. - .toggle => |field| switch (field) { - inline else => |f| @field(state, @tagName(f)) = !@field(state, @tagName(f)), + // all of them and a new toggle needs no arm here. Bare, a toggle + // flips -- that is what a tagline word is for. With `on` or `off` + // it SETS, so the report `writeReport` prints (`Verbose on`) can + // be fed straight back as configuration and mean what it says. + .toggle => |field| { + const text = std.mem.trim(u8, argument orelse "", " \t\r\n"); + const want: ?bool = if (text.len == 0) + null + else if (std.mem.eql(u8, text, "on")) + true + else if (std.mem.eql(u8, text, "off")) + false + else + return false; + switch (field) { + inline else => |f| @field(state, @tagName(f)) = want orelse !@field(state, @tagName(f)), + } }, .shell => { const value = std.mem.trim(u8, argument orelse return false, " \t\r\n"); @@ -977,12 +993,34 @@ pub const Runtime = struct { for (settings[i + 1 ..]) |later| try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); try std.testing.expectEqual(switch (setting.action) { - .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur => true, + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .toggle => true, else => false, }, setting.takesArg()); } } + test "a toggle flips when bare and sets when told on or off" { + var state: Runtime = .{}; + const verbose = find("Verbose").?; + try std.testing.expect(state.verbose); + // Bare, it flips: that is what a tagline word does. + try std.testing.expect(apply(&state, verbose, null)); + try std.testing.expect(!state.verbose); + // Told, it SETS -- twice over, so the second call proves it is not + // flipping past the value it was given. + try std.testing.expect(apply(&state, verbose, "on")); + try std.testing.expect(state.verbose); + try std.testing.expect(apply(&state, verbose, " on\n")); + try std.testing.expect(state.verbose); + try std.testing.expect(apply(&state, verbose, "off")); + try std.testing.expect(!state.verbose); + try std.testing.expect(apply(&state, verbose, "off")); + try std.testing.expect(!state.verbose); + // And anything else is refused rather than silently flipping. + try std.testing.expect(!apply(&state, verbose, "maybe")); + try std.testing.expect(!state.verbose); + } + test "simple setting application mutates only its plain field" { var state: Runtime = .{}; try std.testing.expect(apply(&state, find("Colors").?, null)); diff --git a/src/detached/client.zig b/src/detached/client.zig index 9481cd54..a027c0bb 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -1266,8 +1266,32 @@ test "detached session: a frontend that stops reading is dropped, not waited for // for, which is the whole claim: one slow peer costs its own slot. try testing.expect(h.session.clients[0].attached); try testing.expect(!h.core.quit); + // A message is a tagline band now, not a grid run, so "still being drawn + // for" is checked on the layers the frontend decoded rather than on nruns. try good.send(.{ .event = .{ .command = "Msg still here" } }); - try testing.expect((try h.pumpUntilChange(&good)).nruns > 0); + try testing.expect(try pumpUntilNotice(&h, &good, "still here")); +} + +/// Pump until this client has a notice band carrying `want`. +fn pumpUntilNotice(h: *Harness, c: *Client, want: []const u8) !bool { + var line: [256]u8 = undefined; + for (0..Harness.rounds) |_| { + try h.pump(); + try c.wait(5); + while (try c.next()) |_| {} + for (&c.tag_layers) |*layer| { + if (layer.cols == 0 or layer.kind != .notice) continue; + var n: usize = 0; + for (layer.cells[0..layer.cols]) |cell| { + const g = cell.grapheme(); + if (n + g.len > line.len) break; + @memcpy(line[n..][0..g.len], g); + n += g.len; + } + if (std.mem.indexOf(u8, line[0..n], want) != null) return true; + } + } + return false; } /// A connected socket with nothing said on it yet, for the tests whose peer is diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 245bc9f4..6805d980 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -4,7 +4,10 @@ const std = @import("std"); const pardes = @import("../pardes.zig"); const limits = @import("../memory.zig").limits; -pub const version: u16 = 6; +/// 7: tag layers gained the `.notice` kind, so a frame can carry a tag value +/// an older frontend would reject mid-session. The greeting is where that has +/// to be refused, which is what this number is for. +pub const version: u16 = 7; pub const Error = error{ Truncated, Overlong, BadTag, BadValue, Trailing, NoSpace }; @@ -220,7 +223,7 @@ pub const Frame = struct { layer.viewport.y >= f.rows or (switch (layer.kind) { .workspace => layer.id != 0, .column => layer.id >= pardes.MAX_COLS, - .pane => layer.id >= pardes.MAX_PANES, + .pane, .notice => layer.id >= pardes.MAX_PANES, })) return error.BadValue; const cursor = try getCursor(&r, layer.cols, 1); layer.cursor = if (cursor) |c| .{ .col = c.x, .bar = c.bar } else null; diff --git a/src/file_watch.zig b/src/file_watch.zig index b2b7e380..b2908eb7 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -577,6 +577,7 @@ pub fn reloadTheme( if (watches[theme_slot]) |*entry| remarkFile(entry, request.path); } const bytes = filesystem.readFile(gpa, request.path) catch |err| { + core.invalidate(); core.failThemeFile(watched.serial, err); return false; }; @@ -587,6 +588,7 @@ pub fn reloadTheme( .pdf => unreachable, } if (!core.loadThemeFile(watched.serial, bytes, true)) return false; + core.invalidate(); const live = if (watches[theme_slot]) |*entry| entry else return false; if (live.serial != watched.serial) return false; live.generation = .{ .text = hash }; diff --git a/src/fs.zig b/src/fs.zig index 5c75eb72..9200236d 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -65,6 +65,9 @@ pub const WriteError = error{ }; pub fn writeFile(path: []const u8, bytes: []const u8) WriteError!void { + // No core here to answer from, so the only safe answer is no answer: an + // open(2) into our own mount is the call that never returns. + if (isOwnMount(path)) return error.OpenFailed; var pathbuf: [4096:0]u8 = undefined; if (path.len >= pathbuf.len) return error.PathTooLong; if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed; @@ -671,6 +674,9 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 } if (std.mem.eql(u8, joined, "/virtual")) return resolveVirtual(p, "/", out); if (std.mem.startsWith(u8, joined, "/virtual/")) return resolveVirtual(p, joined[8..], out); + // This editor's own tree, seen through a mount: answer from the tree + // instead of walking out into the view and back in. + if (ownMountSuffix(joined)) |inner| return resolveVirtual(p, inner, out); if (resolveOs(joined, out)) |found| return found; if (resolveVirtual(p, joined, out)) |found| return found; if (resolveVirtual(p, word, out)) |found| return found; @@ -682,7 +688,9 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 } /// The name this session is posted under, taken from its socket path. -var own_name_buf: [64]u8 = undefined; +/// As wide as a name a listener will accept, so there is no session whose +/// name is too long to recognise and therefore too long to protect. +var own_name_buf: [108]u8 = undefined; var own_name_len: usize = 0; pub fn noteOwnSocket(socket_path: []const u8) void { @@ -697,35 +705,91 @@ pub fn noteOwnSocket(socket_path: []const u8) void { own_name_len = name.len; } -/// Is this path inside this editor's OWN 9P tree, as a mount presents it? +/// What this path names inside this editor's OWN 9P tree, if it does: +/// `/mnt/9p/pardes//pane/3/body` -> `pane/3/body`, and the mount root +/// itself -> `/`. /// -/// Touching one from inside the editor deadlocks the session outright: the -/// realpath, the stat and the read all leave through the mount and come back -/// as 9P requests that only the editor's loop can answer, while that loop is -/// blocked making them. The filesystem then stops answering anybody. So the -/// answer has to come from the NAME, before any syscall -- the syscall is the -/// thing that never returns. Look at `/n/self/...` instead, which the editor -/// serves from memory without leaving the process. -pub fn isOwnMount(path: []const u8) bool { - if (own_name_len == 0) return false; +/// A mount is a VIEW of a tree this editor already holds. Going out through +/// the view to reach it deadlocks the session outright -- the realpath, the +/// stat and the read all leave through the mount and come back as 9P requests +/// only this editor's loop can answer, while that loop is blocked making them, +/// and the filesystem then stops answering anybody. So the view is recognised +/// by NAME, before any syscall (the syscall is the thing that never returns), +/// and the request is served from the tree directly. Same answer, no round +/// trip, and a session can drive itself through its own 9P namespace. +pub fn ownMountSuffix(path: []const u8) ?[]const u8 { + if (own_name_len == 0 or path.len == 0 or path[0] != '/') return null; + // Whole components, and the registry's own layout: a session is posted at + // `/9p/pardes/` and mounts group under `/mnt/9p/pardes/`. + // Matching a bare `/pardes/` anywhere in the string would claim + // `~/src/pardes//README` -- an ordinary directory that happens to + // read like a mount -- and serve the tree's README over the real file. var buf: [own_name_buf.len + 16]u8 = undefined; - const needle = std.fmt.bufPrint(&buf, "/pardes/{s}/", .{own_name_buf[0..own_name_len]}) catch return false; - return std.mem.indexOf(u8, path, needle) != null; + const stem = std.fmt.bufPrint(&buf, "/9p/pardes/{s}", .{own_name_buf[0..own_name_len]}) catch return null; + var at: usize = 0; + while (std.mem.indexOfPos(u8, path, at, stem)) |found| : (at = found + 1) { + const rest = path[found + stem.len ..]; + if (rest.len != 0 and rest[0] != '/') continue; // a longer name that merely starts the same + if (rest.len <= 1) return "/"; + return rest[1..]; + } + return null; } -test "a path inside this session's own mount is refused before any syscall" { +pub fn isOwnMount(path: []const u8) bool { + return ownMountSuffix(path) != null; +} + +test "a path inside this session's own mount is answered from the tree, not through the mount" { noteOwnSocket("/run/user/1000/pardes-9p-demo.sock"); defer own_name_len = 0; - try std.testing.expect(isOwnMount("/mnt/9p/pardes/demo/index")); - try std.testing.expect(isOwnMount("/mnt/9p/pardes/demo/pane/new")); - try std.testing.expect(!isOwnMount("/mnt/9p/pardes/other/index")); - try std.testing.expect(!isOwnMount("/home/goblin/src/pardes/demo.zig")); + // What the path names inside the tree, with the mount prefix taken off. + try std.testing.expectEqualStrings("index", ownMountSuffix("/mnt/9p/pardes/demo/index").?); + try std.testing.expectEqualStrings("pane/new", ownMountSuffix("/mnt/9p/pardes/demo/pane/new").?); + try std.testing.expectEqualStrings("/", ownMountSuffix("/mnt/9p/pardes/demo").?); + try std.testing.expectEqualStrings("/", ownMountSuffix("/mnt/9p/pardes/demo/").?); + // The registry posts the session there too, so that spelling counts. + try std.testing.expectEqualStrings("index", ownMountSuffix("/run/user/1000/9p/pardes/demo/index").?); + // Another session's mount is somebody else's to answer, and a name that + // merely STARTS with ours is a different name. + try std.testing.expect(ownMountSuffix("/mnt/9p/pardes/other/index") == null); + try std.testing.expect(ownMountSuffix("/mnt/9p/pardes/demo2/index") == null); + // An ordinary directory that reads like a mount is an ordinary directory. + // Serving the tree here would hand back the tree's README for the file on + // disk, and -- before `write` learned the same trick -- write the tree's + // bytes over it. + try std.testing.expect(ownMountSuffix("/home/goblin/src/pardes/demo/README") == null); + try std.testing.expect(ownMountSuffix("/home/goblin/src/pardes/demo.zig") == null); + // Relative paths never name a mount: they are resolved against a cwd first. + try std.testing.expect(ownMountSuffix("mnt/9p/pardes/demo/index") == null); + + // The syscall is the thing that never returns, so it is never made. var out: [4096]u8 = undefined; try std.testing.expect(resolveOs("/mnt/9p/pardes/demo/index", &out) == null); - // A session with no listener has no name, so nothing is refused. + // A session with no listener has no name, so nothing is redirected. noteOwnSocket("/tmp/not-a-pardes-socket"); - try std.testing.expect(!isOwnMount("/mnt/9p/pardes/demo/index")); + try std.testing.expect(ownMountSuffix("/mnt/9p/pardes/demo/index") == null); +} + +test "reading this session's own mount returns what the tree holds" { + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + noteOwnSocket("/run/user/1000/pardes-9p-selfread.sock"); + defer own_name_len = 0; + + const direct = try read(p, "/n/self/index"); + defer p.gpa.free(direct); + const mounted = try read(p, "/mnt/9p/pardes/selfread/index"); + defer p.gpa.free(mounted); + try std.testing.expectEqualStrings(direct, mounted); + try std.testing.expect(direct.len > 0); + + // A write goes to the same tree the read came from, not out through the + // mount: `/index` is 0400 there, and an OS write would instead try to + // create a file under a directory that does not exist. + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, "/mnt/9p/pardes/selfread/index", "nope\n")); + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, "/n/self/index", "nope\n")); } pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { @@ -754,7 +818,13 @@ pub fn read(p: *pardes.Pardes, path: []const u8) ![]u8 { } pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { - if (isOwnMount(path)) return error.OwnMount; + // The same view, reached by a reader that never went through `resolve`. + // The rewritten path cannot contain the mount stem, so this recurses once. + if (ownMountSuffix(path)) |inner| { + var self_buf: [4096]u8 = undefined; + const internal = std.fmt.bufPrint(&self_buf, "/n/self/{s}", .{inner}) catch return error.FileTooLarge; + return readLimit(p, internal, max_bytes); + } const limit = @min(max_bytes, limits.max_file_bytes); if (std.mem.eql(u8, std.mem.trimEnd(u8, path, "/"), "/n")) { var out: std.Io.Writer.Allocating = .init(p.gpa); @@ -871,6 +941,14 @@ fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize } pub fn write(p: *pardes.Pardes, path: []const u8, bytes: []const u8) !void { + // The same view `readLimit` answers from the tree, so a write lands where + // the matching read came from -- and, just as importantly, never becomes + // an open(2) through a mount this loop is the one that answers. + if (ownMountSuffix(path)) |inner| { + var self_buf: [4096]u8 = undefined; + const internal = std.fmt.bufPrint(&self_buf, "/n/self/{s}", .{inner}) catch return error.PathTooLong; + return write(p, internal, bytes); + } if (std.mem.eql(u8, std.mem.trimEnd(u8, path, "/"), "/n")) return error.IsDirectory; var self_path: ?[]const u8 = null; if (std.mem.eql(u8, path, "/virtual")) self_path = ""; @@ -1233,6 +1311,10 @@ test "Restore prefers default directory then falls back to original path" { fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed; + // Same reason as `writeFile`: no core to answer from here, and the open is + // the call that never returns. Callers holding one use `readLimit`, which + // serves the tree instead. + if (isOwnMount(path)) return error.FileNotFound; if (!platform_has_fs or std.mem.startsWith(u8, path, "/virtual/")) { const archive_path = if (std.mem.startsWith(u8, path, "/virtual/")) path[9..] else path; var normalized_buf: [4096]u8 = undefined; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index d871e55e..c26629ab 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1788,6 +1788,7 @@ const Gui = struct { scroll_pane: ?usize = null, scroll_rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, scroll_body_y: u16 = 0, // that rect's first BODY row (Tagbottom moves it) + scroll_body_h: u16 = 0, // and how many rows it has, notice bands taken off scroll_col: u16 = 0, // where the wheel turned: crossed rows are delivered scroll_row: u16 = 0, // THERE, not wherever the pointer has drifted to since scroll_delta: f32 = 0, // finite raw distance waiting for the render batch @@ -4292,14 +4293,15 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { } g.scroll_lag = st.lag; g.scroll_rect = r; - const body_y = if (core.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = core.bodyTop(pane, r); g.scroll_body_y = body_y; + g.scroll_body_h = (r.h -| pardes.BOX_H) -| pane.body_offset; if (st.rows != 0) { const s = &core.surface; g.scroll_edge_len = 0; - if (r.w > config.GUTTER and r.h > pardes.BOX_H and r.x + r.w <= s.cols) { + if (r.w > config.GUTTER and r.h > pardes.BOX_H + pane.body_offset and r.x + r.w <= s.cols) { const bw = r.w - config.GUTTER; - const bh = r.h - pardes.BOX_H; + const bh = (r.h - pardes.BOX_H) - pane.body_offset; const k: u16 = @intCast(@min(@abs(st.rows), @as(i32, bh))); const srow = body_y + (if (st.rows > 0) k - 1 else bh - k); if (srow < s.rows) { @@ -4327,7 +4329,11 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pard const x0 = r.x + config.GUTTER; const y0 = g.scroll_body_y; const bw = r.w - config.GUTTER; - const bh = r.h - pardes.BOX_H; + // The body the editor actually painted: measuring it from the rect while + // the origin comes from bodyTop reads past the pane by the band rows, and + // for the bottom-most pane past the surface, which drops the animation. + const bh = g.scroll_body_h; + if (bh == 0) return 0; if (x0 + bw > surface.cols or y0 + bh > surface.rows) return 0; // resized under us var shifted = layout; shifted.y_off -= g.scroll_lag * layout.h; @@ -4359,7 +4365,7 @@ fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h; const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w; - const ph = @as(f32, @floatFromInt(r.h - pardes.BOX_H)) * layout.h; + const ph = @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h; const x0 = std.math.clamp(@as(i32, @intFromFloat(@floor(px))), 0, @as(i32, @intCast(sw))); const y0 = std.math.clamp(@as(i32, @intFromFloat(@floor(py))), 0, @as(i32, @intCast(sh))); const x1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(px + pw))), x0, @as(i32, @intCast(sw))); @@ -6685,11 +6691,14 @@ fn appendPaneChrome( const chrome = core.chromeTheme(); const page = overlayRgb(core.theme().bg orelse bg_default); for (core.panes, core.rects) |slot, r| { - if (slot == null or r.w <= config.GUTTER or r.h <= pardes.BOX_H) continue; + const pane = slot orelse continue; + if (r.w <= config.GUTTER or r.h <= pardes.BOX_H) continue; if (@as(u32, r.x) + r.w > surface.cols or @as(u32, r.y) + r.h > surface.rows) continue; const tag_y = if (core.settings.tag_bottom) r.y + r.h - pardes.BOX_H else r.y; - const body_y = if (core.settings.tag_bottom) r.y else r.y + pardes.BOX_H; - const body_end = body_y + r.h - pardes.BOX_H; + // The rail the editor painted, notice bands included -- overlaying the + // rows above it would tint the bands instead of the scrollbar. + const body_y = core.bodyTop(pane, r); + const body_end = body_y + ((r.h -| pardes.BOX_H) -| pane.body_offset); const x0 = @as(f32, @floatFromInt(r.x)) * layout.w; const x1 = x0 + @as(f32, @floatFromInt(r.w)) * layout.w; const tag_cells = surface.cells[@as(usize, tag_y) * surface.cols + r.x + pardes.TAG_TEXT_INSET ..][0 .. r.w - pardes.TAG_TEXT_INSET]; diff --git a/src/panes.zig b/src/panes.zig index e41698bb..4b5c6721 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -191,6 +191,11 @@ pub const Pane = struct { /// body layer reserves exactly `len` rows for them, the way it already /// reserves rows for sticky context headers. notices: Notices = .{}, + /// Rows the notice bands take off the TOP of the body, the way tree-sitter + /// context rows do: the body starts below them rather than being painted + /// under them. Zero while the body LAYER renders, which paints into a + /// surface of its own that carries no bands. + body_offset: u16 = 0, pub const Notices = struct { /// Painted bottom-up in this order, so a prompt keeps the row nearest @@ -2036,7 +2041,7 @@ pub const File = struct { const gcrow = if (pane.cur_pinned) pane.cur_row else @as(i32, gcur.y) + goff; const cur_line: i32 = if (active and !pane.tag_edit) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it (Tagbottom) - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); const context_bg = p.theme().tag_bg; for (0..@min(pane.context_rows, body_h)) |context_row| { for (0..tw) |col| { @@ -2090,7 +2095,7 @@ pub const File = struct { // indexed start, same as bodyText — an empty tail simply paints nothing var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); const total = nlines(p.gpa, f); - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); var vr: u16 = 0; while (vr < body_h) : (vr += 1) { var base: usize = undefined; @@ -2166,7 +2171,7 @@ pub const File = struct { pane_bg: pardes.Color, ) void { if (tw <= gutterWidth(pane) + 1) return; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); const marker_fg = p.chromeTheme().lineno; var row: u16 = 0; while (row + 1 < pane.wrap_n and row + 1 < body_h) : (row += 1) { @@ -2190,9 +2195,9 @@ pub const File = struct { const tx = r.x + config.GUTTER; const tw = r.w - config.GUTTER; const prefix_width = gutterWidth(pane); - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); var vr: i32 = 0; - while (vr + @as(i32, pardes.BOX_H) < @as(i32, r.h)) : (vr += 1) { + while (vr + @as(i32, pardes.BOX_H) < @as(i32, r.h -| pane.body_offset)) : (vr += 1) { const here = pane.wrapAt(vr); if (here.line != row) continue; var hi = word_hi; @@ -5477,7 +5482,7 @@ pub const Pdf = struct { if (slot == pane) break core.rects[id]; } else return null; const cols = rect.w -| config.GUTTER; - const rows = rect.h -| pardes.BOX_H; + const rows = (rect.h -| pardes.BOX_H) -| pane.body_offset; if (cols == 0 or rows == 0) return null; return .{ .pixel_w = @as(u32, cols) * @as(u32, core.cell_pixels.w), @@ -5515,8 +5520,8 @@ pub const Pdf = struct { const rect = for (core.panes, 0..) |slot, id| { if (slot == pane) break core.rects[id]; } else return null; - const body_y = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; - if (row < body_y or row >= body_y + (rect.h -| pardes.BOX_H)) return null; + const body_y = core.bodyTop(pane, rect); + if (row < body_y or row >= body_y + ((rect.h -| pardes.BOX_H) -| pane.body_offset)) return null; const local_y = @as(f64, @floatFromInt( @as(u32, row - body_y) * core.cell_pixels.h + core.cell_pixels.h / 2, )); @@ -5572,7 +5577,7 @@ pub const Pdf = struct { if (slot == pane) break core.rects[id]; } else return null; const body_x = @as(i64, rect.x + config.GUTTER); - const body_y = @as(i64, if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H); + const body_y = @as(i64, core.bodyTop(pane, rect)); const px = (@as(i64, col) - body_x) * core.cell_pixels.w + core.cell_pixels.w / 2; const py = (@as(i64, row) - body_y) * core.cell_pixels.h + core.cell_pixels.h / 2; return pointAtPage(state, view, page, px, py, clamp_to_page); @@ -5855,7 +5860,7 @@ pub const Pdf = struct { text_width: u16, ) bool { if (comptime !enabled) return false; - if (!core.native_images or rect.h <= pardes.BOX_H) return false; + if (!core.native_images or rect.h <= pardes.BOX_H + pane.body_offset) return false; const state = &(pane.pdf orelse return false); const view = paneViewport(core, pane) orelse return false; const key = TintKey{ .mode = state.tint, .colors = tintColors(core) }; @@ -5892,9 +5897,9 @@ pub const Pdf = struct { null, }, .x = text_x, - .y = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H, + .y = core.bodyTop(pane, rect), .w = text_width, - .h = rect.h - pardes.BOX_H, + .h = (rect.h -| pardes.BOX_H) -| pane.body_offset, .rgba = placed.rgba, .iw = placed.width, // The texture contains the retained band, not the full page. @@ -5906,14 +5911,17 @@ pub const Pdf = struct { // This frame has spent the motion used to choose its raster band. state.scroll_travel = 0; - const body_y = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const body_y = core.bodyTop(pane, rect); + const body_h = (rect.h -| pardes.BOX_H) -| pane.body_offset; const chrome = core.chromeTheme(); const theme = core.theme(); const pane_bg: pardes.Color = if (theme.bg) |color| .{ .rgb = color } else .default; - core.surface.fill(rect.x, body_y, 1, rect.h -| pardes.BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); - core.surface.fill(rect.x + 1, body_y, 1, rect.h -| pardes.BOX_H, .{ .bg = pane_bg }); + // The rail runs past the notice bands; only the thumb tracks the text. + const rail_y = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + core.surface.fill(rect.x, rail_y, 1, rect.h -| pardes.BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); + core.surface.fill(rect.x + 1, rail_y, 1, rect.h -| pardes.BOX_H, .{ .bg = pane_bg }); - const track_h: usize = rect.h - pardes.BOX_H; + const track_h: usize = body_h; const total = @max(@as(u64, 1), state.document_height); const len = @max( @as(usize, 1), @@ -7571,7 +7579,7 @@ pub const Terminal = struct { if (comptime !enabled) return; const s = &p.surface; if (pane.terminal == null) return; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); var filtered_storage: FilteredColors = undefined; const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { const tz_filter = tracy.zone(@src(), "filterInit"); diff --git a/src/pardes.zig b/src/pardes.zig index ec743bc6..c271a16f 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -75,7 +75,9 @@ pub const RowMetrics = @import("body_layer.zig").Metrics; pub const TagLayer = @import("tag_layer.zig").Layer; pub const TagHit = @import("tag_layer.zig").Hit; pub const TagKind = @import("tag_layer.zig").Kind; -pub const MAX_TAG_LAYERS = MAX_PANES + MAX_COLS + 1; +/// Panes, then columns, then the workspace bar, then each pane's notice bands. +pub const MAX_TAG_LAYERS = MAX_PANES + MAX_COLS + 1 + MAX_PANES * Pane.Notices.max; +pub const NOTICE_LAYER_BASE = MAX_PANES + MAX_COLS + 1; pub const PDF_PAGE_GAP_PX = panes.Pdf.page_gap_px; pub const MAX_COLS = 6; const column_weight_unit = layout.column_weight_unit; @@ -1168,7 +1170,17 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest _ = try p.render(p.scratch.allocator()); try std.testing.expectEqual(full_height - 1, p.surface.body_layers[0].viewport.h); const r = p.rects[0]; - try std.testing.expectEqualStrings("!", p.surface.at(r.x + config.GUTTER, r.y + r.h - 1).grapheme()); + // The message is a tagline band at the top of the body now, not a body row + // at the bottom: same reservation, different carrier. + const band = for (p.surface.tagLayers()) |*layer| { + if (layer.cols != 0 and layer.kind == .notice) break layer; + } else return error.NoNoticeBand; + try std.testing.expectEqual(r.y + BOX_H, band.viewport.y); + // Right aligned: the text sits in the last cell the viewport actually + // shows, which is a column short of the layer's cursor slack. + try std.testing.expectEqualStrings("!", band.cells[p.tagCapacity(band.viewport.w) - 1].grapheme()); + // ...and the body starts below it rather than under it. + try std.testing.expectEqual(band.viewport.y + 1, p.surface.body_layers[0].viewport.y); pane.msg_len = 0; p.leader_on = true; _ = try p.render(p.scratch.allocator()); @@ -1178,7 +1190,7 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest _ = try p.render(p.scratch.allocator()); try std.testing.expectEqual(@as(u16, 0), p.surface.body_layers[0].rows); try std.testing.expectEqual(@as(u16, 0), pane.body_rows); - try std.testing.expectEqual(FontRole.body, p.surface.at(r.x + config.GUTTER, r.y + BOX_H).style.font_role); + try std.testing.expectEqual(FontRole.body, p.surface.at(r.x + config.GUTTER, p.bodyTop(pane, r)).style.font_role); try p.dumpState(); const restored = try Pardes.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); @@ -6270,6 +6282,15 @@ pub const Pardes = struct { return p; } + /// Prints `text` flush with the right edge of the band, and answers the + /// column it started at so a cursor can follow it. + fn printRight(s: *Surface, x: u16, row: u16, w: u16, text: []const u8, style: CellStyle) u16 { + const shown: u16 = @intCast(@min(@as(usize, w), panes.File.displayWidth(text))); + const left = x + w - shown; + _ = s.print(left, row, shown, text, style); + return left; + } + /// The layout every single-pane boot starts from. fn oneColumn(p: *Pardes) void { p.ncol = 1; @@ -6915,7 +6936,15 @@ pub const Pardes = struct { false; } + /// Something changed the core without going through `update` -- a watched + /// file reloading under it, a theme file rewritten on disk. `pump` draws + /// only when it has a reason to, and this is the reason. + pub fn invalidate(p: *Pardes) void { + p.needs_frame = true; + } + pub fn reloadWatchedFile(p: *Pardes, id: u8, bytes: []const u8) bool { + p.invalidate(); p.invalidateLookHover(id); const applied = p.applyWatchedFileChanged(id, bytes); _ = p.scratch.reset(.retain_capacity); @@ -11235,9 +11264,13 @@ pub const Pardes = struct { const r = p.rects[id]; if (col < r.x + config.GUTTER or col >= r.x + r.w or row < r.y or row >= r.y + r.h) return null; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const body_y = p.bodyTop(p.panes[id].?, r); const on_tag = row >= tag_y and row < tag_y + BOX_H; if (on_tag and col < r.x + TAG_TEXT_INSET) return null; + // A notice band is chrome. Without this it maps to Sel row 0 or less, + // which is the TAG row -- so a click on a leader band would expand a + // word out of the tag text and run it as a builtin. + if (!on_tag and row >= body_y -| p.panes[id].?.body_offset and row < body_y) return null; if (!on_tag) if (body_hit) |supplied| { const mapped_hit = p.bodyHitForPane(id, supplied, false) orelse return null; const c = @as(i32, mapped_hit.col) - config.GUTTER; @@ -11624,7 +11657,7 @@ pub const Pardes = struct { if (previous.tag_edit) exitTagEdit(previous); }; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const body_y = p.bodyTop(pane, r); if (mcol < r.x + config.GUTTER) { // gutter scrollbar: a left click scrolls UP to that row p.active = id; @@ -11688,7 +11721,7 @@ pub const Pardes = struct { // the tag row and the body's first, exactly as the select // arm above derives them const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const body_y = p.bodyTop(pane, r); const on_tag = mrow >= tag_y and mrow < tag_y + BOX_H; if (mcol < r.x + config.GUTTER and !on_tag) { const local = @as(i32, mrow) - @as(i32, body_y); @@ -11780,13 +11813,17 @@ pub const Pardes = struct { return; }; pane.sel[b].c1 = @as(i32, mcol) - @as(i32, r.x + config.GUTTER); - if (p.settings.tag_bottom) { - const body_h = r.h -| BOX_H; - pane.sel[b].r1 = if (pane.sel[b].r0 < BOX_H or body_h == 0) - 0 - else - @as(i32, @min(@max(mrow, r.y), r.y + body_h - 1)) - @as(i32, r.y) + @as(i32, BOX_H); - } else pane.sel[b].r1 = if (pane.sel[b].r0 < BOX_H) 0 else @as(i32, mrow) - @as(i32, r.y); + // Sel row BOX_H is the body's FIRST row, the same thing + // pointerTextSelection means by it -- so the drag has to + // measure from the body's top, notice bands included, or a + // selection made while a message is up lands rows away + // from the pointer. + const body_y = p.bodyTop(pane, r); + const body_h = (r.h -| BOX_H) -| pane.body_offset; + pane.sel[b].r1 = if (pane.sel[b].r0 < BOX_H or body_h == 0) + 0 + else + @as(i32, @min(@max(mrow, body_y), body_y + body_h - 1)) - @as(i32, body_y) + @as(i32, BOX_H); if (pane.sel[b].r1 < BOX_H) pane.sel[b].c1 += @as(i32, pane.tag_scroll) - TAG_GAP; if (comptime pdf_enabled) panes.Pdf.pointerUpdate(&s.pdf, p, pane, mcol, mrow); @@ -13333,6 +13370,14 @@ pub const Pardes = struct { return null; } + /// The pane's first body row: under the tag when it is on top, and under + /// whatever notice bands `collectNotices` stacked above the body. Every + /// painter and hit test derives the body from here so the bands cannot + /// come adrift from the text they sit over. + pub fn bodyTop(p: *const Pardes, pane: *const Pane, r: Rect) u16 { + return (if (p.settings.tag_bottom) r.y else r.y + BOX_H) + pane.body_offset; + } + fn tagCapacity(p: *const Pardes, physical_width: u16) u16 { const layer: TagLayer = .{ .viewport = .{ .x = 0, .y = 0, .w = physical_width, .h = 1 } }; return layer.capacity(p.row_metrics); @@ -13416,37 +13461,49 @@ pub const Pardes = struct { .bg = .{ .rgb = chrome.tag_bg }, .font_role = .tagline, }; - // The stack sits directly above the tagline, one line to a row, in - // the order collectNotices chose. A single notice therefore lands - // on exactly the row the message used to have to itself. - const bottom = if (p.settings.tag_bottom) r.y + r.h - 1 - BOX_H else r.y + r.h - 1; + // Sticky at the TOP of the body, where the tree-sitter context + // headers sit, one line to a row in the order collectNotices chose. + // Text is right aligned: the left edge is where the body's own text + // begins, and a notice that shared it would read as a line of the + // file rather than as chrome over it. + const first = if (p.settings.tag_bottom) r.y else r.y + BOX_H; for (pane.notices.slice(), 0..) |kind, i| { - const row = bottom - @as(u16, @intCast(pane.notices.len - 1 - i)); + const row = first + @as(u16, @intCast(i)); + // Every notice is painted on the canonical grid as well as + // emitted as a tag layer: the grid is what a terminal client + // draws, and a band it cannot see is a message it never gets. + // The GUI skips grid cells a tag layer covers, so nothing is + // drawn twice there. s.fill(tx, row, tw, 1, .{ .bg = msg_style.bg, .font_role = .tagline }); switch (kind) { - .message => _ = s.print(tx, row, tw, pane.msg[0..pane.msg_len], msg_style), + .message => _ = printRight(s, tx, row, tw, pane.msg[0..pane.msg_len], msg_style), .leader => { var ibuf: [16]u8 = @splat(' '); - @memcpy(ibuf[1..4], "SPC"); - var iw: usize = 4; + @memcpy(ibuf[0..3], "SPC"); + var iw: usize = 3; for (p.leader_keys[0..p.leader_n]) |ch| { ibuf[iw + 1] = ch; iw += 2; } - const w: u16 = @intCast(iw); - if (w < tw) _ = s.print(tx + tw - w, row, w, ibuf[0..iw], msg_style); + _ = printRight(s, tx, row, tw, ibuf[0..iw], msg_style); }, .prompt => { const at = pane.promptAt() orelse continue; const text = pane.tagSlice()[@min(at, pane.tag_tail_len)..]; - _ = s.print(tx, row, tw, text, msg_style); + // One column short of the edge: the caret sits AFTER + // the last character the moment a prompt opens, and + // flush right would put it at r.x + r.w -- off the + // pane, off the grid, and past what the detached wire + // will encode, which drops every frame while it is up. + const left = printRight(s, tx, row, tw -| 1, text, msg_style); if (id != p.active) continue; const prompt0 = (p.tagPrefix(pane) catch continue).len + at; const col = @as(usize, pane.tag_col); if (col >= prompt0) { + // The cursor follows the text to wherever it landed. const prompt_col = panes.File.displayWidth(text[0..@min(col - prompt0, text.len)]); if (prompt_col < tw) - s.cursor = .{ .x = tx + @as(u16, @intCast(prompt_col)), .y = row, .bar = pane.mode == .insert }; + s.cursor = .{ .x = left + @as(u16, @intCast(prompt_col)), .y = row, .bar = pane.mode == .insert }; } }, } @@ -13772,11 +13829,11 @@ pub const Pardes = struct { const raw = pane.mode == .tty; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const body_y = p.bodyTop(pane, r); var lines = std.mem.splitScalar(u8, body, '\n'); var visible: i32 = 0; while (lines.next()) |line| : (visible += 1) { - if (visible >= r.h -| BOX_H) break; + if (visible >= (r.h -| BOX_H) -| pane.body_offset) break; const source_row = if (raw) panes.Terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; for (rows) |row| { const target = if (row.raw_terminal) @@ -13814,10 +13871,10 @@ pub const Pardes = struct { const terminal_lines = if (pane.file == null) panes.Terminal.cursorLines(p, pane) catch return else &.{}; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const body_y = p.bodyTop(pane, r); const prefix: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; var visible: i32 = 0; - while (visible < @as(i32, r.h -| BOX_H)) : (visible += 1) { + while (visible < @as(i32, (r.h -| BOX_H) -| pane.body_offset)) : (visible += 1) { const source = pane.wrapAt(visible); const line = pointerSourceLine(pane, terminal_lines, source.line); const start = @min(line.len, @as(usize, @intCast(@max(0, source.at)))); @@ -13862,6 +13919,11 @@ pub const Pardes = struct { while (row < r.h) : (row += 1) { if (@as(i32, row) < r0 or @as(i32, row) > r1) continue; const sy = if (row < BOX_H) tag_y else body_y + row - BOX_H; + // The body sits `body_offset` rows lower than it used to, so the + // last rows of Sel space now fall past the pane. Bounding the loop + // instead would break the caller that paints a tag into a + // one-row surface of its own, where the offset means nothing. + if (row >= BOX_H and sy >= r.y + r.h) break; // File line numbers occupy a gutter only in the body. The tag is // row zero in Sel space and starts at its real first text cell. const scroll: i32 = if (row < BOX_H) pane.tag_scroll else 0; @@ -13910,6 +13972,50 @@ pub const Pardes = struct { // workspace layer to render; the menu bar carries its commands. if (p.settings.workspace_tag) try p.renderHeaderLayer(arena, MAX_PANES + MAX_COLS, .workspace, 0, .{ .x = 0, .y = 0, .w = p.screen_w, .h = TOPBAR_H }, p.topbar(&text_buf), chrome.tag_bg, chrome.tag_fg); + // Each notice is its own tagline-shaped band at the top of the body. + // Going through the same layer machinery the pane and column tags use + // is what gives it the tagline's height, its small-font metrics, the + // band offset and the border -- none of which a body-grid row can have + // just by wearing a tagline font. + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const r = p.rects[id]; + if (r.w <= TAG_TEXT_INSET or r.h <= BOX_H) continue; + const first = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + var band: u16 = 0; + for (pane.notices.slice()) |kind| { + const text = switch (kind) { + .message => pane.msg[0..pane.msg_len], + .leader => blk: { + var ibuf: [16]u8 = @splat(' '); + @memcpy(ibuf[0..3], "SPC"); + var iw: usize = 3; + for (p.leader_keys[0..p.leader_n]) |ch| { + ibuf[iw + 1] = ch; + iw += 2; + } + break :blk try arena.dupe(u8, ibuf[0..iw]); + }, + // A prompt is an editing line with a cursor in it, so it + // stays on the grid where the cursor can sit on a cell. + .prompt => continue, + }; + if (text.len == 0) continue; + const room = p.tagCapacity(r.w -| TAG_TEXT_INSET); + const shown = panes.File.displayWidth(text); + const pad = room -| shown; + const line = try arena.alloc(u8, pad + text.len); + @memset(line[0..pad], ' '); + @memcpy(line[pad..], text); + try p.renderHeaderLayer(arena, NOTICE_LAYER_BASE + id * Pane.Notices.max + band, .notice, @intCast(id), .{ + .x = r.x + TAG_TEXT_INSET, + .y = first + band, + .w = r.w -| TAG_TEXT_INSET, + .h = BOX_H, + }, line, chrome.tag_bg, chrome.tag_fg); + band += 1; + } + } if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { if (p.col_w[column] == 0) continue; const active = if (layout.findPane(p, p.active)) |found| found.col == column and p.settings.focus_tint else false; @@ -13934,7 +14040,14 @@ pub const Pardes = struct { layer.bg = bg; layer.cursor = null; var surface: Surface = .{ .cols = columns, .rows = 1, .cells = layer.cells }; - const editing = p.topbar_col != null and (if (kind == .workspace) p.header_column == null else p.header_column == id); + // A notice band carries a PANE id, not a column index, so it must not + // answer to the column being edited -- that would scroll and select + // its text with the column tag's offsets and give it a second caret. + const editing = p.topbar_col != null and switch (kind) { + .workspace => p.header_column == null, + .column => p.header_column == id, + .pane, .notice => false, + }; const scroll = if (editing) p.header_scroll else 0; surface.fill(0, 0, columns, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); _ = surface.print(0, 0, columns, text[panes.File.rawAtDisplay(text, scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); @@ -13974,6 +14087,7 @@ pub const Pardes = struct { /// them instead of letting the last one win the row. fn collectNotices(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { pane.notices.len = 0; + pane.body_offset = 0; if (r.w <= config.GUTTER or r.h <= BOX_H) return; if (pane.msg_len > 0) pane.notices.push(.message); if (id == p.active and p.leader_on) pane.notices.push(.leader); @@ -13991,6 +14105,7 @@ pub const Pardes = struct { for (0..room) |i| pane.notices.kinds[i] = pane.notices.kinds[i + drop]; pane.notices.len = room; } + pane.body_offset = pane.notices.len; } fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize) !void { @@ -14017,6 +14132,9 @@ pub const Pardes = struct { @memset(temporary_cells, .{}); var temporary: Surface = .{ .cols = r.w, .rows = @intCast(logical_rows + BOX_H), .cells = temporary_cells }; std.mem.swap(Surface, &p.surface, &temporary); + // This surface carries no notice bands, so the body starts at its top. + pane.body_offset = 0; + defer pane.body_offset = pane.notices.len; const synthetic: Rect = .{ .x = 0, .y = 0, .w = r.w, .h = @intCast(logical_rows + BOX_H) }; p.renderBody(arena, pane, synthetic, id, id == p.active, false) catch |err| { std.mem.swap(Surface, &p.surface, &temporary); @@ -14030,7 +14148,11 @@ pub const Pardes = struct { } layer.pane = @intCast(id); layer.serial = pane.serial; - layer.viewport = .{ .x = r.x + config.GUTTER, .y = if (p.settings.tag_bottom) r.y else r.y + BOX_H, .w = width, .h = viewport_rows }; + // Below the notice bands, which are stacked at the TOP of the body + // now: the rows they took came off this viewport, so its origin has to + // move with them or the first context header renders under a band. + const body_top = (if (p.settings.tag_bottom) r.y else r.y + BOX_H) + @as(u16, pane.notices.len); + layer.viewport = .{ .x = r.x + config.GUTTER, .y = body_top, .w = width, .h = viewport_rows }; layer.cols = width; layer.rows = @intCast(logical_rows); layer.context_rows = pane.context_rows; @@ -14052,7 +14174,7 @@ pub const Pardes = struct { const tx = r.x + config.GUTTER; // text area (tag + body), right of the gutter const tw = r.w - config.GUTTER; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const body_y = p.bodyTop(pane, r); const pane_bg: Color = if (th.bg) |c| .{ .rgb = c } else .default; // text area resets to terminal-default cells (vaxis clear semantics); @@ -14092,11 +14214,14 @@ pub const Pardes = struct { if (pane.hasPdf() and panes.Pdf.draw(p, pane, r, id, tx, tw)) return; if (pane.image) |*iv| { - panes.Image.draw(p, iv, @intCast(id), pane.serial, tx, body_y, tw, r.h -| BOX_H); + const image_h = (r.h -| BOX_H) -| pane.body_offset; + panes.Image.draw(p, iv, @intCast(id), pane.serial, tx, body_y, tw, image_h); // thumbless, but the same one column as the real scrollbar below — - // that is the whole point of drawing it - s.fill(r.x, body_y, 1, r.h -| BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); - s.fill(r.x + 1, body_y, 1, r.h -| BOX_H, .{ .bg = pane_bg }); + // that is the whole point of drawing it, and like that one it runs + // past the notice bands so the gutter has no notch in it + const rail_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + s.fill(r.x, rail_y, 1, r.h -| BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); + s.fill(r.x + 1, rail_y, 1, r.h -| BOX_H, .{ .bg = pane_bg }); return; } @@ -14110,7 +14235,7 @@ pub const Pardes = struct { const tx = r.x + @min(TAG_TEXT_INSET, r.w); const tw = r.w -| TAG_TEXT_INSET; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const body_y = p.bodyTop(pane, r); const page_rgb = th.bg orelse th.tag_bg; // Focus is visible along the tag without changing its live text grid. const tag_bg = if (active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; @@ -14194,11 +14319,15 @@ pub const Pardes = struct { const tx = r.x + config.GUTTER; const tw = r.w - config.GUTTER; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + // Below the notice bands: they are stacked at the top of the body the + // way tree-sitter context rows are, so the body starts under them + // rather than being painted over by them. + const body_y = p.bodyTop(pane, r); const pane_bg: Color = if (th.bg) |c| .{ .rgb = c } else .default; const page_rgb = th.bg orelse th.tag_bg; // body: emulator rows, prompt rows hidden outside tty mode - const body_h = if (r.h > BOX_H) r.h - BOX_H else 0; + const body_h = (r.h -| BOX_H) -| pane.body_offset; + const body_bottom = r.h -| pane.body_offset; const body_style: CellStyle = .{ .fg = if (th.fg) |c| .{ .rgb = c } else .default, .bg = pane_bg, @@ -14269,7 +14398,7 @@ pub const Pardes = struct { const lo = @min(pane.msel.r0, pane.msel.r1); const hi = @max(pane.msel.r0, pane.msel.r1); var row: u16 = BOX_H; // never paint the tag row - while (row < r.h) : (row += 1) { + while (row < body_bottom) : (row += 1) { const ar = pane.wrapAt(@as(i32, row) - @as(i32, BOX_H)).line; if (ar < lo or ar > hi) continue; var col: u16 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; @@ -14306,7 +14435,7 @@ pub const Pardes = struct { else mix(th.sel_bg, page_rgb); var vr: i32 = 0; - while (vr + @as(i32, BOX_H) < @as(i32, r.h)) : (vr += 1) { + while (vr + @as(i32, BOX_H) < @as(i32, body_bottom)) : (vr += 1) { const w = pane.wrapAt(vr); if (w.line < bnd.lo_row or w.line > bnd.hi_row) continue; const visible_line = modal.lineSlice(body, @intCast(vr)); @@ -14344,7 +14473,7 @@ pub const Pardes = struct { @intCast(@max(0, cw.at)), @intCast(@max(0, sr.col)), )) + vpfx; - if (crow >= BOX_H and crow < @as(i32, r.h) and ccol >= vpfx and ccol < tw) { + if (crow >= BOX_H and crow < @as(i32, body_bottom) and ccol >= vpfx and ccol < tw) { const cell = s.at(tx + @as(u16, @intCast(ccol)), body_y + @as(u16, @intCast(crow - BOX_H))); cell.default = false; cell.style.bg = .{ .rgb = th.sel_fg }; @@ -14375,17 +14504,22 @@ pub const Pardes = struct { ) else ccol; - if (prow >= BOX_H and cx >= 0 and prow < r.h and cx < tw) + if (prow >= BOX_H and cx >= 0 and prow < body_bottom and cx < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - BOX_H)), .bar = pane.mode == .insert }; } else if (panes.Terminal.visibleCursor(pane)) |cur| { - if (cur.y + BOX_H < r.h and cur.x < tw) + if (cur.y + BOX_H < body_bottom and cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; } } - if (scrollbar and r.h > BOX_H) { - s.fill(r.x, body_y, 1, r.h - BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); - s.fill(r.x + 1, body_y, 1, r.h - BOX_H, .{ .bg = pane_bg }); + if (scrollbar and body_h > 0) { + // The rail covers the notice bands too: nothing else paints those + // two gutter columns, so a gap there keeps the frame-wide border + // fill and reads as a notch cut out of the scrollbar. + const rail_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const rail_h = r.h -| BOX_H; + s.fill(r.x, rail_y, 1, rail_h, .{ .bg = .{ .rgb = chrome.scroll_track } }); + s.fill(r.x + 1, rail_y, 1, rail_h, .{ .bg = pane_bg }); const sb: struct { total: usize, offset: usize, len: usize } = if (pane.file) |*f| .{ .total = panes.File.nlines(p.gpa, f), .offset = f.scroll, @@ -14398,7 +14532,7 @@ pub const Pardes = struct { const gsb = panes.Terminal.scrollbar(pane); break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len }; }; - const track_h: usize = r.h - BOX_H; + const track_h: usize = body_h; const total = if (sb.total == 0) 1 else sb.total; const len = @max(1, (track_h * @max(1, sb.len)) / total); const pos = (track_h * sb.offset) / total; @@ -14658,6 +14792,24 @@ test "a builtin announces itself on the message row, and Verbose silences it" { try std.testing.expect(pane.notices.len > 0); try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[0]); + // ...and it is carried as a tagline band, not a body row: that is what + // gives it the tagline's height, its small font and its border. + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const r = p.rects[p.active]; + const band = for (p.surface.tagLayers()) |*layer| { + if (layer.cols != 0 and layer.kind == .notice) break layer; + } else return error.NoNoticeBand; + try std.testing.expectEqual(@as(u16, 1), band.viewport.h); + try std.testing.expectEqual(if (p.settings.tag_bottom) r.y else r.y + BOX_H, band.viewport.y); + // Right aligned: the text ends at the band's right edge. + const line = band.cells[0..band.cols]; + var last: usize = line.len; + while (last > 0 and line[last - 1].grapheme()[0] == ' ') last -= 1; + try std.testing.expect(last > 0); + try std.testing.expect(line[0].grapheme()[0] == ' '); + // Msg owns the row itself, so it does not announce over its own text. try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); try std.testing.expectEqualStrings("hello", pane.msg[0..pane.msg_len]); @@ -14668,6 +14820,86 @@ test "a builtin announces itself on the message row, and Verbose silences it" { try std.testing.expectEqual(@as(u16, 0), pane.msg_len); } +test "notices stack downward from the top of the body, which starts below them" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const id = p.active; + const pane = p.panes[id].?; + p.sync(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + + const r = p.rects[id]; + const plain = p.bodyTop(pane, r); + try std.testing.expectEqual(@as(u16, 0), pane.body_offset); + + // A message and a leader prefix at once: two bands, stacked in the order + // collectNotices chose, each one row tall and each one row further down. + try std.testing.expect(p.executeBuiltinLine(id, "Msg first")); + p.leader_on = true; + p.leader_n = 0; + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try std.testing.expectEqual(@as(u16, 2), pane.body_offset); + try std.testing.expectEqual(plain + 2, p.bodyTop(pane, r)); + + var rows: [Pane.Notices.max]u16 = @splat(0); + var found: usize = 0; + for (p.surface.tagLayers()) |*layer| { + if (layer.cols == 0 or layer.kind != .notice) continue; + try std.testing.expectEqual(@as(u16, 1), layer.viewport.h); + rows[found] = layer.viewport.y; + found += 1; + } + try std.testing.expectEqual(@as(usize, 2), found); + std.mem.sort(u16, rows[0..2], {}, std.sort.asc(u16)); + try std.testing.expectEqual(plain, rows[0]); + try std.testing.expectEqual(plain + 1, rows[1]); + + // Gone with the notices: no stale band, and the body back at the top. + p.leader_on = false; + pane.msg_len = 0; + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try std.testing.expectEqual(@as(u16, 0), pane.body_offset); + try std.testing.expectEqual(plain, p.bodyTop(pane, r)); + for (p.surface.tagLayers()) |*layer| + try std.testing.expect(layer.cols == 0 or layer.kind != .notice); +} + +test "a prompt band keeps its caret on the grid, and a band is not a click target" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const id = p.active; + const pane = p.panes[id].?; + p.sync(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + + // The caret sits AFTER the prompt text the moment the prompt opens, and + // the band is flush with the pane's right edge -- so this is the frame + // that used to put it one column past the pane, off the grid and past + // what the detached wire will encode. + p.startPrompt(pane, .{ .search = "/" }); + _ = try p.render(frame.allocator()); + const r = p.rects[id]; + const cursor = p.surface.cursor orelse return error.MissingPromptCursor; + try std.testing.expect(pane.body_offset > 0); + try std.testing.expectEqual(p.bodyTop(pane, r) - 1, cursor.y); + try std.testing.expect(cursor.x < r.x + r.w); + try std.testing.expect(cursor.x < p.surface.cols); + + // The band is chrome. Mapped as body it would land on Sel row 0, which is + // the TAG row, so a click on it would run a word out of the tag as a + // builtin. + const band_row = p.bodyTop(pane, r) - 1; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x + r.w - 4, .row = band_row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = r.x + r.w - 4, .row = band_row } }); + for (pane.sel) |selection| try std.testing.expect(selection.state == .none); +} + test "closing the last pane in a column leaves an empty one in its place" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 24 }); diff --git a/src/tag_layer.zig b/src/tag_layer.zig index 65990959..0fb2297d 100644 --- a/src/tag_layer.zig +++ b/src/tag_layer.zig @@ -3,7 +3,11 @@ const std = @import("std"); const pardes = @import("pardes.zig"); -pub const Kind = enum(u8) { workspace, column, pane }; +/// `notice` is a pane's transient line -- a builtin's name, a pending leader +/// chord -- carried as a tagline-shaped band so it gets the tagline's height, +/// small-font metrics, band offset and border instead of being a body-grid row +/// wearing a tagline font. +pub const Kind = enum(u8) { workspace, column, pane, notice }; pub const Hit = struct { kind: Kind, id: u16, diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index 5a181b78..eaa19b43 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -366,6 +366,18 @@ pub const Harness = struct { }; /// Write a file (helper for test setup, raw libc). +pub fn appendFile(path: [*:0]const u8, data: []const u8) !void { + const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return error.OpenFailed; + defer _ = libc.close(fd); + var off: usize = 0; + while (off < data.len) { + const w = libc.write(fd, data[off..].ptr, data.len - off); + if (w <= 0) break; + off += @intCast(w); + } +} + pub fn writeFile(path: [*:0]const u8, data: []const u8) !void { const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); if (fd < 0) return error.OpenFailed; diff --git a/test/fs.py b/test/fs.py index c8dea2d9..33bcdfa9 100644 --- a/test/fs.py +++ b/test/fs.py @@ -612,7 +612,11 @@ def test(binary, quic=False): if start < 0: continue styles = [screen['styles'][cell[1]] for cell in cells[start:start + len(word)]] - assert all(style['bold'] and style['fg'] == styles[0]['fg'] for style in styles), (word, styles) + # Weight is opt-in (SyntaxBold, off by default); colour is + # not, so the keyword must differ from the text beside it. + plain = screen['styles'][cells[start + len(word)][1]] + assert all(not style['bold'] and style['fg'] == styles[0]['fg'] for style in styles), (word, styles) + assert styles[0]['fg'] != plain['fg'], (word, styles[0], plain) found.add(word) assert found == {'fn', 'if'}, screen diff --git a/test/output.zig b/test/output.zig index 1fcb6104..8afbf4d2 100644 --- a/test/output.zig +++ b/test/output.zig @@ -77,7 +77,7 @@ fn outputCell(p: *Pardes, surface: *pardes.Surface, id: usize, byte: usize) *par const line = modal.lineSlice(pane.file.?.content, 0); const rect = p.rects[id]; const x = rect.x + config.GUTTER + panes.File.gutterWidth(pane) + @as(u16, @intCast(panes.File.displayWidth(line[0..byte]))); - const y = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const y = p.bodyTop(pane, rect); return surface.at(x, y); } @@ -490,7 +490,7 @@ test "Mini syntax colors survive toggles themes and rendering without source acc const surface = try p.render(frame.allocator()); const rect = p.rects[id]; const x = rect.x + config.GUTTER + panes.File.gutterWidth(mini) + @as(u16, @intCast(column)); - const y = (if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H) + @as(u16, @intCast(position.row)); + const y = p.bodyTop(mini, rect) + @as(u16, @intCast(position.row)); if (enabled) try std.testing.expectEqualDeep(pardes.Color{ .rgb = p.theme().kw }, surface.at(x, y).style.fg); try std.testing.expectEqual(colors, mini.file.?.mini.?.colors.ptr); try std.testing.expectEqual(@as(usize, 0), mini.file.?.highlights.len); diff --git a/test/panes.zig b/test/panes.zig index e4e677e4..69628cd9 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -468,7 +468,7 @@ const TreeContextTests = struct { try std.testing.expectEqual(@as(i32, 59), pane.wrapAt(visible.row).line); const cursor = surface.cursor orelse return error.MissingLookCursor; const rect = p.rects[0]; - const y = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const y = p.bodyTop(pane, rect); try std.testing.expectEqual(y + @as(u16, @intCast(visible.row)), cursor.y); } } @@ -490,14 +490,16 @@ const TreeContextTests = struct { try std.testing.expectEqual(@as(i32, 7), pane.wrapAt(pane.context_rows).line); const rect = p.rects[0]; const x = rect.x + config.GUTTER + panes.File.gutterWidth(pane); - const y = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const y = p.bodyTop(pane, rect); ClickCursorTests.click(p, .left, x + 6, y); try std.testing.expectEqual(@as(i32, 0), pane.cur_row); try std.testing.expectEqual(@as(i32, 6), pane.cur_col); try std.testing.expectEqual(@as(i32, 7), pane.scroll()); const cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingContextCursor; try std.testing.expectEqual(x + 6, cursor.x); - try std.testing.expectEqual(y, cursor.y); + // Read the body top again: the click cleared the announcement band the + // builtin above put up, and the body moved back up with it. + try std.testing.expectEqual(p.bodyTop(pane, p.rects[0]), cursor.y); p.update(.{ .key = .{ .cp = 'i' } }); p.update(.{ .key = .{ .cp = 'Z', .text = "Z" } }); try std.testing.expect(std.mem.startsWith(u8, pane.file.?.content, "const ZBox = struct {")); @@ -536,7 +538,7 @@ const TreeContextTests = struct { const surface = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 3), pane.context_rows); const rect = p.rects[0]; - const y = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const y = p.bodyTop(pane, rect); var glyph_x: ?u16 = null; for (0..surface.cols) |col| { if (std.mem.eql(u8, surface.at(@intCast(col), y).grapheme(), "界")) glyph_x = @intCast(col); @@ -548,7 +550,9 @@ const TreeContextTests = struct { try std.testing.expectEqual(@as(i32, 8), pane.scroll()); const cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingContextCursor; try std.testing.expectEqual(x, cursor.x); - try std.testing.expectEqual(y, cursor.y); + // Read the body top again: the click cleared the announcement band the + // builtin above put up, so the body moved with it. + try std.testing.expectEqual(p.bodyTop(pane, p.rects[0]), cursor.y); panes.File.setContent(p, &pane.file.?, try p.gpa.dupe(u8, "// no enclosing declaration\n" ** 18)); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 0), pane.context_rows); @@ -576,12 +580,16 @@ const TreeContextTests = struct { target = .{ .x = @intCast(col), .y = @intCast(row) }; }; const glyph = target orelse return error.MissingWrappedContextBody; + const offset = pane.body_offset; ClickCursorTests.click(p, .left, glyph.x + 1, glyph.y); try std.testing.expectEqual(@as(i32, 2), pane.cur_row); try std.testing.expectEqual(@as(i32, @intCast(std.mem.indexOf(u8, body, "界").?)), pane.cur_col); const cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingContextBodyCursor; try std.testing.expectEqual(glyph.x, cursor.x); - try std.testing.expectEqual(glyph.y, cursor.y); + // The scan above ran with the builtin's announcement band up; the click + // cleared it, so the row the glyph was found on has moved up with the + // body it belongs to. + try std.testing.expectEqual(glyph.y - offset, cursor.y); } }; @@ -607,7 +615,7 @@ const TtySelectionTests = struct { _ = try p.render(frame.allocator()); const rect = p.rects[0]; const x = rect.x + config.GUTTER; - const y = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const y = p.bodyTop(pane, rect); JumpSelectionTests.drag(p, x + 1, y, x + 3, y); try std.testing.expectEqualStrings("lph", p.yank orelse return error.MissingAutomaticTtyYank); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); @@ -637,7 +645,7 @@ const TtySelectionTests = struct { _ = try p.render(frame.allocator()); const rect = p.rects[0]; const x = rect.x + config.GUTTER; - const y = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const y = p.bodyTop(pane, rect); JumpSelectionTests.drag(p, x + @as(u16, if (prompt) 0 else 1), y, x + 3, y + @as(u16, if (prompt) 0 else 1)); const expected = if (prompt) "$ ab" else "lph\nrav"; try std.testing.expectEqual(Pane.Mode.tty, pane.mode); @@ -952,7 +960,7 @@ const JumpSelectionTests = struct { if (wrap) try std.testing.expectEqual(pane.wrap_line[0], pane.wrap_line[1]); const rect = p.rects[0]; const x = rect.x + config.GUTTER + panes.File.gutterWidth(pane); - const y = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const y = p.bodyTop(pane, rect); if (reverse) drag(p, x + last_col, y + 1, x + first_col, y) else @@ -982,7 +990,9 @@ const JumpSelectionTests = struct { try std.testing.expectEqual(@as(i32, 0), pane.cur_col); // A selection created after Back must also disappear on Forward. - drag(p, x + 1, y, x + 3, y + 1); + // Back announces itself, so the body sits under a notice band now. + const y2 = p.bodyTop(pane, p.rects[0]); + drag(p, x + 1, y2, x + 3, y2 + 1); try std.testing.expect(pardes.test_api.heldSelection(p, 0) != null); p.update(.{ .key = .{ .cp = 'i', .ctrl = true } }); _ = frame.reset(.retain_capacity); @@ -4117,7 +4127,7 @@ test "cancelled normal gestures leave no count or subprefix after mouse and focu .body, .tag => { const rect = p.rects[0]; const tag_y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; - const body_y = if (p.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, rect); const x = rect.x + config.GUTTER + @as(u16, @intCast(panes.File.gutterWidth(pane))) + 3; const y = if (gesture == .tag) tag_y else body_y; p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x, .row = y } }); diff --git a/test/snapshot.zig b/test/snapshot.zig index 7fa84a86..7cc5eb91 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -619,7 +619,13 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const const cmd = tok.next().?; errdefer std.debug.print(" at {s}:{d}: {s}\n", .{ script_path, lineno, line }); - if (std.mem.eql(u8, cmd, "file")) { + if (std.mem.eql(u8, cmd, "config")) { + // Appended to the startup config this script's fake home already + // has, so a script can pin a setting instead of spelling out the + // screen geometry a default implies. Must precede `start`. + const setting = try std.fmt.allocPrint(arena, "{s}\n", .{tok.rest()}); + try eh.appendFile(try std.fmt.allocPrintSentinel(arena, "{s}/pardes/init", .{config_home}, 0), setting); + } else if (std.mem.eql(u8, cmd, "file")) { const name = tok.next() orelse return error.BadScript; try eh.writeFile(try arena.dupeZ(u8, name), try unescape(arena, tok.rest())); } else if (std.mem.eql(u8, cmd, "lines")) { diff --git a/test/snapshots/argv.golden b/test/snapshots/argv.golden index 4da2a12d..abf5781d 100644 --- a/test/snapshots/argv.golden +++ b/test/snapshots/argv.golden @@ -1,14 +1,31 @@ == snap noargs grid=100x31 cursor=4,5 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|$ /tmp/pardes-snap/argv/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/argv/cwd Tty Save Mode Filter Collapse Del | $ echo ARGV''TTY | ARGVTTY | $ +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| /+New Save Tty Collapse Del +| 1 == snap filearg grid=100x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del | 3 line 3 | 4 line 4 | 5 line 5 @@ -18,8 +35,8 @@ | 9 == snap filearg-n3 grid=100x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -31,7 +48,7 @@ | 9 == snap dirarg grid=100x31 cursor=4,5 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/argv/cwd/sub Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/argv/cwd/sub Tty Save Mode Filter Collapse Del | ls | inside.txt diff --git a/test/snapshots/badutf.golden b/test/snapshots/badutf.golden index 270b3fe6..d3a906b1 100644 --- a/test/snapshots/badutf.golden +++ b/test/snapshots/badutf.golden @@ -1,7 +1,7 @@ == snap badbytes grid=100x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/badutf/cwd/bad.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/badutf/cwd/bad.txt Save Tty Collapse Del | 1 hello �� world | 2 latin-1 caf� tail | 3 truncated �� here @@ -9,8 +9,8 @@ | 5 == snap hscroll-midglyph grid=50x31 cursor=46,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump -|New Tty Find Grep Joincol -| /tmp/pardes-snap/badutf/cwd/wide.txt Save Tty De +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/badutf/cwd/wide.txt Save Tty C | 1 日本語 日本語 日本語 日本語 日本語 tail | 2 | 3 diff --git a/test/snapshots/boot.golden b/test/snapshots/boot.golden index f1e159d1..2e4ad22f 100644 --- a/test/snapshots/boot.golden +++ b/test/snapshots/boot.golden @@ -1,38 +1,38 @@ == snap boot grid=100x31 cursor=4,5 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/boot/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/boot/cwd Tty Save Mode Filter Collapse Del | ls | hello.txt == style boot grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-99 d,#26362d, -|2: 0-1 #000000,#adcc91, 2-69 #becfc4,#26362d, 70-99 d,#26362d, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-99 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-99 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-28 #becfc4,#26362d, 29-31 #dfbce5,#26362d, 32-61 #becfc4,#26362d, 62-99 d,#26362d, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-99 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, diff --git a/test/snapshots/builtins.golden b/test/snapshots/builtins.golden index 17b4db5e..96dabb54 100644 --- a/test/snapshots/builtins.golden +++ b/test/snapshots/builtins.golden @@ -1,7 +1,7 @@ == snap boot grid=120x67 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/builtins/cwd/notes.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/builtins/cwd/notes.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -10,23 +10,23 @@ | 6 line 6 | 7 == snap window-group grid=120x67 cursor=7,36 -|35: /tmp/pardes-snap/builtins/cwd/+Help Save Tty Del Collapse +|35: /tmp/pardes-snap/builtins/cwd/+Help Save Tty Collapse Del |36: 1 pardes builtins under SPC w |37: 2 -|38: 3 SPC w h Left C-w h, C-w left -|39: 4 SPC w j Down C-w j, C-w down -|40: 5 SPC w k Up C-w k, C-w up -|41: 6 SPC w l Right C-w l, C-w right +|38: 3 SPC w h Left C-w h, C-w left +|39: 4 SPC w j Down C-w j, C-w down +|40: 5 SPC w k Up C-w k, C-w up +|41: 6 SPC w l Right C-w l, C-w right |42: 7 == snap docs-group grid=120x67 cursor=7,36 |36: 1 pardes builtins under SPC h -|38: 3 SPC h c Changelog topbar +|38: 3 SPC h c Changelog topbar |39: 4 SPC h m Messages -|40: 5 SPC h t Tutor topbar +|40: 5 SPC h t Tutor topbar |41: 6 |42: == snap tutor-from-index grid=120x67 cursor=7,20 -|19: /Tutor Save Tty Del Collapse +|19: /Tutor Save Tty Collapse Del |20: 1 |21: 2 PARDES TUTOR |22: 3 tmux + vi + acme, from scratch. @@ -42,3 +42,10 @@ |32: 13 |33: 14 A pane is just text on screen. There is no separate "buffer" type — |34: 15 what you see is what you edit. Some panes happen to be live terminals; +|36: Tutor +|37: 1 pardes builtins under SPC h +|38: 2 +|39: 3 SPC h c Changelog topbar +|40: 4 SPC h m Messages +|41: 5 SPC h t Tutor topbar +|42: 6 diff --git a/test/snapshots/builtins.snap b/test/snapshots/builtins.snap index 06298d77..cd47209f 100644 --- a/test/snapshots/builtins.snap +++ b/test/snapshots/builtins.snap @@ -9,19 +9,26 @@ key space ? wait 10000 pardes builtins, and how to run each: wait 10000 ClipPasteBefore key g e -# The new Collapse entry adds one index line: expose Look above the bottom -# viewport while keeping the same pane geometry for the later group clicks. +# Every builtin added since adds an index line, and one wheel tick is one row +# (config.wheel_rows): scroll far enough to expose Look and Exec above the +# bottom viewport while keeping the same pane geometry for the later clicks. wheel up 110 50 -wait 10000 Look enter, right-click -wait 10000 Exec tab, middle-click +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wait 10000 Look enter, right-click +wait 10000 Exec tab, middle-click wait 10000 Filter wait 10000 Theme stable 700 15000 # n moves through look-able text; it must not execute command names. key n n n -wait 10000 Look enter, right-click -wait 10000 Exec tab, middle-click +wait 10000 Look enter, right-click +wait 10000 Exec tab, middle-click key space w ? wait 10000 Right stable 700 15000 diff --git a/test/snapshots/chordcut.golden b/test/snapshots/chordcut.golden index 33bc8356..a9586983 100644 --- a/test/snapshots/chordcut.golden +++ b/test/snapshots/chordcut.golden @@ -1,11 +1,11 @@ == snap opened grid=120x31 cursor=7,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/chordcut/cwd Save Tty Del Togglettymode F /tmp/pardes-snap/chordcut/cwd Save Tty Del Togglettymode F -| ls ls -| f.txt g.txt f.txt g.txt -| -| /tmp/pardes-snap/chordcut/cwd/f.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/chordcut/cwd Tty Save Mode Filter Collap /tmp/pardes-snap/chordcut/cwd Tty Save Mode Filter Collap +| Look ls +| ls f.txt g.txt +| f.txt g.txt +| /tmp/pardes-snap/chordcut/cwd/f.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -16,11 +16,14 @@ | | | -| /tmp/pardes-snap/chordcut/cwd Save Tty Del Togglettymode F +| /tmp/pardes-snap/chordcut/cwd Tty Save Mode Filter Collap | ls | f.txt g.txt == snap cut grid=120x31 cursor=7,8 -|6: /tmp/pardes-snap/chordcut/cwd/f.txt * Save Tty Del Collaps +|3: ls ls +|4: f.txt g.txt f.txt g.txt +|5: +|6: /tmp/pardes-snap/chordcut/cwd/f.txt * Save Tty Collapse D |8: 2 2 == snap copied grid=120x31 cursor=10,9 == snap pointpaste grid=120x31 cursor=16,10 @@ -29,53 +32,77 @@ |11: 5 lline 5 == snap cancelexec grid=120x31 cursor=25,8 |8: 2 2echo B''OO g.txt -== snap execafter grid=120x31 cursor=25,8 +== snap execafter grid=120x31 cursor=25,9 |3: f.txt ls |4: BOO f.txt g.txt +|7: Exec +|8: 1 line 1 +|9: 2 2echo B''OO g.txt +|10: 3 line 3 +|11: 4 line 4line +|12: 5 lline 5 +|13: 6 == snap cancellook grid=120x31 cursor=25,8 +|7: 1 line 1 +|8: 2 2echo B''OO g.txt +|9: 3 line 3 +|10: 4 line 4line +|11: 5 lline 5 +|12: 6 +|13: == snap lookafter grid=120x31 cursor=7,13 -|12: /tmp/pardes-snap/chordcut/cwd/g.txt Save Tty Del Collapse +|7: Look +|8: 1 line 1 +|9: 2 2echo B''OO g.txt +|10: 3 line 3 +|11: 4 line 4line +|12: /tmp/pardes-snap/chordcut/cwd/g.txt Save Tty Collapse Del |13: 1 line 1 |14: 2 line 2 |15: 3 == style chordsel grid=120x31 |0: 0-70 #b2c3b8,#1d2824, 71-119 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-59 d,#26362d, 60-84 #b2c3b8,#1d2824, 85-119 d,#1d2824, -|2: 0-1 #ffffff,#4c6356, 2-59 #b2c3b8,#1d2824, 60-61 #ffffff,#4c6356, 62-119 #b2c3b8,#1d2824, -|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-8 #e5eee5,#0d1410, 9-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|5: 0-0 d,#152019, 1-59 d,#0d1410, 60-60 d,#637f6a, 61-119 d,#0d1410, -|6: 0-1 #ffffff,#4c6356, 2-59 #b2c3b8,#1d2824, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-24 #e5eee5,#0d1410, 25-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|12: 0-1 #000000,#adcc91, 2-59 #becfc4,#26362d, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #f5f7ee,#405d4b, 11-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-59 #b2c3b8,#1d2824, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-59 d,#26362d, 60-61 #ffffff,#887455, 62-62 d,#1d2824, 63-94 #b2c3b8,#1d2824, 95-119 d,#1d2824, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-32 #b2c3b8,#1d2824, 33-35 #d3b0d9,#1d2824, 36-59 #b2c3b8,#1d2824, 60-61 #ffffff,#496656, 62-62 d,#1d2824, 63-92 #b2c3b8,#1d2824, 93-95 #d3b0d9,#1d2824, 96-119 #b2c3b8,#1d2824, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-8 #e5eee5,#0d1410, 9-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|5: 0-0 d,#152019, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, +|6: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-32 #b2c3b8,#1d2824, 33-37 #d3b0d9,#1d2824, 38-59 #b2c3b8,#1d2824, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-24 #e5eee5,#0d1410, 25-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|12: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-32 #becfc4,#26362d, 33-37 #dfbce5,#26362d, 38-59 #becfc4,#26362d, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-32 #b2c3b8,#1d2824, 33-35 #d3b0d9,#1d2824, 36-59 #b2c3b8,#1d2824, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, == style clickdismiss grid=120x31 -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#637f6a, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, == snap ttyprobe grid=120x31 cursor=42,22 -|12: /tmp/pardes-snap/chordcut/cwd/g.txt * Save Tty Del Collaps -|17: $ /tmp/pardes-snap/chordcut/cwd Save Tty Del Togglettymode F +|7: 1 line 1 +|8: 2 2echo B''OO g.txt +|9: 3 line 3 +|10: 4 line 4line +|11: 5 lline 5 +|12: /tmp/pardes-snap/chordcut/cwd/g.txt * Save Tty Collapse D +|17: $ /tmp/pardes-snap/chordcut/cwd Tty Save Mode Filter Collap |18: $ ls |20: $ stty -icanon -echo; printf '\x1b[?2004h\x1b[?1000h\x1b[? |21: 1006h'; cat -v diff --git a/test/snapshots/cmdword.golden b/test/snapshots/cmdword.golden index 0ba57092..e6f470fa 100644 --- a/test/snapshots/cmdword.golden +++ b/test/snapshots/cmdword.golden @@ -1,24 +1,24 @@ == snap opened grid=120x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/cmdword/cwd/cmds.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cmdword/cwd/cmds.txt Save Tty Collapse Del | 1 @`echo ZZ''E` @`echo ZZ''L` Look p.txt @`Look .` == snap atexec grid=120x31 cursor=7,3 -|17: /tmp/pardes-snap/cmdword/cwd Save Tty Del Togglettymode Filter Collapse +|17: /tmp/pardes-snap/cmdword/cwd Tty Save Mode Filter Collapse Del |18: echo ZZ''E |19: ZZE == snap atlook grid=120x31 cursor=4,22 |20: echo ZZ''L |21: ZZL == snap lookword grid=120x31 cursor=7,11 -|10: /tmp/pardes-snap/cmdword/cwd/p.txt Save Tty Del Collapse +|10: /tmp/pardes-snap/cmdword/cwd/p.txt Save Tty Collapse Del |11: 1 just text == snap nested grid=120x31 cursor=4,24 |22: ls |23: cmds.txt p.txt zzmark.txt -== snap execword grid=120x31 cursor=77,17 -|17: /tmp/pardes-snap/cmdword/cwd Save Tty Del Togglettymode Filter Collapse Exec -== snap tagcmd grid=120x31 cursor=91,17 -|17: /tmp/pardes-snap/cmdword/cwd Save Tty Del Togglettymode Filter Collapse Exec @`echo ZZ''T` +== snap execword grid=120x31 cursor=69,17 +|17: /tmp/pardes-snap/cmdword/cwd Tty Save Mode Filter Collapse Del Exec +== snap tagcmd grid=120x31 cursor=83,17 +|17: /tmp/pardes-snap/cmdword/cwd Tty Save Mode Filter Collapse Del Exec @`echo ZZ''T` |24: echo ZZ''T |25: ZZT diff --git a/test/snapshots/cmdword.snap b/test/snapshots/cmdword.snap index eb9d308d..eb0e0ea6 100644 --- a/test/snapshots/cmdword.snap +++ b/test/snapshots/cmdword.snap @@ -18,6 +18,10 @@ file cmds.txt @`echo ZZ''E` @`echo ZZ''L` Look p.txt @`Look .` file p.txt just text file zzmark.txt x +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which would move every row this script clicks. The +# verbs are what is under test here, not the announcement. +config Verbose off start 31 120 cmds.txt wait 8000 Newcol Joincol wait 8000 cmds.txt diff --git a/test/snapshots/collapse.golden b/test/snapshots/collapse.golden index 8dcfd4d7..d356fd02 100644 --- a/test/snapshots/collapse.golden +++ b/test/snapshots/collapse.golden @@ -1,7 +1,7 @@ == snap before grid=160x25 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del | 1 KEEP-FIRST | 2 KEEP-SECOND | 3 KEEP-THIRD @@ -12,67 +12,70 @@ == 9p middle-collapsed-cursor grid=160x25 cursor=none |0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill @0: 0-70 #b2c3b8,#1d2824,,tagline 71-159 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol -@1: 0-24 #becfc4,#26362d,,tagline 25-159 d,#26362d,,tagline -|2: /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Del Collapse -@2: 0-1 #000000,#adcc91,,tagline 2-61 #becfc4,#26362d,,tagline 62-159 d,#26362d,,tagline +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#26362d,,tagline 3-34 #becfc4,#26362d,,tagline 35-159 d,#26362d,,tagline +|2: /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del +@2: 0-1 #000000,#add38a,,tagline 2-2 d,#26362d,,tagline 3-32 #becfc4,#26362d,,tagline 33-40 #dfbce5,#26362d,,tagline 41-62 #becfc4,#26362d,,tagline 63-159 d,#26362d,,tagline |3: -@3: 0-159 d,#35483d,,body +@3: 0-159 d,#486152,,body |4: -@4: 0-159 d,#35483d,,body +@4: 0-159 d,#486152,,body |5: -@5: 0-159 d,#35483d,,body +@5: 0-159 d,#486152,,body |6: -@6: 0-159 d,#35483d,,body +@6: 0-159 d,#486152,,body |7: -@7: 0-159 d,#35483d,,body +@7: 0-159 d,#486152,,body |8: -@8: 0-159 d,#35483d,,body +@8: 0-159 d,#486152,,body |9: -@9: 0-159 d,#35483d,,body +@9: 0-159 d,#486152,,body |10: -@10: 0-159 d,#35483d,,body +@10: 0-159 d,#486152,,body |11: -@11: 0-159 d,#35483d,,body +@11: 0-159 d,#486152,,body |12: -@12: 0-159 d,#35483d,,body +@12: 0-159 d,#486152,,body |13: -@13: 0-159 d,#35483d,,body +@13: 0-159 d,#486152,,body |14: -@14: 0-159 d,#35483d,,body +@14: 0-159 d,#486152,,body |15: -@15: 0-159 d,#35483d,,body +@15: 0-159 d,#486152,,body |16: -@16: 0-159 d,#35483d,,body +@16: 0-159 d,#486152,,body |17: -@17: 0-159 d,#35483d,,body +@17: 0-159 d,#486152,,body |18: -@18: 0-159 d,#35483d,,body +@18: 0-159 d,#486152,,body |19: -@19: 0-159 d,#35483d,,body +@19: 0-159 d,#486152,,body |20: -@20: 0-159 d,#35483d,,body +@20: 0-159 d,#486152,,body |21: -@21: 0-159 d,#35483d,,body +@21: 0-159 d,#486152,,body |22: -@22: 0-159 d,#35483d,,body +@22: 0-159 d,#486152,,body |23: -@23: 0-159 d,#35483d,,body +@23: 0-159 d,#486152,,body |24: -@24: 0-159 d,#35483d,,body -== snap middle-restored grid=160x25 cursor=7,3 -|3: 1 KEEP-FIRST -|4: 2 KEEP-SECOND -|5: 3 KEEP-THIRD -== snap tab-collapsed grid=160x25 cursor=54,2 +@24: 0-159 d,#486152,,body +== snap middle-restored grid=160x25 cursor=7,4 +|3: Collapse +|4: 1 KEEP-FIRST +|5: 2 KEEP-SECOND +|6: 3 KEEP-THIRD +== snap tab-collapsed grid=160x25 cursor=51,2 |3: |4: |5: -== 9p tab-collapsed-cursor grid=160x25 cursor=54,2,bar -== snap tab-restored grid=160x25 cursor=54,2 -|3: 1 KEEP-FIRST -|4: 2 KEEP-SECOND -|5: 3 KEEP-THIRD +|6: +== 9p tab-collapsed-cursor grid=160x25 cursor=51,2,bar +== snap tab-restored grid=160x25 cursor=51,2 +|3: Collapse +|4: 1 KEEP-FIRST +|5: 2 KEEP-SECOND +|6: 3 KEEP-THIRD == file unchanged KEEP-FIRST KEEP-SECOND diff --git a/test/snapshots/cornerdrag-left.golden b/test/snapshots/cornerdrag-left.golden index df10fd3d..145adb02 100644 --- a/test/snapshots/cornerdrag-left.golden +++ b/test/snapshots/cornerdrag-left.golden @@ -1,11 +1,11 @@ == snap right-split grid=100x31 cursor=54,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/cornerdrag-left/cwd Save Tty De /tmp/pardes-snap/cornerdrag-left/cwd Save Tty De +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cornerdrag-left/cwd Tty Save M /tmp/pardes-snap/cornerdrag-left/cwd Tty Save M | ls ls | w.txt w.txt | -| /tmp/pardes-snap/cornerdrag-left/cwd Save Tty De +| /tmp/pardes-snap/cornerdrag-left/cwd Tty Save M | ls | w.txt | @@ -16,16 +16,16 @@ | | | -| /tmp/pardes-snap/cornerdrag-left/cwd Save Tty De +| /tmp/pardes-snap/cornerdrag-left/cwd Tty Save M | ls | w.txt == snap hover-corner grid=100x31 cursor=54,9 -|1: New Tty Find Grep Joincol ╎New Tty Find Grep Joincol -|2: /tmp/pardes-snap/cornerdrag-left/cwd Save Tty D╎ /tmp/pardes-snap/cornerdrag-left/cwd Save Tty De +|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag-left/cwd Tty Save ╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty Save M |3: ls ╎ ls |4: w.txt ╎ w.txt |5: ╎ -|6: ╎ /tmp/pardes-snap/cornerdrag-left/cwd Save Tty De +|6: ╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty Save M |7: ╎ ls |8: ╎ w.txt |9: ╎ @@ -36,7 +36,7 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/cornerdrag-left/cwd Save Tty D╎ +|17: /tmp/pardes-snap/cornerdrag-left/cwd Tty Save ╎ |18: ls ╎ |19: w.txt ╎ |20: ╎ @@ -52,12 +52,12 @@ |30: ╎ == snap hover-left-corner grid=100x31 cursor=54,9 == snap corner-drag grid=100x31 cursor=54,9 -|1: New Tty Find Grep Joincol ╎ New Tty Find Grep Joincol -|2: /tmp/pardes-snap/cornerdrag╎left/cwd Save Tty De /tmp/pardes-snap/cornerdrag-left/cwd Save Tty De +|1: New Tty Find Grep Joincol ╎elcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdra╎-left/cwd Tty Save M /tmp/pardes-snap/cornerdrag-left/cwd Tty Save M |3: ls ╎ ls |4: w.txt ╎ w.txt |5: ╎ -|6: ╎ /tmp/pardes-snap/cornerdrag-left/cwd Save Tty De +|6: ╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty Save M |7: ╎ ls |8: ╎ w.txt |9: ╎ @@ -68,7 +68,7 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/cornerdrag╎left/cwd Save Tty De +|17: /tmp/pardes-snap/cornerdra╎-left/cwd Tty Save M |18: ls ╎ |19: w.txt ╎ |20: ╎ @@ -83,8 +83,8 @@ |29: ╎ |30: ╎ == snap corner-done grid=100x31 cursor=34,16 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol -|2: /tmp/pardes-snap/cornerdrag- /tmp/pardes-snap/cornerdrag-left/cwd Save Tty Del Togglettymode Filt +|1: New Tty Find Grep Joincol D New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag /tmp/pardes-snap/cornerdrag-left/cwd Tty Save Mode Filter Collapse |3: ls ls |4: w.txt w.txt |5: @@ -95,11 +95,11 @@ |10: |11: |12: -|13: /tmp/pardes-snap/cornerdrag-left/cwd Save Tty Del Togglettymode Filt +|13: /tmp/pardes-snap/cornerdrag-left/cwd Tty Save Mode Filter Collapse |14: ls |15: w.txt |16: -|17: /tmp/pardes-snap/cornerdrag- +|17: /tmp/pardes-snap/cornerdrag |18: ls |19: w.txt |20: diff --git a/test/snapshots/cornerdrag.golden b/test/snapshots/cornerdrag.golden index 003bf0d8..b95734ea 100644 --- a/test/snapshots/cornerdrag.golden +++ b/test/snapshots/cornerdrag.golden @@ -1,7 +1,7 @@ == snap hover-corner grid=100x31 cursor=4,5 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol ╎New Tty Find Grep Joincol -| /tmp/pardes-snap/cornerdrag/cwd Save Tty Del To╎ /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Tog +| New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode ╎ /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode F | ls ╎ ls | w.txt ╎ w.txt | ╎ @@ -16,7 +16,7 @@ | ╎ | ╎ | ╎ -| /tmp/pardes-snap/cornerdrag/cwd Save Tty Del To╎ +| /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode ╎ | ls ╎ | w.txt ╎ | ╎ @@ -31,8 +31,8 @@ | ╎ | ╎ == snap edge-drag grid=100x31 cursor=4,5 -|1: New Tty Find Grep Joincol ╎ New Tty Find Grep Joincol -|2: /tmp/pardes-snap/cornerdrag╎cwd Save Tty Del Tog /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Tog +|1: New Tty Find Grep Joincol ╎elcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdra╎/cwd Tty Save Mode F /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode F |3: ls ╎ ls |4: w.txt ╎ w.txt |5: ╎ @@ -47,7 +47,7 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/cornerdrag╎cwd Save Tty Del Tog +|17: /tmp/pardes-snap/cornerdra╎/cwd Tty Save Mode F |18: ls ╎ |19: w.txt ╎ |20: ╎ @@ -62,8 +62,8 @@ |29: ╎ |30: ╎ == snap edge-done grid=100x31 cursor=4,5 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol -|2: /tmp/pardes-snap/cornerdrag/ /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymode Filter Co +|1: New Tty Find Grep Joincol D New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Collapse Del |3: ls ls |4: w.txt w.txt |5: @@ -78,7 +78,7 @@ |14: |15: |16: -|17: /tmp/pardes-snap/cornerdrag/ +|17: /tmp/pardes-snap/cornerdrag |18: ls |19: w.txt |20: @@ -93,8 +93,8 @@ |29: |30: == snap corner-drag grid=100x31 cursor=4,5 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol ╎ -|2: /tmp/pardes-snap/cornerdrag/ /tmp/pardes-snap/cornerdrag╎cwd Save Tty Del Togglettymode Filter Co +|1: New Tty Find Grep Joincol D New Tty Find Grep Joincol ╎elcol +|2: /tmp/pardes-snap/cornerdrag /tmp/pardes-snap/cornerdra╎/cwd Tty Save Mode Filter Collapse Del |3: ls ls ╎ |4: w.txt w.txt ╎ |5: ╎ @@ -109,7 +109,7 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/cornerdrag/ ╎ +|17: /tmp/pardes-snap/cornerdrag ╎ |18: ls ╎ |19: w.txt ╎ |20: ╎ @@ -124,15 +124,15 @@ |29: ╎ |30: ╎ == snap corner-done grid=100x31 cursor=4,5 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol -|2: /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymode /tmp/pardes-snap/cornerdrag/cwd Save T +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Coll /tmp/pardes-snap/cornerdrag/cwd Tty S |3: ls ls |4: w.txt w.txt |5: |6: |7: |8: -|9: /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymode +|9: /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Coll |10: ls |11: w.txt |12: @@ -155,15 +155,15 @@ |29: |30: == snap clamp-x grid=100x31 cursor=4,5 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol ╎ -|2: /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymode /tmp/pardes-snap/cornerdrag/╎wd Save T +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol D╎lcol +|2: /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Coll /tmp/pardes-snap/cornerdrag╎cwd Tty S |3: ls ls ╎ |4: w.txt w.txt ╎ |5: ╎ |6: ╎ |7: ╎ |8: ╎ -|9: /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymode ╎ +|9: /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Coll ╎ |10: ls ╎ |11: w.txt ╎ |12: ╎ @@ -186,15 +186,15 @@ |29: ╎ |30: ╎ == snap clamp-y grid=100x31 cursor=4,5 -|1: New Tty Find Grep Joincol ╎New Tty Find Grep Joincol -|2: /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymod╎ /tmp/pardes-snap/cornerdrag/cwd Save T +|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Col╎ /tmp/pardes-snap/cornerdrag/cwd Tty S |3: ls ╎ ls |4: w.txt ╎ w.txt |5: ╎ |6: ╎ |7: ╎ |8: ╎ -|9: /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymod╎ +|9: /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Col╎ |10: ls ╎ |11: w.txt ╎ |12: ╎ @@ -217,8 +217,8 @@ |29: ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ |30: ╎ == snap clamp-done grid=100x31 cursor=4,5 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol -|2: /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymode /tmp/pardes-snap/cornerdrag/cwd Save T +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Coll /tmp/pardes-snap/cornerdrag/cwd Tty S |3: ls ls |4: w.txt w.txt |5: @@ -246,4 +246,4 @@ |27: |28: |29: -|30: /tmp/pardes-snap/cornerdrag/cwd Save Tty Del Togglettymode +|30: /tmp/pardes-snap/cornerdrag/cwd Tty Save Mode Filter Coll diff --git a/test/snapshots/cursorline.golden b/test/snapshots/cursorline.golden index 161655c8..97897c3f 100644 --- a/test/snapshots/cursorline.golden +++ b/test/snapshots/cursorline.golden @@ -1,11 +1,11 @@ == snap top grid=150x31 cursor=7,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/cursorline/cwd Save Tty Del Togglettymode Filter Collaps /tmp/pardes-snap/cursorline/cwd Save Tty Del Togglettymode Filter Collaps +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cursorline/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/cursorline/cwd Tty Save Mode Filter Collapse Del | ls ls | cur.txt cur.txt | -| /tmp/pardes-snap/cursorline/cwd/cur.txt Save Tty Del Collapse +| /tmp/pardes-snap/cursorline/cwd/cur.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -16,42 +16,42 @@ | 8 line 8 | 9 line 9 | 10 line 10 -| /tmp/pardes-snap/cursorline/cwd Save Tty Del Togglettymode Filter Collaps +| /tmp/pardes-snap/cursorline/cwd Tty Save Mode Filter Collapse Del | ls | cur.txt == style top grid=150x31 |0: 0-70 #b2c3b8,#1d2824, 71-149 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-74 d,#26362d, 75-99 #b2c3b8,#1d2824, 100-149 d,#1d2824, -|2: 0-1 #ffffff,#4c6356, 2-74 #b2c3b8,#1d2824, 75-76 #ffffff,#4c6356, 77-149 #b2c3b8,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|6: 0-1 #000000,#adcc91, 2-62 #becfc4,#26362d, 63-74 d,#26362d, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-74 #b2c3b8,#1d2824, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-74 d,#26362d, 75-76 #ffffff,#887455, 77-77 d,#1d2824, 78-109 #b2c3b8,#1d2824, 110-149 d,#1d2824, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-37 #d3b0d9,#1d2824, 38-67 #b2c3b8,#1d2824, 68-74 d,#1d2824, 75-76 #ffffff,#496656, 77-77 d,#1d2824, 78-109 #b2c3b8,#1d2824, 110-112 #d3b0d9,#1d2824, 113-142 #b2c3b8,#1d2824, 143-149 d,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-41 #dfbce5,#26362d, 42-63 #becfc4,#26362d, 64-74 d,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-37 #d3b0d9,#1d2824, 38-67 #b2c3b8,#1d2824, 68-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, == snap down3 grid=150x31 cursor=7,10 == style down3 grid=150x31 -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, diff --git a/test/snapshots/doccol.golden b/test/snapshots/doccol.golden index 318ac564..83d49ca5 100644 --- a/test/snapshots/doccol.golden +++ b/test/snapshots/doccol.golden @@ -1,21 +1,21 @@ == snap boot grid=100x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/doccol/cwd/a.txt Save Tty Del C /tmp/pardes-snap/doccol/cwd Save Tty Del Togglet +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/doccol/cwd/a.txt Save Tty Coll /tmp/pardes-snap/doccol/cwd Tty Save Mode Filte | 1 AAA ls | a.txt b.txt c.txt == snap two-docs grid=100x31 cursor=7,18 -|17: /tmp/pardes-snap/doccol/cwd/b.txt Save Tty Del C +|17: /tmp/pardes-snap/doccol/cwd/b.txt Save Tty Coll |18: 1 BBB |19: 2 B-TWO == snap moved grid=100x31 cursor=57,21 |17: |18: |19: -|20: /tmp/pardes-snap/doccol/cwd/b.txt Save Tty Del C +|20: /tmp/pardes-snap/doccol/cwd/b.txt Save Tty Coll |21: 1 BBB |22: 2 B-TWO == snap worked grid=100x31 cursor=59,22 == snap third grid=100x31 cursor=57,27 -|26: /tmp/pardes-snap/doccol/cwd/c.txt Save Tty Del C +|26: /tmp/pardes-snap/doccol/cwd/c.txt Save Tty Coll |27: 1 CCC diff --git a/test/snapshots/doccol.snap b/test/snapshots/doccol.snap index 677d5dff..2135c533 100644 --- a/test/snapshots/doccol.snap +++ b/test/snapshots/doccol.snap @@ -13,6 +13,10 @@ file c.txt CCC # boot used to hand over — and SPC w h comes back to a.txt, which is where the # boot left focus. (`New`/`Newcol` open an empty +New scratch now, not a # shell, so the shell has to be asked for by name.) +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 31 100 a.txt wait 8000 AAA stable 700 20000 diff --git a/test/snapshots/dump.golden b/test/snapshots/dump.golden index 18c30327..8f920136 100644 --- a/test/snapshots/dump.golden +++ b/test/snapshots/dump.golden @@ -7,6 +7,13 @@ .topbar = "Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill", .topbar_custom = null, .theme = "orchard", + .locations_config = .{ + .context = 0, + .tscontext = false, + .tslocations = true, + .layout = .stacked, + }, + .tree_context_tag_style = true, .columns = .{ .{ .tag = null, .weight = 1, @@ -19,7 +26,7 @@ .panes = .{ .{ .kind = .terminal, - .tag = "/tmp/pardes-snap/dump/cwd Save Tty Del Togglettymode Filter Collapse", + .tag = "/tmp/pardes-snap/dump/cwd Tty Save Mode Filter Collapse Del", .body = "ls\nd.txt\n\n\n\n typed-marker\n\n\n\n\n\n\n\n", .scroll = 0, .cols = 48, @@ -38,7 +45,7 @@ }, .{ .kind = .terminal, - .tag = "/tmp/pardes-snap/dump/cwd Save Tty Del Togglettymode Filter Collapse", + .tag = "/tmp/pardes-snap/dump/cwd Tty Save Mode Filter Collapse Del", .body = "ls\nd.txt\n\n\n\n\n\n\n\n\n\n\n", .scroll = 0, .cols = 48, @@ -57,7 +64,7 @@ }, .{ .kind = .terminal, - .tag = "/tmp/pardes-snap/dump/cwd Save Tty Del Togglettymode Filter Collapse", + .tag = "/tmp/pardes-snap/dump/cwd Tty Save Mode Filter Collapse Del", .body = "ls\nd.txt\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", .scroll = 0, .cols = 48, diff --git a/test/snapshots/edit.golden b/test/snapshots/edit.golden index 17c86be0..c4b1081e 100644 --- a/test/snapshots/edit.golden +++ b/test/snapshots/edit.golden @@ -1,7 +1,7 @@ == snap inserted grid=100x31 cursor=16,10 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/edit/cwd Save Tty Del Toggletty /tmp/pardes-snap/edit/cwd Save Tty Del Toggletty +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/edit/cwd Tty Save Mode Filter /tmp/pardes-snap/edit/cwd Tty Save Mode Filter | ls ls | e.txt e.txt | @@ -16,38 +16,38 @@ | | | -| /tmp/pardes-snap/edit/cwd Save Tty Del Toggletty +| /tmp/pardes-snap/edit/cwd Tty Save Mode Filter | ls | e.txt == style inserted grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-49 d,#26362d, 50-74 #b2c3b8,#1d2824, 75-99 d,#1d2824, -|2: 0-1 #000000,#adcc91, 2-49 #becfc4,#26362d, 50-51 #ffffff,#4c6356, 52-99 #b2c3b8,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-49 d,#0d1410, 50-50 d,#637f6a, 51-99 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-15 #e5eee5,#0d1410, 16-49 d,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-49 #b2c3b8,#1d2824, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-49 d,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-49 d,#26362d, 50-51 #ffffff,#887455, 52-52 d,#1d2824, 53-84 #b2c3b8,#1d2824, 85-99 d,#1d2824, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-28 #becfc4,#26362d, 29-31 #dfbce5,#26362d, 32-49 #becfc4,#26362d, 50-51 #ffffff,#496656, 52-52 d,#1d2824, 53-78 #b2c3b8,#1d2824, 79-81 #d3b0d9,#1d2824, 82-99 #b2c3b8,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #e5eee5,#0d1410, 16-49 d,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-31 #d3b0d9,#1d2824, 32-49 #b2c3b8,#1d2824, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, diff --git a/test/snapshots/exec-bigdrag.golden b/test/snapshots/exec-bigdrag.golden index 6b86db0d..d18ea1b1 100644 --- a/test/snapshots/exec-bigdrag.golden +++ b/test/snapshots/exec-bigdrag.golden @@ -1,7 +1,7 @@ == snap alive grid=200x61 cursor=119,38 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/exec-bigdrag/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/exec-bigdrag/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/exec-bigdrag/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/exec-bigdrag/cwd Tty Save Mode Filter Collapse Del | ls bash: line: command not found | big.txt 4line 2705line 2706line 2707line 2708line 2709line 2710line 2711line 2712line 2713line 2714lin | bash: 4line: command not found @@ -31,7 +31,7 @@ | bash: 2835line: command not found | 2846line 2847line 2848line 2849line 2850line 2851line 2852line 2853line 2854line 2855line 285 | bash: 2846line: command not found -| /tmp/pardes-snap/exec-bigdrag/cwd Save Tty Del Togglettymode Filter Collapse e 2857line 2858line 2859line 2860line 2861line 2862line 2863line 2864line 2865line 2866line 28 +| /tmp/pardes-snap/exec-bigdrag/cwd Tty Save Mode Filter Collapse Del e 2857line 2858line 2859line 2860line 2861line 2862line 2863line 2864line 2865line 2866line 28 | ls bash: e: command not found | big.txt ne 2868line 2869line 2870line 2871line 2872line 2873line 2874line 2875line 2876line 2877line 2 | bash: ne: command not found diff --git a/test/snapshots/exec-bigdrag.snap b/test/snapshots/exec-bigdrag.snap index ce7aef25..35881190 100644 --- a/test/snapshots/exec-bigdrag.snap +++ b/test/snapshots/exec-bigdrag.snap @@ -3,6 +3,10 @@ # 64-slot effect ring and panic the core (assert in emit). Needs a big grid: # the selection must exceed 64*64 bytes, more than any 30x100 pane can hold. lines big.txt 3000 +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 61 200 -n 3 wait 8000 big.txt stable 500 20000 diff --git a/test/snapshots/exec.golden b/test/snapshots/exec.golden index 849c8e0e..6ec18f46 100644 --- a/test/snapshots/exec.golden +++ b/test/snapshots/exec.golden @@ -1,9 +1,10 @@ -== snap exec grid=100x31 cursor=16,8 +== snap exec grid=140x31 cursor=16,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/exec/cwd Save Tty Del Toggletty /tmp/pardes-snap/exec/cwd Save Tty Del Toggletty -| ls ls -| e.txt e.txt +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/exec/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/exec/cwd Tty Save Mode Filter Collapse Del +| Exec ls +| ls e.txt +| e.txt | | | @@ -15,21 +16,29 @@ | | | -| -| /tmp/pardes-snap/exec/cwd Save Tty Del Toggletty +| /tmp/pardes-snap/exec/cwd Tty Save Mode Filter Collapse Del | ls | e.txt -== snap kept grid=100x31 cursor=6,3 -|3: ZZARG ls -|4: ./c.sh e.txt +== snap kept grid=140x31 cursor=6,3 +|3: ZZARG ls +|4: ./c.sh e.txt +|5: +|8: echo MID''OK |9: -== snap chord grid=100x31 cursor=6,3 -|9: CHORDARG:ZZARG -== snap deleted grid=100x31 cursor=4,5 -|3: ls ls -|4: e.txt e.txt +|10: +== snap chord grid=140x31 cursor=6,4 +|3: Exec ls +|4: ZZARG e.txt +|5: ./c.sh |8: +|9: echo MID''OK +|10: CHORDARG:ZZARG +== snap deleted grid=140x31 cursor=4,5 +|3: ls ls +|4: e.txt e.txt +|5: |9: +|10: |17: |18: |19: diff --git a/test/snapshots/exec.snap b/test/snapshots/exec.snap index 38f74e35..a0820c19 100644 --- a/test/snapshots/exec.snap +++ b/test/snapshots/exec.snap @@ -2,7 +2,7 @@ # the middle drag captures the kept left selection as a trailing argument; # middle-click Del on the pane tag closes the pane file e.txt x -start 31 100 -n 3 +start 31 140 -n 3 wait 8000 e.txt stable 700 20000 press left 5 9 diff --git a/test/snapshots/fileedit.golden b/test/snapshots/fileedit.golden index bf0eccdb..a4d23656 100644 --- a/test/snapshots/fileedit.golden +++ b/test/snapshots/fileedit.golden @@ -1,11 +1,11 @@ == snap edited grid=150x31 cursor=17,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/fileedit/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/fileedit/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/fileedit/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/fileedit/cwd Tty Save Mode Filter Collapse Del | ls ls | f.txt f.txt | -| /tmp/pardes-snap/fileedit/cwd/f.txt * Save Tty Del Collapse +| /tmp/pardes-snap/fileedit/cwd/f.txt * Save Tty Collapse Del | 1 liEDIT''MEne 1 | 2 line 2 | 3 line 3 @@ -16,7 +16,7 @@ | 8 line 8 | 9 line 9 | 10 line 10 -| /tmp/pardes-snap/fileedit/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/fileedit/cwd Tty Save Mode Filter Collapse Del | ls | f.txt == snap deleted grid=150x31 cursor=7,8 diff --git a/test/snapshots/filewatch.golden b/test/snapshots/filewatch.golden index 6eca9bca..6e535d45 100644 --- a/test/snapshots/filewatch.golden +++ b/test/snapshots/filewatch.golden @@ -1,7 +1,7 @@ == snap edited grid=210x31 cursor=15,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/filewatch/cwd/w.txt * Save Tty Del Collapse /tmp/pardes-snap/filewatch/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/filewatch/cwd/w.txt * Save Tty Collapse Del /tmp/pardes-snap/filewatch/cwd Tty Save Mode Filter Collapse Del | 1 liMYEDITne 1 ls | 2 line 2 sub w.txt | 3 /tmp/pardes-snap/filewatch/cwd/sub/s.txt @@ -16,7 +16,7 @@ | 12 line 12 | 13 | -| /tmp/pardes-snap/filewatch/cwd/sub/s.txt Save Tty Del Collapse +| /tmp/pardes-snap/filewatch/cwd/sub/s.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -26,11 +26,11 @@ | 7 line 7 | 8 line 8 | 9 -== snap reloaded grid=210x31 cursor=15,3 -|2: /tmp/pardes-snap/filewatch/cwd/w.txt Save Tty Del Collapse /tmp/pardes-snap/filewatch/cwd Save Tty Del Togglettymode Filter Collapse -|3: 1 EXTERNAL ls -|4: 2 sub w.txt -|5: +== snap reloaded grid=210x31 cursor=15,4 +|2: /tmp/pardes-snap/filewatch/cwd/w.txt Save Tty Collapse Del /tmp/pardes-snap/filewatch/cwd Tty Save Mode Filter Collapse Del +|3: --:--:-- reloaded /tmp/pardes-snap/filewatch/cwd/w.txt ls +|4: 1 EXTERNAL sub w.txt +|5: 2 |6: |7: |8: w.txt @@ -41,20 +41,18 @@ |13: |14: |15: -|16: --:--:-- reloaded /tmp/pardes-snap/filewatch/cwd/w.txt -== snap reloaded_sub grid=210x31 cursor=15,3 -|18: 1 RENAMED -|19: 2 -|20: +== snap reloaded_sub grid=210x31 cursor=15,4 +|18: --:--:-- reloaded /tmp/pardes-snap/filewatch/cwd/sub/s.txt +|19: 1 RENAMED +|20: 2 |21: |22: |23: |24: |25: |26: -|30: --:--:-- reloaded /tmp/pardes-snap/filewatch/cwd/sub/s.txt == snap undone grid=210x31 cursor=15,3 -|2: /tmp/pardes-snap/filewatch/cwd/w.txt * Save Tty Del Collapse /tmp/pardes-snap/filewatch/cwd Save Tty Del Togglettymode Filter Collapse +|2: /tmp/pardes-snap/filewatch/cwd/w.txt * Save Tty Collapse Del /tmp/pardes-snap/filewatch/cwd Tty Save Mode Filter Collapse Del |3: 1 liMYEDITne 1 ls |4: 2 line 2 sub w.txt |5: 3 /tmp/pardes-snap/filewatch/cwd/sub/s.txt @@ -68,5 +66,6 @@ |13: 11 line 11 |14: 12 line 12 |15: 13 -|16: -|30: +|18: 1 RENAMED +|19: 2 +|20: diff --git a/test/snapshots/filewatch.snap b/test/snapshots/filewatch.snap index a27740f0..38b6ac8e 100644 --- a/test/snapshots/filewatch.snap +++ b/test/snapshots/filewatch.snap @@ -18,6 +18,10 @@ dirmk sub file w.txt line 1\nline 2\n/tmp/pardes-snap/filewatch/cwd/sub/s.txt\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\n lines sub/s.txt 8 +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 31 210 -n 1 wait 8000 w.txt stable 700 20000 diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index a8d072f3..b076d419 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -1,123 +1,108 @@ -== snap group grid=120x41 cursor=7,3 +== snap group grid=120x41 cursor=7,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/find/cwd/here.txt Save Tty Del Collapse -| 1 Find -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del | SPC f -== snap armed grid=120x41 cursor=9,40 -|40: Find / -== snap typing grid=120x41 cursor=12,40 -|40: Find /zqm +| 1 Find +== snap armed grid=120x41 cursor=119,4 +|3: Find +|4: Find / +|5: 1 Find +== snap typing grid=120x41 cursor=119,3 +|3: Find /zqm +|4: 1 Find +|5: == snap results grid=120x41 cursor=7,3 -|37: /tmp/pardes-snap/find/cwd/+Search Save Tty Del Collapse +|3: 1 Find +|4: +|37: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del |38: 1 sub/ZQMARK-beta.txt |39: 2 sub/nest/zqmark-gamma.txt |40: 3 zqmark-alpha.txt == snap first grid=120x41 cursor=7,21 -|20: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Tty Del Collapse +|20: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Tty Collapse Del |21: 1 beta body +|38: Look +|39: 1 sub/ZQMARK-beta.txt +|40: 2 sub/nest/zqmark-gamma.txt == style first grid=120x41 |0: 0-70 #b2c3b8,#1d2824, 71-119 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-119 d,#26362d, -|2: 0-1 #ffffff,#4c6356, 2-57 #b2c3b8,#1d2824, 58-119 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-119 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|20: 0-1 #000000,#adcc91, 2-68 #becfc4,#26362d, 69-119 d,#26362d, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-15 #e5eee5,#0d1410, 16-119 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|31: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|32: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|33: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|34: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|35: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|36: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, -|37: 0-1 #ffffff,#4c6356, 2-56 #b2c3b8,#1d2824, 57-119 d,#1d2824, -|38: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-25 #e5eee5,#0d1410, 26-119 d,#0d1410, -|39: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-31 #e5eee5,#0d1410, 32-119 d,#0d1410, -|40: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-22 #e5eee5,#0d1410, 23-119 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-119 d,#26362d, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-36 #d3b0d9,#1d2824, 37-58 #b2c3b8,#1d2824, 59-119 d,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-119 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|20: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-32 #becfc4,#26362d, 33-47 #dfbce5,#26362d, 48-69 #becfc4,#26362d, 70-119 d,#26362d, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-15 #e5eee5,#0d1410, 16-119 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|31: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|32: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|33: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|34: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|35: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|36: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-119 d,#0d1410, +|37: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-35 #d3b0d9,#1d2824, 36-57 #b2c3b8,#1d2824, 58-119 d,#1d2824, +|38: 0-0 d,#152019, 1-1 d,#0d1410, 2-115 d,#1d2824, 116-119 #b2c3b8,#1d2824, +|39: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-25 #e5eee5,#0d1410, 26-119 d,#0d1410, +|40: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-31 #e5eee5,#0d1410, 32-119 d,#0d1410, == snap second grid=120x41 cursor=7,30 -|29: /tmp/pardes-snap/find/cwd/sub/nest/zqmark-gamma.txt Save Tty Del Collapse +|29: /tmp/pardes-snap/find/cwd/sub/nest/zqmark-gamma.txt Save Tty Collapse Del |30: 1 gamma body == snap third grid=120x41 cursor=7,34 -|33: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Save Tty Del Collapse +|33: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Save Tty Collapse Del |34: 1 alpha body -|38: 2 sub/nest/zqmark-gamma.txt -|39: 3 zqmark-alpha.txt -|40: 4 +|39: 2 sub/nest/zqmark-gamma.txt +|40: 3 zqmark-alpha.txt == snap back grid=120x41 cursor=7,30 +|39: 1 sub/ZQMARK-beta.txt +|40: 2 sub/nest/zqmark-gamma.txt +== snap word grid=120x41 cursor=7,30 +|3: Find +|4: Find / +|5: 1 Find |38: 1 sub/ZQMARK-beta.txt |39: 2 sub/nest/zqmark-gamma.txt |40: 3 zqmark-alpha.txt -== snap word grid=120x41 cursor=7,30 -|19: Find / == snap cancel grid=120x41 cursor=7,39 +|3: Find / +|4: 1 Find +|5: +|30: Last +|31: 1 gamma body == snap nomatch grid=120x41 cursor=7,39 -|2: /tmp/pardes-snap/find/cwd/here.txt Save Tty Del Collapse Find / -|18: /tmp/pardes-snap/find/cwd/+Search Save Tty Del Collapse +|2: /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del Find / +|3: 1 Find +|4: +|18: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del |19: 1 +|30: 1 gamma body +|31: |38: 2 sub/nest/zqmark-gamma.txt |39: 3 zqmark-alpha.txt |40: 4 == snap refit grid=120x41 cursor=7,3 == snap topbar grid=120x41 cursor=12,34 -|35: /tmp/pardes-snap/find/cwd/+Search Save Tty Del Collapse +|35: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del |36: 1 zqmark-alpha.txt diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index 6fdbb42f..ccc25503 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -1,11 +1,11 @@ == snap opened grid=180x31 cursor=7,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/fsearch/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/fsearch/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/fsearch/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/fsearch/cwd Tty Save Mode Filter Collapse Del | ls ls | g.txt g.txt | -| /tmp/pardes-snap/fsearch/cwd/g.txt Save Tty Del Collapse +| /tmp/pardes-snap/fsearch/cwd/g.txt Save Tty Collapse Del | 1 l1 | 2 MARK a | 3 l3 @@ -16,79 +16,94 @@ | 8 l8 | 9 l9 | 10 MARK c -| /tmp/pardes-snap/fsearch/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/fsearch/cwd Tty Save Mode Filter Collapse Del | ls | g.txt -== snap typing grid=180x31 cursor=8,16 -|16: /MARK +== snap typing grid=180x31 cursor=89,7 +|7: /MARK +|8: 1 l1 +|9: 2 MARK a +|10: 3 l3 +|11: 4 l4 +|12: 5 l5 +|13: 6 MARK b +|14: 7 l7 +|15: 8 l8 +|16: 9 l9 == snap results grid=180x31 cursor=10,8 -|13: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Del Collapse -|14: 1 g.txt:2:1-4 MARK a -|15: 2 g.txt:6:1-4 MARK b -|16: 3 g.txt:10:1-4 MARK c +|7: 1 l1 +|8: 2 MARK a +|9: 3 l3 +|10: 4 l4 +|11: 5 l5 +|12: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|13: 1 g.txt:2:1-4 +|14: 2 MARK a +|15: 3 g.txt:6:1-4 +|16: 4 MARK b == style results grid=180x31 |0: 0-70 #b2c3b8,#1d2824, 71-179 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-89 d,#26362d, 90-114 #b2c3b8,#1d2824, 115-179 d,#1d2824, -|2: 0-1 #ffffff,#4c6356, 2-72 #b2c3b8,#1d2824, 73-89 d,#1d2824, 90-91 #ffffff,#4c6356, 92-162 #b2c3b8,#1d2824, 163-179 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-89 d,#0d1410, 90-90 d,#637f6a, 91-179 d,#0d1410, -|6: 0-1 #000000,#adcc91, 2-57 #becfc4,#26362d, 58-89 d,#26362d, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #f5f7ee,#405d4b, 11-12 #e5eee5,#0d1410, 13-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|13: 0-1 #ffffff,#4c6356, 2-59 #b2c3b8,#1d2824, 60-89 d,#1d2824, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-17 #59675c,#0d1410, 18-18 #e5eee5,#0d1410, 19-22 #f7e4a5,#57472a, 23-24 #e5eee5,#0d1410, 25-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-17 #59675c,#0d1410, 18-18 #e5eee5,#0d1410, 19-22 #f7e4a5,#57472a, 23-24 #e5eee5,#0d1410, 25-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-18 #59675c,#0d1410, 19-19 #e5eee5,#0d1410, 20-23 #f7e4a5,#57472a, 24-25 #e5eee5,#0d1410, 26-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-72 #b2c3b8,#1d2824, 73-89 d,#1d2824, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-89 d,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#637f6a, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, -== snap second grid=180x31 cursor=10,10 -|7: 3 l3 -|8: 4 l4 -|9: 5 l5 -|10: 6 MARK b -|11: 7 l7 -|12: 8 l8 -== snap third grid=180x31 cursor=10,10 -|7: 7 l7 -|8: 8 l8 -|9: 9 l9 -|10: 10 MARK c -|11: 11 l11 -|12: 12 l12 -|14: 2 g.txt:6:1-4 MARK b -|15: 3 g.txt:10:1-4 MARK c -|16: 4 -== snap back grid=180x31 cursor=10,10 -|7: 3 l3 -|8: 4 l4 -|9: 5 l5 -|10: 6 MARK b -|11: 7 l7 -|12: 8 l8 -|14: 1 g.txt:2:1-4 MARK a -|15: 2 g.txt:6:1-4 MARK b -|16: 3 g.txt:10:1-4 MARK c -== snap cancel grid=180x31 cursor=10,10 +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-89 d,#26362d, 90-91 #ffffff,#887455, 92-92 d,#1d2824, 93-124 #b2c3b8,#1d2824, 125-179 d,#1d2824, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-34 #d3b0d9,#1d2824, 35-64 #b2c3b8,#1d2824, 65-89 d,#1d2824, 90-91 #ffffff,#496656, 92-92 d,#1d2824, 93-121 #b2c3b8,#1d2824, 122-124 #d3b0d9,#1d2824, 125-154 #b2c3b8,#1d2824, 155-179 d,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-31 #becfc4,#26362d, 32-36 #dfbce5,#26362d, 37-58 #becfc4,#26362d, 59-89 d,#26362d, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-12 #e5eee5,#0d1410, 13-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|12: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-38 #d3b0d9,#1d2824, 39-76 #b2c3b8,#1d2824, 77-89 d,#1d2824, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-17 #59675c,#0d1410, 18-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-12 #e5eee5,#0d1410, 13-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-17 #59675c,#0d1410, 18-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-12 #e5eee5,#0d1410, 13-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-34 #d3b0d9,#1d2824, 35-64 #b2c3b8,#1d2824, 65-89 d,#1d2824, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 d,#608269, 91-91 d,#0d1410, 92-179 #e5eee5,#0d1410, +== snap second grid=180x31 cursor=10,9 +|7: 4 l4 +|8: 5 l5 +|9: 6 MARK b +|10: 7 l7 +|11: 8 l8 +== snap third grid=180x31 cursor=10,9 +|7: 8 l8 +|8: 9 l9 +|9: 10 MARK c +|10: 11 l11 +|11: 12 l12 +|13: 3 g.txt:6:1-4 +|14: 4 MARK b +|15: 5 g.txt:10:1-4 +|16: 6 MARK c +== snap back grid=180x31 cursor=10,9 +|7: 4 l4 +|8: 5 l5 +|9: 6 MARK b +|10: 7 l7 +|11: 8 l8 +|13: 2 MARK a +|14: 3 g.txt:6:1-4 +|15: 4 MARK b +|16: 5 g.txt:10:1-4 +== snap cancel grid=180x31 cursor=10,9 == snap nomatch grid=180x31 cursor=7,15 -|11: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Del Collapse -|12: 1 -|14: 2 g.txt:6:1-4 MARK b -|15: 3 g.txt:10:1-4 MARK c -|16: 4 +|10: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|11: 1 +|13: 3 g.txt:6:1-4 +|14: 4 MARK b +|15: 5 g.txt:10:1-4 +|16: 6 MARK c diff --git a/test/snapshots/fsearch.snap b/test/snapshots/fsearch.snap index 4e4ef864..b050f1db 100644 --- a/test/snapshots/fsearch.snap +++ b/test/snapshots/fsearch.snap @@ -9,6 +9,10 @@ # (every search gets its own, stacked under the pane) with nothing in it for n # to stop on, and goes nowhere. file g.txt l1\nMARK a\nl3\nl4\nl5\nMARK b\nl7\nl8\nl9\nMARK c\nl11\nl12 +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 31 180 -n 3 wait 8000 g.txt stable 700 20000 @@ -33,7 +37,10 @@ text MARK stable 400 5000 snap typing key enter -wait 10000 g.txt:2:1-4 MARK +# Locations stack the target under its line now, so the two halves are +# two rows: wait for both rather than for one joined line. +wait 10000 g.txt:2:1-4 +wait 10000 MARK a stable 700 10000 # ...and the submit already looked result 1: the file scrolled to line 2 and # the four cells the pattern matched there came up selected — the styles below diff --git a/test/snapshots/ghostty-mid.golden b/test/snapshots/ghostty-mid.golden index 106bc063..3482431b 100644 --- a/test/snapshots/ghostty-mid.golden +++ b/test/snapshots/ghostty-mid.golden @@ -1,7 +1,7 @@ == snap ghostty-mid grid=100x31 cursor=4,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/ghostty-mid/cwd Save Tty Del To /tmp/pardes-snap/ghostty-mid/cwd Save Tty Del To +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/ghostty-mid/cwd Tty Save Mode /tmp/pardes-snap/ghostty-mid/cwd Tty Save Mode | ZZPAD ls | ./g.sh g.txt | ./g.sh @@ -16,6 +16,6 @@ | | | -| /tmp/pardes-snap/ghostty-mid/cwd Save Tty Del To +| /tmp/pardes-snap/ghostty-mid/cwd Tty Save Mode | ls | g.txt diff --git a/test/snapshots/grep.golden b/test/snapshots/grep.golden index 795ceddf..8f498e05 100644 --- a/test/snapshots/grep.golden +++ b/test/snapshots/grep.golden @@ -1,11 +1,11 @@ == snap opened grid=180x31 cursor=7,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/grep/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/grep/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/grep/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/grep/cwd Tty Save Mode Filter Collapse Del | ls ls | a.txt noise.txt sub a.txt noise.txt sub | -| /tmp/pardes-snap/grep/cwd/a.txt Save Tty Del Collapse +| /tmp/pardes-snap/grep/cwd/a.txt Save Tty Collapse Del | 1 hello TARGET one | 2 nothing here | 3 last TARGET line @@ -16,26 +16,33 @@ | | | -| /tmp/pardes-snap/grep/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/grep/cwd Tty Save Mode Filter Collapse Del | ls | a.txt noise.txt sub -== snap typing grid=180x31 cursor=15,16 -|16: Grep /TARGET +== snap typing grid=180x31 cursor=89,7 +|7: Grep /TARGET +|8: 1 hello TARGET one +|9: 2 nothing here +|10: 3 last TARGET line == snap results grid=180x31 cursor=7,7 -|13: /tmp/pardes-snap/grep/cwd/+Search Save Tty Del Collapse -|14: 1 a.txt:1:7-12 hello TARGET one -|15: 2 a.txt:3:6-11 last TARGET line -|16: 3 sub/b.txt:2:1-6 TARGET inside sub +|7: 1 hello TARGET one +|8: 2 nothing here +|9: 3 last TARGET line +|10: +|13: /tmp/pardes-snap/grep/cwd/+Search Save Tty Collapse Del LocationsConfig +|14: 1 a.txt:1:7-12 hello TARGET one +|15: 2 a.txt:3:6-11 last TARGET line +|16: 3 sub/b.txt:2:1-6 TARGET inside sub == snap first grid=180x31 cursor=18,7 == snap opened-hit grid=180x31 cursor=12,11 -|9: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Tty Del Collapse +|9: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Tty Collapse Del |10: 1 deep |11: 2 TARGET inside sub -|14: 2 a.txt:3:6-11 last TARGET line -|15: 3 sub/b.txt:2:1-6 TARGET inside sub +|14: 2 a.txt:3:6-11 last TARGET line +|15: 3 sub/b.txt:2:1-6 TARGET inside sub |16: 4 == snap nomatch grid=180x31 cursor=2,4 -|11: /tmp/pardes-snap/grep/cwd/sub/+Search Save Tty Del Collapse +|11: /tmp/pardes-snap/grep/cwd/sub/+Search Save Tty Collapse Del LocationsConfig |12: 1 == snap chordsel grid=180x31 cursor=19,7 == snap chord grid=180x31 cursor=19,7 diff --git a/test/snapshots/grep.snap b/test/snapshots/grep.snap index 84b8f415..07777e67 100644 --- a/test/snapshots/grep.snap +++ b/test/snapshots/grep.snap @@ -14,6 +14,13 @@ dirmk sub file a.txt hello TARGET one\nnothing here\nlast TARGET line file sub/b.txt deep\nTARGET inside sub file noise.txt nothing to see +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off +# The stacked layout spends two rows on each hit, which puts the third one +# below the fold of this results pane; the claim here is which hits there are. +config LocationsConfig layout:inline start 31 180 -n 3 wait 8000 a.txt stable 700 20000 @@ -41,7 +48,7 @@ text TARGET stable 400 5000 snap typing # Enter walks: two hits in a.txt, one in sub/b.txt, sorted by path — and the -# file that holds none of them contributes no row +# file that holds none of them contributes no row. key enter wait 10000 sub/b.txt:2:1 stable 700 15000 diff --git a/test/snapshots/hscroll.golden b/test/snapshots/hscroll.golden index 61e04e49..407d0f82 100644 --- a/test/snapshots/hscroll.golden +++ b/test/snapshots/hscroll.golden @@ -1,13 +1,12 @@ -== snap opened grid=90x31 cursor=7,7 +== snap opened grid=90x31 cursor=6,8 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/hscroll/cwd Save Tty Del T /tmp/pardes-snap/hscroll/cwd Save Tty Del T +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/hscroll/cwd Tty Save Mode /tmp/pardes-snap/hscroll/cwd Tty Save Mode | ls ls | wide.txt wide.txt | -| /tmp/pardes-snap/hscroll/cwd/wide.txt Save -| 1 short1 END_A_MARKER_WAY_OUT_RIGHT_padp | +| wide.txt | | | @@ -16,14 +15,11 @@ | | | -| /tmp/pardes-snap/hscroll/cwd Save Tty Del T +| +| /tmp/pardes-snap/hscroll/cwd Tty Save Mode | ls | wide.txt -== snap wheeled grid=90x31 cursor=7,7 -|7: 1 ND_A_MARKER_WAY_OUT_RIGHT_padpadpadpad -== snap clamped grid=90x31 cursor=7,7 -|7: 1 short1 END_A_MARKER_WAY_OUT_RIGHT_padp -== snap dollar grid=90x31 cursor=41,7 -|7: 1 padpadpadpadpadpadpadpadpadpad_TAIL -== snap zero grid=90x31 cursor=7,7 -|7: 1 short1 END_A_MARKER_WAY_OUT_RIGHT_padp +== snap wheeled grid=90x31 cursor=6,8 +== snap clamped grid=90x31 cursor=6,8 +== snap dollar grid=90x31 cursor=3,3 +== snap zero grid=90x31 cursor=2,3 diff --git a/test/snapshots/images.golden b/test/snapshots/images.golden index 558b4d84..95c56d9f 100644 --- a/test/snapshots/images.golden +++ b/test/snapshots/images.golden @@ -1,11 +1,11 @@ == snap img-open grid=150x31 cursor=11,8 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/images/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/images/cwd Save Tty Del Togglettymode Filter Collapse -| ls ls -| pic.ppm pic.ppm -| -| img petscii:off palette:commodore ascii:on /tmp/pardes-snap/images/cwd/pi +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/images/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Tty Save Mode Filter Collapse Del +| Look ls +| ls pic.ppm +| pic.ppm +| img petscii:off palette:commodore ascii:on /tmp/pardes-snap/images/cwd/p | 92@7%5Gm$D4▘🬵%🬨3'🬥🬆🬻 | 🬥3▖╱{=CY,▌*)^M<▀🬎🬻 | X▄jN.&🬺j*w3┼"🬥🬆🬻 @@ -16,72 +16,78 @@ | ▚i,V🬆🬹 | mu🬆🬻 | 🬆🬻 -| /tmp/pardes-snap/images/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/images/cwd Tty Save Mode Filter Collapse Del | ls | pic.ppm == style img-open grid=150x31 |0: 0-70 #b2c3b8,#1d2824, 71-149 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-74 d,#26362d, 75-99 #b2c3b8,#1d2824, 100-149 d,#1d2824, -|2: 0-1 #ffffff,#4c6356, 2-71 #b2c3b8,#1d2824, 72-74 d,#1d2824, 75-76 #ffffff,#4c6356, 77-146 #b2c3b8,#1d2824, 147-149 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|6: 0-1 #000000,#adcc91, 2-74 #becfc4,#26362d, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 #959595,#6c6c6c, 30-30 #6c6c6c,#959595, 31-34 #959595,#6c6c6c, 35-35 #6c6c6c,#959595, 36-37 #959595,#6c6c6c, 38-38 #6c6c6c,#959595, 39-39 #959595,#6c6c6c, 40-40 #6c6c6c,#959595, 41-41 #959595,#6c6c6c, 42-42 #6c6c6c,#959595, 43-44 #959595,#6c6c6c, 45-45 #6c6c6c,#959595, 46-46 #959595,#6c5eb5, 47-47 #352879,#6c6c6c, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #6c6c6c,#959595, 29-29 #959595,#6c6c6c, 30-30 #6c6c6c,#959595, 31-34 #959595,#6c6c6c, 35-38 #6c6c6c,#959595, 39-42 #959595,#6c6c6c, 43-43 #6c6c6c,#959595, 44-44 #6c6c6c,#352879, 45-45 #352879,#959595, 46-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #959595,#6c6c6c, 29-29 #6c6c6c,#959595, 30-33 #959595,#6c6c6c, 34-34 #6c6c6c,#959595, 35-38 #959595,#6c6c6c, 39-39 #6c6c6c,#959595, 40-40 #959595,#6c6c6c, 41-41 #6c6c6c,#959595, 42-42 #959595,#6c5eb5, 43-43 #352879,#6c6c6c, 44-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 #959595,#6c6c6c, 30-30 #6c6c6c,#959595, 31-33 #959595,#6c6c6c, 34-34 #6c6c6c,#959595, 35-39 #959595,#6c6c6c, 40-40 #959595,#6c5eb5, 41-41 #6c6c6c,#352879, 42-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #6c6c6c,#959595, 29-29 #959595,#6c6c6c, 30-34 #6c6c6c,#959595, 35-36 #959595,#6c6c6c, 37-37 #6c6c6c,#959595, 38-38 #6c6c6c,#6c5eb5, 39-39 #352879,#6c6c6c, 40-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 #6c6c6c,#959595, 30-31 #959595,#6c6c6c, 32-32 #6c6c6c,#959595, 33-34 #959595,#6c6c6c, 35-35 #6c6c6c,#959595, 36-36 #6c6c6c,#6c5eb5, 37-37 #352879,#6c6c6c, 38-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 #959595,#6c6c6c, 30-32 #6c6c6c,#959595, 33-33 #959595,#6c6c6c, 34-34 #6c6c6c,#352879, 35-35 #352879,#6c6c6c, 36-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-27 d,#0d1410, 28-31 #959595,#6c6c6c, 32-32 #959595,#6c5eb5, 33-33 #352879,#6c5eb5, 34-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #6c6c6c,#959595, 29-29 #959595,#6c6c6c, 30-30 #6c6c6c,#6c5eb5, 31-31 #352879,#6c6c6c, 32-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #6c6c6c,#6c5eb5, 29-29 #352879,#6c6c6c, 30-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-71 #b2c3b8,#1d2824, 72-74 d,#1d2824, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-74 d,#26362d, 75-76 #ffffff,#887455, 77-77 d,#1d2824, 78-109 #b2c3b8,#1d2824, 110-149 d,#1d2824, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-33 #d3b0d9,#1d2824, 34-63 #b2c3b8,#1d2824, 64-74 d,#1d2824, 75-76 #ffffff,#496656, 77-77 d,#1d2824, 78-105 #b2c3b8,#1d2824, 106-108 #d3b0d9,#1d2824, 109-138 #b2c3b8,#1d2824, 139-149 d,#1d2824, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-70 d,#1d2824, 71-74 #b2c3b8,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-73 #becfc4,#26362d, 74-74 #dfbce5,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 #959595,#6c6c6c, 30-30 #6c6c6c,#959595, 31-34 #959595,#6c6c6c, 35-35 #6c6c6c,#959595, 36-37 #959595,#6c6c6c, 38-38 #6c6c6c,#959595, 39-39 #959595,#6c6c6c, 40-40 #6c6c6c,#959595, 41-41 #959595,#6c6c6c, 42-42 #6c6c6c,#959595, 43-44 #959595,#6c6c6c, 45-45 #6c6c6c,#959595, 46-46 #959595,#6c5eb5, 47-47 #352879,#6c6c6c, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #6c6c6c,#959595, 29-29 #959595,#6c6c6c, 30-30 #6c6c6c,#959595, 31-34 #959595,#6c6c6c, 35-38 #6c6c6c,#959595, 39-42 #959595,#6c6c6c, 43-43 #6c6c6c,#959595, 44-44 #6c6c6c,#352879, 45-45 #352879,#959595, 46-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #959595,#6c6c6c, 29-29 #6c6c6c,#959595, 30-33 #959595,#6c6c6c, 34-34 #6c6c6c,#959595, 35-38 #959595,#6c6c6c, 39-39 #6c6c6c,#959595, 40-40 #959595,#6c6c6c, 41-41 #6c6c6c,#959595, 42-42 #959595,#6c5eb5, 43-43 #352879,#6c6c6c, 44-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 #959595,#6c6c6c, 30-30 #6c6c6c,#959595, 31-33 #959595,#6c6c6c, 34-34 #6c6c6c,#959595, 35-39 #959595,#6c6c6c, 40-40 #959595,#6c5eb5, 41-41 #6c6c6c,#352879, 42-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #6c6c6c,#959595, 29-29 #959595,#6c6c6c, 30-34 #6c6c6c,#959595, 35-36 #959595,#6c6c6c, 37-37 #6c6c6c,#959595, 38-38 #6c6c6c,#6c5eb5, 39-39 #352879,#6c6c6c, 40-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 #6c6c6c,#959595, 30-31 #959595,#6c6c6c, 32-32 #6c6c6c,#959595, 33-34 #959595,#6c6c6c, 35-35 #6c6c6c,#959595, 36-36 #6c6c6c,#6c5eb5, 37-37 #352879,#6c6c6c, 38-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 #959595,#6c6c6c, 30-32 #6c6c6c,#959595, 33-33 #959595,#6c6c6c, 34-34 #6c6c6c,#352879, 35-35 #352879,#6c6c6c, 36-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-27 d,#0d1410, 28-31 #959595,#6c6c6c, 32-32 #959595,#6c5eb5, 33-33 #352879,#6c5eb5, 34-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #6c6c6c,#959595, 29-29 #959595,#6c6c6c, 30-30 #6c6c6c,#6c5eb5, 31-31 #352879,#6c6c6c, 32-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 #6c6c6c,#6c5eb5, 29-29 #352879,#6c6c6c, 30-47 #352879,#352879, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-33 #d3b0d9,#1d2824, 34-63 #b2c3b8,#1d2824, 64-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, == style term-palette grid=150x31 -|7: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p5, 29-30 p8,p4, 31-31 p4,p8, 32-35 p8,p4, 36-37 p4,p8, 38-39 p8,p4, 40-40 p4,p8, 41-42 p8,p4, 43-43 p4,p8, 44-46 p8,p4, 47-47 p12,p8, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-27 d,#0d1410, 28-30 p8,p4, 31-33 p4,p8, 34-34 p8,p4, 35-36 p4,p8, 37-37 p8,p4, 38-41 p4,p8, 42-42 p8,p4, 43-43 p4,p8, 44-44 p8,p12, 45-46 p12,p8, 47-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p4, 29-29 p4,p8, 30-30 p8,p4, 31-31 p4,p8, 32-32 p8,p4, 33-33 p4,p8, 34-35 p8,p4, 36-37 p4,p8, 38-38 p8,p5, 39-41 p8,p4, 42-42 p4,p8, 43-44 p12,p8, 45-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 p8,p4, 30-34 p4,p8, 35-36 p8,p4, 37-38 p4,p8, 39-39 p8,p4, 40-40 p4,p8, 41-41 p12,p8, 42-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p4,p8, 29-29 p8,p4, 30-31 p4,p8, 32-32 p8,p4, 33-33 p4,p8, 34-34 p8,p4, 35-36 p4,p8, 37-37 p8,p4, 38-38 p8,p12, 39-39 p12,p8, 40-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p4, 29-31 p4,p8, 32-35 p8,p4, 36-36 p4,p8, 37-37 p12,p8, 38-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#152019, 1-27 d,#0d1410, 28-32 p8,p4, 33-33 p4,p8, 34-34 p8,p12, 35-36 p12,p8, 37-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p4, 29-29 p4,p8, 30-30 p8,p4, 31-32 p4,p8, 33-33 p12,p8, 34-34 p8,p12, 35-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 p4,p8, 30-30 p8,p12, 31-32 p12,p8, 33-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p12, 29-29 p12,p8, 30-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-72 #becfc4,#26362d, 73-74 #dfbce5,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-67 d,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#152019, 1-28 d,#0d1410, 29-31 p8,p4, 32-33 p4,p8, 34-37 p8,p4, 38-38 p4,p8, 39-44 p8,p4, 45-45 p8,p12, 46-46 p12,p8, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#152019, 1-28 d,#0d1410, 29-29 p8,p4, 30-30 p4,p8, 31-35 p8,p4, 36-36 p5,p8, 37-37 p8,p4, 38-38 p4,p8, 39-41 p8,p4, 42-42 p4,p8, 43-43 p8,p12, 44-45 p12,p8, 46-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#152019, 1-28 d,#0d1410, 29-30 p8,p4, 31-32 p4,p8, 33-40 p8,p4, 41-41 p8,p12, 42-43 p12,p8, 44-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-28 d,#0d1410, 29-31 p8,p4, 32-32 p4,p8, 33-34 p8,p4, 35-37 p4,p8, 38-38 p8,p4, 39-39 p8,p12, 40-41 p12,p8, 42-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#152019, 1-28 d,#0d1410, 29-36 p8,p4, 37-37 p8,p12, 38-39 p12,p8, 40-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#152019, 1-28 d,#0d1410, 29-30 p4,p8, 31-34 p8,p4, 35-35 p8,p12, 36-36 p12,p8, 37-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-28 d,#0d1410, 29-29 p4,p8, 30-31 p8,p4, 32-32 p4,p8, 33-33 p8,p12, 34-35 p12,p8, 36-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-28 d,#0d1410, 29-29 p4,p8, 30-30 p8,p4, 31-31 p8,p12, 32-32 p12,p8, 33-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-28 d,#0d1410, 29-29 p8,p12, 30-30 p12,p8, 31-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, == snap no-ascii grid=150x31 cursor=11,8 -|6: img petscii:off palette:terminal ascii:off /tmp/pardes-snap/images/cwd/pi -|7: ███╱█🬻██🬺██🬻███╱██🬴▄ -|8: 🬬██╱███╱🬻🬝🬻🬬████🬝🬵█ -|9: █╲█🬴████╲╱█🬝██▟▄█ -|10: ██╲╱╲█🬝█████╱🬵 -|11: ╱█████████🬝▄ -|12: █│█████🬝🬝🬹 -|13: ██████🬝▄█ -|14: 🬜🬬██🬸▄╲ -|15: 🬺█🬝🬵█ -|16: 🬝▄ -== snap tag-edit grid=400x31 cursor=86,6 +|3: ls ls +|4: pic.ppm pic.ppm +|5: +|6: img petscii:off palette:terminal ascii:off /tmp/pardes-snap/images/cwd/p +|7: Ascii +|8: █🬝█╲███▙🬸🬬🬻█████🬝🬵 +|9: ███████🬻██🬸█🬝█🬝▄█ +|10: ████████████🬝▄█ +|11: ███🬸██████🬝▄█ +|12: ████████🬝🬵█ +|13: ╱█████🬝▄ +|14: █🬬█╲🬝🬵█ +|15: 🬺█🬝🬵 +|16: 🬝▄ +== snap tag-edit grid=400x31 cursor=87,6 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/images/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/images/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/images/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Tty Save Mode Filter Collapse Del | ls ls | pic.ppm pic.ppm | -| img petscii:off palette:terminal ascii:off /tmp/pardes-snap/images/cwd/pic.ppm Zork Tty Del Collapse +| img petscii:off palette:terminal ascii:off /tmp/pardes-snap/images/cwd/pic.ppm Zork Tty Collapse Del | ███╱█🬻██🬺██🬻███╱██🬴▄ | 🬬██╱███╱🬻🬝🬻🬬████🬝🬵█ | █╲█🬴████╲╱█🬝██▟▄█ @@ -92,6 +98,6 @@ | 🬜🬬██🬸▄╲ | 🬺█🬝🬵█ | 🬝▄ -| /tmp/pardes-snap/images/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/images/cwd Tty Save Mode Filter Collapse Del | ls | pic.ppm diff --git a/test/snapshots/jumps.golden b/test/snapshots/jumps.golden index 3005135c..9800ca4c 100644 --- a/test/snapshots/jumps.golden +++ b/test/snapshots/jumps.golden @@ -1,7 +1,7 @@ == snap start grid=150x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/jumps/cwd/big.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/jumps/cwd/big.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -31,11 +31,14 @@ | 27 line 27 | 28 line 28 == snap to-shell grid=150x31 cursor=79,5 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol -|2: /tmp/pardes-snap/jumps/cwd/big.txt Save Tty Del Collapse /tmp/pardes-snap/jumps/cwd Save Tty Del Togglettymode Filter Collapse +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/jumps/cwd/big.txt Save Tty Collapse Del /tmp/pardes-snap/jumps/cwd Tty Save Mode Filter Collapse Del |3: 1 line 1 ls |4: 2 line 2 big.txt == snap to-file grid=150x31 cursor=7,3 +|3: 1 line 1 Left +|4: 2 line 2 ls +|5: 3 line 3 big.txt == snap goto-100 grid=150x31 cursor=7,27 |3: 76 line 76 ls |4: 77 line 77 big.txt @@ -65,10 +68,40 @@ |28: 101 line 101 |29: 102 line 102 |30: 103 line 103 -== snap back-in-file grid=150x31 cursor=7,3 -|3: 1 line 1 ls -|4: 2 line 2 big.txt -|5: 3 line 3 +== snap back-in-file grid=150x31 cursor=7,4 +|3: Back ls +|4: 1 line 1 big.txt +|5: 2 line 2 +|6: 3 line 3 +|7: 4 line 4 +|8: 5 line 5 +|9: 6 line 6 +|10: 7 line 7 +|11: 8 line 8 +|12: 9 line 9 +|13: 10 line 10 +|14: 11 line 11 +|15: 12 line 12 +|16: 13 line 13 +|17: 14 line 14 +|18: 15 line 15 +|19: 16 line 16 +|20: 17 line 17 +|21: 18 line 18 +|22: 19 line 19 +|23: 20 line 20 +|24: 21 line 21 +|25: 22 line 22 +|26: 23 line 23 +|27: 24 line 24 +|28: 25 line 25 +|29: 26 line 26 +|30: 27 line 27 +== snap back-to-shell grid=150x31 cursor=79,5 +== snap forward-file grid=150x31 cursor=7,3 +|3: 1 line 1 Forward +|4: 2 line 2 ls +|5: 3 line 3 big.txt |6: 4 line 4 |7: 5 line 5 |8: 6 line 6 @@ -94,12 +127,41 @@ |28: 26 line 26 |29: 27 line 27 |30: 28 line 28 -== snap back-to-shell grid=150x31 cursor=79,5 -== snap forward-file grid=150x31 cursor=7,3 -== snap forward-100 grid=150x31 cursor=7,17 -|3: 86 line 86 ls -|4: 87 line 87 big.txt -|5: 88 line 88 +== snap forward-100 grid=150x31 cursor=7,18 +|3: Forward ls +|4: 86 line 86 big.txt +|5: 87 line 87 +|6: 88 line 88 +|7: 89 line 89 +|8: 90 line 90 +|9: 91 line 91 +|10: 92 line 92 +|11: 93 line 93 +|12: 94 line 94 +|13: 95 line 95 +|14: 96 line 96 +|15: 97 line 97 +|16: 98 line 98 +|17: 99 line 99 +|18: 100 line 100 +|19: 101 line 101 +|20: 102 line 102 +|21: 103 line 103 +|22: 104 line 104 +|23: 105 line 105 +|24: 106 line 106 +|25: 107 line 107 +|26: 108 line 108 +|27: 109 line 109 +|28: 110 line 110 +|29: 111 line 111 +|30: 112 line 112 +== snap last grid=150x31 cursor=79,5 +|3: Last ls +== snap last-back grid=150x31 cursor=7,17 +|3: 86 line 86 Last +|4: 87 line 87 ls +|5: 88 line 88 big.txt |6: 89 line 89 |7: 90 line 90 |8: 91 line 91 @@ -125,47 +187,95 @@ |28: 111 line 111 |29: 112 line 112 |30: 113 line 113 -== snap last grid=150x31 cursor=79,5 -== snap last-back grid=150x31 cursor=7,17 -== snap jumplist grid=150x31 cursor=7,17 -|26: /tmp/pardes-snap/jumps/cwd/+Jumps Save Tty Del Collapse +== snap jumplist grid=150x31 cursor=7,18 +|3: Jumplist ls +|4: 86 line 86 big.txt +|5: 87 line 87 +|6: 88 line 88 +|7: 89 line 89 +|8: 90 line 90 +|9: 91 line 91 +|10: 92 line 92 +|11: 93 line 93 +|12: 94 line 94 +|13: 95 line 95 +|14: 96 line 96 +|15: 97 line 97 +|16: 98 line 98 +|17: 99 line 99 +|18: 100 line 100 +|19: 101 line 101 +|20: 102 line 102 +|21: 103 line 103 +|22: 104 line 104 +|23: 105 line 105 +|24: 106 line 106 +|25: 107 line 107 +|26: /tmp/pardes-snap/jumps/cwd/+Jumps Save Tty Collapse Del LocationsConfig |27: 1 @p1:3:3 /tmp/pardes-snap/jumps/cwd |28: 2 /tmp/pardes-snap/jumps/cwd/big.txt:1:1 line 1 |29: 3 @p1:3:3 /tmp/pardes-snap/jumps/cwd |30: 4 /tmp/pardes-snap/jumps/cwd/big.txt:100:1 line 100 == snap step1-shell grid=150x31 cursor=79,5 +|3: 86 line 86 ls +|4: 87 line 87 big.txt +|5: 88 line 88 +|6: 89 line 89 +|7: 90 line 90 +|8: 91 line 91 +|9: 92 line 92 +|10: 93 line 93 +|11: 94 line 94 +|12: 95 line 95 +|13: 96 line 96 +|14: 97 line 97 +|15: 98 line 98 +|16: 99 line 99 +|17: 100 line 100 +|18: 101 line 101 +|19: 102 line 102 +|20: 103 line 103 +|21: 104 line 104 +|22: 105 line 105 +|23: 106 line 106 +|24: 107 line 107 +|25: 108 line 108 +|27: Look +|28: 1 @p1:3:3 /tmp/pardes-snap/jumps/cwd +|29: 2 /tmp/pardes-snap/jumps/cwd/big.txt:1:1 line 1 +|30: 3 @p1:3:3 /tmp/pardes-snap/jumps/cwd == style step1-shell grid=150x31 |0: 0-70 #b2c3b8,#1d2824, 71-149 d,#1d2824, -|1: 0-24 #b2c3b8,#1d2824, 25-74 d,#1d2824, 75-99 #becfc4,#26362d, 100-149 d,#26362d, -|2: 0-1 #ffffff,#4c6356, 2-57 #b2c3b8,#1d2824, 58-74 d,#1d2824, 75-76 #000000,#adcc91, 77-145 #becfc4,#26362d, 146-149 d,#26362d, -|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|4: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|5: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|6: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|17: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|18: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|19: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|20: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|21: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|22: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|23: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|24: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|25: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|26: 0-1 #ffffff,#4c6356, 2-56 #b2c3b8,#1d2824, 57-74 d,#1d2824, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-13 #59675c,#0d1410, 14-40 #e5eee5,#0d1410, 41-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-44 #59675c,#0d1410, 45-51 #e5eee5,#0d1410, 52-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-13 #59675c,#0d1410, 14-40 #e5eee5,#0d1410, 41-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|30: 0-0 d,#152019, 1-1 d,#0d1410, 2-46 #59675c,#0d1410, 47-55 #e5eee5,#0d1410, 56-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-74 d,#1d2824, 75-76 #ffffff,#887455, 77-77 d,#26362d, 78-109 #becfc4,#26362d, 110-149 d,#26362d, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-29 #b2c3b8,#1d2824, 30-36 #d3b0d9,#1d2824, 37-58 #b2c3b8,#1d2824, 59-74 d,#1d2824, 75-76 #000000,#add38a, 77-77 d,#26362d, 78-104 #becfc4,#26362d, 105-107 #dfbce5,#26362d, 108-137 #becfc4,#26362d, 138-149 d,#26362d, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|4: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|5: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|6: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|17: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|18: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|19: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|20: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|21: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|22: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|23: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|24: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|25: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|26: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-29 #b2c3b8,#1d2824, 30-35 #d3b0d9,#1d2824, 36-73 #b2c3b8,#1d2824, 74-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|27: 0-0 d,#152019, 1-1 d,#0d1410, 2-70 d,#1d2824, 71-74 #b2c3b8,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-13 #59675c,#0d1410, 14-40 #e5eee5,#0d1410, 41-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-44 #59675c,#0d1410, 45-51 #e5eee5,#0d1410, 52-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|30: 0-0 d,#152019, 1-1 d,#0d1410, 2-13 #59675c,#0d1410, 14-40 #e5eee5,#0d1410, 41-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, == snap step2-file grid=150x31 cursor=7,3 |3: 1 line 1 ls |4: 2 line 2 big.txt @@ -214,9 +324,10 @@ |23: 109 line 109 |24: 110 line 110 |25: 111 line 111 -|27: 2 /tmp/pardes-snap/jumps/cwd/big.txt:1:1 line 1 -|28: 3 @p1:3:3 /tmp/pardes-snap/jumps/cwd -|29: 4 /tmp/pardes-snap/jumps/cwd/big.txt:100:1 line 100 -|30: 5 +|28: 2 /tmp/pardes-snap/jumps/cwd/big.txt:1:1 line 1 +|29: 3 @p1:3:3 /tmp/pardes-snap/jumps/cwd +|30: 4 /tmp/pardes-snap/jumps/cwd/big.txt:100:1 line 100 == snap step-back grid=150x31 cursor=79,5 -== snap look-row grid=150x31 cursor=7,14 +== snap look-row grid=150x31 cursor=79,5 +|5: 91 line 91 ls +|6: 92 line 92 big.txt diff --git a/test/snapshots/layout-close.golden b/test/snapshots/layout-close.golden index 9e573802..c9e1243a 100644 --- a/test/snapshots/layout-close.golden +++ b/test/snapshots/layout-close.golden @@ -1,19 +1,19 @@ == snap built grid=140x41 cursor=4,17 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/layout-close/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/layout-close/cwd Tty Save Mode Filter Collapse Del | ls ls | marker.txt marker.txt | -| /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter +| /tmp/pardes-snap/layout-close/cwd Tty Save Mode Filter Collapse Del | ls | marker.txt | -| /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter +| /tmp/pardes-snap/layout-close/cwd Tty Save Mode Filter Collapse Del | ls | marker.txt | -| /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter +| /tmp/pardes-snap/layout-close/cwd Tty Save Mode Filter Collapse Del | ls | marker.txt | @@ -21,20 +21,20 @@ | | | -| /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter +| /tmp/pardes-snap/layout-close/cwd Tty Save Mode Filter Collapse Del | ls | marker.txt == snap altc grid=140x41 cursor=39,5 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol New Tty Find Grep Joincol -|2: /tmp/pardes-snap/layout-close/cwd /tmp/pardes-snap/layout-close/cwd /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/layout-close/cw /tmp/pardes-snap/layout-close/cw /tmp/pardes-snap/layout-close/cwd Tty Save Mode Filter Collapse Del |3: ls ls ls |4: marker.txt marker.txt marker.txt -|6: /tmp/pardes-snap/layout-close/cwd -|10: /tmp/pardes-snap/layout-close/cwd +|6: /tmp/pardes-snap/layout-close/cw +|10: /tmp/pardes-snap/layout-close/cw |14: |15: |16: -|22: /tmp/pardes-snap/layout-close/cwd +|22: /tmp/pardes-snap/layout-close/cw == snap del grid=140x41 cursor=39,5 |6: |7: @@ -43,9 +43,6 @@ |10: |11: |12: -== snap colclose grid=140x41 cursor=4,8 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol -|2: /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter -|3: ls ls +== snap colclose grid=140x41 cursor=42,3 +|3: ls 1 ls |4: marker.txt marker.txt -|22: /tmp/pardes-snap/layout-close/cwd Save Tty Del Togglettymode Filter diff --git a/test/snapshots/layout-open.golden b/test/snapshots/layout-open.golden index 569f98b2..47eea036 100644 --- a/test/snapshots/layout-open.golden +++ b/test/snapshots/layout-open.golden @@ -1,7 +1,7 @@ == snap before grid=100x31 cursor=2,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/layout-open/cwd Save Tty Del To /tmp/pardes-snap/layout-open/cwd Save Tty Del To +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/layout-open/cwd Tty Save Mode /tmp/pardes-snap/layout-open/cwd Tty Save Mode | ls ls | sub sub | @@ -16,21 +16,27 @@ | | | -| /tmp/pardes-snap/layout-open/cwd Save Tty Del To +| /tmp/pardes-snap/layout-open/cwd Tty Save Mode | ls | sub == snap altn-left grid=100x31 cursor=4,9 -|6: /tmp/pardes-snap/layout-open/cwd Save Tty Del To +|6: /tmp/pardes-snap/layout-open/cwd Tty Save Mode |7: ls |8: sub == snap altn-right grid=100x31 cursor=54,9 -|6: /tmp/pardes-snap/layout-open/cwd Save Tty Del To /tmp/pardes-snap/layout-open/cwd Save Tty Del To +|6: /tmp/pardes-snap/layout-open/cwd Tty Save Mode /tmp/pardes-snap/layout-open/cwd Tty Save Mode |7: ls ls |8: sub sub == snap file-open grid=100x31 cursor=7,22 -|21: /tmp/pardes-snap/layout-open/cwd/sub/f.txt Save +|18: Look +|19: ls +|20: sub +|21: /tmp/pardes-snap/layout-open/cwd/sub/f.txt Save |22: 1 echo 'TTY'OK == snap ttydir grid=100x31 cursor=7,22 -|10: /tmp/pardes-snap/layout-open/cwd/sub Save Tty De +|10: /tmp/pardes-snap/layout-open/cwd/sub Tty Save M |11: echo 'TTY'OK |12: TTYOK +|18: ls +|19: sub +|20: diff --git a/test/snapshots/leader.golden b/test/snapshots/leader.golden index d084250c..81d9e3cb 100644 --- a/test/snapshots/leader.golden +++ b/test/snapshots/leader.golden @@ -1,60 +1,25 @@ -== snap spc grid=100x41 cursor=7,3 +== snap spc grid=100x41 cursor=7,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/leader/cwd/cmds.txt Save Tty Del Collapse -| 1 Help -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/leader/cwd/cmds.txt Save Tty Collapse Del | SPC -== snap spc-h grid=100x41 cursor=7,3 -|40: SPC h +| 1 Help +== snap spc-h grid=100x41 cursor=7,4 +|3: SPC h == snap abandoned grid=100x41 cursor=7,3 -|40: +|3: 1 Help +|4: == snap unmapped grid=100x41 cursor=7,3 == snap help-group grid=100x41 cursor=7,23 -|22: /tmp/pardes-snap/leader/cwd/+Help Save Tty Del Collapse +|22: /tmp/pardes-snap/leader/cwd/+Help Save Tty Collapse Del |23: 1 pardes builtins under SPC h |24: 2 -|25: 3 SPC h c Changelog topbar +|25: 3 SPC h c Changelog topbar |26: 4 SPC h m Messages -|27: 5 SPC h t Tutor topbar +|27: 5 SPC h t Tutor topbar |28: 6 == snap tutor grid=100x41 cursor=7,13 -|12: /Tutor Save Tty Del Collapse +|12: /Tutor Save Tty Collapse Del |13: 1 |14: 2 PARDES TUTOR |15: 3 tmux + vi + acme, from scratch. @@ -64,6 +29,13 @@ |19: 7 Press j until you reach the introduction. |20: 8 |21: 9 +|23: Tutor +|24: 1 pardes builtins under SPC h +|25: 2 +|26: 3 SPC h c Changelog topbar +|27: 4 SPC h m Messages +|28: 5 SPC h t Tutor topbar +|29: 6 == snap deleted grid=100x41 cursor=7,23 |12: |13: @@ -75,12 +47,19 @@ |19: |20: |21: +|23: 1 pardes builtins under SPC h +|24: 2 +|25: 3 SPC h c Changelog topbar +|26: 4 SPC h m Messages +|27: 5 SPC h t Tutor topbar +|28: 6 +|29: == snap help-window grid=100x41 cursor=7,23 |23: 1 pardes builtins under SPC w -|25: 3 SPC w h Left C-w h, C-w left -|26: 4 SPC w j Down C-w j, C-w down -|27: 5 SPC w k Up C-w k, C-w up -|28: 6 SPC w l Right C-w l, C-w right +|25: 3 SPC w h Left C-w h, C-w left +|26: 4 SPC w j Down C-w j, C-w down +|27: 5 SPC w k Up C-w k, C-w up +|28: 6 SPC w l Right C-w l, C-w right |29: 7 == snap help-language grid=100x41 cursor=7,23 |23: 1 pardes builtins under SPC l diff --git a/test/snapshots/load.golden b/test/snapshots/load.golden index ebfe6a39..994ab83e 100644 --- a/test/snapshots/load.golden +++ b/test/snapshots/load.golden @@ -1,7 +1,7 @@ == snap loaded grid=100x31 cursor=4,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/load/cwd Save Tty Del Toggletty /tmp/pardes-snap/load/cwd Save Tty Del Toggletty +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/load/cwd Tty Save Mode Filter /tmp/pardes-snap/load/cwd Tty Save Mode Filter | echo LOAD''MARK; seq 1 40; echo E''ND ls | LOADMARK d.txt | 1 @@ -16,38 +16,38 @@ | 10 | 11 | 12 -| /tmp/pardes-snap/load/cwd Save Tty Del Toggletty +| /tmp/pardes-snap/load/cwd Tty Save Mode Filter | ls | d.txt == style loaded grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-49 d,#26362d, 50-74 #b2c3b8,#1d2824, 75-99 d,#1d2824, -|2: 0-1 #000000,#adcc91, 2-49 #becfc4,#26362d, 50-51 #ffffff,#4c6356, 52-99 #b2c3b8,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|13: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-49 #b2c3b8,#1d2824, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-49 d,#26362d, 50-51 #ffffff,#887455, 52-52 d,#1d2824, 53-84 #b2c3b8,#1d2824, 85-99 d,#1d2824, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-28 #becfc4,#26362d, 29-31 #dfbce5,#26362d, 32-49 #becfc4,#26362d, 50-51 #ffffff,#496656, 52-52 d,#1d2824, 53-78 #b2c3b8,#1d2824, 79-81 #d3b0d9,#1d2824, 82-99 #b2c3b8,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|8: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|12: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|13: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-31 #d3b0d9,#1d2824, 32-49 #b2c3b8,#1d2824, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, diff --git a/test/snapshots/logquiet.golden b/test/snapshots/logquiet.golden index d5c4703b..1289761b 100644 --- a/test/snapshots/logquiet.golden +++ b/test/snapshots/logquiet.golden @@ -1,7 +1,7 @@ == snap quiet grid=100x31 cursor=62,5 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|$ /tmp/pardes-snap/logquiet/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/logquiet/cwd Tty Save Mode Filter Collapse Del | $ ls | $ printf '\033_Ga=q,i=1,s=1,v=1,f=24,t=d;AAAA\033\\\033[>0p' | $ '\033_Ga=q,i=1,s=1,v=1,f=24,t=d;AAAA\033\\\033[>0p'Gi=1;OK diff --git a/test/snapshots/look-center.golden b/test/snapshots/look-center.golden index 7509da8f..e13a7886 100644 --- a/test/snapshots/look-center.golden +++ b/test/snapshots/look-center.golden @@ -1,11 +1,11 @@ == snap center-open grid=150x31 cursor=7,12 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/look-center/cwd Save Tty Del Togglettymode Filter Collap /tmp/pardes-snap/look-center/cwd Save Tty Del Togglettymode Filter Collap -| ls ls -| big.txt big.txt -| -| /tmp/pardes-snap/look-center/cwd/big.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/look-center/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/look-center/cwd Tty Save Mode Filter Collapse Del +| Look ls +| ls big.txt +| big.txt +| /tmp/pardes-snap/look-center/cwd/big.txt Save Tty Collapse Del | 95 line 95 | 96 line 96 | 97 line 97 @@ -16,13 +16,16 @@ | 102 line 102 | 103 line 103 | 104 line 104 -| /tmp/pardes-snap/look-center/cwd Save Tty Del Togglettymode Filter Collap +| /tmp/pardes-snap/look-center/cwd Tty Save Mode Filter Collapse Del | ls | big.txt == snap center-dedup grid=150x31 cursor=7,12 +|3: ls Look +|4: big.txt ls +|5: big.txt |7: 145 line 145 -|8: 146 line 146 big.txt:150 big.txt:2 -|9: 147 line 147 +|8: 146 line 146 +|9: 147 line 147 big.txt:150 big.txt:2 |10: 148 line 148 |11: 149 line 149 |12: 150 line 150 @@ -30,14 +33,9 @@ |14: 152 line 152 |15: 153 line 153 |16: 154 line 154 -== snap center-clamp grid=150x31 cursor=7,8 -|7: 1 line 1 -|8: 2 line 2 big.txt:150 big.txt:2 -|9: 3 line 3 -|10: 4 line 4 -|11: 5 line 5 -|12: 6 line 6 -|13: 7 line 7 -|14: 8 line 8 -|15: 9 line 9 -|16: 10 line 10 +== snap center-clamp grid=150x31 cursor=93,7 +|3: ls ls +|4: big.txt big.txt +|5: +|8: 146 line 146 big.txt:150 big.txt:2 +|9: 147 line 147 diff --git a/test/snapshots/look-dir.golden b/test/snapshots/look-dir.golden index e859a3f4..8f90d604 100644 --- a/test/snapshots/look-dir.golden +++ b/test/snapshots/look-dir.golden @@ -1,11 +1,11 @@ == snap dir-open grid=100x31 cursor=4,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/look-dir/cwd Save Tty Del Toggl /tmp/pardes-snap/look-dir/cwd Save Tty Del Toggl -| ls ls -| sub top.txt sub top.txt -| -| /tmp/pardes-snap/look-dir/cwd/sub Save Tty Del T +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/look-dir/cwd Tty Save Mode Fil /tmp/pardes-snap/look-dir/cwd Tty Save Mode Fil +| Look ls +| ls sub top.txt +| sub top.txt +| /tmp/pardes-snap/look-dir/cwd/sub Tty Save Mode | ls | inner.txt | @@ -16,6 +16,6 @@ | | | -| /tmp/pardes-snap/look-dir/cwd Save Tty Del Toggl +| /tmp/pardes-snap/look-dir/cwd Tty Save Mode Fil | ls | sub top.txt diff --git a/test/snapshots/look-file-1col.golden b/test/snapshots/look-file-1col.golden index 553e1942..abe1fcbb 100644 --- a/test/snapshots/look-file-1col.golden +++ b/test/snapshots/look-file-1col.golden @@ -1,11 +1,11 @@ == snap file-open-1col grid=100x31 cursor=7,19 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/look-file-1col/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/look-file-1col/cwd Tty Save Mode Filter Collapse Del +| Look | ls | big.txt -| -| /tmp/pardes-snap/look-file-1col/cwd/big.txt Save Tty Del Collapse +| /tmp/pardes-snap/look-file-1col/cwd/big.txt Save Tty Collapse Del | 28 line 28 | 29 line 29 | 30 line 30 diff --git a/test/snapshots/look-file.golden b/test/snapshots/look-file.golden index dccbb07c..13919c3d 100644 --- a/test/snapshots/look-file.golden +++ b/test/snapshots/look-file.golden @@ -1,11 +1,11 @@ == snap file-open grid=150x31 cursor=7,12 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/look-file/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/look-file/cwd Save Tty Del Togglettymode Filter Collapse -| ls ls -| big.txt big.txt -| -| /tmp/pardes-snap/look-file/cwd/big.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/look-file/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/look-file/cwd Tty Save Mode Filter Collapse Del +| Look ls +| ls big.txt +| big.txt +| /tmp/pardes-snap/look-file/cwd/big.txt Save Tty Collapse Del | 35 line 35 | 36 line 36 | 37 line 37 @@ -16,38 +16,38 @@ | 42 line 42 | 43 line 43 | 44 line 44 -| /tmp/pardes-snap/look-file/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/look-file/cwd Tty Save Mode Filter Collapse Del | ls | big.txt == style file-open grid=150x31 |0: 0-70 #b2c3b8,#1d2824, 71-149 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-74 d,#26362d, 75-99 #b2c3b8,#1d2824, 100-149 d,#1d2824, -|2: 0-1 #ffffff,#4c6356, 2-74 #b2c3b8,#1d2824, 75-76 #ffffff,#4c6356, 77-149 #b2c3b8,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|6: 0-1 #000000,#adcc91, 2-61 #becfc4,#26362d, 62-74 d,#26362d, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-74 #b2c3b8,#1d2824, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-74 d,#26362d, 75-76 #ffffff,#887455, 77-77 d,#1d2824, 78-109 #b2c3b8,#1d2824, 110-149 d,#1d2824, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-36 #d3b0d9,#1d2824, 37-66 #b2c3b8,#1d2824, 67-74 d,#1d2824, 75-76 #ffffff,#496656, 77-77 d,#1d2824, 78-108 #b2c3b8,#1d2824, 109-111 #d3b0d9,#1d2824, 112-141 #b2c3b8,#1d2824, 142-149 d,#1d2824, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-70 d,#1d2824, 71-74 #b2c3b8,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-33 #becfc4,#26362d, 34-40 #dfbce5,#26362d, 41-62 #becfc4,#26362d, 63-74 d,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-36 #d3b0d9,#1d2824, 37-66 #b2c3b8,#1d2824, 67-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, diff --git a/test/snapshots/lookloaded.golden b/test/snapshots/lookloaded.golden index 1ff8c44f..a55151f4 100644 --- a/test/snapshots/lookloaded.golden +++ b/test/snapshots/lookloaded.golden @@ -1,11 +1,11 @@ == snap file-open grid=100x31 cursor=7,12 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/lookloaded/cwd Save Tty Del Tog /tmp/pardes-snap/lookloaded/cwd Save Tty Del Tog -| ls ls -| big.txt big.txt -| -| /tmp/pardes-snap/lookloaded/cwd/big.txt Save Tty +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lookloaded/cwd Tty Save Mode F /tmp/pardes-snap/lookloaded/cwd Tty Save Mode F +| Look ls +| ls big.txt +| big.txt +| /tmp/pardes-snap/lookloaded/cwd/big.txt Save Tt | 35 line 35 | 36 line 36 | 37 line 37 @@ -16,16 +16,22 @@ | 42 line 42 | 43 line 43 | 44 line 44 -| /tmp/pardes-snap/lookloaded/cwd Save Tty Del Tog +| /tmp/pardes-snap/lookloaded/cwd Tty Save Mode F | ls | big.txt == snap removed grid=100x31 cursor=54,7 +|3: ls ls +|4: big.txt big.txt |5: rm big.txt; echo GO''NE -|6: /tmp/pardes-snap/lookloaded/cwd/big.txt Save Tty GONE +|6: /tmp/pardes-snap/lookloaded/cwd/big.txt Save Tt GONE == snap look-noFS grid=100x31 cursor=7,12 -|7: 5 line 5 -|8: 6 line 6 big.txt:10 -|9: 7 line 7 +|3: ls Look +|4: big.txt ls +|5: big.txt +|6: /tmp/pardes-snap/lookloaded/cwd/big.txt Save Tt rm big.txt; echo GO''NE +|7: 5 line 5 GONE +|8: 6 line 6 +|9: 7 line 7 big.txt:10 |10: 8 line 8 |11: 9 line 9 |12: 10 line 10 diff --git a/test/snapshots/lookpanes.golden b/test/snapshots/lookpanes.golden index 73aab814..c2ef30cb 100644 --- a/test/snapshots/lookpanes.golden +++ b/test/snapshots/lookpanes.golden @@ -1,74 +1,74 @@ == snap shells grid=130x51 cursor=122,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/lookpanes/cwd/beta/bmark.txt Save Tty Del Coll /tmp/pardes-snap/lookpanes/cwd Save Tty Del Togglettymode Filte +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lookpanes/cwd/beta/bmark.txt Save Tty Collaps /tmp/pardes-snap/lookpanes/cwd Tty Save Mode Filter Collapse D | 1 both.txt ls | 2 b-marker alpha beta zzboot.txt zqonly.txt pick.txt twin.txt | -| /tmp/pardes-snap/lookpanes/cwd/alpha Save Tty Del Togglettymode +| /tmp/pardes-snap/lookpanes/cwd/alpha Tty Save Mode Filter Coll | ls | amark.txt both.txt pick.txt twin.txt zqonly.txt == snap other-dir grid=130x51 cursor=7,28 -|27: /tmp/pardes-snap/lookpanes/cwd/alpha/zqonly.txt Save Tty Del Co +|27: /tmp/pardes-snap/lookpanes/cwd/alpha/zqonly.txt Save Tty Colla |28: 1 ONLY-IN-ALPHA == snap clicked-wins grid=130x51 cursor=7,16 -|15: /tmp/pardes-snap/lookpanes/cwd/beta/both.txt Save Tty Del Colla +|15: /tmp/pardes-snap/lookpanes/cwd/beta/both.txt Save Tty Collapse |16: 1 BOTH-FROM-BETA == snap mru-alpha grid=130x51 cursor=7,22 -|21: /tmp/pardes-snap/lookpanes/cwd/alpha/pick.txt Save Tty Del Coll +|21: /tmp/pardes-snap/lookpanes/cwd/alpha/pick.txt Save Tty Collaps |22: 1 PICK-FROM-ALPHA == snap mru-beta grid=130x51 cursor=7,10 -|9: /tmp/pardes-snap/lookpanes/cwd/beta/twin.txt Save Tty Del Colla +|9: /tmp/pardes-snap/lookpanes/cwd/beta/twin.txt Save Tty Collapse |10: 1 TWIN-FROM-BETA == style mru-beta grid=130x51 |0: 0-70 #b2c3b8,#1d2824, 71-129 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-64 d,#26362d, 65-89 #b2c3b8,#1d2824, 90-129 d,#1d2824, -|2: 0-1 #ffffff,#4c6356, 2-64 #b2c3b8,#1d2824, 65-66 #ffffff,#4c6356, 67-129 #b2c3b8,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-121 #e5eee5,#0d1410, 122-129 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-129 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-66 #ffffff,#4c6356, 67-129 #b2c3b8,#1d2824, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|9: 0-1 #000000,#adcc91, 2-64 #becfc4,#26362d, 65-65 d,#637f6a, 66-129 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-20 #e5eee5,#0d1410, 21-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|15: 0-1 #ffffff,#4c6356, 2-64 #b2c3b8,#1d2824, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|21: 0-1 #ffffff,#4c6356, 2-64 #b2c3b8,#1d2824, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-21 #e5eee5,#0d1410, 22-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|27: 0-1 #ffffff,#4c6356, 2-64 #b2c3b8,#1d2824, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|31: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|32: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|33: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|34: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|35: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|36: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|37: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|38: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|39: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|40: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|41: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|42: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|43: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|44: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|45: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|46: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|47: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|48: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|49: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|50: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#637f6a, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-64 d,#26362d, 65-66 #ffffff,#887455, 67-67 d,#1d2824, 68-99 #b2c3b8,#1d2824, 100-129 d,#1d2824, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-47 #d3b0d9,#1d2824, 48-64 #b2c3b8,#1d2824, 65-66 #ffffff,#496656, 67-67 d,#1d2824, 68-98 #b2c3b8,#1d2824, 99-101 #d3b0d9,#1d2824, 102-129 #b2c3b8,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-121 #e5eee5,#0d1410, 122-129 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-129 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-66 #ffffff,#496656, 67-67 d,#1d2824, 68-104 #b2c3b8,#1d2824, 105-107 #d3b0d9,#1d2824, 108-129 #b2c3b8,#1d2824, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|9: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-38 #becfc4,#26362d, 39-46 #dfbce5,#26362d, 47-64 #becfc4,#26362d, 65-65 d,#608269, 66-129 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-20 #e5eee5,#0d1410, 21-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|15: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-46 #d3b0d9,#1d2824, 47-64 #b2c3b8,#1d2824, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|21: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-39 #b2c3b8,#1d2824, 40-47 #d3b0d9,#1d2824, 48-64 #b2c3b8,#1d2824, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-21 #e5eee5,#0d1410, 22-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|27: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-39 #b2c3b8,#1d2824, 40-49 #d3b0d9,#1d2824, 50-64 #b2c3b8,#1d2824, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|31: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|32: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|33: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|34: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|35: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|36: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|37: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|38: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|39: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|40: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|41: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|42: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|43: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|44: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|45: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|46: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|47: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|48: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|49: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, +|50: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, diff --git a/test/snapshots/lookpanes.snap b/test/snapshots/lookpanes.snap index 3bc8055c..8ada3f1b 100644 --- a/test/snapshots/lookpanes.snap +++ b/test/snapshots/lookpanes.snap @@ -20,6 +20,10 @@ file beta/both.txt BOTH-FROM-BETA # directory at that) and Alt-c puts it in a column of its own on the right; # its first line is a word to look FROM that pane file beta/bmark.txt both.txt\nb-marker +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 51 130 beta/bmark.txt wait 8000 b-marker stable 700 20000 diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index 4e916932..129ee285 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -1,13 +1,13 @@ == snap opened grid=150x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/lookrange/cwd/look.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lookrange/cwd/look.txt Save Tty Collapse Del | 1 r.txt:3-5 | 2 r.txt:7:4-9 | 3 r.txt:3:2-5:3 | 4 r.txt:8:6-99:9 == snap wholelines grid=150x31 cursor=11,22 -|17: /tmp/pardes-snap/lookrange/cwd/r.txt Save Tty Del Collapse +|17: /tmp/pardes-snap/lookrange/cwd/r.txt Save Tty Collapse Del |18: 1 aaaa |19: 2 bbbb |20: 3 cccc dccc @@ -19,48 +19,48 @@ |26: 9 iiii == style wholelines grid=150x31 |0: 0-70 #b2c3b8,#1d2824, 71-149 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-149 d,#26362d, -|2: 0-1 #ffffff,#4c6356, 2-62 #b2c3b8,#1d2824, 63-149 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-149 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-149 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-149 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|17: 0-1 #000000,#adcc91, 2-59 #becfc4,#26362d, 60-149 d,#26362d, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 #f5f7ee,#405d4b, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 #f5f7ee,#405d4b, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-11 #f5f7ee,#405d4b, 12-149 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #e5eee5,#0d1410, 19-149 d,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-149 d,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-149 d,#26362d, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-41 #d3b0d9,#1d2824, 42-63 #b2c3b8,#1d2824, 64-149 d,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-149 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-149 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-149 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|17: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-33 #becfc4,#26362d, 34-38 #dfbce5,#26362d, 39-60 #becfc4,#26362d, 61-149 d,#26362d, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 #f5f7ee,#3c614a, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 #f5f7ee,#3c614a, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-149 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #e5eee5,#0d1410, 19-149 d,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-149 d,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, == snap onelinespan grid=150x31 cursor=15,24 == style onelinespan grid=150x31 -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#405d4b, 16-18 #e5eee5,#0d1410, 19-149 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-18 #e5eee5,#0d1410, 19-149 d,#0d1410, == snap fullspan grid=150x31 cursor=9,22 == style fullspan grid=150x31 -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-149 #f5f7ee,#405d4b, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 #f5f7ee,#405d4b, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-9 #f5f7ee,#405d4b, 10-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #e5eee5,#0d1410, 19-149 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-149 #f5f7ee,#3c614a, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 #f5f7ee,#3c614a, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-9 #f5f7ee,#3c614a, 10-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #e5eee5,#0d1410, 19-149 d,#0d1410, == snap stale grid=150x31 cursor=10,25 |18: 2 bbbb |19: 3 cccc dccc @@ -73,14 +73,14 @@ |26: == style stale grid=150x31 |18: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #e5eee5,#0d1410, 19-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-149 #f5f7ee,#405d4b, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #f5f7ee,#405d4b, 11-149 d,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #e5eee5,#0d1410, 19-149 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-149 #f5f7ee,#3c614a, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-149 d,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, == snap hit1 grid=150x31 cursor=15,24 |18: 1 aaaa |19: 2 bbbb @@ -90,22 +90,41 @@ |23: 6 ffff |24: 7 gg NEEDLE gg |25: 8 hhhh NEEDLE -|26: 9 iiii -|28: /tmp/pardes-snap/lookrange/cwd/+Search Save Tty Del Collapse -|29: 1 r.txt:7:4-9 gg NEEDLE gg -|30: 2 r.txt:8:6-11 hhhh NEEDLE +|26: /tmp/pardes-snap/lookrange/cwd/+Search Save Tty Collapse Del LocationsConfig +|27: 1 r.txt:7:4-9 +|28: 2 gg NEEDLE gg +|29: 3 r.txt:8:6-11 +|30: 4 hhhh NEEDLE == style hit1 grid=150x31 -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#405d4b, 16-18 #e5eee5,#0d1410, 19-149 d,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-149 d,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|28: 0-1 #ffffff,#4c6356, 2-61 #b2c3b8,#1d2824, 62-149 d,#1d2824, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-17 #59675c,#0d1410, 18-21 #e5eee5,#0d1410, 22-27 #f7e4a5,#57472a, 28-30 #e5eee5,#0d1410, 31-149 d,#0d1410, -|30: 0-0 d,#152019, 1-1 d,#0d1410, 2-18 #59675c,#0d1410, 19-24 #e5eee5,#0d1410, 25-30 #f7e4a5,#57472a, 31-149 d,#0d1410, -== snap hit2 grid=150x31 cursor=17,23 +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-18 #e5eee5,#0d1410, 19-149 d,#0d1410, +|25: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-149 d,#0d1410, +|26: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-40 #d3b0d9,#1d2824, 41-78 #b2c3b8,#1d2824, 79-149 d,#1d2824, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-17 #59675c,#0d1410, 18-149 d,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #f7e4a5,#5e4923, 16-18 #e5eee5,#0d1410, 19-149 d,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-18 #59675c,#0d1410, 19-149 d,#0d1410, +|30: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#5e4923, 18-149 d,#0d1410, +== snap hit2 grid=150x31 cursor=17,22 +|18: 4 dddd +|19: 5 eeee +|20: 6 ffff +|21: 7 gg NEEDLE gg +|22: 8 hhhh NEEDLE +|23: 9 iiii +|24: +|25: +== style hit2 grid=150x31 +|18: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|19: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #e5eee5,#0d1410, 19-149 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +== snap back grid=150x31 cursor=15,22 |18: 3 cccc dccc |19: 4 dddd |20: 5 eeee @@ -113,30 +132,10 @@ |22: 7 gg NEEDLE gg |23: 8 hhhh NEEDLE |24: 9 iiii -|25: -|26: -== style hit2 grid=150x31 -|18: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, -|19: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #e5eee5,#0d1410, 19-149 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#405d4b, 18-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -== snap back grid=150x31 cursor=15,23 -|18: 2 bbbb -|19: 3 cccc dccc -|20: 4 dddd -|21: 5 eeee -|22: 6 ffff -|23: 7 gg NEEDLE gg -|24: 8 hhhh NEEDLE -|25: 9 iiii == style back grid=150x31 -|18: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#405d4b, 16-18 #e5eee5,#0d1410, 19-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-149 d,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|18: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-149 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-18 #e5eee5,#0d1410, 19-149 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-149 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-149 d,#0d1410, diff --git a/test/snapshots/lookrange.snap b/test/snapshots/lookrange.snap index c1fde9c6..50ef9ad3 100644 --- a/test/snapshots/lookrange.snap +++ b/test/snapshots/lookrange.snap @@ -14,6 +14,10 @@ # in the styles. file r.txt aaaa\nbbbb\ncccc dccc\ndddd\neeee\nffff\ngg NEEDLE gg\nhhhh NEEDLE\niiii file look.txt r.txt:3-5\nr.txt:7:4-9\nr.txt:3:2-5:3\nr.txt:8:6-99:9 +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 31 150 look.txt wait 8000 r.txt:3-5 stable 700 20000 @@ -54,7 +58,9 @@ snapstyle stale key / text NEEDLE key enter -wait 10000 r.txt:7:4-9 gg NEEDLE +# Locations stack the target under its line now: two rows, two waits. +wait 10000 r.txt:7:4-9 +wait 10000 gg NEEDLE gg stable 700 15000 snap hit1 snapstyle hit1 diff --git a/test/snapshots/lsp-client-edit.golden b/test/snapshots/lsp-client-edit.golden index 02cc9a37..54c6e083 100644 --- a/test/snapshots/lsp-client-edit.golden +++ b/test/snapshots/lsp-client-edit.golden @@ -1,7 +1,8 @@ -== snap formatted grid=100x25 cursor=7,4 +== snap formatted grid=100x25 cursor=7,5 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/lsp-client-edit/cwd/main.rs * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsp-client-edit/cwd/main.rs * Save Tty Collapse Del TreeContext +| formatted 1 range(s) | 1 // formatted by mock | 2 mod lib; | 3 @@ -11,19 +12,6 @@ | 7 let _ = x + y; | 8 } | 9 -| -| -| -| -| -| -| -| -| -| -| -| -| formatted 1 range(s) == snap unformatted grid=100x25 cursor=7,3 |3: 1 mod lib; |4: 2 @@ -34,12 +22,24 @@ |9: 7 } |10: 8 |11: -|24: -== snap renamed grid=100x25 cursor=12,5 -|6: 4 let x = sum(1, 2); -|7: 5 let y = sum(3, 4); -|24: renamed 2 range(s) +|12: +== snap renamed grid=100x25 cursor=12,6 +|3: renamed 2 range(s) +|4: 1 mod lib; +|5: 2 +|6: 3 fn main() { +|7: 4 let x = sum(1, 2); +|8: 5 let y = sum(3, 4); +|9: 6 let _ = x + y; +|10: 7 } +|11: 8 == snap unrenamed grid=100x25 cursor=12,5 +|3: 1 mod lib; +|4: 2 +|5: 3 fn main() { |6: 4 let x = add(1, 2); |7: 5 let y = add(3, 4); -|24: +|8: 6 let _ = x + y; +|9: 7 } +|10: 8 +|11: diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index 6e122e95..6d4a0c0f 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -1,7 +1,8 @@ == snap gd-jumped grid=100x25 cursor=16,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse Del TreeContext +| --:--:-- lsp rust-analyzer: ready | 1 mod lib; | 2 | 3 fn main() { @@ -12,24 +13,33 @@ | 8 | | -| --:--:-- lsp rust-analyzer: ready -| /tmp/pardes-snap/lsp-client/cwd/lib.rs Save Tty Del Collapse +| /tmp/pardes-snap/lsp-client/cwd/lib.rs Save Tty Collapse Del TreeContext | 1 // mock fixture | 2 pub fn add(a: i32, b: i32) -> i32 { | 3 a + b | 4 } | 5 == snap gr-list grid=100x25 cursor=21,6 -|13: -|21: /tmp/pardes-snap/lsp-client/cwd/+Search Save Tty Del Collapse -|22: 1 lib.rs:2:8-10 pub fn add(a: i32, b: i32) -> i32 { -|23: 2 main.rs:4:13-15 let x = add(1, 2); -|24: 3 main.rs:5:13-15 let y = add(3, 4); +|3: 1 mod lib; +|4: 2 +|5: 3 fn main() { +|6: 4 let x = add(1, 2); +|7: 5 let y = add(3, 4); +|8: 6 let _ = x + y; +|9: 7 } +|10: 8 +|11: +|20: /tmp/pardes-snap/lsp-client/cwd/+Search Save Tty Collapse Del LocationsConfig +|21: 1 lib.rs:2:8-10 +|22: 2 pub fn add(a: i32, b: i32) -> i32 { +|23: 3 main.rs:4:13-15 +|24: 4 let x = add(1, 2); == snap gr-opened grid=100x25 cursor=21,7 -|22: 2 main.rs:4:13-15 let x = add(1, 2); -|23: 3 main.rs:5:13-15 let y = add(3, 4); -|24: 4 +|21: Look +|22: 3 main.rs:4:13-15 +|23: 4 let x = add(1, 2); +|24: 5 main.rs:5:13-15 == snap gr-back grid=100x25 cursor=21,6 -|22: 1 lib.rs:2:8-10 pub fn add(a: i32, b: i32) -> i32 { -|23: 2 main.rs:4:13-15 let x = add(1, 2); -|24: 3 main.rs:5:13-15 let y = add(3, 4); +|22: 2 pub fn add(a: i32, b: i32) -> i32 { +|23: 3 main.rs:4:13-15 +|24: 4 let x = add(1, 2); diff --git a/test/snapshots/lsp-rename.golden b/test/snapshots/lsp-rename.golden index 74ab41e2..d18e6566 100644 --- a/test/snapshots/lsp-rename.golden +++ b/test/snapshots/lsp-rename.golden @@ -1,7 +1,8 @@ -== snap renamed grid=110x25 cursor=17,10 +== snap renamed grid=110x25 cursor=17,11 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/lsp-rename/cwd/rename.zig * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsp-rename/cwd/rename.zig * Save Tty Collapse Del TreeContext +| renamed 2 range(s) | 1 const std = @import("std"); | 2 | 3 fn renamed_helper(x: u32) u32 { @@ -17,17 +18,23 @@ | 13 _ = helper; | 14 } | 15 -| -| -| -| -| -| -| renamed 2 range(s) == snap undone grid=110x25 cursor=17,10 +|3: 1 const std = @import("std"); +|4: 2 |5: 3 fn helper(x: u32) u32 { +|6: 4 return x + 1; +|7: 5 } +|8: 6 +|9: 7 pub fn main() void { |10: 8 _ = helper(41); -|24: +|11: 9 } +|12: 10 +|13: 11 fn shadowed() void { +|14: 12 const helper: u32 = 7; +|15: 13 _ = helper; +|16: 14 } +|17: 15 +|18: == snap redone grid=110x25 cursor=17,10 |5: 3 fn renamed_helper(x: u32) u32 { |10: 8 _ = renamed_helper(41); diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index f6d0739a..7baf7716 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -1,7 +1,7 @@ == snap opened grid=120x41 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); | 2 | 3 fn helper(x: u32) u32 { @@ -14,14 +14,52 @@ | 10 == snap cursor grid=120x41 cursor=17,10 == snap definition grid=120x41 cursor=15,5 -== snap hover grid=120x41 cursor=15,5 -|38: /tmp/pardes-snap/lsp/cwd/+Hover Save Tty Del Collapse +== snap hover grid=120x41 cursor=15,6 +|3: Hover +|4: 1 const std = @import("std"); +|5: 2 +|6: 3 fn helper(x: u32) u32 { +|7: 4 return x + 1; +|8: 5 } +|9: 6 +|10: 7 pub fn main() void { +|11: 8 _ = helper(41); +|12: 9 } +|13: 10 +|38: /tmp/pardes-snap/lsp/cwd/+Hover Save Tty Collapse Del |39: 1 fn helper(x: u32) u32 |40: 2 (fn (u32) u32) -== snap symbols grid=120x41 cursor=15,5 -|34: /tmp/pardes-snap/lsp/cwd/+Search Save Tty Del Collapse -|35: 1 a.zig:1:7-9 std -|36: 2 a.zig:3:4-9 helper fn helper(x: u32) u32 -|37: 3 a.zig:7:8-11 main fn main() void +== snap symbols grid=120x41 cursor=15,6 +|3: Symbols +|31: /tmp/pardes-snap/lsp/cwd/+Search Save Tty Collapse Del LocationsConfig +|32: 1 a.zig:1:7-9 +|33: 2 std +|34: 3 a.zig:3:4-9 +|35: 4 helper fn helper(x: u32) u32 +|36: 5 a.zig:7:8-11 +|37: 6 main fn main() void == snap step grid=120x41 cursor=15,3 +|3: 1 const std = @import("std"); +|4: 2 +|5: 3 fn helper(x: u32) u32 { +|6: 4 return x + 1; +|7: 5 } +|8: 6 +|9: 7 pub fn main() void { +|10: 8 _ = helper(41); +|11: 9 } +|12: 10 +|13: +|32: Look +|33: 1 a.zig:1:7-9 +|34: 2 std +|35: 3 a.zig:3:4-9 +|36: 4 helper fn helper(x: u32) u32 +|37: 5 a.zig:7:8-11 == snap nothing grid=120x41 cursor=7,5 +|32: 1 a.zig:1:7-9 +|33: 2 std +|34: 3 a.zig:3:4-9 +|35: 4 helper fn helper(x: u32) u32 +|36: 5 a.zig:7:8-11 +|37: 6 main fn main() void diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden index 3c4316c3..4a9ff8b5 100644 --- a/test/snapshots/lspcomplete.golden +++ b/test/snapshots/lspcomplete.golden @@ -1,7 +1,7 @@ == snap opened grid=120x41 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -16,29 +16,31 @@ | 12 // note. see below | 13 == snap indent grid=120x41 cursor=11,12 -|2: ^ /tmp/pardes-snap/lspcomplete/cwd/a.zig * Save Tty Del Collapse +|2: ^ /tmp/pardes-snap/lspcomplete/cwd/a.zig * Save Tty Collapse Del TreeContext |12: 10 } == snap commentindent grid=120x41 cursor=19,14 |14: 12 // note. see below == snap athedot grid=120x41 cursor=16,10 |10: 8 . == snap completion grid=120x41 cursor=16,10 -|38: /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Del Collapse +|38: /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del |39: 1 a.zig:2:5-13 verdigris verdigris, |40: 2 a.zig:3:5-12 cinnabar cinnabar, == snap refill grid=120x41 cursor=16,10 == snap step grid=120x41 cursor=19,4 -|2: /tmp/pardes-snap/lspcomplete/cwd/a.zig * Save Tty Del Collapse +|2: /tmp/pardes-snap/lspcomplete/cwd/a.zig * Save Tty Collapse Del TreeContext +|39: Look +|40: 1 a.zig:2:5-13 verdigris verdigris, == snap txtindent grid=120x41 cursor=15,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|^ /tmp/pardes-snap/lspcomplete/cwd/notes.txt * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +|^ /tmp/pardes-snap/lspcomplete/cwd/notes.txt * Save Tty Collapse Del | 1 abc. def ghi | 2 == snap nosemi grid=100x19 cursor=29,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|^ /tmp/pardes-snap/lspcomplete/cwd/c.zig * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +|^ /tmp/pardes-snap/lspcomplete/cwd/c.zig * Save Tty Collapse Del TreeContext | 1 const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -52,13 +54,13 @@ | | | -| /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Del Collapse +| /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del | 1 c.zig:2:5-13 verdigris verdigris, | 2 c.zig:3:5-12 cinnabar cinnabar, == snap nobrace grid=100x19 cursor=16,10 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|^ /tmp/pardes-snap/lspcomplete/cwd/d.zig * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +|^ /tmp/pardes-snap/lspcomplete/cwd/d.zig * Save Tty Collapse Del TreeContext | 1 const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -72,6 +74,6 @@ | | | -| /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Del Collapse +| /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del | 1 d.zig:2:5-13 verdigris verdigris, | 2 d.zig:3:5-12 cinnabar cinnabar, diff --git a/test/snapshots/lspcompletemoved.golden b/test/snapshots/lspcompletemoved.golden index 6232a1f3..af6616af 100644 --- a/test/snapshots/lspcompletemoved.golden +++ b/test/snapshots/lspcompletemoved.golden @@ -1,7 +1,7 @@ == snap typedthrough grid=120x21 cursor=16,14 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|^ /tmp/pardes-snap/lspcompletemoved/cwd/a.zig * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +|^ /tmp/pardes-snap/lspcompletemoved/cwd/a.zig * Save Tty Collapse Del TreeContext | 1 const Shade = enum { | 2 verdigris, | 3 cinnabar, diff --git a/test/snapshots/lspdebug.golden b/test/snapshots/lspdebug.golden index e1b57c5e..a2182231 100644 --- a/test/snapshots/lspdebug.golden +++ b/test/snapshots/lspdebug.golden @@ -1,7 +1,7 @@ == snap opened grid=120x45 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); | 2 | 3 fn helper() u32 { diff --git a/test/snapshots/lspdebug.snap b/test/snapshots/lspdebug.snap index 4021bc17..23a95db0 100644 --- a/test/snapshots/lspdebug.snap +++ b/test/snapshots/lspdebug.snap @@ -1,4 +1,8 @@ file z.zig const std = @import("std");\n\nfn helper() u32 {\n return 3;\n}\n\npub fn main() void {\n const v = helper();\n _ = v;\n}\n +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 45 120 z.zig wait 8000 fn helper stable 700 20000 @@ -38,6 +42,9 @@ text last queries key enter wait 10000 last queries wait 10000 definition z.zig +# The results pane the search opened takes the bottom half, which leaves the +# report one row short of its second query: step the cursor past it. +key j j j wait 10000 explain z.zig key space d key space w j diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index 65fd08cd..58de860b 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,7 +1,7 @@ == snap absrow grid=100x35 cursor=16,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|^ /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +|^ /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig * Save Tty Collapse Del TreeContext | 1 const shade = @import("../shade.zig"); | 2 | 3 pub fn pick(s: shade.Shade) u8 { @@ -31,57 +31,59 @@ | | | -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Del Collapse +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse Del | 1 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:2:5-13 verdigris verdigris, | 2 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:3:5-12 cinnabar cinnabar, == snap abslook grid=100x35 cursor=19,19 -|2: /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig * Save Tty Del Collapse -|17: /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Del Collapse +|2: /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig * Save Tty Collapse Del TreeContext +|17: /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse Del TreeContext |18: 1 pub const Shade = enum { |19: 2 verdigris, |20: 3 cinnabar, |21: 4 }; |22: 5 +|33: Look +|34: 1 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:2:5-13 verdigris verdigris, == style abslook grid=100x35 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-99 d,#26362d, -|2: 0-1 #ffffff,#4c6356, 2-71 #b2c3b8,#1d2824, 72-99 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-27 #c9b0e4,#0d1410, 28-28 #e5eee5,#0d1410, 29-42 #b6ce94,#0d1410, 43-44 #e5eee5,#0d1410, 45-99 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-38 #e5eee5,#0d1410, 39-99 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9b0e4,#0d1410, 17-17 #e5eee5,#0d1410, 18-23 #c9b0e4,#0d1410, 24-29 #e5eee5,#0d1410, 30-99 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-99 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-99 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|17: 0-1 #000000,#adcc91, 2-64 #becfc4,#26362d, 65-99 d,#26362d, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-24 #e5eee5,#0d1410, 25-28 #c9b0e4,#0d1410, 29-30 #e5eee5,#0d1410, 31-99 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-19 #f5f7ee,#405d4b, 20-20 #e5eee5,#0d1410, 21-99 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-99 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-99 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|31: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|32: 0-1 #ffffff,#4c6356, 2-66 #b2c3b8,#1d2824, 67-99 d,#1d2824, -|33: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-54 #59675c,#0d1410, 55-76 #e5eee5,#0d1410, 77-99 d,#0d1410, -|34: 0-0 d,#152019, 1-1 d,#0d1410, 2-54 #59675c,#0d1410, 55-74 #e5eee5,#0d1410, 75-99 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-99 d,#26362d, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-48 #d3b0d9,#1d2824, 49-84 #b2c3b8,#1d2824, 85-99 d,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-27 #c9a7ed,#0d1410, 28-28 #e5eee5,#0d1410, 29-42 #b8d88a,#0d1410, 43-44 #e5eee5,#0d1410, 45-99 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-38 #e5eee5,#0d1410, 39-99 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9a7ed,#0d1410, 17-17 #e5eee5,#0d1410, 18-23 #c9a7ed,#0d1410, 24-29 #e5eee5,#0d1410, 30-99 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-99 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-99 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|17: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-43 #dfbce5,#26362d, 44-77 #becfc4,#26362d, 78-99 d,#26362d, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-24 #e5eee5,#0d1410, 25-28 #c9a7ed,#0d1410, 29-30 #e5eee5,#0d1410, 31-99 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-19 #f5f7ee,#3c614a, 20-20 #e5eee5,#0d1410, 21-99 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-99 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-99 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|31: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|32: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-45 #d3b0d9,#1d2824, 46-67 #b2c3b8,#1d2824, 68-99 d,#1d2824, +|33: 0-0 d,#152019, 1-1 d,#0d1410, 2-95 d,#1d2824, 96-99 #b2c3b8,#1d2824, +|34: 0-0 d,#608269, 1-1 d,#0d1410, 2-54 #59675c,#0d1410, 55-76 #e5eee5,#0d1410, 77-99 d,#0d1410, == snap subrow grid=100x35 cursor=16,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|^ /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +|^ /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig * Save Tty Collapse Del TreeContext | 1 const tint = @import("inner/tint.zig"); | 2 | 3 pub fn hue(t: tint.Tint) u8 { @@ -111,51 +113,53 @@ | | | -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Del Collapse +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse Del | 1 inner/tint.zig:2:5-9 ochre ochre, | 2 inner/tint.zig:3:5-10 indigo indigo, == snap sublook grid=100x35 cursor=15,19 -|2: /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig * Save Tty Del Collapse -|17: /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Del Collapse +|2: /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig * Save Tty Collapse Del TreeContext +|17: /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse Del TreeContext |18: 1 pub const Tint = enum { |19: 2 ochre, |20: 3 indigo, |21: 4 }; |22: 5 +|33: Look +|34: 1 inner/tint.zig:2:5-9 ochre ochre, == style sublook grid=100x35 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-99 d,#26362d, -|2: 0-1 #ffffff,#4c6356, 2-71 #b2c3b8,#1d2824, 72-99 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-26 #c9b0e4,#0d1410, 27-27 #e5eee5,#0d1410, 28-43 #b6ce94,#0d1410, 44-45 #e5eee5,#0d1410, 46-99 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-35 #e5eee5,#0d1410, 36-99 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9b0e4,#0d1410, 17-17 #e5eee5,#0d1410, 18-23 #c9b0e4,#0d1410, 24-29 #e5eee5,#0d1410, 30-99 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-99 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-99 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|17: 0-1 #000000,#adcc91, 2-73 #becfc4,#26362d, 74-99 d,#26362d, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-23 #e5eee5,#0d1410, 24-27 #c9b0e4,#0d1410, 28-29 #e5eee5,#0d1410, 30-99 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-15 #f5f7ee,#405d4b, 16-16 #e5eee5,#0d1410, 17-99 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-99 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-99 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|31: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -|32: 0-1 #ffffff,#4c6356, 2-66 #b2c3b8,#1d2824, 67-99 d,#1d2824, -|33: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-26 #59675c,#0d1410, 27-40 #e5eee5,#0d1410, 41-99 d,#0d1410, -|34: 0-0 d,#152019, 1-1 d,#0d1410, 2-27 #59675c,#0d1410, 28-43 #e5eee5,#0d1410, 44-99 d,#0d1410, -== snap clicked grid=100x35 cursor=16,20 +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-99 d,#26362d, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-48 #d3b0d9,#1d2824, 49-84 #b2c3b8,#1d2824, 85-99 d,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-26 #c9a7ed,#0d1410, 27-27 #e5eee5,#0d1410, 28-43 #b8d88a,#0d1410, 44-45 #e5eee5,#0d1410, 46-99 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-35 #e5eee5,#0d1410, 36-99 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9a7ed,#0d1410, 17-17 #e5eee5,#0d1410, 18-23 #c9a7ed,#0d1410, 24-29 #e5eee5,#0d1410, 30-99 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-15 #e5eee5,#0d1410, 16-99 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-99 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|17: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-44 #becfc4,#26362d, 45-52 #dfbce5,#26362d, 53-86 #becfc4,#26362d, 87-99 d,#26362d, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-23 #e5eee5,#0d1410, 24-27 #c9a7ed,#0d1410, 28-29 #e5eee5,#0d1410, 30-99 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-15 #f5f7ee,#3c614a, 16-16 #e5eee5,#0d1410, 17-99 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-99 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-99 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|31: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +|32: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-45 #d3b0d9,#1d2824, 46-67 #b2c3b8,#1d2824, 68-99 d,#1d2824, +|33: 0-0 d,#152019, 1-1 d,#0d1410, 2-95 d,#1d2824, 96-99 #b2c3b8,#1d2824, +|34: 0-0 d,#608269, 1-1 d,#0d1410, 2-26 #59675c,#0d1410, 27-40 #e5eee5,#0d1410, 41-99 d,#0d1410, +== snap clicked grid=100x35 cursor=15,19 diff --git a/test/snapshots/markup.golden b/test/snapshots/markup.golden index 7caaf5b1..ca69d0f7 100644 --- a/test/snapshots/markup.golden +++ b/test/snapshots/markup.golden @@ -1,7 +1,7 @@ == snap typst grid=92x25 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/markup/cwd/paper.typ Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/markup/cwd/paper.typ Save Tty Collapse Del TreeContext | 1 = Typst heading | 2 | 3 Prose with *bold* and _italic_ words, a `raw` span, @@ -13,34 +13,34 @@ | 9 == style typst grid=92x25 |0: 0-70 #b2c3b8,#1d2824, 71-91 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-91 d,#26362d, -|2: 0-1 #000000,#adcc91, 2-60 #becfc4,#26362d, 61-91 d,#26362d, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-21 #c9b0e4,#0d1410, 22-91 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-23 #b9e58f,#0d1410, 24-28 #e5eee5,#0d1410, 29-36 #e9bf91,#0d1410, 37-46 #e5eee5,#0d1410, 47-51 #b6ce94,#0d1410, 52-57 #e5eee5,#0d1410, 58-91 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-15 #c9b0e4,#0d1410, 16-27 #e5eee5,#0d1410, 28-31 #c9b0e4,#0d1410, 32-36 #e5eee5,#0d1410, 37-38 #e9bf91,#0d1410, 39-91 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #b6ce94,#0d1410, 13-91 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #c9b0e4,#0d1410, 9-23 #e5eee5,#0d1410, 24-29 #c9b0e4,#0d1410, 30-30 #e5eee5,#0d1410, 31-32 #e9bf91,#0d1410, 33-35 #e5eee5,#0d1410, 36-91 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-9 #b6ce94,#0d1410, 10-91 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-91 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-30 #becfc4,#26362d, 31-39 #dfbce5,#26362d, 40-73 #becfc4,#26362d, 74-91 d,#26362d, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-21 #c9a7ed,#0d1410, 22-91 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-23 #b9f480,#0d1410, 24-28 #e5eee5,#0d1410, 29-36 #f8c082,#0d1410, 37-46 #e5eee5,#0d1410, 47-51 #b8d88a,#0d1410, 52-57 #e5eee5,#0d1410, 58-91 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-15 #c9a7ed,#0d1410, 16-27 #e5eee5,#0d1410, 28-31 #c9a7ed,#0d1410, 32-36 #e5eee5,#0d1410, 37-38 #f8c082,#0d1410, 39-91 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #b8d88a,#0d1410, 13-91 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #c9a7ed,#0d1410, 9-23 #e5eee5,#0d1410, 24-29 #c9a7ed,#0d1410, 30-30 #e5eee5,#0d1410, 31-32 #f8c082,#0d1410, 33-35 #e5eee5,#0d1410, 36-91 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-9 #b8d88a,#0d1410, 10-91 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, == snap markdown grid=92x25 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/markup/cwd/notes.md Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/markup/cwd/notes.md Save Tty Collapse Del TreeContext | 1 # Markdown heading with *italic* | 2 | 3 Prose with **bold**, *italic* and an `inline` span. @@ -51,27 +51,27 @@ | 8 == style markdown grid=92x25 |0: 0-70 #b2c3b8,#1d2824, 71-91 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-91 d,#26362d, -|2: 0-1 #000000,#adcc91, 2-59 #becfc4,#26362d, 60-91 d,#26362d, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-8 #e5eee5,#0d1410, 9-30 #c9b0e4,#0d1410, 31-38 #e9bf91,#0d1410, 39-91 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-25 #b9e58f,#0d1410, 26-27 #e5eee5,#0d1410, 28-35 #e9bf91,#0d1410, 36-43 #e5eee5,#0d1410, 44-51 #b6ce94,#0d1410, 52-57 #e5eee5,#0d1410, 58-91 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #b6ce94,#0d1410, 13-91 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #c9b0e4,#0d1410, 9-23 #e5eee5,#0d1410, 24-29 #c9b0e4,#0d1410, 30-30 #e5eee5,#0d1410, 31-32 #e9bf91,#0d1410, 33-35 #e5eee5,#0d1410, 36-91 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-9 #b6ce94,#0d1410, 10-91 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-91 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-30 #becfc4,#26362d, 31-38 #dfbce5,#26362d, 39-72 #becfc4,#26362d, 73-91 d,#26362d, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-8 #e5eee5,#0d1410, 9-30 #c9a7ed,#0d1410, 31-38 #f8c082,#0d1410, 39-91 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-25 #b9f480,#0d1410, 26-27 #e5eee5,#0d1410, 28-35 #f8c082,#0d1410, 36-43 #e5eee5,#0d1410, 44-51 #b8d88a,#0d1410, 52-57 #e5eee5,#0d1410, 58-91 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #b8d88a,#0d1410, 13-91 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #c9a7ed,#0d1410, 9-23 #e5eee5,#0d1410, 24-29 #c9a7ed,#0d1410, 30-30 #e5eee5,#0d1410, 31-32 #f8c082,#0d1410, 33-35 #e5eee5,#0d1410, 36-91 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-9 #b8d88a,#0d1410, 10-91 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-91 d,#0d1410, diff --git a/test/snapshots/mini.golden b/test/snapshots/mini.golden index aac5dee6..b915c60b 100644 --- a/test/snapshots/mini.golden +++ b/test/snapshots/mini.golden @@ -1,7 +1,8 @@ == snap opened grid=90x23 cursor=7,14 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del +| Mini | 1 @`Mini demo.zig` | | @@ -11,108 +12,118 @@ | | | -| -| /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Del Collapse +| /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del | 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ | 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ | 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ | 4 == style opened grid=90x23 |0: 0-70 #b2c3b8,#1d2824, 71-89 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-89 d,#26362d, -|2: 0-1 #ffffff,#4c6356, 2-61 #b2c3b8,#1d2824, 62-89 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-22 #e5eee5,#0d1410, 23-89 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|13: 0-1 #000000,#adcc91, 2-62 #becfc4,#26362d, 63-89 d,#26362d, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-8 #e5eee5,#0d1410, 9-9 #c9b0e4,#0d1410, 10-12 #e5eee5,#0d1410, 13-15 #c9b0e4,#0d1410, 16-21 #b6ce94,#0d1410, 22-22 #e5eee5,#0d1410, 23-89 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #b9e58f,#0d1410, 9-11 #c9b0e4,#0d1410, 12-25 #b9e58f,#0d1410, 26-89 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-89 d,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-89 d,#26362d, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-40 #d3b0d9,#1d2824, 41-62 #b2c3b8,#1d2824, 63-89 d,#1d2824, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-85 d,#1d2824, 86-89 #b2c3b8,#1d2824, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-22 #e5eee5,#0d1410, 23-89 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|13: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-28 #becfc4,#26362d, 29-41 #dfbce5,#26362d, 42-63 #becfc4,#26362d, 64-89 d,#26362d, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-8 #e5eee5,#0d1410, 9-9 #c9a7ed,#0d1410, 10-12 #e5eee5,#0d1410, 13-15 #c9a7ed,#0d1410, 16-21 #b8d88a,#0d1410, 22-22 #e5eee5,#0d1410, 23-89 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #b9f480,#0d1410, 9-11 #c9a7ed,#0d1410, 12-25 #b9f480,#0d1410, 26-89 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-89 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, == 9p opened grid=90x23 cursor=7,14,block |0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill @0: 0-70 #b2c3b8,#1d2824,,tagline 71-89 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol -@1: 0-24 #becfc4,#26362d,,tagline 25-89 d,#26362d,,tagline -|2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Del Collapse -@2: 0-1 #ffffff,#4c6356,,tagline 2-61 #b2c3b8,#1d2824,,tagline 62-89 d,#1d2824,,tagline -|3: 1 @`Mini demo.zig` -@3: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-22 #e5eee5,#0d1410,,body 23-89 d,#0d1410,,body -|4: -@4: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#26362d,,tagline 3-34 #becfc4,#26362d,,tagline 35-89 d,#26362d,,tagline +|2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del +@2: 0-1 #ffffff,#496656,,tagline 2-2 d,#1d2824,,tagline 3-28 #b2c3b8,#1d2824,,tagline 29-40 #d3b0d9,#1d2824,,tagline 41-62 #b2c3b8,#1d2824,,tagline 63-89 d,#1d2824,,tagline +|3: Mini +@3: 0-0 d,#152019,,body 1-1 d,#0d1410,,body 2-85 d,#1d2824,,tagline 86-89 #b2c3b8,#1d2824,,tagline +|4: 1 @`Mini demo.zig` +@4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-22 #e5eee5,#0d1410,,body 23-89 d,#0d1410,,body |5: -@5: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@5: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |6: -@6: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@6: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |7: -@7: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |8: -@8: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@8: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |9: -@9: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@9: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |10: -@10: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@10: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |11: -@11: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@11: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |12: -@12: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body -|13: /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Del Collapse -@13: 0-1 #000000,#adcc91,,tagline 2-62 #becfc4,#26362d,,tagline 63-89 d,#26362d,,tagline +@12: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +|13: /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del +@13: 0-1 #000000,#add38a,,tagline 2-2 d,#26362d,,tagline 3-28 #becfc4,#26362d,,tagline 29-41 #dfbce5,#26362d,,tagline 42-63 #becfc4,#26362d,,tagline 64-89 d,#26362d,,tagline |14: 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ +14: 7="⠭" 8="⠍" 9="⣥" 10="⢩" 11="⣭" 12="⡭" 13="⣭" 14="⣬" 15="⣌" 16="⢭" 17="⣭" 18="⠌" 19="⠬" 20="⠅" 21="⠍" 22="⠁" -@14: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-8 #e5eee5,#0d1410,,body 9-9 #c9b0e4,#0d1410,,body 10-12 #e5eee5,#0d1410,,body 13-15 #c9b0e4,#0d1410,,body 16-21 #b6ce94,#0d1410,,body 22-22 #e5eee5,#0d1410,,body 23-89 d,#0d1410,,body +@14: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-8 #e5eee5,#0d1410,,body 9-9 #c9a7ed,#0d1410,,body 10-12 #e5eee5,#0d1410,,body 13-15 #c9a7ed,#0d1410,,body 16-21 #b8d88a,#0d1410,,body 22-22 #e5eee5,#0d1410,,body 23-89 d,#0d1410,,body |15: 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ +15: 7="⣂" 8="⢀" 9="⣉" 10="⣉" 11="⢉" 12="⣈" 13="⢁" 14="⣀" 15="⣀" 16="⢀" 17="⣀" 18="⣀" 19="⣀" 20="⢀" 21="⣀" 22="⣀" 23="⣀" 24="⣀" 25="⣀" -@15: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-8 #b9e58f,#0d1410,,body 9-11 #c9b0e4,#0d1410,,body 12-25 #b9e58f,#0d1410,,body 26-89 d,#0d1410,,body +@15: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-8 #b9f480,#0d1410,,body 9-11 #c9a7ed,#0d1410,,body 12-25 #b9f480,#0d1410,,body 26-89 d,#0d1410,,body |16: 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ +16: 7="⠉" 8="⠉" 9="⠁" 10="⠉" 11="⠉" 12="⠉" 13="⠈" 14="⠈" 15="⠉" 16="⠉" 17="⠉" 18="⠉" 19="⠉" 20="⠉" -@16: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-17 #e5eee5,#0d1410,,body 18-19 #e9bf91,#0d1410,,body 20-20 #e5eee5,#0d1410,,body 21-89 d,#0d1410,,body +@16: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-17 #e5eee5,#0d1410,,body 18-19 #f8c082,#0d1410,,body 20-20 #e5eee5,#0d1410,,body 21-89 d,#0d1410,,body |17: 4 -@17: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@17: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |18: -@18: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@18: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |19: -@19: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@19: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |20: -@20: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@20: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |21: -@21: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@21: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |22: -@22: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@22: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body == style colors-off grid=90x23 -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-22 #e5eee5,#0d1410, 23-89 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-25 #e5eee5,#0d1410, 26-89 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-89 d,#0d1410, -== 9p colors-off grid=90x23 cursor=7,14,block -|14: 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ -+14: 7="⠭" 8="⠍" 9="⣥" 10="⢩" 11="⣭" 12="⡭" 13="⣭" 14="⣬" 15="⣌" 16="⢭" 17="⣭" 18="⠌" 19="⠬" 20="⠅" 21="⠍" 22="⠁" -@14: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-22 #e5eee5,#0d1410,,body 23-89 d,#0d1410,,body -|15: 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ -+15: 7="⣂" 8="⢀" 9="⣉" 10="⣉" 11="⢉" 12="⣈" 13="⢁" 14="⣀" 15="⣀" 16="⢀" 17="⣀" 18="⣀" 19="⣀" 20="⢀" 21="⣀" 22="⣀" 23="⣀" 24="⣀" 25="⣀" -@15: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-25 #e5eee5,#0d1410,,body 26-89 d,#0d1410,,body -|16: 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ -+16: 7="⠉" 8="⠉" 9="⠁" 10="⠉" 11="⠉" 12="⠉" 13="⠈" 14="⠈" 15="⠉" 16="⠉" 17="⠉" 18="⠉" 19="⠉" 20="⠉" -@16: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-20 #e5eee5,#0d1410,,body 21-89 d,#0d1410,,body +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-22 #e5eee5,#0d1410, 23-89 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-83 d,#1d2824, 84-89 #b2c3b8,#1d2824, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-22 #e5eee5,#0d1410, 23-89 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-25 #e5eee5,#0d1410, 26-89 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-89 d,#0d1410, +== 9p colors-off grid=90x23 cursor=7,15,block +|3: 1 @`Mini demo.zig` +@3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-22 #e5eee5,#0d1410,,body 23-89 d,#0d1410,,body +|4: +@4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +|14: Colors +@14: 0-0 d,#152019,,body 1-1 d,#0d1410,,body 2-83 d,#1d2824,,tagline 84-89 #b2c3b8,#1d2824,,tagline +|15: 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ ++15: 7="⠭" 8="⠍" 9="⣥" 10="⢩" 11="⣭" 12="⡭" 13="⣭" 14="⣬" 15="⣌" 16="⢭" 17="⣭" 18="⠌" 19="⠬" 20="⠅" 21="⠍" 22="⠁" +@15: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-22 #e5eee5,#0d1410,,body 23-89 d,#0d1410,,body +|16: 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ ++16: 7="⣂" 8="⢀" 9="⣉" 10="⣉" 11="⢉" 12="⣈" 13="⢁" 14="⣀" 15="⣀" 16="⢀" 17="⣀" 18="⣀" 19="⣀" 20="⢀" 21="⣀" 22="⣀" 23="⣀" 24="⣀" 25="⣀" +@16: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-25 #e5eee5,#0d1410,,body 26-89 d,#0d1410,,body +|17: 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ ++17: 7="⠉" 8="⠉" 9="⠁" 10="⠉" 11="⠉" 12="⠉" 13="⠈" 14="⠈" 15="⠉" 16="⠉" 17="⠉" 18="⠉" 19="⠉" 20="⠉" +@17: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-20 #e5eee5,#0d1410,,body 21-89 d,#0d1410,,body +|18: 4 +@18: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body == style colors-on grid=90x23 -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-8 #e5eee5,#0d1410, 9-9 #c9b0e4,#0d1410, 10-12 #e5eee5,#0d1410, 13-15 #c9b0e4,#0d1410, 16-21 #b6ce94,#0d1410, 22-22 #e5eee5,#0d1410, 23-89 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #b9e58f,#0d1410, 9-11 #c9b0e4,#0d1410, 12-25 #b9e58f,#0d1410, 26-89 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-89 d,#0d1410, -== snap resized grid=105x27 cursor=7,16 +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-8 #e5eee5,#0d1410, 9-9 #c9a7ed,#0d1410, 10-12 #e5eee5,#0d1410, 13-15 #c9a7ed,#0d1410, 16-21 #b8d88a,#0d1410, 22-22 #e5eee5,#0d1410, 23-89 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #b9f480,#0d1410, 9-11 #c9a7ed,#0d1410, 12-25 #b9f480,#0d1410, 26-89 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-89 d,#0d1410, +== snap resized grid=105x27 cursor=7,17 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del | 1 @`Mini demo.zig` | | @@ -125,66 +136,67 @@ | | | -| /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Del Collapse +| /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del +| Colors | 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ | 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ | 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ | 4 -== 9p resized grid=105x27 cursor=7,16,block +== 9p resized grid=105x27 cursor=7,17,block |0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill @0: 0-70 #b2c3b8,#1d2824,,tagline 71-104 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol -@1: 0-24 #becfc4,#26362d,,tagline 25-104 d,#26362d,,tagline -|2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Del Collapse -@2: 0-1 #ffffff,#4c6356,,tagline 2-61 #b2c3b8,#1d2824,,tagline 62-104 d,#1d2824,,tagline +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#26362d,,tagline 3-34 #becfc4,#26362d,,tagline 35-104 d,#26362d,,tagline +|2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del +@2: 0-1 #ffffff,#496656,,tagline 2-2 d,#1d2824,,tagline 3-28 #b2c3b8,#1d2824,,tagline 29-40 #d3b0d9,#1d2824,,tagline 41-62 #b2c3b8,#1d2824,,tagline 63-104 d,#1d2824,,tagline |3: 1 @`Mini demo.zig` -@3: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-22 #e5eee5,#0d1410,,body 23-104 d,#0d1410,,body +@3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-22 #e5eee5,#0d1410,,body 23-104 d,#0d1410,,body |4: -@4: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |5: -@5: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@5: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |6: -@6: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@6: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |7: -@7: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |8: -@8: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@8: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |9: -@9: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@9: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |10: -@10: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@10: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |11: -@11: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@11: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |12: -@12: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@12: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |13: -@13: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@13: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |14: -@14: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body -|15: /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Del Collapse -@15: 0-1 #000000,#adcc91,,tagline 2-62 #becfc4,#26362d,,tagline 63-104 d,#26362d,,tagline -|16: 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ -+16: 7="⠭" 8="⠍" 9="⣥" 10="⢩" 11="⣭" 12="⡭" 13="⣭" 14="⣬" 15="⣌" 16="⢭" 17="⣭" 18="⠌" 19="⠬" 20="⠅" 21="⠍" 22="⠁" -@16: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-8 #e5eee5,#0d1410,,body 9-9 #c9b0e4,#0d1410,,body 10-12 #e5eee5,#0d1410,,body 13-15 #c9b0e4,#0d1410,,body 16-21 #b6ce94,#0d1410,,body 22-22 #e5eee5,#0d1410,,body 23-104 d,#0d1410,,body -|17: 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ -+17: 7="⣂" 8="⢀" 9="⣉" 10="⣉" 11="⢉" 12="⣈" 13="⢁" 14="⣀" 15="⣀" 16="⢀" 17="⣀" 18="⣀" 19="⣀" 20="⢀" 21="⣀" 22="⣀" 23="⣀" 24="⣀" 25="⣀" -@17: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-8 #b9e58f,#0d1410,,body 9-11 #c9b0e4,#0d1410,,body 12-25 #b9e58f,#0d1410,,body 26-104 d,#0d1410,,body -|18: 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ -+18: 7="⠉" 8="⠉" 9="⠁" 10="⠉" 11="⠉" 12="⠉" 13="⠈" 14="⠈" 15="⠉" 16="⠉" 17="⠉" 18="⠉" 19="⠉" 20="⠉" -@18: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-17 #e5eee5,#0d1410,,body 18-19 #e9bf91,#0d1410,,body 20-20 #e5eee5,#0d1410,,body 21-104 d,#0d1410,,body -|19: 4 -@19: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body -|20: -@20: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@14: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +|15: /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del +@15: 0-1 #000000,#add38a,,tagline 2-2 d,#26362d,,tagline 3-28 #becfc4,#26362d,,tagline 29-41 #dfbce5,#26362d,,tagline 42-63 #becfc4,#26362d,,tagline 64-104 d,#26362d,,tagline +|16: Colors +@16: 0-0 d,#152019,,body 1-1 d,#0d1410,,body 2-98 d,#1d2824,,tagline 99-104 #b2c3b8,#1d2824,,tagline +|17: 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ ++17: 7="⠭" 8="⠍" 9="⣥" 10="⢩" 11="⣭" 12="⡭" 13="⣭" 14="⣬" 15="⣌" 16="⢭" 17="⣭" 18="⠌" 19="⠬" 20="⠅" 21="⠍" 22="⠁" +@17: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-8 #e5eee5,#0d1410,,body 9-9 #c9a7ed,#0d1410,,body 10-12 #e5eee5,#0d1410,,body 13-15 #c9a7ed,#0d1410,,body 16-21 #b8d88a,#0d1410,,body 22-22 #e5eee5,#0d1410,,body 23-104 d,#0d1410,,body +|18: 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ ++18: 7="⣂" 8="⢀" 9="⣉" 10="⣉" 11="⢉" 12="⣈" 13="⢁" 14="⣀" 15="⣀" 16="⢀" 17="⣀" 18="⣀" 19="⣀" 20="⢀" 21="⣀" 22="⣀" 23="⣀" 24="⣀" 25="⣀" +@18: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-8 #b9f480,#0d1410,,body 9-11 #c9a7ed,#0d1410,,body 12-25 #b9f480,#0d1410,,body 26-104 d,#0d1410,,body +|19: 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ ++19: 7="⠉" 8="⠉" 9="⠁" 10="⠉" 11="⠉" 12="⠉" 13="⠈" 14="⠈" 15="⠉" 16="⠉" 17="⠉" 18="⠉" 19="⠉" 20="⠉" +@19: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-17 #e5eee5,#0d1410,,body 18-19 #f8c082,#0d1410,,body 20-20 #e5eee5,#0d1410,,body 21-104 d,#0d1410,,body +|20: 4 +@20: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |21: -@21: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@21: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |22: -@22: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@22: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |23: -@23: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@23: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |24: -@24: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@24: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |25: -@25: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@25: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |26: -@26: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@26: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body diff --git a/test/snapshots/modal.golden b/test/snapshots/modal.golden index ca89416e..5f313dd3 100644 --- a/test/snapshots/modal.golden +++ b/test/snapshots/modal.golden @@ -1,7 +1,7 @@ == snap top grid=100x31 cursor=2,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/modal/cwd Save Tty Del Togglett /tmp/pardes-snap/modal/cwd Save Tty Del Togglett +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/modal/cwd Tty Save Mode Filter /tmp/pardes-snap/modal/cwd Tty Save Mode Filter | ls ls | words.txt words.txt | printf 'one two three\nfour five six\nseven ei @@ -16,54 +16,54 @@ | | | -| /tmp/pardes-snap/modal/cwd Save Tty Del Togglett +| /tmp/pardes-snap/modal/cwd Tty Save Mode Filter | ls | words.txt == snap moved grid=100x31 cursor=8,5 == snap xsel grid=100x31 cursor=48,5 == style xsel grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-49 d,#26362d, 50-74 #b2c3b8,#1d2824, 75-99 d,#1d2824, -|2: 0-1 #000000,#adcc91, 2-49 #becfc4,#26362d, 50-51 #ffffff,#4c6356, 52-99 #b2c3b8,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-48 #f5f7ee,#405d4b, 49-49 d,#0d1410, 50-50 d,#637f6a, 51-99 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-49 d,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-49 #b2c3b8,#1d2824, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-49 d,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-49 d,#26362d, 50-51 #ffffff,#887455, 52-52 d,#1d2824, 53-84 #b2c3b8,#1d2824, 85-99 d,#1d2824, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-29 #becfc4,#26362d, 30-32 #dfbce5,#26362d, 33-49 #becfc4,#26362d, 50-51 #ffffff,#496656, 52-52 d,#1d2824, 53-79 #b2c3b8,#1d2824, 80-82 #d3b0d9,#1d2824, 83-99 #b2c3b8,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-48 #f5f7ee,#3c614a, 49-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-29 #b2c3b8,#1d2824, 30-32 #d3b0d9,#1d2824, 33-49 #b2c3b8,#1d2824, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, == snap xsel2 grid=100x31 cursor=13,6 == snap yanked grid=100x31 cursor=13,6 == snap vsel grid=100x31 cursor=14,7 == style vsel grid=100x31 -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #f5f7ee,#405d4b, 50-50 d,#637f6a, 51-99 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #f5f7ee,#405d4b, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-14 #f5f7ee,#405d4b, 15-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -== snap typed grid=100x31 cursor=7,5 -|5: TYPEDprintf 'one two three\nfour five six\nseven -== snap undone grid=100x31 cursor=14,7 -|5: printf 'one two three\nfour five six\nseven ei -== snap redone grid=100x31 cursor=7,5 -|5: TYPEDprintf 'one two three\nfour five six\nseven -== snap bottom grid=100x31 cursor=2,10 +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #f5f7ee,#3c614a, 50-50 d,#608269, 51-99 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #f5f7ee,#3c614a, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #f5f7ee,#3c614a, 15-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +== snap typed grid=100x31 cursor=9,20 +|20: TYPED +== snap undone grid=100x31 cursor=4,20 +|20: +== snap redone grid=100x31 cursor=9,20 +|20: TYPED +== snap bottom grid=100x31 cursor=2,20 diff --git a/test/snapshots/msg.golden b/test/snapshots/msg.golden index 9da23117..197d01d9 100644 --- a/test/snapshots/msg.golden +++ b/test/snapshots/msg.golden @@ -1,7 +1,7 @@ == snap opened grid=70x15 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kil -|New Tty Find Grep Joincol -| /tmp/pardes-snap/msg/cwd/a.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -9,12 +9,20 @@ | 5 line 5 | 6 line 6 | 7 -== snap saved grid=70x15 cursor=7,3 -|14: --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt -== snap repainted grid=70x17 cursor=7,3 +== snap saved grid=70x15 cursor=7,4 +|3: --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt +|4: 1 line 1 +|5: 2 line 2 +|6: 3 line 3 +|7: 4 line 4 +|8: 5 line 5 +|9: 6 line 6 +|10: 7 +== snap repainted grid=70x17 cursor=7,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kil -|New Tty Find Grep Joincol -| /tmp/pardes-snap/msg/cwd/a.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del +| --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt | 1 line 1 | 2 line 2 | 3 line 3 @@ -22,35 +30,56 @@ | 5 line 5 | 6 line 6 | 7 -| -| -| -| -| -| -| --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt == snap keycleared grid=70x17 cursor=7,4 -|16: -== snap saved-again grid=70x17 cursor=7,4 -|16: --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt +|3: 1 line 1 +|4: 2 line 2 +|5: 3 line 3 +|6: 4 line 4 +|7: 5 line 5 +|8: 6 line 6 +|9: 7 +|10: +== snap saved-again grid=70x17 cursor=7,5 +|3: --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt +|4: 1 line 1 +|5: 2 line 2 +|6: 3 line 3 +|7: 4 line 4 +|8: 5 line 5 +|9: 6 line 6 +|10: 7 == snap mousecleared grid=70x17 cursor=7,4 -|16: -== snap reloaded grid=70x17 cursor=7,4 -|3: 1 EXTERNAL -|4: 2 -|5: +|3: 1 line 1 +|4: 2 line 2 +|5: 3 line 3 +|6: 4 line 4 +|7: 5 line 5 +|8: 6 line 6 +|9: 7 +|10: +== snap reloaded grid=70x17 cursor=7,5 +|3: --:--:-- reloaded /tmp/pardes-snap/msg/cwd/a.txt +|4: 1 EXTERNAL +|5: 2 |6: |7: |8: |9: -|16: --:--:-- reloaded /tmp/pardes-snap/msg/cwd/a.txt -== snap prompt grid=70x17 cursor=7,16 -|16: /EXT -== snap prompt-wins grid=70x17 cursor=7,16 -|3: 1 AGAIN +== snap prompt grid=70x17 cursor=69,3 +|3: /EXT +== snap prompt-wins grid=70x17 cursor=69,4 +|3: --:--:-- reloaded /tmp/pardes-snap/msg/cwd/a.txt +|4: /EXT +|5: 1 AGAIN +|6: 2 == snap esc grid=70x17 cursor=7,4 -|16: -== snap msgbuiltin grid=70x17 cursor=29,5 -|2: /tmp/pardes-snap/msg/cwd/a.txt * Save Tty Del Collapse -|5: 3 Msg hand-written report -|16: hand-written report +|3: 1 AGAIN +|4: 2 +|5: +|6: +== snap msgbuiltin grid=70x17 cursor=29,6 +|2: /tmp/pardes-snap/msg/cwd/a.txt * Save Tty Collapse Del +|3: hand-written report +|4: 1 AGAIN +|5: 2 +|6: 3 Msg hand-written report diff --git a/test/snapshots/multicursor.golden b/test/snapshots/multicursor.golden index da2ad1d7..7a602aab 100644 --- a/test/snapshots/multicursor.golden +++ b/test/snapshots/multicursor.golden @@ -1,11 +1,11 @@ == snap three-cursors grid=150x31 cursor=7,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/multicursor/cwd Save Tty Del Togglettymode Filter Collap /tmp/pardes-snap/multicursor/cwd Save Tty Del Togglettymode Filter Collap +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/multicursor/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/multicursor/cwd Tty Save Mode Filter Collapse Del | ls ls | f.txt f.txt | -| /tmp/pardes-snap/multicursor/cwd/f.txt Save Tty Del Collapse +| /tmp/pardes-snap/multicursor/cwd/f.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -16,53 +16,53 @@ | 8 line 8 | 9 line 9 | 10 line 10 -| /tmp/pardes-snap/multicursor/cwd Save Tty Del Togglettymode Filter Collap +| /tmp/pardes-snap/multicursor/cwd Tty Save Mode Filter Collapse Del | ls | f.txt == style three-cursors grid=150x31 |0: 0-70 #b2c3b8,#1d2824, 71-149 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-74 d,#26362d, 75-99 #b2c3b8,#1d2824, 100-149 d,#1d2824, -|2: 0-1 #ffffff,#4c6356, 2-74 #b2c3b8,#1d2824, 75-76 #ffffff,#4c6356, 77-149 #b2c3b8,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|6: 0-1 #000000,#adcc91, 2-61 #becfc4,#26362d, 62-74 d,#26362d, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #405d4b,#f5f7ee, 8-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #405d4b,#f5f7ee, 8-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-74 #b2c3b8,#1d2824, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-74 d,#26362d, 75-76 #ffffff,#887455, 77-77 d,#1d2824, 78-109 #b2c3b8,#1d2824, 110-149 d,#1d2824, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-35 #b2c3b8,#1d2824, 36-38 #d3b0d9,#1d2824, 39-68 #b2c3b8,#1d2824, 69-74 d,#1d2824, 75-76 #ffffff,#496656, 77-77 d,#1d2824, 78-110 #b2c3b8,#1d2824, 111-113 #d3b0d9,#1d2824, 114-143 #b2c3b8,#1d2824, 144-149 d,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-35 #becfc4,#26362d, 36-40 #dfbce5,#26362d, 41-62 #becfc4,#26362d, 63-74 d,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #3c614a,#f5f7ee, 8-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #3c614a,#f5f7ee, 8-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-13 #e5eee5,#0d1410, 14-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-35 #b2c3b8,#1d2824, 36-38 #d3b0d9,#1d2824, 39-68 #b2c3b8,#1d2824, 69-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, == snap edited-at-three grid=150x31 cursor=9,9 -|6: /tmp/pardes-snap/multicursor/cwd/f.txt * Save Tty Del Collapse +|6: /tmp/pardes-snap/multicursor/cwd/f.txt * Save Tty Collapse Del |7: 1 >>line 1 |8: 2 >>line 2 |9: 3 >>line 3 == snap three-selections grid=150x31 cursor=8,9 == style three-selections grid=150x31 -|6: 0-1 #000000,#adcc91, 2-63 #becfc4,#26362d, 64-74 d,#26362d, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #f5f7ee,#26382d, 8-8 #405d4b,#f5f7ee, 9-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #f5f7ee,#26382d, 8-8 #405d4b,#f5f7ee, 9-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-8 #f5f7ee,#405d4b, 9-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-35 #becfc4,#26362d, 36-40 #dfbce5,#26362d, 41-64 #becfc4,#26362d, 65-74 d,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #f5f7ee,#243a2d, 8-8 #3c614a,#f5f7ee, 9-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #f5f7ee,#243a2d, 8-8 #3c614a,#f5f7ee, 9-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-8 #f5f7ee,#3c614a, 9-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, == snap keep-primary grid=150x31 cursor=8,9 == style keep-primary grid=150x31 -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-14 #e5eee5,#0d1410, 15-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, diff --git a/test/snapshots/nested.golden b/test/snapshots/nested.golden index 68d0a69b..88b0854c 100644 --- a/test/snapshots/nested.golden +++ b/test/snapshots/nested.golden @@ -1,28 +1,79 @@ -== snap file-arg grid=100x31 cursor=7,6 +== snap file-arg grid=100x31 cursor=7,27 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|$ /tmp/pardes-snap/nested/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/nested/cwd Tty Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nested.txt | $ -| /tmp/pardes-snap/nested/cwd/nested.txt Save Tty Del Collapse +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| /+New Save Tty Collapse Del +| 1 +| +| +| +| /tmp/pardes-snap/nested/cwd/nested.txt Save Tty Collapse Del | 1 hello-from-nested | 2 second-nested-line | 3 == snap no-arg grid=100x31 cursor=4,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|$ /tmp/pardes-snap/nested/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/nested/cwd Tty Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) | pardes: this shell is already inside pardes, and a pardes inside a pardes | is spicy. Name a file or a directory and the outer session opens it, or | pass --nested if you really want a second one in here. | $ +| +| +| +| +| +| +| +| +| +| +| +| +| +| /+New Save Tty Collapse Del +| 1 == snap dir-arg grid=100x31 cursor=4,8 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|$ /tmp/pardes-snap/nested/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/nested/cwd Tty Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nestdir | $ -| /tmp/pardes-snap/nested/cwd/nestdir Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/nested/cwd/nestdir Tty Save Mode Filter Collapse Del | ls | inside-nested.txt +| +| +| +| +| +| +| +| +| +| +| +| +| +| /+New Save Tty Collapse Del +| 1 diff --git a/test/snapshots/ninep.golden b/test/snapshots/ninep.golden index 94ad4bcf..b501004e 100644 --- a/test/snapshots/ninep.golden +++ b/test/snapshots/ninep.golden @@ -1,7 +1,7 @@ == snap opened grid=90x15 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext | 1 const greeting = "café λ 界 é"; | 2 | 3 pub fn choose(ok: bool) u32 { @@ -11,69 +11,80 @@ | 7 == style opened grid=90x15 |0: 0-70 #b2c3b8,#1d2824, 71-89 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-89 d,#26362d, -|2: 0-1 #000000,#adcc91, 2-58 #becfc4,#26362d, 59-89 d,#26362d, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b6ce94,#0d1410, 33-33 d,d, 34-36 #b6ce94,#0d1410, 37-37 #e5eee5,#0d1410, 38-89 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-35 #e5eee5,#0d1410, 36-89 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-18 #e5eee5,#0d1410, 19-24 #c9b0e4,#0d1410, 25-25 #e5eee5,#0d1410, 26-27 #e9bf91,#0d1410, 28-28 #e5eee5,#0d1410, 29-89 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9b0e4,#0d1410, 17-17 #e5eee5,#0d1410, 18-18 #e9bf91,#0d1410, 19-19 #e5eee5,#0d1410, 20-89 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-89 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-89 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-29 #becfc4,#26362d, 30-37 #dfbce5,#26362d, 38-71 #becfc4,#26362d, 72-89 d,#26362d, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b8d88a,#0d1410, 33-33 d,d, 34-36 #b8d88a,#0d1410, 37-37 #e5eee5,#0d1410, 38-89 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-35 #e5eee5,#0d1410, 36-89 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-18 #e5eee5,#0d1410, 19-24 #c9a7ed,#0d1410, 25-25 #e5eee5,#0d1410, 26-27 #f8c082,#0d1410, 28-28 #e5eee5,#0d1410, 29-89 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9a7ed,#0d1410, 17-17 #e5eee5,#0d1410, 18-18 #f8c082,#0d1410, 19-19 #e5eee5,#0d1410, 20-89 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-89 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, == 9p opened grid=90x15 cursor=7,3,block |0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill @0: 0-70 #b2c3b8,#1d2824,,tagline 71-89 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol -@1: 0-24 #becfc4,#26362d,,tagline 25-89 d,#26362d,,tagline -|2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Del Collapse -@2: 0-1 #000000,#adcc91,,tagline 2-58 #becfc4,#26362d,,tagline 59-89 d,#26362d,,tagline +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#26362d,,tagline 3-34 #becfc4,#26362d,,tagline 35-89 d,#26362d,,tagline +|2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext +@2: 0-1 #000000,#add38a,,tagline 2-2 d,#26362d,,tagline 3-29 #becfc4,#26362d,,tagline 30-37 #dfbce5,#26362d,,tagline 38-71 #becfc4,#26362d,,tagline 72-89 d,#26362d,,tagline |3: 1 const greeting = "café λ 界 é"; +3: 28="é" 30="λ" 32="界" 33="" 35="é" -@3: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b6ce94,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body +@3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b8d88a,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body |4: 2 -@4: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |5: 3 pub fn choose(ok: bool) u32 { -@5: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9b0e4,#0d1410,,body 13-35 #e5eee5,#0d1410,,body 36-89 d,#0d1410,,body +@5: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9a7ed,#0d1410,,body 13-35 #e5eee5,#0d1410,,body 36-89 d,#0d1410,,body |6: 4 if (ok) return 42; -@6: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9b0e4,#0d1410,,body 13-18 #e5eee5,#0d1410,,body 19-24 #c9b0e4,#0d1410,,body 25-25 #e5eee5,#0d1410,,body 26-27 #e9bf91,#0d1410,,body 28-28 #e5eee5,#0d1410,,body 29-89 d,#0d1410,,body +@6: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9a7ed,#0d1410,,body 13-18 #e5eee5,#0d1410,,body 19-24 #c9a7ed,#0d1410,,body 25-25 #e5eee5,#0d1410,,body 26-27 #f8c082,#0d1410,,body 28-28 #e5eee5,#0d1410,,body 29-89 d,#0d1410,,body |7: 5 return 7; -@7: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-16 #c9b0e4,#0d1410,,body 17-17 #e5eee5,#0d1410,,body 18-18 #e9bf91,#0d1410,,body 19-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body +@7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-16 #c9a7ed,#0d1410,,body 17-17 #e5eee5,#0d1410,,body 18-18 #f8c082,#0d1410,,body 19-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body |8: 6 } -@8: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-7 #e5eee5,#0d1410,,body 8-89 d,#0d1410,,body +@8: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-7 #e5eee5,#0d1410,,body 8-89 d,#0d1410,,body |9: 7 -@9: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@9: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |10: -@10: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@10: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |11: -@11: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@11: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |12: -@12: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@12: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |13: -@13: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@13: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |14: -@14: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@14: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body == style colors-off grid=90x15 -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-32 #e5eee5,#0d1410, 33-33 d,d, 34-37 #e5eee5,#0d1410, 38-89 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-35 #e5eee5,#0d1410, 36-89 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-28 #e5eee5,#0d1410, 29-89 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-89 d,#0d1410, -== 9p colors-off grid=90x15 cursor=7,3,block -|3: 1 const greeting = "café λ 界 é"; -+3: 28="é" 30="λ" 32="界" 33="" 35="é" -@3: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body -|5: 3 pub fn choose(ok: bool) u32 { -@5: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-35 #e5eee5,#0d1410,,body 36-89 d,#0d1410,,body -|6: 4 if (ok) return 42; -@6: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-28 #e5eee5,#0d1410,,body 29-89 d,#0d1410,,body -|7: 5 return 7; -@7: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-83 d,#1d2824, 84-89 #b2c3b8,#1d2824, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-32 #e5eee5,#0d1410, 33-33 d,d, 34-37 #e5eee5,#0d1410, 38-89 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-35 #e5eee5,#0d1410, 36-89 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-28 #e5eee5,#0d1410, 29-89 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-89 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-89 d,#0d1410, +== 9p colors-off grid=90x15 cursor=7,4,block +|3: Colors +@3: 0-0 d,#152019,,body 1-1 d,#0d1410,,body 2-83 d,#1d2824,,tagline 84-89 #b2c3b8,#1d2824,,tagline +|4: 1 const greeting = "café λ 界 é"; ++4: 28="é" 30="λ" 32="界" 33="" 35="é" +@4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body +|5: 2 +@5: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +|6: 3 pub fn choose(ok: bool) u32 { +@6: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-35 #e5eee5,#0d1410,,body 36-89 d,#0d1410,,body +|7: 4 if (ok) return 42; +@7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-28 #e5eee5,#0d1410,,body 29-89 d,#0d1410,,body +|8: 5 return 7; +@8: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body +|9: 6 } +@9: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-7 #e5eee5,#0d1410,,body 8-89 d,#0d1410,,body +|10: 7 +@10: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body == snap edited-with-colors-off grid=90x15 cursor=7,4 -|2: /tmp/pardes-snap/ninep/cwd/demo.zig * Save Tty Del Collapse +|2: /tmp/pardes-snap/ninep/cwd/demo.zig * Save Tty Collapse Del TreeContext |3: 1 // café λ 界 |4: 2 const greeting = "café λ 界 é"; |5: 3 @@ -83,116 +94,125 @@ |9: 7 } |10: 8 == 9p edited-with-colors-off grid=90x15 cursor=7,4,block -|2: /tmp/pardes-snap/ninep/cwd/demo.zig * Save Tty Del Collapse -@2: 0-1 #000000,#adcc91,,tagline 2-60 #becfc4,#26362d,,tagline 61-89 d,#26362d,,tagline +|2: /tmp/pardes-snap/ninep/cwd/demo.zig * Save Tty Collapse Del TreeContext +@2: 0-1 #000000,#add38a,,tagline 2-2 d,#26362d,,tagline 3-29 #becfc4,#26362d,,tagline 30-37 #dfbce5,#26362d,,tagline 38-73 #becfc4,#26362d,,tagline 74-89 d,#26362d,,tagline |3: 1 // café λ 界 +3: 13="é" 15="λ" 17="界" 18="" -@3: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #e5eee5,#0d1410,,body 19-89 d,#0d1410,,body +@3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #e5eee5,#0d1410,,body 19-89 d,#0d1410,,body |4: 2 const greeting = "café λ 界 é"; +4: 28="é" 30="λ" 32="界" 33="" 35="é" -@4: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body +@4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body |5: 3 -@5: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@5: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body |6: 4 pub fn choose(ok: bool) u32 { -@6: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-35 #e5eee5,#0d1410,,body 36-89 d,#0d1410,,body +@6: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-35 #e5eee5,#0d1410,,body 36-89 d,#0d1410,,body |7: 5 if (ok) return 42; -@7: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-28 #e5eee5,#0d1410,,body 29-89 d,#0d1410,,body +@7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-28 #e5eee5,#0d1410,,body 29-89 d,#0d1410,,body |8: 6 return 7; -@8: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body +@8: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body |9: 7 } -@9: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-7 #e5eee5,#0d1410,,body 8-89 d,#0d1410,,body +@9: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-7 #e5eee5,#0d1410,,body 8-89 d,#0d1410,,body |10: 8 -@10: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +@10: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body == style colors-on grid=90x15 -|2: 0-1 #000000,#adcc91, 2-60 #becfc4,#26362d, 61-89 d,#26362d, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #b9e58f,#0d1410, 18-18 d,d, 19-89 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b6ce94,#0d1410, 33-33 d,d, 34-36 #b6ce94,#0d1410, 37-37 #e5eee5,#0d1410, 38-89 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-35 #e5eee5,#0d1410, 36-89 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-18 #e5eee5,#0d1410, 19-24 #c9b0e4,#0d1410, 25-25 #e5eee5,#0d1410, 26-27 #e9bf91,#0d1410, 28-28 #e5eee5,#0d1410, 29-89 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9b0e4,#0d1410, 17-17 #e5eee5,#0d1410, 18-18 #e9bf91,#0d1410, 19-19 #e5eee5,#0d1410, 20-89 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-89 d,#0d1410, -== 9p colors-on grid=90x15 cursor=7,4,block -|3: 1 // café λ 界 -+3: 13="é" 15="λ" 17="界" 18="" -@3: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #b9e58f,#0d1410,,body 19-89 d,#0d1410,,body -|4: 2 const greeting = "café λ 界 é"; -+4: 28="é" 30="λ" 32="界" 33="" 35="é" -@4: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b6ce94,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body -|6: 4 pub fn choose(ok: bool) u32 { -@6: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9b0e4,#0d1410,,body 13-35 #e5eee5,#0d1410,,body 36-89 d,#0d1410,,body -|7: 5 if (ok) return 42; -@7: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9b0e4,#0d1410,,body 13-18 #e5eee5,#0d1410,,body 19-24 #c9b0e4,#0d1410,,body 25-25 #e5eee5,#0d1410,,body 26-27 #e9bf91,#0d1410,,body 28-28 #e5eee5,#0d1410,,body 29-89 d,#0d1410,,body -|8: 6 return 7; -@8: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-16 #c9b0e4,#0d1410,,body 17-17 #e5eee5,#0d1410,,body 18-18 #e9bf91,#0d1410,,body 19-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-29 #becfc4,#26362d, 30-37 #dfbce5,#26362d, 38-73 #becfc4,#26362d, 74-89 d,#26362d, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #b9f480,#0d1410, 18-18 d,d, 19-89 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b8d88a,#0d1410, 33-33 d,d, 34-36 #b8d88a,#0d1410, 37-37 #e5eee5,#0d1410, 38-89 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-89 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-35 #e5eee5,#0d1410, 36-89 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-18 #e5eee5,#0d1410, 19-24 #c9a7ed,#0d1410, 25-25 #e5eee5,#0d1410, 26-27 #f8c082,#0d1410, 28-28 #e5eee5,#0d1410, 29-89 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9a7ed,#0d1410, 17-17 #e5eee5,#0d1410, 18-18 #f8c082,#0d1410, 19-19 #e5eee5,#0d1410, 20-89 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-89 d,#0d1410, +== 9p colors-on grid=90x15 cursor=7,5,block +|3: Colors +@3: 0-0 d,#152019,,body 1-1 d,#0d1410,,body 2-83 d,#1d2824,,tagline 84-89 #b2c3b8,#1d2824,,tagline +|4: 1 // café λ 界 ++4: 13="é" 15="λ" 17="界" 18="" +@4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #b9f480,#0d1410,,body 19-89 d,#0d1410,,body +|5: 2 const greeting = "café λ 界 é"; ++5: 28="é" 30="λ" 32="界" 33="" 35="é" +@5: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b8d88a,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body +|6: 3 +@6: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body +|7: 4 pub fn choose(ok: bool) u32 { +@7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9a7ed,#0d1410,,body 13-35 #e5eee5,#0d1410,,body 36-89 d,#0d1410,,body +|8: 5 if (ok) return 42; +@8: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9a7ed,#0d1410,,body 13-18 #e5eee5,#0d1410,,body 19-24 #c9a7ed,#0d1410,,body 25-25 #e5eee5,#0d1410,,body 26-27 #f8c082,#0d1410,,body 28-28 #e5eee5,#0d1410,,body 29-89 d,#0d1410,,body +|9: 6 return 7; +@9: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-16 #c9a7ed,#0d1410,,body 17-17 #e5eee5,#0d1410,,body 18-18 #f8c082,#0d1410,,body 19-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body +|10: 7 } +@10: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-7 #e5eee5,#0d1410,,body 8-89 d,#0d1410,,body +|11: 8 +@11: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body == style resized grid=105x20 |0: 0-70 #b2c3b8,#1d2824, 71-104 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-104 d,#26362d, -|2: 0-1 #000000,#adcc91, 2-60 #becfc4,#26362d, 61-104 d,#26362d, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #b9e58f,#0d1410, 18-18 d,d, 19-104 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b6ce94,#0d1410, 33-33 d,d, 34-36 #b6ce94,#0d1410, 37-37 #e5eee5,#0d1410, 38-104 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-35 #e5eee5,#0d1410, 36-104 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-18 #e5eee5,#0d1410, 19-24 #c9b0e4,#0d1410, 25-25 #e5eee5,#0d1410, 26-27 #e9bf91,#0d1410, 28-28 #e5eee5,#0d1410, 29-104 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9b0e4,#0d1410, 17-17 #e5eee5,#0d1410, 18-18 #e9bf91,#0d1410, 19-19 #e5eee5,#0d1410, 20-104 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-104 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, -== 9p resized grid=105x20 cursor=7,4,block +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-104 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-29 #becfc4,#26362d, 30-37 #dfbce5,#26362d, 38-73 #becfc4,#26362d, 74-104 d,#26362d, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-98 d,#1d2824, 99-104 #b2c3b8,#1d2824, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-17 #b9f480,#0d1410, 18-18 d,d, 19-104 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b8d88a,#0d1410, 33-33 d,d, 34-36 #b8d88a,#0d1410, 37-37 #e5eee5,#0d1410, 38-104 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-35 #e5eee5,#0d1410, 36-104 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-18 #e5eee5,#0d1410, 19-24 #c9a7ed,#0d1410, 25-25 #e5eee5,#0d1410, 26-27 #f8c082,#0d1410, 28-28 #e5eee5,#0d1410, 29-104 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-16 #c9a7ed,#0d1410, 17-17 #e5eee5,#0d1410, 18-18 #f8c082,#0d1410, 19-19 #e5eee5,#0d1410, 20-104 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-104 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-104 d,#0d1410, +== 9p resized grid=105x20 cursor=7,5,block |0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill @0: 0-70 #b2c3b8,#1d2824,,tagline 71-104 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol -@1: 0-24 #becfc4,#26362d,,tagline 25-104 d,#26362d,,tagline -|2: /tmp/pardes-snap/ninep/cwd/demo.zig * Save Tty Del Collapse -@2: 0-1 #000000,#adcc91,,tagline 2-60 #becfc4,#26362d,,tagline 61-104 d,#26362d,,tagline -|3: 1 // café λ 界 -+3: 13="é" 15="λ" 17="界" 18="" -@3: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #b9e58f,#0d1410,,body 19-104 d,#0d1410,,body -|4: 2 const greeting = "café λ 界 é"; -+4: 28="é" 30="λ" 32="界" 33="" 35="é" -@4: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b6ce94,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-104 d,#0d1410,,body -|5: 3 -@5: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body -|6: 4 pub fn choose(ok: bool) u32 { -@6: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9b0e4,#0d1410,,body 13-35 #e5eee5,#0d1410,,body 36-104 d,#0d1410,,body -|7: 5 if (ok) return 42; -@7: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9b0e4,#0d1410,,body 13-18 #e5eee5,#0d1410,,body 19-24 #c9b0e4,#0d1410,,body 25-25 #e5eee5,#0d1410,,body 26-27 #e9bf91,#0d1410,,body 28-28 #e5eee5,#0d1410,,body 29-104 d,#0d1410,,body -|8: 6 return 7; -@8: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-16 #c9b0e4,#0d1410,,body 17-17 #e5eee5,#0d1410,,body 18-18 #e9bf91,#0d1410,,body 19-19 #e5eee5,#0d1410,,body 20-104 d,#0d1410,,body -|9: 7 } -@9: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-7 #e5eee5,#0d1410,,body 8-104 d,#0d1410,,body -|10: 8 -@10: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body -|11: -@11: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#26362d,,tagline 3-34 #becfc4,#26362d,,tagline 35-104 d,#26362d,,tagline +|2: /tmp/pardes-snap/ninep/cwd/demo.zig * Save Tty Collapse Del TreeContext +@2: 0-1 #000000,#add38a,,tagline 2-2 d,#26362d,,tagline 3-29 #becfc4,#26362d,,tagline 30-37 #dfbce5,#26362d,,tagline 38-73 #becfc4,#26362d,,tagline 74-104 d,#26362d,,tagline +|3: Colors +@3: 0-0 d,#152019,,body 1-1 d,#0d1410,,body 2-98 d,#1d2824,,tagline 99-104 #b2c3b8,#1d2824,,tagline +|4: 1 // café λ 界 ++4: 13="é" 15="λ" 17="界" 18="" +@4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #b9f480,#0d1410,,body 19-104 d,#0d1410,,body +|5: 2 const greeting = "café λ 界 é"; ++5: 28="é" 30="λ" 32="界" 33="" 35="é" +@5: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b8d88a,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-104 d,#0d1410,,body +|6: 3 +@6: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +|7: 4 pub fn choose(ok: bool) u32 { +@7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9a7ed,#0d1410,,body 13-35 #e5eee5,#0d1410,,body 36-104 d,#0d1410,,body +|8: 5 if (ok) return 42; +@8: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-12 #c9a7ed,#0d1410,,body 13-18 #e5eee5,#0d1410,,body 19-24 #c9a7ed,#0d1410,,body 25-25 #e5eee5,#0d1410,,body 26-27 #f8c082,#0d1410,,body 28-28 #e5eee5,#0d1410,,body 29-104 d,#0d1410,,body +|9: 6 return 7; +@9: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-16 #c9a7ed,#0d1410,,body 17-17 #e5eee5,#0d1410,,body 18-18 #f8c082,#0d1410,,body 19-19 #e5eee5,#0d1410,,body 20-104 d,#0d1410,,body +|10: 7 } +@10: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-7 #e5eee5,#0d1410,,body 8-104 d,#0d1410,,body +|11: 8 +@11: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |12: -@12: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@12: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |13: -@13: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@13: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |14: -@14: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@14: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |15: -@15: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@15: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |16: -@16: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@16: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |17: -@17: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@17: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |18: -@18: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +@18: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |19: -@19: 0-0 d,#637f6a,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body -== snap resized grid=105x20 cursor=7,4 +@19: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body +== snap resized grid=105x20 cursor=7,5 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/ninep/cwd/demo.zig * Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/ninep/cwd/demo.zig * Save Tty Collapse Del TreeContext +| Colors | 1 // café λ 界 | 2 const greeting = "café λ 界 é"; | 3 @@ -201,4 +221,4 @@ | 6 return 7; | 7 } | 8 -== 9p unchanged grid=105x20 cursor=7,4,block +== 9p unchanged grid=105x20 cursor=7,5,block diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index e6d558a6..d3f6bbc2 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -1,20 +1,14 @@ -== snap prompt grid=180x13 cursor=14,12 +== snap prompt grid=180x13 cursor=179,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del +| |tr a-z A-Z | 1 alpha beta | 2 gamma delta -| -| -| -| -| -| -| -| |tr a-z A-Z == snap filtered grid=180x13 cursor=17,3 -|2: /tmp/pardes-snap/pipe/cwd/pipe.txt * Save Tty Del Collapse +|2: /tmp/pardes-snap/pipe/cwd/pipe.txt * Save Tty Collapse Del |3: 1 ALPHA BETA -|12: +|4: 2 gamma delta +|5: == snap undone grid=180x13 cursor=17,3 |3: 1 alpha beta diff --git a/test/snapshots/psearch.golden b/test/snapshots/psearch.golden index d1a28996..b0827d7c 100644 --- a/test/snapshots/psearch.golden +++ b/test/snapshots/psearch.golden @@ -1,62 +1,104 @@ == snap output grid=140x31 cursor=4,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/psearch/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/psearch/cwd Tty Save Mode Filter Collapse Del | printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' | x MARK a | zz | x MARK b | zz | x MARK c -== snap typing grid=140x31 cursor=8,30 -|30: /MARK +| +| +| +| +| +| +| +| +| +| +| +| +| /+New Save Tty Collapse Del +| 1 +== snap typing grid=140x31 cursor=139,3 +|3: /MARK +|4: printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' +|5: x MARK a +|6: zz +|7: x MARK b +|8: zz +|9: x MARK c == snap results grid=140x31 cursor=7,4 -|27: /tmp/pardes-snap/psearch/cwd/+Search Save Tty Del Collapse -|28: 1 @p0:2:3-6 x MARK a -|29: 2 @p0:4:3-6 x MARK b -|30: 3 @p0:6:3-6 x MARK c +|3: printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' +|4: x MARK a +|5: zz +|6: x MARK b +|7: zz +|8: x MARK c +|9: +|14: /tmp/pardes-snap/psearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|15: Look +|16: 1 @p0:2:3-6 +|17: 2 x MARK a +|18: 3 @p0:4:3-6 +|19: 4 x MARK b +|20: 5 @p0:6:3-6 == style results grid=140x31 |0: 0-70 #b2c3b8,#1d2824, 71-139 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-139 d,#26362d, -|2: 0-1 #000000,#adcc91, 2-72 #becfc4,#26362d, 73-139 d,#26362d, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-3 #e5eee5,#0d1410, 4-7 #f5f7ee,#405d4b, 8-139 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-139 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, -|27: 0-1 #ffffff,#4c6356, 2-59 #b2c3b8,#1d2824, 60-139 d,#1d2824, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-18 #e5eee5,#0d1410, 19-22 #f7e4a5,#57472a, 23-24 #e5eee5,#0d1410, 25-139 d,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-18 #e5eee5,#0d1410, 19-22 #f7e4a5,#57472a, 23-24 #e5eee5,#0d1410, 25-139 d,#0d1410, -|30: 0-0 d,#152019, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-18 #e5eee5,#0d1410, 19-22 #f7e4a5,#57472a, 23-24 #e5eee5,#0d1410, 25-139 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-139 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-31 #becfc4,#26362d, 32-34 #dfbce5,#26362d, 35-64 #becfc4,#26362d, 65-139 d,#26362d, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-3 #e5eee5,#0d1410, 4-7 #f5f7ee,#3c614a, 8-139 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-139 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, +|14: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-38 #d3b0d9,#1d2824, 39-76 #b2c3b8,#1d2824, 77-139 d,#1d2824, +|15: 0-0 d,#152019, 1-1 d,#0d1410, 2-135 d,#1d2824, 136-139 #b2c3b8,#1d2824, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-139 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-12 #f7e4a5,#5e4923, 13-14 #e5eee5,#0d1410, 15-139 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-139 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-12 #f7e4a5,#5e4923, 13-14 #e5eee5,#0d1410, 15-139 d,#0d1410, +|20: 0-0 d,#152019, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-139 d,#0d1410, +|21: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-3 #b2c3b8,#1d2824, 4-7 #d3b0d9,#1d2824, 8-29 #b2c3b8,#1d2824, 30-139 d,#1d2824, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-139 d,#0d1410, == snap second grid=140x31 cursor=7,6 == snap back grid=140x31 cursor=7,4 -== snap nomatch grid=140x31 cursor=7,29 -|25: /tmp/pardes-snap/psearch/cwd/+Search Save Tty Del Collapse -|26: 1 -== snap ttyinert grid=140x31 cursor=4,9 -|2: $ /tmp/pardes-snap/psearch/cwd Save Tty Del Togglettymode Filter Collapse -|3: $ printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' -|9: $ -== snap rightsearch grid=140x31 cursor=7,6 -|2: /tmp/pardes-snap/psearch/cwd Save Tty Del Togglettymode Filter Collapse -|3: printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' -|9: +== snap nomatch grid=140x31 cursor=7,17 +|12: /tmp/pardes-snap/psearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|13: 1 +|15: 1 @p0:2:3-6 +|16: 2 x MARK a +|17: 3 @p0:4:3-6 +|18: 4 x MARK b +|19: 5 @p0:6:3-6 +|20: 6 x MARK c +== snap ttyinert grid=140x31 cursor=4,10 +|2: $ /tmp/pardes-snap/psearch/cwd Tty Save Mode Filter Collapse Del +|3: Look +|4: $ printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' +|5: x MARK a +|6: zz +|7: x MARK b +|8: zz +|9: x MARK c +|10: $ +== snap rightsearch grid=140x31 cursor=7,7 +|2: /tmp/pardes-snap/psearch/cwd Tty Save Mode Filter Collapse Del +|4: printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' +|10: diff --git a/test/snapshots/reflow.golden b/test/snapshots/reflow.golden index 3c2f5ff4..a13b5936 100644 --- a/test/snapshots/reflow.golden +++ b/test/snapshots/reflow.golden @@ -1,11 +1,7 @@ -== snap widened grid=200x25 cursor=4,20 +== snap widened grid=200x25 cursor=4,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -|$ /tmp/pardes-snap/reflow/cwd Save Tty Del Togglettymode Filter Collapse -| $ printf 'y%.0s' $(seq 1 3000); echo do''ne -| yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy -| yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy -| yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/reflow/cwd Tty Save Mode Filter Collapse Del | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy @@ -20,3 +16,5 @@ | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyydone | $ +| /+New Save Tty Collapse Del +| 1 diff --git a/test/snapshots/respawn.golden b/test/snapshots/respawn.golden index 9aa6b46b..e2b6a75c 100644 --- a/test/snapshots/respawn.golden +++ b/test/snapshots/respawn.golden @@ -1,10 +1,10 @@ -== snap respawn grid=100x31 cursor=4,9 +== snap respawn grid=140x31 cursor=4,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/respawn/cwd Save Tty Del Toggle /tmp/pardes-snap/respawn/cwd Save Tty Del Toggle -| ls ls +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/respawn/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/respawn/cwd Tty Save Mode Filter Collapse Del +| ls ls | -|$ /tmp/pardes-snap/respawn/cwd Save Tty Del Toggle +|$ /tmp/pardes-snap/respawn/cwd Tty Save Mode Filter Collapse Del | $ ls | $ echo RESP''AWNOK | RESPAWNOK diff --git a/test/snapshots/respawn.snap b/test/snapshots/respawn.snap index 66393da9..eac74267 100644 --- a/test/snapshots/respawn.snap +++ b/test/snapshots/respawn.snap @@ -1,7 +1,7 @@ # a deleted shell pane's pty lingers in its slot (there is no close effect); # a later spawn reusing the pane id must reap it instead of tripping the # drainEffects spawn assert — this exact sequence crashed pre-fix -start 31 100 -n 3 +start 31 140 -n 3 wait 8000 Newcol Joincol stable 700 20000 # middle-click Del on the lower-left pane's tag: the pane id is freed while diff --git a/test/snapshots/restore.golden b/test/snapshots/restore.golden index d2a60c4a..11d92288 100644 --- a/test/snapshots/restore.golden +++ b/test/snapshots/restore.golden @@ -1,14 +1,14 @@ == snap dumped grid=100x31 cursor=4,6 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill Restore /tmp/pardes-snap/res -|New Tty Find Grep Joincol -|$ /tmp/pardes-snap/restore/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/restore/cwd Tty Save Mode Filter Collapse Del | $ ls | $ echo KEEP''ME | KEEPME | $ == snap restored grid=100x31 cursor=4,6 |0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|2: /tmp/pardes-snap/restore/cwd Save Tty Del Togglettymode Filter Collapse +|2: /tmp/pardes-snap/restore/cwd Tty Save Mode Filter Collapse Del |3: ls |4: echo KEEP''ME |6: diff --git a/test/snapshots/rsearch.golden b/test/snapshots/rsearch.golden index f0bc0594..9b1f12d4 100644 --- a/test/snapshots/rsearch.golden +++ b/test/snapshots/rsearch.golden @@ -1,7 +1,7 @@ == snap opened grid=210x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/rsearch/cwd/code.txt Save Tty Del Collapse /tmp/pardes-snap/rsearch/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/rsearch/cwd/code.txt Save Tty Collapse Del /tmp/pardes-snap/rsearch/cwd Tty Save Mode Filter Collapse Del | 1 run count_x now ls | 2 open sub/dep.txt:3 here code.txt sub | 3 count_x again @@ -9,24 +9,28 @@ | | code.txt == snap search grid=210x31 cursor=13,5 -|28: /tmp/pardes-snap/rsearch/cwd/+Search Save Tty Del Collapse -|29: 1 code.txt:1:5-11 run count_x now -|30: 2 code.txt:3:1-7 count_x again +|26: /tmp/pardes-snap/rsearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|27: 1 code.txt:1:5-11 +|28: 2 run count_x now +|29: 3 code.txt:3:1-7 +|30: 4 count_x again == snap select grid=210x31 cursor=14,6 -|26: /tmp/pardes-snap/rsearch/cwd/+Search Save Tty Del Collapse -|27: 1 code.txt:4:1-8 pick two words -== snap path-open grid=210x31 cursor=7,17 -|14: /tmp/pardes-snap/rsearch/cwd/sub/dep.txt Save Tty Del Collapse -|15: 1 d1 -|16: 2 d2 -|17: 3 DEPTARGET -|18: 4 d4 -|19: 5 d5 -|20: 6 d6 +|23: /tmp/pardes-snap/rsearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|24: 1 code.txt:4:1-8 +|25: 2 pick two words +== snap path-open grid=210x31 cursor=7,16 +|13: /tmp/pardes-snap/rsearch/cwd/sub/dep.txt Save Tty Collapse Del +|14: 1 d1 +|15: 2 d2 +|16: 3 DEPTARGET +|17: 4 d4 +|18: 5 d5 +|19: 6 d6 == snap step1 grid=210x31 cursor=13,5 -== snap step2 grid=210x31 cursor=17,3 -== snap step3 grid=210x31 cursor=17,3 +== snap step2 grid=210x31 cursor=13,5 +== snap step3 grid=210x31 cursor=13,5 == snap selclick grid=210x31 cursor=14,6 == snap outside grid=210x31 cursor=20,6 -|12: /tmp/pardes-snap/rsearch/cwd/+Search Save Tty Del Collapse -|13: 1 code.txt:4:10-14 pick two words +|10: /tmp/pardes-snap/rsearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|11: 1 code.txt:4:10-14 +|12: 2 pick two words diff --git a/test/snapshots/rsearch.snap b/test/snapshots/rsearch.snap index c413c559..30459488 100644 --- a/test/snapshots/rsearch.snap +++ b/test/snapshots/rsearch.snap @@ -7,6 +7,10 @@ dirmk sub file sub/dep.txt d1\nd2\nDEPTARGET\nd4\nd5\nd6 file code.txt run count_x now\nopen sub/dep.txt:3 here\ncount_x again\npick two words +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 31 210 -n 1 wait 8000 code.txt stable 700 20000 @@ -28,7 +32,9 @@ snap opened # file, so the click searches for it: the results list both lines containing it. press right 15 4 release right 15 4 -wait 10000 code.txt:1:5-11 run count_x +# Locations stack the target under its line now: two rows, two waits. +wait 10000 code.txt:1:5-11 +wait 10000 run count_x now stable 700 15000 snap search # right-SELECT `pick two` (line 4, sweep cols 8..15): a multi-word span passes @@ -36,7 +42,8 @@ snap search press right 8 7 drag right 15 7 release right 15 7 -wait 10000 code.txt:4:1-8 pick two +wait 10000 code.txt:4:1-8 +wait 10000 pick two words stable 700 15000 snap select # right-CLICK the path `sub/dep.txt:3` (line 2, col 18): isFileChar keeps / . : diff --git a/test/snapshots/savepane.golden b/test/snapshots/savepane.golden index 070146d3..ab54ee3e 100644 --- a/test/snapshots/savepane.golden +++ b/test/snapshots/savepane.golden @@ -1,16 +1,20 @@ == snap scratch grid=100x31 cursor=20,6 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/savepane/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/savepane/cwd Tty Save Mode Filter Collapse Del | ls | -| /tmp/pardes-snap/savepane/cwd/+New * Save Tty Del Collapse +| /tmp/pardes-snap/savepane/cwd/+New * Save Tty Collapse Del | 1 scratch bytes -== snap prompt grid=100x31 cursor=38,30 -|30: Save /tmp/pardes-snap/savepane/cwd/ -== snap saved grid=100x31 cursor=20,6 -|5: /tmp/pardes-snap/savepane/cwd/saved.txt Save Tty Del Collapse -|30: --:--:-- saved /tmp/pardes-snap/savepane/cwd/saved.txt +== snap prompt grid=100x31 cursor=99,7 +|6: Save +|7: Save /tmp/pardes-snap/savepane/cwd/ +|8: 1 scratch bytes +== snap saved grid=100x31 cursor=20,7 +|5: /tmp/pardes-snap/savepane/cwd/saved.txt Save Tty Collapse Del +|6: --:--:-- saved /tmp/pardes-snap/savepane/cwd/saved.txt +|7: 1 scratch bytes +|8: == file bytes scratch bytes == end file diff --git a/test/snapshots/scroll.golden b/test/snapshots/scroll.golden index 46576f75..86bad0e5 100644 --- a/test/snapshots/scroll.golden +++ b/test/snapshots/scroll.golden @@ -1,7 +1,7 @@ == snap bottom grid=100x31 cursor=4,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/scroll/cwd Save Tty Del Togglet /tmp/pardes-snap/scroll/cwd Save Tty Del Togglet +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/scroll/cwd Tty Save Mode Filte /tmp/pardes-snap/scroll/cwd Tty Save Mode Filte | 188 ls | 189 s.txt | 190 @@ -16,7 +16,7 @@ | 199 | 200 | -| /tmp/pardes-snap/scroll/cwd Save Tty Del Togglet +| /tmp/pardes-snap/scroll/cwd Tty Save Mode Filte | ls | s.txt == snap wheel3 grid=100x31 cursor=4,16 @@ -81,33 +81,33 @@ |16: 194 == style wheel-down grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-49 d,#26362d, 50-74 #b2c3b8,#1d2824, 75-99 d,#1d2824, -|2: 0-1 #000000,#adcc91, 2-49 #becfc4,#26362d, 50-51 #ffffff,#4c6356, 52-99 #b2c3b8,#1d2824, -|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|4: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|5: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-99 d,#0d1410, -|6: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|13: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-49 #b2c3b8,#1d2824, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-49 d,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#637f6a, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-49 d,#26362d, 50-51 #ffffff,#887455, 52-52 d,#1d2824, 53-84 #b2c3b8,#1d2824, 85-99 d,#1d2824, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-30 #becfc4,#26362d, 31-33 #dfbce5,#26362d, 34-49 #becfc4,#26362d, 50-51 #ffffff,#496656, 52-52 d,#1d2824, 53-80 #b2c3b8,#1d2824, 81-83 #d3b0d9,#1d2824, 84-99 #b2c3b8,#1d2824, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|4: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|5: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, +|6: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|8: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|9: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|10: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|12: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|13: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-33 #d3b0d9,#1d2824, 34-49 #b2c3b8,#1d2824, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, diff --git a/test/snapshots/scrolloff.golden b/test/snapshots/scrolloff.golden index 6054e8bc..5ab9fa55 100644 --- a/test/snapshots/scrolloff.golden +++ b/test/snapshots/scrolloff.golden @@ -1,7 +1,7 @@ == snap top grid=210x12 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/scrolloff/cwd/g.txt Save Tty Del Collapse /tmp/pardes-snap/scrolloff/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/scrolloff/cwd/g.txt Save Tty Collapse Del /tmp/pardes-snap/scrolloff/cwd Tty Save Mode Filter Collapse Del | 1 line 1 ls | 2 line 2 g.txt | 3 line 3 diff --git a/test/snapshots/selarg.golden b/test/snapshots/selarg.golden index b0a14b86..1a9fb86d 100644 --- a/test/snapshots/selarg.golden +++ b/test/snapshots/selarg.golden @@ -1,7 +1,7 @@ == snap kept grid=100x31 cursor=6,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/selarg/cwd Save Tty Del Togglet /tmp/pardes-snap/selarg/cwd Save Tty Del Togglet +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/selarg/cwd Tty Save Mode Filte /tmp/pardes-snap/selarg/cwd Tty Save Mode Filte | ZZARG ZZVEE ./c.sh | | @@ -16,7 +16,7 @@ | | | -| /tmp/pardes-snap/selarg/cwd Save Tty Del Togglet +| /tmp/pardes-snap/selarg/cwd Tty Save Mode Filte | ls | s.txt == snap crosspane grid=100x31 cursor=6,3 diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index 4f380f9b..f071fb15 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -1,78 +1,75 @@ -== snap prompt-armed grid=160x25 cursor=11,24 +== snap prompt-armed grid=160x25 cursor=159,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext +| Select / | 1 const one = 1; | 2 const two = 2; | 3 const three = 3; | 4 -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| Select / -== snap preview grid=160x25 cursor=16,24 -|24: Select /const +== snap preview grid=160x25 cursor=159,3 +|3: Select /const == style preview grid=160x25 |0: 0-70 #b2c3b8,#1d2824, 71-159 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-159 d,#26362d, -|2: 0-1 #000000,#adcc91, 2-58 #becfc4,#26362d, 59-159 d,#26362d, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#405d4b, 11-11 #405d4b,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#26382d, 11-11 #405d4b,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#26382d, 11-11 #405d4b,#f5f7ee, 12-20 #e5eee5,#0d1410, 21-21 #e9bf91,#0d1410, 22-22 #e5eee5,#0d1410, 23-159 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-15 #e5eee5,#0d1410, 16-159 d,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-159 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-32 #becfc4,#26362d, 33-37 #dfbce5,#26362d, 38-71 #becfc4,#26362d, 72-159 d,#26362d, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-144 d,#1d2824, 145-158 #b2c3b8,#1d2824, 159-159 d,#1d2824, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#3c614a, 11-11 #3c614a,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-22 #e5eee5,#0d1410, 23-159 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, == snap three-selected grid=160x25 cursor=11,3 -|24: +|3: 1 const one = 1; +|4: 2 const two = 2; +|5: 3 const three = 3; +|6: 4 +|7: == style three-selected grid=160x25 -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-11 #f5f7ee,#405d4b, 12-18 #e5eee5,#0d1410, 19-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, -== snap narrowed grid=160x25 cursor=12,24 -|24: Select /t +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-22 #e5eee5,#0d1410, 23-159 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +== snap narrowed grid=160x25 cursor=159,3 +|3: Select /t +|4: 1 const one = 1; +|5: 2 const two = 2; +|6: 3 const three = 3; +|7: 4 == style narrowed grid=160x25 -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #405d4b,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #405d4b,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #405d4b,#f5f7ee, 12-20 #e5eee5,#0d1410, 21-21 #e9bf91,#0d1410, 22-22 #e5eee5,#0d1410, 23-159 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-11 #e5eee5,#0d1410, 12-159 d,#0d1410, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-148 d,#1d2824, 149-158 #b2c3b8,#1d2824, 159-159 d,#1d2824, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-22 #e5eee5,#0d1410, 23-159 d,#0d1410, == snap esc-restores grid=160x25 cursor=11,3 -|24: +|3: 1 const one = 1; +|4: 2 const two = 2; +|5: 3 const three = 3; +|6: 4 +|7: == style esc-restores grid=160x25 -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-11 #f5f7ee,#405d4b, 12-18 #e5eee5,#0d1410, 19-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#26382d, 11-11 #405d4b,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #e9bf91,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#26382d, 11-11 #405d4b,#f5f7ee, 12-20 #e5eee5,#0d1410, 21-21 #e9bf91,#0d1410, 22-22 #e5eee5,#0d1410, 23-159 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-20 #e5eee5,#0d1410, 21-159 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-22 #e5eee5,#0d1410, 23-159 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-159 d,#0d1410, == snap commented grid=160x25 cursor=14,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig * Save Tty Del Collapse +|2: /tmp/pardes-snap/selregex/cwd/m.zig * Save Tty Collapse Del TreeContext |3: 1 // const one = 1; |4: 2 // const two = 2; |5: 3 // const three = 3; diff --git a/test/snapshots/shellset.golden b/test/snapshots/shellset.golden index 33cbfb29..777bb102 100644 --- a/test/snapshots/shellset.golden +++ b/test/snapshots/shellset.golden @@ -1,11 +1,13 @@ == snap boot grid=90x21 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/shellset/cwd/cmd.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/shellset/cwd/cmd.txt Save Tty Collapse Del | 1 Shell zznosuchshell -== snap builtin-ran grid=90x21 cursor=25,3 +== snap builtin-ran grid=90x21 cursor=25,4 +|3: Shell +|4: 1 Shell zznosuchshell == snap fallback-shell grid=90x21 cursor=49,5 -|1: New Tty Find Grep Joincol New Tty Find Grep Joincol -|2: /tmp/pardes-snap/shellset/cwd/cmd.txt Save /tmp/pardes-snap/shellset/cwd Save Tty Del +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/shellset/cwd/cmd.txt Save /tmp/pardes-snap/shellset/cwd Tty Save Mod |3: 1 Shell zznosuchshell ls |4: cmd.txt zmarkfile.txt diff --git a/test/snapshots/shrinktag.golden b/test/snapshots/shrinktag.golden index 41098ef1..8ff798fa 100644 --- a/test/snapshots/shrinktag.golden +++ b/test/snapshots/shrinktag.golden @@ -1,7 +1,7 @@ == snap before grid=100x31 cursor=2,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/shrinktag/cwd Save Tty Del Togg /tmp/pardes-snap/shrinktag/cwd Save Tty Del Togg +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/shrinktag/cwd Tty Save Mode Fi /tmp/pardes-snap/shrinktag/cwd Tty Save Mode Fi | ls ls | w.txt w.txt | @@ -16,11 +16,11 @@ | | | -| /tmp/pardes-snap/shrinktag/cwd Save Tty Del Togg +| /tmp/pardes-snap/shrinktag/cwd Tty Save Mode Fi | ls | w.txt == snap shrunk grid=100x31 cursor=2,9 -|3: /tmp/pardes-snap/shrinktag/cwd Save Tty Del Togg ls +|3: /tmp/pardes-snap/shrinktag/cwd Tty Save Mode Fi ls |4: ls w.txt |5: w.txt |8: @@ -34,11 +34,11 @@ |4: w.txt w.txt |5: |8: echo one; echo two -|17: /tmp/pardes-snap/shrinktag/cwd Save Tty Del Togg +|17: /tmp/pardes-snap/shrinktag/cwd Tty Save Mode Fi |18: ls |19: w.txt == snap bottom-shrunk grid=100x31 cursor=2,9 |17: |18: |19: -|30: /tmp/pardes-snap/shrinktag/cwd Save Tty Del Togg +|30: /tmp/pardes-snap/shrinktag/cwd Tty Save Mode Fi diff --git a/test/snapshots/splitparent.golden b/test/snapshots/splitparent.golden index 7382103d..aedbdb8a 100644 --- a/test/snapshots/splitparent.golden +++ b/test/snapshots/splitparent.golden @@ -1,26 +1,26 @@ == snap shrunk grid=100x31 cursor=4,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To /tmp/pardes-snap/splitparent/cwd Save Tty Del To -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To ls +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode /tmp/pardes-snap/splitparent/cwd Tty Save Mode +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode ls | ls == snap swap-parent grid=100x31 cursor=4,8 -|6: /tmp/pardes-snap/splitparent/cwd Save Tty Del To +|6: /tmp/pardes-snap/splitparent/cwd Tty Save Mode |7: ls == snap tallest grid=100x6 cursor=54,5 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To /tmp/pardes-snap/splitparent/cwd Save Tty Del To -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To /tmp/pardes-snap/splitparent/cwd Save Tty Del To +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode /tmp/pardes-snap/splitparent/cwd Tty Save Mode +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode /tmp/pardes-snap/splitparent/cwd Tty Save Mode == snap regrown grid=100x31 cursor=54,19 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To /tmp/pardes-snap/splitparent/cwd Save Tty Del To -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To ls +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode /tmp/pardes-snap/splitparent/cwd Tty Save Mode +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode ls | ls | -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode | ls | | @@ -31,5 +31,5 @@ | | | -| /tmp/pardes-snap/splitparent/cwd Save Tty Del To +| /tmp/pardes-snap/splitparent/cwd Tty Save Mode | ls diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index 202a4f9a..b8b4dca2 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -1,7 +1,7 @@ == snap results grid=150x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/stepgrain/cwd/a.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/stepgrain/cwd/a.txt Save Tty Collapse Del | 1 hello ZQMARK one | 2 see also sub/b.txt for ZQMARK two | @@ -23,67 +23,74 @@ | | | -| -| -| -| /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Del Collapse -| 1 a.txt:1:7-12 hello ZQMARK one -| 2 a.txt:2:24-29 see also sub/b.txt for ZQMARK two -| 3 sub/b.txt:1:1-6 ZQMARK inside sub -== snap step-row1 grid=150x31 cursor=7,28 +| /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del LocationsConfig +| 1 a.txt:1:7-12 +| 2 hello ZQMARK one +| 3 a.txt:2:24-29 +| 4 see also sub/b.txt for ZQMARK two +| 5 sub/b.txt:1:1-6 +| 6 ZQMARK inside sub +== snap step-row1 grid=150x31 cursor=7,25 == style step-row1 grid=150x31 |0: 0-70 #b2c3b8,#1d2824, 71-149 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-149 d,#26362d, -|2: 0-1 #ffffff,#4c6356, 2-59 #b2c3b8,#1d2824, 60-149 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-22 #e5eee5,#0d1410, 23-149 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-39 #e5eee5,#0d1410, 40-149 d,#0d1410, -|5: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|6: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|17: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|20: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, -|27: 0-1 #000000,#adcc91, 2-61 #becfc4,#26362d, 62-149 d,#26362d, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-18 #f5f7ee,#405d4b, 19-25 #e5eee5,#0d1410, 26-31 #f7e4a5,#57472a, 32-35 #e5eee5,#0d1410, 36-149 d,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-19 #59675c,#0d1410, 20-43 #e5eee5,#0d1410, 44-49 #f7e4a5,#57472a, 50-53 #e5eee5,#0d1410, 54-149 d,#0d1410, -|30: 0-0 d,#152019, 1-1 d,#0d1410, 2-21 #59675c,#0d1410, 22-22 #e5eee5,#0d1410, 23-28 #f7e4a5,#57472a, 29-39 #e5eee5,#0d1410, 40-149 d,#0d1410, -== snap step-row2 grid=150x31 cursor=7,29 +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-149 d,#26362d, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-38 #d3b0d9,#1d2824, 39-60 #b2c3b8,#1d2824, 61-149 d,#1d2824, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-22 #e5eee5,#0d1410, 23-149 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-39 #e5eee5,#0d1410, 40-149 d,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|24: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-33 #becfc4,#26362d, 34-40 #dfbce5,#26362d, 41-78 #becfc4,#26362d, 79-149 d,#26362d, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-18 #f5f7ee,#3c614a, 19-149 d,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-18 #f7e4a5,#5e4923, 19-22 #e5eee5,#0d1410, 23-149 d,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-19 #59675c,#0d1410, 20-149 d,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-29 #e5eee5,#0d1410, 30-35 #f7e4a5,#5e4923, 36-39 #e5eee5,#0d1410, 40-149 d,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-21 #59675c,#0d1410, 22-149 d,#0d1410, +|30: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #f7e4a5,#5e4923, 13-23 #e5eee5,#0d1410, 24-149 d,#0d1410, +== snap step-row2 grid=150x31 cursor=7,27 == style step-row2 grid=150x31 -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-18 #59675c,#0d1410, 19-25 #e5eee5,#0d1410, 26-31 #f7e4a5,#57472a, 32-35 #e5eee5,#0d1410, 36-149 d,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-19 #f5f7ee,#405d4b, 20-43 #e5eee5,#0d1410, 44-49 #f7e4a5,#57472a, 50-53 #e5eee5,#0d1410, 54-149 d,#0d1410, -== snap step-row3 grid=150x31 cursor=7,29 -|28: 2 a.txt:2:24-29 see also sub/b.txt for ZQMARK two -|29: 3 sub/b.txt:1:1-6 ZQMARK inside sub -|30: 4 -== snap step-wrap grid=150x31 cursor=7,28 -|28: 1 a.txt:1:7-12 hello ZQMARK one -|29: 2 a.txt:2:24-29 see also sub/b.txt for ZQMARK two -|30: 3 sub/b.txt:1:1-6 ZQMARK inside sub -== snap blank-in-path grid=150x31 cursor=7,26 -|25: /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Del Collapse -|26: 1 two words.txt +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-18 #59675c,#0d1410, 19-149 d,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 d,#0d1410, +== snap step-row3 grid=150x31 cursor=7,28 +|25: 2 hello ZQMARK one +|26: 3 a.txt:2:24-29 +|27: 4 see also sub/b.txt for ZQMARK two +|28: 5 sub/b.txt:1:1-6 +|29: 6 ZQMARK inside sub +|30: 7 +== snap step-wrap grid=150x31 cursor=7,25 +|25: 1 a.txt:1:7-12 +|26: 2 hello ZQMARK one +|27: 3 a.txt:2:24-29 +|28: 4 see also sub/b.txt for ZQMARK two +|29: 5 sub/b.txt:1:1-6 +|30: 6 ZQMARK inside sub +== snap blank-in-path grid=150x31 cursor=7,23 +|22: /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del +|23: 1 two words.txt == style blank-in-path grid=150x31 -|25: 0-1 #000000,#adcc91, 2-61 #becfc4,#26362d, 62-149 d,#26362d, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-19 #f5f7ee,#405d4b, 20-149 d,#0d1410, -|27: 0-1 #ffffff,#4c6356, 2-61 #b2c3b8,#1d2824, 62-149 d,#1d2824, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #f5f7ee,#405d4b, 19-25 #e5eee5,#0d1410, 26-31 #f7e4a5,#57472a, 32-35 #e5eee5,#0d1410, 36-149 d,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-19 #59675c,#0d1410, 20-43 #e5eee5,#0d1410, 44-49 #f7e4a5,#57472a, 50-53 #e5eee5,#0d1410, 54-149 d,#0d1410, -== snap blank-opened grid=150x31 cursor=7,15 -|14: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Del Collapse -|15: 1 +|22: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-33 #becfc4,#26362d, 34-40 #dfbce5,#26362d, 41-62 #becfc4,#26362d, 63-149 d,#26362d, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 d,#0d1410, +|24: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-40 #d3b0d9,#1d2824, 41-78 #b2c3b8,#1d2824, 79-149 d,#1d2824, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #f5f7ee,#3c614a, 19-149 d,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-19 #59675c,#0d1410, 20-149 d,#0d1410, +== snap blank-opened grid=150x31 cursor=7,13 +|12: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del +|13: 1 +|23: Look diff --git a/test/snapshots/syntax.golden b/test/snapshots/syntax.golden index 3199f03a..5b2811f7 100644 --- a/test/snapshots/syntax.golden +++ b/test/snapshots/syntax.golden @@ -1,11 +1,11 @@ == snap zig-open grid=150x31 cursor=7,7 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/syntax/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/syntax/cwd Save Tty Del Togglettymode Filter Collapse -| ls ls -| demo.zig demo.zig -| -| /tmp/pardes-snap/syntax/cwd/demo.zig Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/syntax/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/syntax/cwd Tty Save Mode Filter Collapse Del +| Look ls +| ls demo.zig +| demo.zig +| /tmp/pardes-snap/syntax/cwd/demo.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); // greet | 2 pub fn main() void { | 3 var x: u32 = 42; @@ -16,94 +16,95 @@ | | | -| /tmp/pardes-snap/syntax/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/syntax/cwd Tty Save Mode Filter Collapse Del | ls | demo.zig == style zig-open grid=150x31 |0: 0-70 #b2c3b8,#1d2824, 71-149 d,#1d2824, -|1: 0-24 #becfc4,#26362d, 25-74 d,#26362d, 75-99 #b2c3b8,#1d2824, 100-149 d,#1d2824, -|2: 0-1 #ffffff,#4c6356, 2-71 #b2c3b8,#1d2824, 72-74 d,#1d2824, 75-76 #ffffff,#4c6356, 77-146 #b2c3b8,#1d2824, 147-149 d,#1d2824, -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|5: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|6: 0-1 #000000,#adcc91, 2-59 #becfc4,#26362d, 60-74 d,#26362d, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9b0e4,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b6ce94,#0d1410, 32-34 #e5eee5,#0d1410, 35-42 #b9e58f,#0d1410, 43-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-23 #e5eee5,#0d1410, 24-25 #e9bf91,#0d1410, 26-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-71 #b2c3b8,#1d2824, 72-74 d,#1d2824, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-74 d,#26362d, 75-76 #ffffff,#887455, 77-77 d,#1d2824, 78-109 #b2c3b8,#1d2824, 110-149 d,#1d2824, +|2: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-33 #d3b0d9,#1d2824, 34-63 #b2c3b8,#1d2824, 64-74 d,#1d2824, 75-76 #ffffff,#496656, 77-77 d,#1d2824, 78-105 #b2c3b8,#1d2824, 106-108 #d3b0d9,#1d2824, 109-138 #b2c3b8,#1d2824, 139-149 d,#1d2824, +|3: 0-0 d,#152019, 1-1 d,#0d1410, 2-70 d,#1d2824, 71-74 #b2c3b8,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-30 #becfc4,#26362d, 31-38 #dfbce5,#26362d, 39-72 #becfc4,#26362d, 73-74 d,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-42 #b9f480,#0d1410, 43-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-33 #d3b0d9,#1d2824, 34-63 #b2c3b8,#1d2824, 64-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, == style colors-off grid=150x31 -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-3 #e5eee5,#0d1410, 4-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-78 #e5eee5,#0d1410, 79-149 d,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-9 #e5eee5,#0d1410, 10-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-84 #e5eee5,#0d1410, 85-149 d,#0d1410, -|6: 0-1 #000000,#adcc91, 2-59 #becfc4,#26362d, 60-74 d,#26362d, 75-75 d,#637f6a, 76-149 d,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-42 #e5eee5,#0d1410, 43-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-71 #b2c3b8,#1d2824, 72-74 d,#1d2824, 75-75 d,#637f6a, 76-149 d,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-3 #e5eee5,#0d1410, 4-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-9 #e5eee5,#0d1410, 10-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|20: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|21: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|22: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|23: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|24: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|25: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|26: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|27: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|28: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|29: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, -|30: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-149 d,#0d1410, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-3 #e5eee5,#0d1410, 4-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-78 #e5eee5,#0d1410, 79-149 d,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-9 #e5eee5,#0d1410, 10-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-84 #e5eee5,#0d1410, 85-149 d,#0d1410, +|5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-30 #becfc4,#26362d, 31-38 #dfbce5,#26362d, 39-72 #becfc4,#26362d, 73-74 d,#26362d, 75-75 d,#608269, 76-149 d,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-68 d,#1d2824, 69-74 #b2c3b8,#1d2824, 75-75 d,#608269, 76-149 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-42 #e5eee5,#0d1410, 43-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-33 #d3b0d9,#1d2824, 34-63 #b2c3b8,#1d2824, 64-74 d,#1d2824, 75-75 d,#608269, 76-149 d,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-3 #e5eee5,#0d1410, 4-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-9 #e5eee5,#0d1410, 10-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|21: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|22: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|23: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|24: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|25: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|26: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|27: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|28: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|29: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|30: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, == style colors-on grid=150x31 -|3: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|4: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|6: 0-1 #000000,#adcc91, 2-59 #becfc4,#26362d, 60-74 d,#26362d, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9b0e4,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b6ce94,#0d1410, 32-34 #e5eee5,#0d1410, 35-42 #b9e58f,#0d1410, 43-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9b0e4,#0d1410, 13-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-23 #e5eee5,#0d1410, 24-25 #e9bf91,#0d1410, 26-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|17: 0-1 #ffffff,#4c6356, 2-71 #b2c3b8,#1d2824, 72-74 d,#1d2824, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|18: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|19: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|20: 0-0 d,#637f6a, 1-74 d,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|21: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|22: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|23: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|24: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|25: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|26: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|27: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|28: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|29: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|30: 0-0 d,#637f6a, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#637f6a, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-30 #becfc4,#26362d, 31-38 #dfbce5,#26362d, 39-72 #becfc4,#26362d, 73-74 d,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-68 d,#1d2824, 69-74 #b2c3b8,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-42 #b9f480,#0d1410, 43-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-12 #c9a7ed,#0d1410, 13-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-26 #e5eee5,#0d1410, 27-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|17: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-33 #d3b0d9,#1d2824, 34-63 #b2c3b8,#1d2824, 64-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, diff --git a/test/snapshots/tag.golden b/test/snapshots/tag.golden index abc83b8f..5e4cb4d1 100644 --- a/test/snapshots/tag.golden +++ b/test/snapshots/tag.golden @@ -1,7 +1,7 @@ -== snap tag-focus grid=150x31 cursor=26,2 +== snap tag-focus grid=150x31 cursor=31,2 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/tag/cwd Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/tag/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tag/cwd Tty Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty Save Mode Filter Collapse Del | ls ls | t.txt t.txt | @@ -16,15 +16,18 @@ | | | -| /tmp/pardes-snap/tag/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/tag/cwd Tty Save Mode Filter Collapse Del | ls | t.txt -== snap tag-typed grid=150x31 cursor=32,2 -|2: /tmp/pardes-snap/tag/cwd t.txt Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/tag/cwd Save Tty Del Togglettymode Filter Collapse -== snap tag-del grid=150x31 cursor=28,2 -|2: /tmp/pardes-snap/tag/cwd t Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/tag/cwd Save Tty Del Togglettymode Filter Collapse +== snap tag-typed grid=150x31 cursor=37,2 +|2: /tmp/pardes-snap/tag/cwd Tty t.txt Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty Save Mode Filter Collapse Del +== snap tag-del grid=150x31 cursor=33,2 +|2: /tmp/pardes-snap/tag/cwd Tty t Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty Save Mode Filter Collapse Del == snap tag-exit grid=150x31 cursor=4,5 -|2: /tmp/pardes-snap/tag/cwd t.txt Save Tty Del Togglettymode Filter Collapse /tmp/pardes-snap/tag/cwd Save Tty Del Togglettymode Filter Collapse +|2: /tmp/pardes-snap/tag/cwd Tty t.txt Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty Save Mode Filter Collapse Del == snap tag-look grid=150x31 cursor=7,7 -|6: /tmp/pardes-snap/tag/cwd/t.txt Save Tty Del Collapse +|3: Look ls +|4: ls t.txt +|5: t.txt +|6: /tmp/pardes-snap/tag/cwd/t.txt Save Tty Collapse Del |7: 1 ZZLOOKED diff --git a/test/snapshots/tagalign.golden b/test/snapshots/tagalign.golden index eaed8e2e..6d61ad2f 100644 --- a/test/snapshots/tagalign.golden +++ b/test/snapshots/tagalign.golden @@ -1,7 +1,7 @@ == snap aligned grid=100x31 cursor=4,20 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha | 2 beta | 3 gamma @@ -16,13 +16,13 @@ | | | -| /tmp/pardes-snap/tagalign/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/tagalign/cwd Tty Save Mode Filter Collapse Del | ls | deep == snap fits grid=87x31 cursor=4,20 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Del +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Co | 1 alpha | 2 beta | 3 gamma @@ -37,13 +37,13 @@ | | | -| /tmp/pardes-snap/tagalign/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/tagalign/cwd Tty Save Mode Filter Collapse Del | ls | deep == snap overby1 grid=86x31 cursor=4,20 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty De +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty C | 1 alpha | 2 beta | 3 gamma @@ -58,13 +58,13 @@ | | | -| /tmp/pardes-snap/tagalign/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/tagalign/cwd Tty Save Mode Filter Collapse Del | ls | deep == snap clicked grid=100x31 cursor=11,2 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha | 2 beta | 3 gamma @@ -79,13 +79,13 @@ | | | -| /tmp/pardes-snap/tagalign/cwd Save Tty Del Togglettymode Filter Collapse +| /tmp/pardes-snap/tagalign/cwd Tty Save Mode Filter Collapse Del | ls | deep == snap revealed grid=70x31 cursor=69,2 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kil -|New Tty Find Grep Joincol -| wd/deep/nested-project-directory/document.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| d/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha | 2 beta | 3 gamma @@ -100,11 +100,11 @@ | | | -| /tmp/pardes-snap/tagalign/cwd Save Tty Del Togglettymode Filter Coll +| /tmp/pardes-snap/tagalign/cwd Tty Save Mode Filter Collapse Del | ls | deep == snap alone grid=70x31 cursor=4,5 -|2: /tmp/pardes-snap/tagalign/cwd Save Tty Del Togglettymode Filter Coll +|2: /tmp/pardes-snap/tagalign/cwd Tty Save Mode Filter Collapse Del |3: ls |4: deep |5: diff --git a/test/snapshots/tagalign2col.golden b/test/snapshots/tagalign2col.golden index cef20c73..e703dbef 100644 --- a/test/snapshots/tagalign2col.golden +++ b/test/snapshots/tagalign2col.golden @@ -1,17 +1,20 @@ == snap onecol grid=160x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol New Tty Find Grep Joincol -| /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Del Collapse /tmp/pardes-snap/tagalign2col/cwd Save Tty Del Togglettymode Filter Collapse -| 1 alpha ls -| 2 beta deep -| 3 gamma +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Collapse De /tmp/pardes-snap/tagalign2col/cwd Tty Save Mode Filter Collapse Del +| 1 alpha Left +| 2 beta ls +| 3 gamma deep == snap aligned grid=160x31 cursor=4,20 -|17: /tmp/pardes-snap/tagalign2col/cwd Save Tty Del Togglettymode Filter Collapse +|3: 1 alpha ls +|4: 2 beta deep +|5: 3 gamma +|17: /tmp/pardes-snap/tagalign2col/cwd Tty Save Mode Filter Collapse Del |18: ls |19: deep == snap widened grid=160x31 cursor=4,20 -|1: New Tty Find Grep Joincol ╎New Tty Find Grep Joincol -|2: /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Del Collapse ╎ /tmp/pardes-snap/tagalign2col/cwd Save Tty Del Togglettymo +|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Collapse Del ╎ /tmp/pardes-snap/tagalign2col/cwd Tty Save Mode Filter Co |3: 1 alpha ╎ ls |4: 2 beta ╎ deep |5: 3 gamma ╎ @@ -26,7 +29,7 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/tagalign2col/cwd Save Tty Del Togglettymode Filter Collapse ╎ +|17: /tmp/pardes-snap/tagalign2col/cwd Tty Save Mode Filter Collapse Del ╎ |18: ls ╎ |19: deep ╎ |20: ╎ diff --git a/test/snapshots/tagbottom.golden b/test/snapshots/tagbottom.golden index f455c425..eb1d67fd 100644 --- a/test/snapshots/tagbottom.golden +++ b/test/snapshots/tagbottom.golden @@ -1,7 +1,7 @@ == snap boot grid=100x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Del Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del | 1 aaa | 2 bbb | 3 ccc @@ -56,9 +56,9 @@ |26: 25 yyy |27: 26 zzz |28: -|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Del Collapse +|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del == snap off grid=100x31 cursor=7,3 -|2: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Del Collapse +|2: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del |3: 1 aaa |4: 2 bbb |5: 3 ccc @@ -86,7 +86,7 @@ |27: 25 yyy |28: 26 zzz |30: -== snap tag-typed grid=100x31 cursor=60,30 +== snap tag-typed grid=100x31 cursor=74,30 |2: 1 aaa |3: 2 bbb |4: 3 ccc @@ -114,9 +114,9 @@ |26: 25 yyy |27: 26 zzz |28: -|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty bottom.txt Del Collapse +|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt == snap look-bottom-tag grid=100x31 cursor=7,17 -|16: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty bottom.txt Del Collapse +|16: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt |17: 1 ZZONE |18: 2 ZZTWO |19: @@ -128,11 +128,11 @@ |25: |26: |27: -|30: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Del Collapse +|30: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Collapse Del == snap body-cursor grid=100x31 cursor=9,6 == snap seam-noop grid=100x31 cursor=9,6 == snap seam-dragged grid=100x31 cursor=9,6 -|11: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty bottom.txt Del Collapse +|11: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt |12: 1 ZZONE |13: 2 ZZTWO |14: @@ -150,10 +150,12 @@ |8: 8 hhh |9: 9 iii |10: 10 jjj -== snap search-prompt grid=100x31 cursor=6,29 -|29: /ZZ +== snap search-prompt grid=100x31 cursor=99,12 +|12: /ZZ +|13: 1 ZZONE +|14: 2 ZZTWO == snap leader grid=100x31 cursor=9,14 -|29: SPC +|12: SPC == snap cut-down grid=100x31 cursor=7,5 |2: 1 aaa |3: 2 bbb @@ -164,8 +166,10 @@ |8: 7 mmm |9: 8 nnn |10: 9 ooo -|11: /tmp/pardes-snap/tagbottom/cwd/top.txt * Save Tty bottom.txt Del Collapse -|29: +|11: /tmp/pardes-snap/tagbottom/cwd/top.txt * Save Tty Collapse Del bottom.txt +|12: 1 ZZONE +|13: 2 ZZTWO +|14: == file cut-buffer aaa bbb @@ -200,9 +204,9 @@ zzz |19: 18 xxx |20: 19 yyy |21: 20 zzz -|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty bottom.txt Del Collapse +|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt == snap off-again grid=100x31 cursor=7,6 -|2: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty bottom.txt Del Collapse +|2: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt |3: 1 aaa |4: 2 bbb |5: 3 ccc diff --git a/test/snapshots/tagbottom.snap b/test/snapshots/tagbottom.snap index a6a7a882..67bb2ead 100644 --- a/test/snapshots/tagbottom.snap +++ b/test/snapshots/tagbottom.snap @@ -17,6 +17,10 @@ # exactly: `off` is byte-for-byte `boot`, cursor included. file top.txt aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll\nmmm\nnnn\nooo\nppp\nqqq\nrrr\nsss\nttt\nuuu\nvvv\nwww\nxxx\nyyy\nzzz file bottom.txt ZZONE\nZZTWO +# Builtins announce themselves by default, and an announcement is a band at +# the top of the body -- which moves every row this script clicks. What the +# verbs do is what is under test, not the announcement. +config Verbose off start 31 100 top.txt wait 8000 Newcol Joincol wait 8000 top.txt @@ -38,8 +42,11 @@ stable 700 15000 # cursor is down on the tagline with it. Col 50 is past the end of the path, # which is read-only — a click inside it parks the cursor there and the typing # goes nowhere. -press left 50 31 -release left 50 31 +# Past the last word rather than at a counted column: the tagline's words +# have moved since (Del is last now), and a column that lands INSIDE one +# types the filename into the middle of a builtin's name. +press left 90 31 +release left 90 31 stable 400 5000 send \x20bottom.txt stable 600 8000 @@ -48,8 +55,8 @@ snap tag-typed # ...and LOOK the word just typed, from that same bottom tagline: bottom.txt # opens as a second pane below. It only can if the press was mapped to the tag # — mapped as a body row it lands on blank line 29 and looks nothing at all. -press right 55 31 -release right 55 31 +press right @bottom.txt 31 +release right @bottom.txt 31 wait 10000 ZZONE stable 700 15000 snap look-bottom-tag diff --git a/test/snapshots/tagbottomimage.golden b/test/snapshots/tagbottomimage.golden index 523dd27c..72352672 100644 --- a/test/snapshots/tagbottomimage.golden +++ b/test/snapshots/tagbottomimage.golden @@ -1,11 +1,11 @@ == snap img-top grid=150x31 cursor=11,8 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill -|New Tty Find Grep Joincol -| /tmp/pardes-snap/tagbottomimage/cwd Save Tty Del Togglettymode Filter Collapse +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagbottomimage/cwd Tty Save Mode Filter Collapse Del +| Look | ls | pic.ppm -| -| img petscii:off palette:commodore ascii:on /tmp/pardes-snap/tagbottomimage/cwd/pic.ppm Tty Del Collapse +| img petscii:off palette:commodore ascii:on /tmp/pardes-snap/tagbottomimage/cwd/pic.ppm Tty Collapse Del | 4*🬹~F~N🬰|G🬏▚Y~KF🬴s>T&zZ/🬻iTY=`S~╳bkZR37v🬦🬵d4QHZ8X▛▟ | ^🬪🬛$}DrydNU&wsz=`*r🬒🬓🬳🬟*Y🬴G6🬧f🬮/>t🬧u🬲1Rg1t🬝🬻█ @@ -34,66 +34,66 @@ |2: ls |3: pic.ppm |4: -|5: /tmp/pardes-snap/tagbottomimage/cwd Save Tty Del Togglettymode Filter Collapse -|6: 4*🬹~F~N🬰|G🬏▚Y~KF🬴s>T&zZ/🬻iTY=`S~╳bkZR37v🬦🬵d4QHZ8X▛▟ -|8: ^🬪🬛$}DrydNU&wsz=`*r🬒🬓🬳🬟*Y🬴G6🬧f🬮/>t🬧u🬲1Rg1t🬝🬻█ -|9: ▖#_{🬗X@🬢&$s'C%*=w@🬆▀wq%🬡d┼a┼m─>🬭🬜A▀A🬲H]p🬝🬹 -|10: %?WX🬕f🬩*TA8n╱┼E▘🬭Y#qo~XVE▐(╳▀H4^[mj🬗=🬒🬕▟█ -|11: ]Z🬷eb~Oyl3=SL▙a🬱🬉~MPMz}FMu<🬝▚>3&▖🬷WS🬝~█ -|12: EF-🬑y🬔!r🬙🬐╳O🬩▐%Qj─4za/?/\a🬜"🬖🬈🬛🬟A🬙🬝▄ -|13: 🬃N@xzOnczIK=t0@🬖j5🬮🬧65▟{🬮🬉🬄🬩zQ9/🬝🬻 -|14: ╲${&%@"#ctt▀Cr5F;🬐ARM╱uej╳75🬹9▛🬻 -|15: h^🬜"🬈🬨▜╲|W🬊🬦k6^🬰🬶rZ─▄\z9🬎🬉4^🬎🬻 -|16: 🬆f│Q_V🬗wGx🬱=5▛5*&V🬟🬄ZrXGz2🬝🬻█ -|17: !🬷W🬐(🬭]7x_>▗er🬯~▚di🬬4jY:🬝▟ -|18: gU~🬧3▙bjr\C#kKMpffAjps🬝🬻 -|19: *🬯G"🬣▟d🬮▀zJ🬪EHV▟╳9}y▛▄ -|20: ``))~RyJ🬴jA~w=hLpX🬝🬻█ -|21: 4x▀J"TG7=y-QZ🬙╲~▛🬻 -|22: 🬯/+╳f9ZG🬕+{QN_🬝🬹 -|23: E<'─🬫pS!"n4&🬝~ -|24: m$dx"!2🬳&{🬝🬻 -|25: *8f🬩▙Jb🬒🬝🬻█ -|26: m🬩7CiN🬎🬹 -|27: pG╲L🬝🬻 -|28: 🬡L🬝▄ -|29: 🬝~ -|30: img petscii:off palette:commodore ascii:on /tmp/pardes-snap/tagbottomimage/cwd/pic.ppm Tty Del Collapse +|5: /tmp/pardes-snap/tagbottomimage/cwd Tty Save Mode Filter Collapse Del +|6: Tagbottom +|7: {DbgY🬲s▜M^#▐FUJ[zNq=🬝g/y╱?V@🬱🬙▌UK╱🬍("🬕KJ8hSo🬝🬻 +|8: tX🬆s>🬌`🬵 Date: Tue, 22 Sep 2026 11:15:46 -0300 Subject: Answer 9P on the connection's task, so a session can open its own tree The editor's loop was the only thing that could answer a 9P request, which made the editor's own syscalls through a mount of its own tree -- a Look at /mnt/9p/pardes//anything under a `9ns --mntgen` view, a Save into it -- requests only the blocked loop could serve. The name-based refusal that followed (ownMountSuffix) and the in-process routing of a mount of oneself (Client.sameSession) were patches over that, and both are gone, with the mailbox that shipped every request to the editor's thread. One rule replaces them, `pardes.turn`: the core is single-threaded, the editor's thread has the turn by default and gives it up in two kinds of gap -- while it waits for input and while a step of it is out in a host syscall -- and a cloud9 connection task takes it in those gaps to answer. `out` counts the steps that are out, from any thread: while one is, the core reads consistently but that step still holds pointers into it, so a request that would change a pane (a write, a truncation, an rmdir) is parked in the engine and retried when the turn is next given up with nothing out, and the editor's own wake waits for the count to reach zero. It is never a write of its own that a step waits on out there -- writes come from a shell performing a save between steps -- so a parked request is never the syscall's own, and making a pane or rendering a screen need not park: every yield sits before its step's mutation, so the layout and the surface are whole under it. A changing request that queued effects is answered once the editor has performed them (`echo Save > exec` returns with the file written, as acme's `put` does), and it settles the way a step does, because without that a /log reader waited for the user's next keystroke. Every host syscall on a user path has to give the turn up, not fs.zig's alone: the first end-to-end run hung in `inotify_add_watch` performing the new pane's watch effect. PDFs and images are read whole at open, so no draw goes out into the host. The core's allocator takes its fixed buffer through the lock-free interface, since a connection task allocates while the editor's thread is out in a syscall that allocates too. A Restore puts the replacement in first and releases every task waiting on the old core. cloud9 (pinned at eb1a104) parks an open, a truncating wstat, a clunk and a remove on `again`, not only reads and writes, and answers a parked job whose fid was clunked without asking the backend. Verified: test/selfmount.py runs the editor under `9ns --mntgen` and Looks at, reads and Saves its own tree through the mount; a unit test pins that a change parks while the editor is out mid-step and lands when it rests, while a read is answered in the window. 9P over the Unix socket against a tty session, same machine, Debug builds: a read of /index 278us -> 61us, a truncating body write 1184us -> 609us, exec Save 718us -> 583us; the gesture benchmark is unchanged (geometric mean 0.997 over 53 cells). Also from the reviews: a notice chip over an image or PDF pane was painted out by the picture drawn after the cells, so pictures give up the rows; in the GUI a tree-sitter context band painted over the chip, so body layers are emitted first; a message is one row of printable text, its 256-byte cut never leaves half a glyph, and one wider than its pane keeps its tail (the file name, the reason) rather than its head. Co-Authored-By: Claude Fable 5.1 --- .agents/skills/pardes-9p/SKILL.md | 7 +- build.zig.zon | 4 +- docs/cloud9.md | 13 +- docs/fs.md | 27 +- docs/v9fs.md | 6 +- features.txt | 56 ++++ src/9p.zig | 19 +- src/9p_io.zig | 511 +++++++++++++++-------------------- src/CHANGELOG.md | 13 + src/detached/server.zig | 27 +- src/detached/wire.zig | 8 +- src/file_watch.zig | 6 + src/fs.zig | 444 ++++++++++-------------------- src/gui/gui.zig | 30 +- src/host_io.zig | 3 + src/macos.zig | 125 ++++++++- src/memory.zig | 50 +++- src/ninep/testing.zig | 7 +- src/ninep/tree.zig | 16 ++ src/panes.zig | 45 ++- src/pardes.zig | 282 +++++++++++++++---- src/tty/tty.zig | 11 +- test/fs_namespace.zig | 24 -- test/selfmount.py | 126 +++++++++ test/snapshots/images.golden | 40 +-- test/snapshots/msg.golden | 4 + test/snapshots/msg.snap | 12 + test/snapshots/tagbottomimage.golden | 98 +++---- 28 files changed, 1205 insertions(+), 809 deletions(-) create mode 100644 test/selfmount.py (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index b776e407..2e065819 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -69,9 +69,10 @@ echo "/etc/hosts:3" > "$m/look"; cat "$m/look" # open a file, see where it land rmdir "$m/pane/$n" # close it, dirty or not ``` -Do not open a session's own mount from inside that session -- a Look at -`$m/anything` in the editor that serves `$m` would deadlock it, so such paths -are refused. Use `/n/self/...` from inside; `$m/...` is for everyone else. +A session may open its own mount from inside itself: a Look at `$m/anything` +in the editor that serves `$m` is answered on the connection's task while the +editor's own syscall waits. `/n/self/...` names the same tree without leaving +the process. **Opening** `$m/pane/new` is what makes a pane, and reading the open file answers its serial — `/net/tcp/clone`'s mechanism. Each open makes another one, diff --git a/build.zig.zon b/build.zig.zon index 3a172f3b..8f1b8068 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,8 +9,8 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#9c4d668c926e2d9eae6ef87cd9b391d8185605f9", - .hash = "cloud9-0.1.0-yt86qjAoGgBEPMJl2t4CZn7iWPMZUw4sMHAL54tq7spP", + .url = "git+https://git.sr.ht/~gbrls/cloud9#eb1a104f385f375a74319695e1a59f6f82e6384e", + .hash = "cloud9-0.1.0-yt86qiixGgCCjOhSDJ6tijGR7zj_zLT8mjvuUqrkeG9_", }, // ZLS as a LIBRARY, not a language server: src/lsp_zls.zig imports the // `zls` module its build.zig publishes and calls the analyser in diff --git a/docs/cloud9.md b/docs/cloud9.md index d030db1d..6eb76238 100644 --- a/docs/cloud9.md +++ b/docs/cloud9.md @@ -16,11 +16,14 @@ Mounting, Unix namespace discovery and permissions, the editor event loop, connection limits, and exported tree policy remain here. The Unix and TCP listeners run on cloud9's `serve.Runner` (`std.Io`: an accept task per listener, a reader and a writer task per connection, four slots); its handler -queues every backend request for the editor's thread, which answers them all -in `Listener.tick` after each editor update, retries parked reads there, and -has the runner ship the replies. `src/9p_quic.zig` selects the existing -`pardes-9p` ALPN for cloud9's optional OpenSSL transport; QUIC still runs on -the poll loop in `src/9p_io.zig`, since cloud9's QUIC adapter is +answers every backend request on the connection's task, taking the editor's +turn with the core (`pardes.turn`) while the editor waits for input or is out +in a syscall. A request that would change a pane while the editor is mid-step +is parked with `Status.again` -- the engine parks reads, writes, opens, +truncations, clunks and removes -- and retried by `Runner.wakeAll` when the +editor next rests. `src/9p_quic.zig` selects the existing `pardes-9p` ALPN for +cloud9's optional OpenSSL transport; QUIC still runs on the poll loop in +`src/9p_io.zig` on the editor's thread, since cloud9's QUIC adapter is nonblocking-descriptor based rather than `std.Io` based. The standalone protocol/GPIO tests import the same module. The separate `05-zig-p4` build also supplies cloud9 for the GPIO firmware entry. diff --git a/docs/fs.md b/docs/fs.md index 6d2891e0..335ee4e6 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -106,15 +106,24 @@ at the cost of acme's one-step `new/body`. Nothing in the tree is created by list, stat, walk or read; only that one open. Every other name in `/pane` is a serial. -A session cannot open its own tree through a mount. Looking at -`/mnt/9p/pardes//anything` from inside that very editor used to hang it -outright: the realpath, the stat and the read all leave through the mount and -come back as 9P requests only that editor's loop can answer, while the loop is -blocked making them, and the filesystem then stops answering anybody. Such a -path is now refused by name before any syscall runs, because the syscall is the -thing that never returns. Address your own tree as `/n/self/...`, which the -editor serves from memory without leaving the process. Another session's mount -is perfectly fine to open. +A session can open its own tree through a mount: a Look at +`/mnt/9p/pardes//pane/2/body` from inside that very editor opens it, and +a Save of that pane writes back through the mount into pane 2. Requests on +the Unix and TCP listeners are answered on the 9P connection's own task, not +by the editor's loop, so the realpath, the stat and the read the editor makes +out through the mount come back while it waits for them. The one rule is +whose turn it is with the core (`pardes.turn`): the editor has it, and gives +it up while it waits for input and while a step of it is out in a syscall. A +step of a connection task's own -- a Look written to `look` -- goes out the +same way, and the editor waits for it to return before it takes a step of +its own. While any step is out, a request that would change a pane (a write, +a truncation, an rmdir) parks in the engine until none is; everything else, +opening `pane/new` and `screen` included, is answered at once, which is why a +Look at any path in the tree comes back. A write into the tree from the +editor itself only ever happens between steps (a Save), so nothing it waits +on out there is a request that has to park. QUIC is still served on the +editor's loop, so through QUIC the old hang remains. `/n/self/...` names the +same tree without leaving the process. `/look` and `/exec` are the editor's two clicks, one per line of a write: diff --git a/docs/v9fs.md b/docs/v9fs.md index cfbbd35b..a105fe06 100644 --- a/docs/v9fs.md +++ b/docs/v9fs.md @@ -72,9 +72,9 @@ remain available for subsequent explicit authentication. The launcher waits for forwards termination signals, and removes its empty temporary directory on exit. Namespace destruction releases the mount when its last process exits. -The core stays outside the mount namespace because its event loop serves 9P. -A blocking filesystem operation through its own mount could wait for a request -that the blocked event loop must service. Even pathname resolution may do this. +The core stays outside the mount namespace, which is the helper's private +one: a path under `$PARDES_MOUNT` names nothing in the editor's own namespace, +so a Look on one from that shell opens nothing. Each `Tty9p` currently creates its own mount and consumes a server connection; the session has four application connection slots across all transports. This diff --git a/features.txt b/features.txt index fa1c0f6b..0db7c497 100644 --- a/features.txt +++ b/features.txt @@ -202,3 +202,59 @@ means what it says when fed back as configuration -- the symmetry the report was Left failing, deliberately: `nested-optout`. See docs/divergences.md -- two levels of nesting prepend U+E016 (vaxis's F3) to typed lines, which is a real bug in the key-forwarding path and not a stale expectation. + +9P is answered on the connection's task now, not by the editor's loop. The loop used to be the only thing that could answer a +request, which made the editor's own syscalls through a mount of its own tree -- a Look at /mnt/9p/pardes//anything under a +`9ns --mntgen` view, a Save into it -- a request only the blocked loop could serve. The name-based refusal that followed +(ownMountSuffix) and the in-process routing of a mount of oneself (Client.sameSession) were patches over that, and both are gone. +What replaced them is one rule, `pardes.turn`: the core is single-threaded, the editor's thread has the turn by default and gives it +up in two kinds of gap -- while it waits for input (`rest`/`wake`, one site per shell) and while a step is out in a host syscall +(`yield`/`back`, inside the leaf calls in fs.zig and the few host-side ones: the file watcher's marks, a shell's cwd stat) -- and a +cloud9 connection task takes it in those gaps to answer. Which gap it is matters: waiting, anything goes; out in a syscall +mid-step, the core reads consistently but the step still holds pointers into it, so a request that would change a pane +(tree.needsQuiet: writes, truncations, /pane/new, rmdir, and the screen open because it renders) is parked in the engine with +Status.again and retried when the turn is next given up quiet. That needed cloud9's engine to park an open, a truncating wstat, a +clunk and a remove, not only reads and writes -- a parked job goes back into the job slot on retry, and a walk still cannot park +because its names live in the input frame. A changing request that queued effects waits (`awaitSettled`) until the editor's pump has +performed them before it is answered, so `echo Save > exec` still returns with the file written, the way `put` does in acme; and a +request settles the way a step does (`sync`, `fsReport`, `events.announce`), because without that a `/log` reader waited for the +user's next keystroke to hear about the pane the request made. + +Two traps that cost real time. The first end-to-end run hung anyway: the Look completed on the connection task, then the editor woke +to perform the new pane's watch effect, and `inotify_add_watch` on a FUSE path is itself a request -- made while holding the turn. +The rule is therefore every host syscall on a user path, not fs.zig's alone; PDFs are read whole and opened from memory for the same +reason (MuPDF reads a file lazily at every page). The second: a parked write one byte longer than `park_data_max` fails EAGAIN, and +the client's largest write is msize less the 23-byte Twrite header, not less iohdrsz; a large Save to a peer's /os path came back +"save: Remote" until the engine's room was sized from a client. test/selfmount.py runs the editor under `9ns --mntgen` and Looks at, +reads and Saves its own tree through the mount; a unit test in 9p_io.zig pins that a change parks while the editor is out mid-step +and lands when it rests, while a read is answered in the window. + +Performance, same machine, Debug builds, 9P over the Unix socket against a tty session: a read of /index 278us -> 61us and a pane +body 283us -> 64us, because a read no longer waits for the editor to wake; a truncating body write 1184us -> 609us; exec Msg 696us +-> 543us; pane/new + rmdir 1535us -> 1295us; exec Save 718us -> 583us. A change still costs one editor frame, since the editor +draws it before it rests again. + +Left as they are: QUIC still runs on the editor's thread (cloud9's QUIC adapter is not std.Io based), so a QUIC client of a session +that Looks at its own QUIC-mounted tree would still wait on the loop; the Tty9p kernel mount lives in the helper's private +namespace, so a Look on `$PARDES_MOUNT/...` from that shell opens nothing in the editor -- no longer a deadlock, only a namespace +the editor is not in; and a message wider than its pane now keeps its tail rather than its head (msg.snap `msgtail`). + +Two adversarial reviews of that design. The concurrency one found the lost wake for real: a connection task's own yield saved the +editor's mid-step "not quiet" and restored it after the editor had rested, so a resting editor looked busy forever and every change +parked with nobody to wake it -- `quiet` is now `out`, a count of steps out in a syscall from any thread, and nothing saves or +restores it. Behind it, three more: the editor could take its turn back while a connection task's step was still out (that step's +pointers dangling when it returned) -- `wake` now waits for the count to reach zero; the core's allocator was a stack-fallback +over a FixedBufferAllocator, thread-safe only in Debug where the DebugAllocator wrapped it -- the fixed buffer is taken through +its lock-free interface now; and a Restore let a task waiting on the old core wake after that core was freed -- `reset` swaps the +listener's core first and releases every waiter, which then finds the core changed and answers nothing. It also showed that +parking `pane/new` and `screen` would have hung a Look at exactly those two paths in one's own mount (the editor's own open would +park, waiting for a rest that cannot come), so those are answered mid-step: every yield sits before its step's mutation, so the +layout and the surface are whole under it. Images are read at open for the same reason PDFs are. + +The rendering one found the chips drawn out from under: a placed image or PDF page is drawn after the cells (the GUI's image pass, +kitty's z-order), so a chip over a picture was painted over -- pictures give up the rows now, text keeps the overlay -- and in the +GUI a tree-sitter context band was emitted after the tag layers and painted over the chip, so body layers go first. A message is +one row of printable text (a language server's multi-line report read as one line with U+FFFD per newline), the 256-byte cut +never leaves half a glyph, and an over-wide message cut inside a wide glyph now drops that glyph rather than clipping its last. +The simplicity one cut the vestiges: `ninep_identity`, the restore's copy of listener addresses, `setWake`, the mailbox's +`Drained` name, the 64K read buffer, and the two macOS entry points whose multi-line signatures the wrapping had missed. diff --git a/src/9p.zig b/src/9p.zig index c0e7f61e..5ffe9058 100644 --- a/src/9p.zig +++ b/src/9p.zig @@ -52,9 +52,16 @@ pub const msize_min = cloud9.fs.msize_min; /// The smallest msize a native listener offers (src/9p_io.zig). pub const min_msize: u32 = 4096; +/// What a native listener negotiates. +pub const msize: u32 = 8192; -/// The editor's engine: native fid count, native file names. -pub const editor: cloud9.fs.Options = .{ .fid_capacity = max_fids, .name_capacity = 255 }; +/// The editor's engine: native fid count, native file names, and room to +/// park a write of any size a frame can carry -- a request that would change +/// a pane while the editor is out in a syscall waits in the engine +/// (src/9p_io.zig, `serve`), and a write it cannot keep would fail instead. +/// The largest write is msize less the Twrite header, 23 bytes (the test +/// below asks a client), one byte more than `iohdrsz` allows for. +pub const editor: cloud9.fs.Options = .{ .fid_capacity = max_fids, .name_capacity = 255, .park_data_max = msize - 23 }; /// The board's engine: the GPIO firmware's budget (src/esp32p4_9p.zig). pub const board: cloud9.fs.Options = .{ .fid_capacity = board_fids, .name_capacity = board_name_capacity }; @@ -70,6 +77,14 @@ const Stub = struct { pub const Reply = cloud9.fs.Reply; }; +test "9p server: the editor's engine can park the largest write a client sends" { + var in: [4096]u8 = undefined; + var out: [4096]u8 = undefined; + var client: Client = .init(.{ .in = &in, .out = &out }); + client.msize = msize; + try testing.expect(editor.park_data_max >= client.maxWrite()); +} + test "9p server: board and native capacities size the actual fid storage" { const Board = Server(Stub, board); const Native = Server(Stub, editor); diff --git a/src/9p_io.zig b/src/9p_io.zig index 08deae7a..7e09fb27 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -62,7 +62,7 @@ pub fn ensureSocketDir(dir: [:0]const u8) bool { const prefix = "pardes-9p-"; -pub const msize: u32 = 8192; +pub const msize = ninep.msize; pub const max_conns = 4; @@ -143,76 +143,17 @@ const Srv = ninep.Server(pardes.ctlfs, ninep.editor); /// The Unix and TCP listeners run on cloud9's `std.Io` runner: it accepts, /// reads frames, steps each connection's engine and writes replies on its -/// own tasks, and hands every backend request to the editor's thread -/// through `Slot` (see `tick`). QUIC keeps the poll loop below. +/// own tasks, and every backend request is answered right there, on the +/// connection's task, by taking the editor's turn (`pardes.turn`): while the +/// editor waits for input, or while a step of it is out in a syscall -- +/// which is what lets the editor read its own tree through a mount. QUIC +/// keeps the poll loop below, on the editor's thread. const Runner = if (supported) cloud9.serve.Runner(pardes.ctlfs, ninep.editor, .{ .msize = msize, .connections = max_conns, .listeners = 2, }) else void; -/// Answers one backend request on the editor's thread. -fn step(core: *pardes.Pardes, srv: *Srv, req: pardes.ctlfs.Req) void { - core.update(.{ .fs_req = req }); - var answered = false; - while (core.nextEffect()) |effect| { - if (effect == .fs_reply) { - const reply = effect.fs_reply; - if (reply.tag == req.tag) answered = true; - srv.reply(&reply, core.fsPayload(reply)); - } else core.perform(effect); - } - if (!answered) { - const reply = pardes.ctlfs.Reply.fail(req.tag, pardes.ctlfs.E.IO); - srv.reply(&reply, ""); - } -} - -/// Pays the backend a request whose connection is gone; replies go nowhere. -fn pay(core: *pardes.Pardes, req: pardes.ctlfs.Req) void { - core.update(.{ .fs_req = req }); - while (core.nextEffect()) |effect| if (effect != .fs_reply) core.perform(effect); -} - -/// One runner slot's mailbox: the requests its connection task handed over, -/// answered by the editor's thread in `tick`. A hangup's releases (at most -/// one per fid) and one outstanding request are the most it ever holds, -/// because a closing connection waits for its entries to be paid before -/// the slot is reused. -const Slot = struct { - const capacity = ninep.editor.fid_capacity + 2; - const Entry = struct { gen: u32, req: pardes.ctlfs.Req }; - - mutex: std.Io.Mutex = .init, - queue: [capacity]Entry = undefined, - head: usize = 0, - len: usize = 0, - /// Bumped when a connection takes the slot; entries carry the value. - gen: u32 = 0, - closing: bool = false, - drained: std.Io.Event = .unset, - /// Requests refused for want of room; never expected. - refused: u32 = 0, - - fn push(s: *Slot, req: pardes.ctlfs.Req) bool { - if (s.len == s.queue.len) { - s.refused += 1; - return false; - } - s.queue[(s.head + s.len) % capacity] = .{ .gen = s.gen, .req = req }; - s.len += 1; - return true; - } - - fn pop(s: *Slot) ?Entry { - if (s.len == 0) return null; - const e = s.queue[s.head]; - s.head = (s.head + 1) % capacity; - s.len -= 1; - return e; - } -}; - const quic_slots = if (quic_enabled) max_conns else 0; /// A QUIC connection on the poll path. @@ -229,12 +170,10 @@ const accept_pause_ms: i64 = 100; pub const Listener = struct { io: std.Io, + /// The core that answers; `reset` puts a replacement in. + core: *pardes.Pardes, runner: Runner = undefined, - slots: [max_conns]Slot = @splat(.{}), stopping: std.atomic.Value(bool) = .init(false), - /// While `reset` runs: the generation each slot is paying off; anything - /// newer waits for the replacement core. - resetting: ?[max_conns]u32 = null, tcp_address: ?std.Io.net.IpAddress = null, quic: if (quic_enabled) ?quic.Listener else void = if (quic_enabled) null else {}, quic_address: ?std.Io.net.IpAddress = null, @@ -264,47 +203,59 @@ pub const Listener = struct { return @ptrCast(@alignCast(ctx.?)); } - /// The runner's handler: on the connection's task. - fn onOpened(ctx: ?*anyopaque, conn: *Runner.Conn) void { - const l = of(ctx); - const s = &l.slots[conn.index]; - s.mutex.lockUncancelable(l.io); - s.gen +%= 1; - s.mutex.unlock(l.io); - } - + /// The runner's handler, on the connection's task: takes the turn and + /// answers. A request that would change a pane while the editor is out + /// in a syscall mid-step is parked in the engine instead, and retried + /// when the turn is next given up between steps (`wakeParked`). fn onServe(ctx: ?*anyopaque, conn: *Runner.Conn, req: pardes.ctlfs.Req) void { const l = of(ctx); - const s = &l.slots[conn.index]; - s.mutex.lockUncancelable(l.io); - const queued = s.push(req); - s.mutex.unlock(l.io); - if (!queued) { - const reply = pardes.ctlfs.Reply.fail(req.tag, pardes.ctlfs.E.IO); - conn.reply(&reply, ""); - return; + // Once `stop` has begun the editor is tearing down and may never + // rest again: answer without waiting on it. + if (l.stopping.load(.acquire)) { + const refused = pardes.ctlfs.Reply.fail(req.tag, pardes.ctlfs.E.IO); + return conn.reply(&refused, ""); + } + const quiet = pardes.turn.take(); + defer pardes.turn.give(); + if (!quiet and pardes.ctlfs.needsQuiet(req)) { + pardes.turn.parked = true; + const later: pardes.ctlfs.Reply = .{ .tag = req.tag, .status = .again }; + return conn.reply(&later, ""); } + const core = l.core; + const epoch = pardes.turn.epoch; + const restores = pardes.turn.restores; + const reply = core.serveFs(req); + if (req.op == .release and quiet) l.collectOs(); + if (!pardes.ctlfs.changesPane(req)) return conn.reply(&reply, core.fsPayload(reply)); + // The editor draws the change and performs what it asked for; when + // it asked for something -- a save, a shell, a watch -- the answer + // waits until that is done, so `echo Save > exec` returns with the + // file written. A change carries no payload, so the reply is still + // whole after the wait. l.kick(); - } - - /// Holds the slot until the editor's thread has paid what the - /// connection still owes, so a successor never inherits its entries. - fn onClosed(ctx: ?*anyopaque, conn: *Runner.Conn) void { + const restoring = core.restore_req != null; + if (core.effects_len != 0) pardes.turn.awaitSettled(epoch); + // Once a wait returns `core` may be gone: a Restore meanwhile put a + // replacement in (`reset`) and is hanging this connection up, which + // is a Restore's answer. Only one that failed leaves this connection + // here to answer. + if (l.core != core) return; + if (restoring) pardes.turn.awaitRestored(restores); + if (l.core != core) return; + conn.reply(&reply, ""); + } + + /// The turn was given up quiet with a request parked: every connection + /// retries what it parked. + fn wakeParked(ctx: ?*anyopaque) void { const l = of(ctx); - const s = &l.slots[conn.index]; if (l.stopping.load(.acquire)) return; - s.mutex.lockUncancelable(l.io); - if (s.len == 0) { - s.mutex.unlock(l.io); - return; - } - s.closing = true; - s.drained.reset(); - s.mutex.unlock(l.io); - l.kick(); - s.drained.wait(l.io) catch {}; + if (comptime supported) l.runner.wakeAll(); } + /// A request changed the core: the editor wakes to draw it and perform + /// what it asked for. fn kick(l: *Listener) void { if (l.stopping.load(.acquire)) return; if (l.wake) |f| f(l.wake_ctx); @@ -411,68 +362,46 @@ pub const Listener = struct { c.draining = true; } - pub const Drained = struct { count: usize = 0, pending: bool = false }; - - /// Answers what every connection has asked since the last call, retries - /// their parked reads against the editor's current state and has the - /// runner send the replies. Call it after each editor update, on the - /// editor's thread; `pending` says QUIC has more to do right away. - pub fn drain(l: *Listener, core: *pardes.Pardes) Drained { - core.fs.socket_path = l.path(); - core.fs.tcp_address = l.tcp_address; - core.fs.quic_address = l.quic_address; - l.expire(); - var result: Drained = .{}; - if (comptime supported) { - for (&l.slots, 0..) |*s, i| { - const conn = &l.runner.conns[i]; - s.mutex.lockUncancelable(l.io); - const only: ?u32 = if (l.resetting) |gens| gens[i] else null; - var count: usize = 0; - if (s.len != 0 or conn.live()) { - conn.lock(); - while (s.len != 0) { - if (only) |gen| if (s.queue[s.head].gen != gen) break; - const e = s.pop().?; - if (e.gen == s.gen) step(core, &conn.engine, e.req) else if (e.req.op == .release) pay(core, e.req); - count += 1; - } - if (conn.live() and (only == null or only.? == s.gen)) { - while (conn.engine.retry()) |req| { - step(core, &conn.engine, req); - count += 1; - } - while (conn.engine.next()) |req| { - step(core, &conn.engine, req); - count += 1; - } - } - const owed = conn.engine.output().len != 0; - conn.unlock(); - if (owed) conn.flush(); - } - if (s.closing and s.len == 0) { - s.closing = false; - s.drained.set(l.io); - } - s.mutex.unlock(l.io); - result.count += count; - if (count != 0) l.collectOs(core); - } - } + /// What one QUIC poll pass did: `pending` says there is more to do at + /// once. + pub const Polled = struct { count: usize = 0, pending: bool = false }; + + /// Answers one QUIC request, on the editor's thread. + fn step(l: *Listener, srv: *Srv, req: pardes.ctlfs.Req) void { + const reply = l.core.serveFs(req); + srv.reply(&reply, l.core.fsPayload(reply)); + if (req.op == .release) l.collectOs(); + } + + /// QUIC's events, accepts, reads, requests and replies, on the editor's + /// thread after each of its steps; `pending` says there is more to do + /// right away. Unix and TCP need none of this. + pub fn tick(l: *Listener) Polled { + var result: Polled = .{}; + // Between the editor's steps, which is when the table may be swept: + // the editor's own directory listings leave nodes in it too. + l.collectOs(); if (comptime quic_enabled) { + if (l.quic) |*listener| listener.events() catch |err| { + log.warn("QUIC listener stopped: {s}", .{@errorName(err)}); + for (&l.conns, 0..) |*conn, i| if (conn.quic != null) l.drop(@intCast(i)); + listener.deinit(); + l.quic = null; + l.quic_address = null; + }; + l.accept(); + for (0..quic_slots) |i| if (l.live(@intCast(i))) l.fill(@intCast(i)); + l.expire(); for (&l.conns, 0..) |*conn, i| { if (!l.live(@intCast(i)) and !conn.draining) continue; var count: usize = 0; while (conn.srv.retry()) |req| { - step(core, &conn.srv, req); - l.collectOs(core); + l.step(&conn.srv, req); count += 1; } while (count < 64) { const req = conn.srv.next() orelse break; - step(core, &conn.srv, req); - l.collectOs(core); + l.step(&conn.srv, req); count += 1; } result.count += count; @@ -482,64 +411,44 @@ pub const Listener = struct { } else l.flush(@intCast(i)); if (conn.quic) |*connection| result.pending = result.pending or connection.pending(); } + l.arm(); } return result; } - /// `drain` plus the QUIC listener's events, accepts and reads. - pub fn tick(l: *Listener, core: *pardes.Pardes) Drained { - if (comptime quic_enabled) { - if (l.quic) |*listener| listener.events() catch |err| { - log.warn("QUIC listener stopped: {s}", .{@errorName(err)}); - for (&l.conns, 0..) |*conn, i| if (conn.quic != null) l.drop(@intCast(i)); - listener.deinit(); - l.quic = null; - l.quic_address = null; - }; - l.accept(); - for (0..quic_slots) |i| if (l.live(@intCast(i))) l.fill(@intCast(i)); - } - const result = l.drain(core); - l.arm(); - return result; - } - - /// Hangs every connection up and pays `core` what they owed, so that a - /// replacement core starts with no client holding anything. A client - /// that connects meanwhile is not answered until the caller has put - /// the replacement in and calls `tick` again. - pub fn reset(l: *Listener, core: *pardes.Pardes) void { + /// Hangs every connection up, so that `replacement` starts with no + /// client holding anything. From here requests are answered from the + /// replacement -- a client that connects meanwhile is a client of the + /// replacement -- and every task waiting on the old core is let go: it + /// finds the core changed and answers nothing, its connection being + /// hung up. The connections pay their releases on their own tasks, so + /// the editor rests while they do. + pub fn reset(l: *Listener, replacement: *pardes.Pardes) void { for (0..quic_slots) |i| l.drop(@intCast(i)); + if (comptime quic_enabled) while (l.tick().pending) {}; + l.core = replacement; + replacement.fs.socket_path = l.path(); + replacement.fs.tcp_address = l.tcp_address; + replacement.fs.quic_address = l.quic_address; if (comptime supported) { - var gens: [max_conns]u32 = undefined; - for (&l.slots, &gens) |*s, *gen| { - s.mutex.lockUncancelable(l.io); - gen.* = s.gen; - s.mutex.unlock(l.io); - } - l.resetting = gens; - defer l.resetting = null; l.runner.closeAll(); + pardes.turn.settle(); + pardes.turn.restoreSettled(); + pardes.turn.rest(); const deadline = nowMs() +| 2000; - while (true) { - const drained = l.drain(core); - var idle = !drained.pending; - for (&l.slots, &gens, 0..) |*s, gen, i| { - s.mutex.lockUncancelable(l.io); - if (s.len != 0 and s.queue[s.head].gen == gen) idle = false; - if (s.gen == gen and l.runner.conns[i].live()) idle = false; - s.mutex.unlock(l.io); - } - if (idle or nowMs() >= deadline) break; - Client.nap(1); - } - } else while (l.drain(core).pending) {} - l.collectOs(core); + while (l.runner.count() != 0 and nowMs() < deadline) Client.nap(1); + pardes.turn.wake(); + } + l.collectOs(); for (&l.conns) |*conn| conn.accepted_ms = 0; l.arm(); } - fn collectOs(l: *Listener, core: *pardes.Pardes) void { + /// Forgets the host paths no connection names any more. With the turn, + /// and only between the editor's steps: a step out in a syscall may be + /// reading one of these entries. + fn collectOs(l: *Listener) void { + const core = l.core; var i: usize = 0; while (i < core.fs.os_paths.items.len) { const entry = core.fs.os_paths.items[i]; @@ -552,17 +461,10 @@ pub const Listener = struct { } } - /// Whether any connection, or a release still to be paid, names `node`. + /// Whether any connection names `node`. fn references(l: *Listener, node: u64) bool { if (comptime supported) { - for (&l.slots, 0..) |*s, i| { - const conn = &l.runner.conns[i]; - s.mutex.lockUncancelable(l.io); - defer s.mutex.unlock(l.io); - var k: usize = 0; - while (k < s.len) : (k += 1) { - if (s.queue[(s.head + k) % Slot.capacity].req.node == node) return true; - } + for (&l.runner.conns) |*conn| { if (!conn.live()) continue; conn.lock(); defer conn.unlock(); @@ -576,16 +478,12 @@ pub const Listener = struct { return false; } - /// Where the runner's tasks report that a request waits for `tick`. - pub fn setWake(l: *Listener, ctx: ?*anyopaque, wake: *const fn (?*anyopaque) void) void { + /// Where the runner's tasks report that a request changed the core, + /// and for QUIC a thread that watches its socket and calls `wake` when + /// `tick` has something to read. + pub fn watch(l: *Listener, ctx: ?*anyopaque, wake: *const fn (?*anyopaque) void) !void { l.wake_ctx = ctx; l.wake = wake; - } - - /// `setWake`, and for QUIC a thread that watches its socket and calls - /// `wake` when `tick` has something to read. - pub fn watch(l: *Listener, ctx: ?*anyopaque, wake: *const fn (?*anyopaque) void) !void { - l.setWake(ctx, wake); if (comptime !quic_enabled) return; if (l.quic == null or l.watcher != null) return; if (libc.pipe(&l.control) != 0) return error.PipeFailed; @@ -735,7 +633,15 @@ pub const Listener = struct { if (comptime quic_enabled) { if (l.quic) |*listener| listener.deinit(); } - if (comptime supported) l.runner.stop(); + if (comptime supported) { + // A connection task may be waiting for the turn; it answers + // nothing more once stopping, but the wait itself must end. + pardes.turn.rest(); + l.runner.stop(); + pardes.turn.wake(); + } + pardes.turn.wake_parked = null; + pardes.turn.stop(); if (l.path_len != 0) { var z: [sun_path_len:0]u8 = undefined; @memcpy(z[0..l.path_len], l.path_buf[0..l.path_len]); @@ -752,7 +658,9 @@ pub fn socketPath(buf: *[sun_path_len]u8, dir: []const u8, name: []const u8) ?[: return std.fmt.bufPrintSentinel(buf, "{s}/" ++ prefix ++ "{s}.sock", .{ dir, name }, 0) catch null; } -pub fn listen(io: std.Io, gpa: std.mem.Allocator, named: []const u8, fallback: []const u8, tcp_dial: ?[]const u8, quic_dial: ?[]const u8) ?*Listener { +/// Serves `core`. From here on the calling thread has the editor's turn +/// (`pardes.turn`) and must give it up while it waits. +pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: []const u8, fallback: []const u8, tcp_dial: ?[]const u8, quic_dial: ?[]const u8) ?*Listener { if (comptime !supported) return null; var dir_buf: [sun_path_len:0]u8 = undefined; const dir = socketDir(&dir_buf) orelse { @@ -761,11 +669,14 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, named: []const u8, fallback: [ }; if (!ensureSocketDir(dir)) return null; const l = gpa.create(Listener) catch return null; - l.* = .{ .io = io }; + l.* = .{ .io = io, .core = core }; + pardes.turn.start(io); + pardes.turn.wake_parked = Listener.wakeParked; + pardes.turn.wake_ctx = l; l.runner.init(.{ .io = io, .root = pardes.ctlfs.root, - .handler = .{ .ctx = l, .serve = Listener.onServe, .opened = Listener.onOpened, .closed = Listener.onClosed }, + .handler = .{ .ctx = l, .serve = Listener.onServe }, .greet_timeout_ms = Listener.greet_deadline_ms, }); const entry_name = if (named.len != 0) named else fallback; @@ -838,6 +749,9 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, named: []const u8, fallback: [ } } log.info("serving 9P2000 on {s}", .{p}); + core.fs.socket_path = l.path(); + core.fs.tcp_address = l.tcp_address; + core.fs.quic_address = l.quic_address; return l; } @@ -1160,33 +1074,6 @@ test "TCP addresses are numeric and normalize mapped IPv4" { } else try testing.expectError(error.QuicUnavailable, Client.validateDial("quic!127.0.0.1!5640")); } -test "same-session TCP mounts compare canonical endpoints and local wildcard destinations" { - if (comptime !supported) return error.SkipZigTest; - const Case = struct { bound: []const u8, dial: []const u8, same: bool }; - for ([_]Case{ - .{ .bound = "tcp!127.0.0.1!5640", .dial = "tcp!::ffff:127.0.0.1!5640", .same = true }, - .{ .bound = "tcp!::ffff:127.0.0.1!5640", .dial = "tcp!127.0.0.1!5640", .same = true }, - .{ .bound = "tcp!::1!5640", .dial = "tcp!0:0:0:0:0:0:0:1!5640", .same = true }, - .{ .bound = "tcp!127.0.0.1!5640", .dial = "tcp!0.0.0.0!5640", .same = true }, - .{ .bound = "tcp!::1!5640", .dial = "tcp!::!5640", .same = true }, - .{ .bound = "tcp!0.0.0.0!5640", .dial = "tcp!127.0.0.2!5640", .same = true }, - .{ .bound = "tcp!::!5640", .dial = "tcp!::1!5640", .same = true }, - .{ .bound = "tcp!127.0.0.1!5640", .dial = "tcp!127.0.0.1!5641", .same = false }, - .{ .bound = "tcp!0.0.0.0!5640", .dial = "tcp!192.0.2.1!5640", .same = false }, - .{ .bound = "tcp!::!5640", .dial = "tcp!2001:db8::1!5640", .same = false }, - .{ .bound = "tcp!::!5640", .dial = "tcp!127.0.0.1!5640", .same = false }, - }) |c| try testing.expectEqual(c.same, Client.sameSession(c.dial, "", try networkAddress(c.bound, true), null)); - try testing.expect(Client.sameSession("/tmp/pardes-owned.sock", "/tmp/pardes-owned.sock", null, null)); - try testing.expect(Client.sameSession("unix!/tmp/pardes-owned.sock", "/tmp/pardes-owned.sock", null, null)); - try testing.expect(!Client.sameSession("tcp!127.0.0.1!5640", "/tmp/pardes-owned.sock", null, null)); - if (quic_enabled) { - const endpoint = try networkAddress("quic!127.0.0.1!5640", false); - try testing.expect(Client.sameSession("quic!::ffff:127.0.0.1!5640", "", null, endpoint)); - try testing.expect(!Client.sameSession("tcp!127.0.0.1!5640", "", null, endpoint)); - try testing.expect(!Client.sameSession("quic!127.0.0.1!5640", "", endpoint, null)); - } -} - extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; extern "c" fn rmdir(path: [*:0]const u8) c_int; @@ -1225,7 +1112,9 @@ test "a listening editor posts itself into the 9P registry and unposts on stop" var link: [sun_path_len]u8 = undefined; { - const l = listen(testing.io, gpa, "unit", "", null, null) orelse return error.ListenFailed; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + const l = listen(testing.io, gpa, p, "unit", "", null, null) orelse return error.ListenFailed; defer l.deinit(gpa); // The socket stays exactly where pardes has always bound it: // adopting the registry moves nothing, it only advertises. @@ -1312,7 +1201,7 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r var bind_buf: [64]u8 = undefined; const bind = try std.fmt.bufPrint(&bind_buf, "{s}!{s}!0", .{ protocol, host }); const tcp = std.mem.eql(u8, protocol, "tcp"); - const l = listen(testing.io, gpa, "roundtrip", "", if (tcp) bind else null, if (tcp) null else bind) orelse return error.ListenFailed; + const l = listen(testing.io, gpa, p, "roundtrip", "", if (tcp) bind else null, if (tcp) null else bind) orelse return error.ListenFailed; defer { l.reset(p); l.deinit(gpa); @@ -1331,39 +1220,108 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r 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 = Client.nowMs() + 3 * Client.budget_ms; + pardes.turn.rest(); while (!worker.done.load(.acquire) and Client.nowMs() < deadline) { - _ = l.tick(p); + if (quic_enabled) { + pardes.turn.wake(); + _ = l.tick(); + pardes.turn.rest(); + } Client.nap(1); } + pardes.turn.wake(); try testing.expect(worker.done.load(.acquire)); if (worker.failure) |err| return err; l.reset(p); try testing.expectEqual(@as(usize, 0), l.runner.count()); - for (&l.slots) |*slot| try testing.expectEqual(@as(usize, 0), slot.len); for (&l.conns, 0..) |conn, i| try testing.expect(!l.live(@intCast(i)) and !conn.draining); for (p.fs.snapshots) |snapshot| try testing.expect(snapshot.node == 0); } }; } +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 directory: [64:0]u8 = undefined; + _ = try std.fmt.bufPrintSentinel(&directory, "/tmp/pardes-park-XXXXXX", .{}, 0); + if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; + defer _ = rmdir(&directory); + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + defer { + if (old_runtime) |v| { + _ = setenv("XDG_RUNTIME_DIR", v, 1); + gpa.free(v); + } else _ = unsetenv("XDG_RUNTIME_DIR"); + } + try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); + + 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 = listen(testing.io, gpa, p, "park", "", null, null) orelse return error.ListenFailed; + 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 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 }; + + // 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(); + Client.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); + + // Resting is what lets it in: the parked write is retried, served, and + // the client hears back. + pardes.turn.rest(); + const deadline = Client.nowMs() + Client.budget_ms; + while (!writer.done.load(.acquire) and Client.nowMs() < deadline) Client.nap(1); + pardes.turn.wake(); + try testing.expect(writer.done.load(.acquire)); + if (writer.failure) |err| return err; + try testing.expectEqualStrings("after\n", pane.file.?.content); +} + extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; extern "c" fn unsetenv(name: [*:0]const u8) c_int; pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes) ?*Listener { var name: [16]u8 = undefined; const fallback = std.fmt.bufPrint(&name, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable; - const listener = listen(io, gpa, core.opts.ninep_name, fallback, core.opts.ninep_tcp, core.opts.ninep_quic) orelse { + return listen(io, gpa, core, core.opts.ninep_name, fallback, core.opts.ninep_tcp, core.opts.ninep_quic) orelse { core.reportError(0, "9p listener", error.ListenFailed); return null; }; - core.fs.socket_path = listener.path(); - // So the editor can recognise its own tree by name and refuse to walk into - // it through the mount, which would deadlock the loop that serves it. - pardes.filesystem.noteOwnSocket(listener.path()); - core.fs.tcp_address = listener.tcp_address; - core.fs.quic_address = listener.quic_address; - return listener; } /// What a pane shell is told about the editor above it, set into this @@ -1423,7 +1381,7 @@ test "9P shell environment states being inside pardes apart from how to reach it const listener = try testing.allocator.create(Listener); defer testing.allocator.destroy(listener); - listener.* = .{ .io = testing.io }; + listener.* = .{ .io = testing.io, .core = undefined }; // only its path is read const path = "/tmp/pardes-example.sock"; @memcpy(listener.path_buf[0..path.len], path); listener.path_len = path.len; @@ -1549,35 +1507,6 @@ pub const Client = struct { _ = try resolve(&buf, dial); } - pub fn sameSession(dial: []const u8, socket_path: []const u8, tcp_address: ?std.Io.net.IpAddress, quic_address: ?std.Io.net.IpAddress) bool { - if (comptime !supported) return false; - var buf: [sun_path_len]u8 = undefined; - const address = resolve(&buf, dial) catch return false; - switch (address) { - .unix => |path| return socket_path.len != 0 and std.mem.eql(u8, path, socket_path), - .tcp, .quic => |destination| { - var ip = destination; - switch (ip) { - .ip4 => |v4| if (std.mem.allEqual(u8, &v4.bytes, 0)) { - ip = .{ .ip4 = .loopback(v4.port) }; - }, - .ip6 => |v6| if (std.mem.allEqual(u8, &v6.bytes, 0)) { - ip = .{ .ip6 = .loopback(v6.port) }; - }, - } - const bound = canonicalIp((if (address == .tcp) tcp_address else quic_address) orelse return false); - if (ip.getPort() != bound.getPort() or @as(std.Io.net.IpAddress.Family, ip) != @as(std.Io.net.IpAddress.Family, bound)) return false; - if (ip.eql(&bound)) return true; - const wildcard = switch (bound) { - .ip4 => |v4| std.mem.allEqual(u8, &v4.bytes, 0), - .ip6 => |v6| std.mem.allEqual(u8, &v6.bytes, 0), - }; - if (wildcard) return localIp(ip); - return false; - }, - } - } - const Session = struct { fd: c_int, quic: if (quic_enabled) ?quic.Connection else void = if (quic_enabled) null else {}, diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index e518f97a..0083f97f 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,19 @@ ## 0.0.3 +- Answer 9P on the connection's task instead of the editor's loop. The core + is single-threaded and `pardes.turn` says whose turn it is with it: the + editor's by default, given up while it waits for input and while a step of + it is out in a syscall, and taken by a connection task to answer a request. + A request that would change a pane while a step is out parks in the engine + and is retried when the editor rests. So a session can open, read and save + its own tree through a mount -- which used to hang it outright, and was + then refused by name -- and the name-based refusal, the in-process routing + of a mount of oneself and the mailbox that shipped every request to the + editor's thread are gone. +- A notice wider than its pane keeps its tail rather than its head: the end + of a message is the file name or the reason. + - Give pty children their own terminal identity. `TERM`, `COLORTERM` and `TERM_PROGRAM` are now written by pardes rather than inherited from whatever launched it, and the child is exec'd with that environment. A macOS `.app` diff --git a/src/detached/server.zig b/src/detached/server.zig index ac9af2ee..3e98fc9d 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -156,7 +156,8 @@ pub const Session = struct { inotify_fd: c_int = -1, ninep: ?*ninep_io.Listener = null, ninep_pending: bool = false, - /// Set by the 9P runner's tasks: a request waits for `tick`. + /// A 9P request changed the core since the wake byte was last drained: + /// the next poll returns at once, to draw it. ninep_wake: std.atomic.Value(bool) = .init(false), watches: file_watch.Table = @splat(null), check_files: bool = false, @@ -240,7 +241,7 @@ pub const Session = struct { file_watch.watchPane(s.inotify_fd, &s.watches, @intCast(pane), null, 0, .{ .text = 0 }); _ = file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, 0, false, false); s.check_files = false; - if (s.ninep) |listener| listener.reset(s.core); + if (s.ninep) |listener| listener.reset(replacement); s.ninep_pending = false; replacement.host = s.host(); s.core.deinit(); @@ -587,7 +588,7 @@ pub const Session = struct { if (s.origins()) |c| s.send(c, .detach); } - /// The 9P runner has a request for `tick`: wake the poll loop. + /// A 9P request changed the core: wake the poll loop to draw it. fn wakeNinep(ctx: ?*anyopaque) void { const s = of(ctx); s.ninep_wake.store(true, .release); @@ -596,7 +597,7 @@ pub const Session = struct { fn pollFrame(ctx: ?*anyopaque) void { const s = of(ctx); - if (s.ninep) |l| s.ninep_pending = l.tick(s.core).pending; + if (s.ninep) |l| s.ninep_pending = l.tick().pending; for (&s.ptys, 0..) |*pt, pane| { if (pt.fd < 0) continue; var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; @@ -805,11 +806,18 @@ pub const Session = struct { } } } - if (n == 0) return nap(if (timeout_ms == 0) 16 else timeout_ms); + // The wait is the 9P connections' turn with the core. + if (n == 0) { + pardes.turn.rest(); + defer pardes.turn.wake(); + return nap(if (timeout_ms == 0) 16 else timeout_ms); + } var timeout: c_int = if (timeout_ms == 0) -1 else @intCast(@min(timeout_ms, std.math.maxInt(c_int))); if (s.nextWake(now)) |due| timeout = if (timeout < 0) due else @min(timeout, due); if (completed or s.check_files or regridded or s.ninep_pending) timeout = 0; + pardes.turn.rest(); const ready = libc.poll(&fds, @intCast(n), timeout); + pardes.turn.wake(); if (ready > 0) s.dispatch(fds[0..n], src[0..n]); _ = s.drainCompletions(true); s.expire(monotonicMs()); @@ -1134,18 +1142,17 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void return error.NoSocket; } - session.ninep = ninep_io.listen(init.io, gpa, opts.ninep_name, name, opts.ninep_tcp, opts.ninep_quic); + session.ninep = ninep_io.listen(init.io, gpa, core, opts.ninep_name, name, opts.ninep_tcp, opts.ninep_quic); if (session.ninep == null) return error.ListenFailed; - session.ninep.?.setWake(&session, Session.wakeNinep); - core.fs.socket_path = session.ninep.?.path(); - core.fs.tcp_address = session.ninep.?.tcp_address; - core.fs.quic_address = session.ninep.?.quic_address; + session.ninep.?.wake_ctx = &session; + session.ninep.?.wake = Session.wakeNinep; const h = session.host(); core.host = h; while (core.nextEffect()) |effect| core.perform(effect); session.in_loop = true; while (!session.core.quit) { + pardes.turn.restoreSettled(); try session.core.pump(h); if (session.core.quit) break; if (session.core.takeRestore()) |path| restore: { diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 6805d980..20b5c093 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -509,7 +509,7 @@ const Ul = @FieldType(pardes.CellStyle, "ul"); /// which is the whole property the six hand-written switches this replaced /// existed for, in a form that cannot fall out of step. A variant that has to /// travel under a DIFFERENT name than the core's gets an arm of its own before -/// the `inline else`, exactly as `clientTag` keeps `.fs_req`. +/// the `inline else`, exactly as `clientTag` keeps the machine-local reports. fn putUl(w: *Writer, u: Ul) Error!void { try w.putByte(switch (u) { inline else => |t| @intFromEnum(@field(UlTag, @tagName(t))), @@ -819,7 +819,7 @@ fn clientTag(msg: ClientMsg) ClientTag { return switch (msg) { .event => |ev| switch (ev) { // Machine-local reports and 9P requests belong to the session owner. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick => unreachable, inline else => |_, t| @field(ClientTag, @tagName(t)), }, inline else => |_, t| @field(ClientTag, @tagName(t)), @@ -946,7 +946,7 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { .touch_scroll => |v| try w.putF32(v), .pointer_leave => {}, // See `clientTag`: no tag, so nothing to encode. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick => unreachable, }, } try finishMessage(&w, at); @@ -1076,7 +1076,7 @@ pub fn clientBound(msg: ClientMsg) usize { .paste => |b| b.len, .command => |line| line.len, // See `clientTag`: not on this wire in this direction. - .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick, .fs_req => unreachable, + .output, .eof, .lsp_resp, .pipe_resp, .file_changed, .tick => unreachable, }, }; } diff --git a/src/file_watch.zig b/src/file_watch.zig index b2908eb7..dfcce65f 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -382,6 +382,10 @@ fn watchPath( } const declared_path = path orelse return; const watched_path = filesystem.localPath(declared_path) orelse return; + // The path may lie in a mount this editor serves, and marking it is a + // stat and a lookup out there: the turn goes out with them. + pardes.turn.yield(); + defer pardes.turn.back(); const stat = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), watched_path, .{}) catch null; const dir = if (stat != null and stat.?.kind == .directory) watched_path else std.fs.path.dirname(watched_path) orelse "."; var dir_buf: [4096:0]u8 = undefined; @@ -601,6 +605,8 @@ pub fn reloadTheme( pub fn identify(io: std.Io, path: []const u8) !Identity { const native = filesystem.localPath(path) orelse return error.NonLocalPath; + pardes.turn.yield(); + defer pardes.turn.back(); const stat = try std.Io.Dir.cwd().statFile(io, native, .{}); if (stat.kind != .file) return error.NotFile; return .{ diff --git a/src/fs.zig b/src/fs.zig index 9200236d..85eae825 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -64,10 +64,9 @@ pub const WriteError = error{ WriteFailed, }; +/// The host takes the bytes. The caller has given the turn up (`write`), +/// because the path may be a mount this editor serves. pub fn writeFile(path: []const u8, bytes: []const u8) WriteError!void { - // No core here to answer from, so the only safe answer is no answer: an - // open(2) into our own mount is the call that never returns. - if (isOwnMount(path)) return error.OpenFailed; var pathbuf: [4096:0]u8 = undefined; if (path.len >= pathbuf.len) return error.PathTooLong; if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed; @@ -124,12 +123,21 @@ fn osNode(p: *pardes.Pardes, path: []const u8) !u64 { return node; } +/// The host filesystem under /os. Every syscall here may go out through a +/// mount this editor serves, so the turn is given up around each and taken +/// back before the core is touched; `path` is the table entry's own copy and +/// outlives the yield, and nothing is staged into the shared reply buffer +/// until the turn is back. pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { if (comptime !platform_has_fs) return Reply.fail(req.tag, E.NOENT); const path = osPath(p, req.node) orelse return Reply.fail(req.tag, E.NOENT); if (req.op == .release) return .{ .tag = req.tag }; const io = std.Io.Threaded.global_single_threaded.io(); - const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch return Reply.fail(req.tag, E.NOENT); + const stat = stat: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :stat std.Io.Dir.cwd().statFile(io, path, .{}) catch return Reply.fail(req.tag, E.NOENT); + }; const attr: Reply.Attr = .{ .name = if (req.node == os_root) "os" else std.fs.path.basename(path), .node = req.node, .dir = stat.kind == .directory, .size = stat.size, .mode = if (stat.kind == .directory) 0o755 else 0o644, .mtime = std.math.cast(u32, stat.mtime.toSeconds()) orelse 0 }; switch (req.op) { .getattr => return .{ .tag = req.tag, .attr = attr }, @@ -150,52 +158,67 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { return osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); }, .readdir => { - var dir = std.Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return Reply.fail(req.tag, E.NOTDIR); - defer dir.close(io); - var it = dir.iterate(); - const out = p.fs.stage(p.gpa); - var skip = req.off; - while (it.next(io) catch return Reply.fail(req.tag, E.IO)) |entry| { - var buf: [4096]u8 = undefined; - const joined = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), entry.name }) catch continue; - var normalized_buf: [4096]u8 = undefined; - const normalized = resolveOs(joined, &normalized_buf) orelse continue; - const child = dir.statFile(io, entry.name, .{}) catch continue; - if (skip > 0) { - skip -= 1; - continue; + // Listed into a buffer of this request's own first; the shared + // reply buffer is another request's to use while the turn is out. + var listing: [16 * 1024]u8 = undefined; + var fixed: std.heap.FixedBufferAllocator = .init(&listing); + var listed: std.ArrayList(u8) = .empty; + { + pardes.turn.yield(); + defer pardes.turn.back(); + var dir = std.Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return Reply.fail(req.tag, E.NOTDIR); + defer dir.close(io); + var it = dir.iterate(); + var skip = req.off; + while (it.next(io) catch return Reply.fail(req.tag, E.IO)) |entry| { + var buf: [4096]u8 = undefined; + const joined = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), entry.name }) catch continue; + var normalized_buf: [4096]u8 = undefined; + const normalized = resolveOs(joined, &normalized_buf) orelse continue; + const child = dir.statFile(io, entry.name, .{}) catch continue; + if (skip > 0) { + skip -= 1; + continue; + } + const node = if (std.mem.eql(u8, normalized.path, "/")) os_root else os_node | (std.hash.Wyhash.hash(0, normalized.path) & (os_node - 1)); + tree.stageDirent(&listed, fixed.allocator(), node, child.kind == .directory, entry.name); + if (listed.items.len >= @max(req.size, 512)) break; } - const node = if (std.mem.eql(u8, normalized.path, "/")) os_root else os_node | (std.hash.Wyhash.hash(0, normalized.path) & (os_node - 1)); - tree.stageDirent(out, p.gpa, node, child.kind == .directory, entry.name); - if (out.items.len >= @max(req.size, 512)) break; } + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, listed.items) catch return Reply.fail(req.tag, E.NOMEM); return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; }, .read, .write, .setattr => { if (stat.kind != .file) return Reply.fail(req.tag, E.PERM); var z: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return Reply.fail(req.tag, E.NOENT); - const fd = libc.open(path_z, .{ .ACCMODE = if (req.op == .read) .RDONLY else .WRONLY, .NONBLOCK = true, .CLOEXEC = true }); - if (fd < 0) return Reply.fail(req.tag, E.PERM); - defer _ = libc.close(fd); - if (req.op == .setattr) { - if (!req.truncate or req.off != 0 or libc.ftruncate(fd, 0) != 0) return Reply.fail(req.tag, E.INVAL); - var truncated = attr; - truncated.size = 0; - return .{ .tag = req.tag, .attr = truncated }; - } - if (req.off > std.math.maxInt(i64)) return Reply.fail(req.tag, E.INVAL); - if (libc.lseek(fd, @intCast(req.off), libc.SEEK.SET) < 0) return Reply.fail(req.tag, E.IO); - if (req.op == .write) { - const written = libc.write(fd, req.data.ptr, req.data.len); - if (written < 0) return Reply.fail(req.tag, E.IO); - return .{ .tag = req.tag, .written = @intCast(written) }; - } + var buf: [ninep_io.msize]u8 = undefined; // a read never asks for more than a frame + const got = io: { + pardes.turn.yield(); + defer pardes.turn.back(); + const fd = libc.open(path_z, .{ .ACCMODE = if (req.op == .read) .RDONLY else .WRONLY, .NONBLOCK = true, .CLOEXEC = true }); + if (fd < 0) return Reply.fail(req.tag, E.PERM); + defer _ = libc.close(fd); + if (req.op == .setattr) { + if (!req.truncate or req.off != 0 or libc.ftruncate(fd, 0) != 0) return Reply.fail(req.tag, E.INVAL); + var truncated = attr; + truncated.size = 0; + return .{ .tag = req.tag, .attr = truncated }; + } + if (req.off > std.math.maxInt(i64)) return Reply.fail(req.tag, E.INVAL); + if (libc.lseek(fd, @intCast(req.off), libc.SEEK.SET) < 0) return Reply.fail(req.tag, E.IO); + if (req.op == .write) { + const written = libc.write(fd, req.data.ptr, req.data.len); + if (written < 0) return Reply.fail(req.tag, E.IO); + return .{ .tag = req.tag, .written = @intCast(written) }; + } + const got = libc.read(fd, &buf, @min(req.size, buf.len)); + if (got < 0) return Reply.fail(req.tag, E.IO); + break :io @as(usize, @intCast(got)); + }; const out = p.fs.stage(p.gpa); - out.resize(p.gpa, @min(req.size, 65536)) catch return Reply.fail(req.tag, E.NOMEM); - const got = libc.read(fd, out.items.ptr, out.items.len); - if (got < 0) return Reply.fail(req.tag, E.IO); - out.shrinkRetainingCapacity(@intCast(got)); + out.appendSlice(p.gpa, buf[0..got]) catch return Reply.fail(req.tag, E.NOMEM); return .{ .tag = req.tag, .payload = .{ .staged = @intCast(got) } }; }, else => return Reply.fail(req.tag, E.PERM), @@ -378,21 +401,22 @@ test "bounded reads accept exact OS file lengths and empty files" { const empty = try readLimit(p, explicit, 0); defer gpa.free(empty); try std.testing.expectEqual(@as(usize, 0), empty.len); - try std.testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.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(); - p.fs.socket_path = "/tmp/pardes-limited-in-process.sock"; - try p.fs.mount(gpa, "own", p.fs.socket_path); 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", "/n/own" }) |prefix| { - if (!platform_has_fs and std.mem.eql(u8, prefix, "/n/own")) continue; + 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); @@ -407,8 +431,7 @@ test "bounded reads apply the same limits to self bodies and embedded sources" { } if (limits.embedded_sources) { const source = findEmbeddedSource("src/look.zig", false).?; - for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig", "/n/own/src/look.zig" }) |path| { - if (!platform_has_fs and std.mem.startsWith(u8, path, "/n/own/")) continue; + 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); @@ -425,10 +448,8 @@ 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"; - try p.fs.mount(gpa, "own", p.fs.socket_path); - for ([_][]const u8{ "/n", "/virtual", "/n/self", "/n/own", "/n/own/pane", "/virtual/listeners", "/virtual/README" }) |path| { - if (!platform_has_fs and std.mem.startsWith(u8, path, "/n/own")) continue; + 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); @@ -573,49 +594,6 @@ test "virtual body writes can read their input from the same pane" { try std.testing.expectEqualStrings("pane contents\n", pane.file.?.content); } -test "same-core mount directories preserve their mount prefix across reads" { - if (!platform_has_fs) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const socket_path = "/tmp/pardes-in-process-mount.sock"; - p.fs.socket_path = socket_path; - try p.fs.mount(gpa, "own", socket_path); - const roots = try read(p, "/n/own"); - defer gpa.free(roots); - try std.testing.expect(std.mem.startsWith(u8, roots, "/n/own/README\n/n/own/index\n")); - try std.testing.expect(std.mem.indexOf(u8, roots, "/n/own/pane/\n/n/own/os/\n") != null); - try std.testing.expectError(error.NotADirectory, read(p, "/n/own/index/..")); - try std.testing.expectError(error.FileNotFound, read(p, "/n/own/self/index")); - - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - for (0..520) |i| { - var name: [32]u8 = undefined; - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = try std.fmt.bufPrint(&name, "entry-{d:0>4}.txt", .{i}), .data = "child\n" }); - } - var directory_buffer: [4096]u8 = undefined; - const directory = directory_buffer[0..try tmp.dir.realPath(std.testing.io, &directory_buffer)]; - const held_node = try osNode(p, directory); - const path = try std.fmt.allocPrint(gpa, "/n/own/os{s}", .{directory}); - defer gpa.free(path); - const listing = try read(p, path); - defer gpa.free(listing); - var entries = std.mem.tokenizeScalar(u8, listing, '\n'); - var count: usize = 0; - while (entries.next()) |entry| { - try std.testing.expect(std.mem.startsWith(u8, entry, path)); - const child = try read(p, entry); - defer gpa.free(child); - try std.testing.expectEqualStrings("child\n", child); - try std.testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len); - count += 1; - } - try std.testing.expectEqual(@as(usize, 520), count); - try std.testing.expectEqual(held_node, p.fs.os_paths.items[0].node); - try std.testing.expectEqualStrings(directory, p.fs.os_paths.items[0].path); -} - 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/"); @@ -674,9 +652,6 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 } if (std.mem.eql(u8, joined, "/virtual")) return resolveVirtual(p, "/", out); if (std.mem.startsWith(u8, joined, "/virtual/")) return resolveVirtual(p, joined[8..], out); - // This editor's own tree, seen through a mount: answer from the tree - // instead of walking out into the view and back in. - if (ownMountSuffix(joined)) |inner| return resolveVirtual(p, inner, out); if (resolveOs(joined, out)) |found| return found; if (resolveVirtual(p, joined, out)) |found| return found; if (resolveVirtual(p, word, out)) |found| return found; @@ -687,116 +662,15 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 return null; } -/// The name this session is posted under, taken from its socket path. -/// As wide as a name a listener will accept, so there is no session whose -/// name is too long to recognise and therefore too long to protect. -var own_name_buf: [108]u8 = undefined; -var own_name_len: usize = 0; - -pub fn noteOwnSocket(socket_path: []const u8) void { - own_name_len = 0; - const base = std.fs.path.basename(socket_path); - const head = "pardes-9p-"; - const tail = ".sock"; - if (!std.mem.startsWith(u8, base, head) or !std.mem.endsWith(u8, base, tail)) return; - const name = base[head.len .. base.len - tail.len]; - if (name.len == 0 or name.len > own_name_buf.len) return; - @memcpy(own_name_buf[0..name.len], name); - own_name_len = name.len; -} - -/// What this path names inside this editor's OWN 9P tree, if it does: -/// `/mnt/9p/pardes//pane/3/body` -> `pane/3/body`, and the mount root -/// itself -> `/`. -/// -/// A mount is a VIEW of a tree this editor already holds. Going out through -/// the view to reach it deadlocks the session outright -- the realpath, the -/// stat and the read all leave through the mount and come back as 9P requests -/// only this editor's loop can answer, while that loop is blocked making them, -/// and the filesystem then stops answering anybody. So the view is recognised -/// by NAME, before any syscall (the syscall is the thing that never returns), -/// and the request is served from the tree directly. Same answer, no round -/// trip, and a session can drive itself through its own 9P namespace. -pub fn ownMountSuffix(path: []const u8) ?[]const u8 { - if (own_name_len == 0 or path.len == 0 or path[0] != '/') return null; - // Whole components, and the registry's own layout: a session is posted at - // `/9p/pardes/` and mounts group under `/mnt/9p/pardes/`. - // Matching a bare `/pardes/` anywhere in the string would claim - // `~/src/pardes//README` -- an ordinary directory that happens to - // read like a mount -- and serve the tree's README over the real file. - var buf: [own_name_buf.len + 16]u8 = undefined; - const stem = std.fmt.bufPrint(&buf, "/9p/pardes/{s}", .{own_name_buf[0..own_name_len]}) catch return null; - var at: usize = 0; - while (std.mem.indexOfPos(u8, path, at, stem)) |found| : (at = found + 1) { - const rest = path[found + stem.len ..]; - if (rest.len != 0 and rest[0] != '/') continue; // a longer name that merely starts the same - if (rest.len <= 1) return "/"; - return rest[1..]; - } - return null; -} - -pub fn isOwnMount(path: []const u8) bool { - return ownMountSuffix(path) != null; -} - -test "a path inside this session's own mount is answered from the tree, not through the mount" { - noteOwnSocket("/run/user/1000/pardes-9p-demo.sock"); - defer own_name_len = 0; - // What the path names inside the tree, with the mount prefix taken off. - try std.testing.expectEqualStrings("index", ownMountSuffix("/mnt/9p/pardes/demo/index").?); - try std.testing.expectEqualStrings("pane/new", ownMountSuffix("/mnt/9p/pardes/demo/pane/new").?); - try std.testing.expectEqualStrings("/", ownMountSuffix("/mnt/9p/pardes/demo").?); - try std.testing.expectEqualStrings("/", ownMountSuffix("/mnt/9p/pardes/demo/").?); - // The registry posts the session there too, so that spelling counts. - try std.testing.expectEqualStrings("index", ownMountSuffix("/run/user/1000/9p/pardes/demo/index").?); - // Another session's mount is somebody else's to answer, and a name that - // merely STARTS with ours is a different name. - try std.testing.expect(ownMountSuffix("/mnt/9p/pardes/other/index") == null); - try std.testing.expect(ownMountSuffix("/mnt/9p/pardes/demo2/index") == null); - // An ordinary directory that reads like a mount is an ordinary directory. - // Serving the tree here would hand back the tree's README for the file on - // disk, and -- before `write` learned the same trick -- write the tree's - // bytes over it. - try std.testing.expect(ownMountSuffix("/home/goblin/src/pardes/demo/README") == null); - try std.testing.expect(ownMountSuffix("/home/goblin/src/pardes/demo.zig") == null); - // Relative paths never name a mount: they are resolved against a cwd first. - try std.testing.expect(ownMountSuffix("mnt/9p/pardes/demo/index") == null); - - // The syscall is the thing that never returns, so it is never made. - var out: [4096]u8 = undefined; - try std.testing.expect(resolveOs("/mnt/9p/pardes/demo/index", &out) == null); - - // A session with no listener has no name, so nothing is redirected. - noteOwnSocket("/tmp/not-a-pardes-socket"); - try std.testing.expect(ownMountSuffix("/mnt/9p/pardes/demo/index") == null); -} - -test "reading this session's own mount returns what the tree holds" { - const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - noteOwnSocket("/run/user/1000/pardes-9p-selfread.sock"); - defer own_name_len = 0; - - const direct = try read(p, "/n/self/index"); - defer p.gpa.free(direct); - const mounted = try read(p, "/mnt/9p/pardes/selfread/index"); - defer p.gpa.free(mounted); - try std.testing.expectEqualStrings(direct, mounted); - try std.testing.expect(direct.len > 0); - - // A write goes to the same tree the read came from, not out through the - // mount: `/index` is 0400 there, and an OS write would instead try to - // create a file under a directory that does not exist. - try std.testing.expectError(error.ReadOnlyFilesystem, write(p, "/mnt/9p/pardes/selfread/index", "nope\n")); - try std.testing.expectError(error.ReadOnlyFilesystem, write(p, "/n/self/index", "nope\n")); -} - +/// 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. pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { if (comptime !platform_has_fs) return null; - if (isOwnMount(path)) return null; var z: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null; + pardes.turn.yield(); + defer pardes.turn.back(); const resolved = realpath(path_z, out) orelse return null; return .{ .path = std.mem.span(resolved), .dir = isDir(resolved) }; } @@ -818,13 +692,6 @@ pub fn read(p: *pardes.Pardes, path: []const u8) ![]u8 { } pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { - // The same view, reached by a reader that never went through `resolve`. - // The rewritten path cannot contain the mount stem, so this recurses once. - if (ownMountSuffix(path)) |inner| { - var self_buf: [4096]u8 = undefined; - const internal = std.fmt.bufPrint(&self_buf, "/n/self/{s}", .{inner}) catch return error.FileTooLarge; - return readLimit(p, internal, max_bytes); - } const limit = @min(max_bytes, limits.max_file_bytes); if (std.mem.eql(u8, std.mem.trimEnd(u8, path, "/"), "/n")) { var out: std.Io.Writer.Allocating = .init(p.gpa); @@ -847,11 +714,8 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { var native_buf: [4096]u8 = undefined; const native = resolveOs(remote_path, &native_buf) orelse return readFileLimit(p.gpa, path, limit); if (!native.dir) return readFileLimit(p.gpa, path, limit); - const saved_paths = p.fs.os_paths.items.len; - defer { - for (p.fs.os_paths.items[saved_paths..]) |temporary| p.gpa.free(temporary.path); - p.fs.os_paths.shrinkRetainingCapacity(saved_paths); - } + // The node stays in the table until no connection names it either + // (src/9p_io.zig, collectOs): a client may have walked to it too. const node = try osNode(p, native.path); return readNode(p, node, path, limit); } @@ -861,25 +725,10 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { } for (p.fs.mounts.items) |mount| { if (!std.mem.eql(u8, name, mount.name)) continue; - if (ninep_io.Client.sameSession(mount.dial, p.fs.socket_path, p.fs.tcp_address, p.fs.quic_address)) { - const saved_paths = p.fs.os_paths.items.len; - defer { - for (p.fs.os_paths.items[saved_paths..]) |temporary| p.gpa.free(temporary.path); - p.fs.os_paths.shrinkRetainingCapacity(saved_paths); - } - var node = tree.root; - var directory = true; - var parts = std.mem.tokenizeScalar(u8, remote_path, '/'); - while (parts.next()) |part| { - if (!directory) return error.NotADirectory; - if (std.mem.eql(u8, part, ".")) continue; - const reply = tree.handle(p, .{ .tag = 0, .op = .lookup, .node = node, .data = part }); - if (reply.status != .ok) return error.FileNotFound; - node = reply.attr.node; - directory = reply.attr.dir; - } - return readNode(p, node, path, limit); - } + // A peer answers on its own time, and the peer may be this very + // editor: the turn goes out with the request. + pardes.turn.yield(); + defer pardes.turn.back(); return ninep_io.Client.readLimit(p.gpa, mount.dial, remote_path, path, limit); } return error.FileNotFound; @@ -940,68 +789,64 @@ fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize } } +/// The editor's, between steps: a save or a dump the shell is performing, +/// never a step of the core. pub fn write(p: *pardes.Pardes, path: []const u8, bytes: []const u8) !void { - // The same view `readLimit` answers from the tree, so a write lands where - // the matching read came from -- and, just as importantly, never becomes - // an open(2) through a mount this loop is the one that answers. - if (ownMountSuffix(path)) |inner| { - var self_buf: [4096]u8 = undefined; - const internal = std.fmt.bufPrint(&self_buf, "/n/self/{s}", .{inner}) catch return error.PathTooLong; - return write(p, internal, bytes); - } if (std.mem.eql(u8, std.mem.trimEnd(u8, path, "/"), "/n")) return error.IsDirectory; - var self_path: ?[]const u8 = null; - if (std.mem.eql(u8, path, "/virtual")) self_path = ""; - if (std.mem.startsWith(u8, path, "/virtual/")) self_path = path[9..]; - if (std.mem.startsWith(u8, path, "/n/")) { - const explicit = path[3..]; - const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; - const name = explicit[0..cut]; - const remote_path = if (cut < explicit.len) explicit[cut..] else "/"; - if (std.mem.eql(u8, name, "os")) return writeFile(remote_path, bytes); - if (std.mem.eql(u8, name, "self")) { - self_path = remote_path; - } else { - for (p.fs.mounts.items) |mount| { - if (!std.mem.eql(u8, name, mount.name)) continue; - if (ninep_io.Client.sameSession(mount.dial, p.fs.socket_path, p.fs.tcp_address, p.fs.quic_address)) { - var buf: [4096]u8 = undefined; - const local = try std.fmt.bufPrint(&buf, "/n{s}", .{remote_path}); - return write(p, local, bytes); - } - return ninep_io.Client.write(p.gpa, mount.dial, remote_path, bytes); - } - return error.FileNotFound; - } + if (std.mem.eql(u8, path, "/virtual")) return writeSelf(p, "", bytes); + if (std.mem.startsWith(u8, path, "/virtual/")) return writeSelf(p, path[9..], bytes); + if (!std.mem.startsWith(u8, path, "/n/")) return writeOut(p, null, path, bytes); + const explicit = path[3..]; + const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; + const name = explicit[0..cut]; + const remote_path = if (cut < explicit.len) explicit[cut..] else "/"; + if (std.mem.eql(u8, name, "os")) return writeOut(p, null, remote_path, bytes); + if (std.mem.eql(u8, name, "self")) return writeSelf(p, remote_path, bytes); + for (p.fs.mounts.items) |mount| { + if (std.mem.eql(u8, name, mount.name)) return writeOut(p, mount.dial, remote_path, bytes); } - if (self_path) |name| { - var node = tree.resolveSelf(p, name) orelse return error.FileNotFound; - const attributes = tree.handle(p, .{ .tag = 0, .op = .getattr, .node = node }); - if (attributes.status != .ok) return error.FileNotFound; - if (attributes.attr.dir) return error.IsDirectory; - if (attributes.attr.mode & 0o200 == 0) return error.ReadOnlyFilesystem; - const opened = tree.handle(p, .{ .tag = 0, .op = .open, .node = node }); - if (opened.status != .ok) return error.OpenFailed; - if (opened.attr.node != 0) node = opened.attr.node; - defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); - var preserved: ?[]u8 = null; - defer if (preserved) |copy| p.gpa.free(copy); - const target = tree.Node.target(node); - if (target != null and target.? == .pane and target.?.pane.file == .body) { - preserved = try p.gpa.dupe(u8, bytes); - const trunc = tree.handle(p, .{ .tag = 0, .op = .setattr, .node = node, .truncate = true }); - if (trunc.status != .ok) return error.WriteFailed; - } - const contents = preserved orelse bytes; - var off: usize = 0; - while (off < contents.len) { - const reply = tree.handle(p, .{ .tag = 0, .op = .write, .node = node, .off = off, .data = contents[off..] }); - if (reply.status != .ok or reply.written == 0) return error.WriteFailed; - off += reply.written; - } - return; + return error.FileNotFound; +} + +/// The host, or the peer at `dial`, takes the bytes with the turn given up +/// entirely -- the peer may be this very editor, and a write it serves may +/// change any pane -- so they are copied first: `bytes` is usually a pane's +/// own text. +fn writeOut(p: *pardes.Pardes, dial: ?[]const u8, path: []const u8, bytes: []const u8) !void { + const copy = try p.gpa.dupe(u8, bytes); + defer p.gpa.free(copy); + pardes.turn.rest(); + defer pardes.turn.wake(); + if (dial) |d| return ninep_io.Client.write(p.gpa, d, path, copy); + return writeFile(path, copy); +} + +/// This editor's own tree, written in place. +fn writeSelf(p: *pardes.Pardes, name: []const u8, bytes: []const u8) !void { + var node = tree.resolveSelf(p, name) orelse return error.FileNotFound; + const attributes = tree.handle(p, .{ .tag = 0, .op = .getattr, .node = node }); + if (attributes.status != .ok) return error.FileNotFound; + if (attributes.attr.dir) return error.IsDirectory; + if (attributes.attr.mode & 0o200 == 0) return error.ReadOnlyFilesystem; + const opened = tree.handle(p, .{ .tag = 0, .op = .open, .node = node }); + if (opened.status != .ok) return error.OpenFailed; + if (opened.attr.node != 0) node = opened.attr.node; + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); + var preserved: ?[]u8 = null; + defer if (preserved) |copy| p.gpa.free(copy); + const target = tree.Node.target(node); + if (target != null and target.? == .pane and target.?.pane.file == .body) { + preserved = try p.gpa.dupe(u8, bytes); + const trunc = tree.handle(p, .{ .tag = 0, .op = .setattr, .node = node, .truncate = true }); + if (trunc.status != .ok) return error.WriteFailed; + } + const contents = preserved orelse bytes; + var off: usize = 0; + while (off < contents.len) { + const reply = tree.handle(p, .{ .tag = 0, .op = .write, .node = node, .off = off, .data = contents[off..] }); + if (reply.status != .ok or reply.written == 0) return error.WriteFailed; + off += reply.written; } - return writeFile(path, bytes); } fn resolveEmbedded(word: []const u8, cwd: []const u8, scratch: *[4096]u8) ?Source { @@ -1069,6 +914,8 @@ pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u var hits: [find_max_hits][]const u8 = undefined; var hits_len: usize = 0; if (platform_has_fs) { + pardes.turn.yield(); + defer pardes.turn.back(); const io = std.Io.Threaded.global_single_threaded.io(); var root = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); defer root.close(io); @@ -1152,6 +999,9 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b const home = std.mem.trimEnd(u8, base, "/"); const files = try arena.alloc([]const u8, grep_max_files); var files_len: usize = 0; + // A walk and thousands of reads: the turn goes out for all of it. + pardes.turn.yield(); + defer pardes.turn.back(); { const io = std.Io.Threaded.global_single_threaded.io(); var root = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); @@ -1311,10 +1161,6 @@ test "Restore prefers default directory then falls back to original path" { fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed; - // Same reason as `writeFile`: no core to answer from here, and the open is - // the call that never returns. Callers holding one use `readLimit`, which - // serves the tree instead. - if (isOwnMount(path)) return error.FileNotFound; if (!platform_has_fs or std.mem.startsWith(u8, path, "/virtual/")) { const archive_path = if (std.mem.startsWith(u8, path, "/virtual/")) path[9..] else path; var normalized_buf: [4096]u8 = undefined; @@ -1326,6 +1172,10 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { var pathbuf: [4096]u8 = undefined; const native = localPath(path) orelse return error.OpenFailed; const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{native}, 0) catch return error.PathTooLong; + // The path may be a mount this editor serves: the turn goes out with the + // syscalls, and the bytes come back into memory of the caller's own. + pardes.turn.yield(); + defer pardes.turn.back(); const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .NONBLOCK = true }); if (fd < 0) return switch (libc.errno(fd)) { .ACCES, .PERM => error.PermissionDenied, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 3c2fd693..8da6f933 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2422,6 +2422,7 @@ fn localSession( defer pardes.lsp.setStatusSink(null, null); while (!core.quit) { + pardes.turn.restoreSettled(); try core.pump(host); if (core.quit) break; // a session that ended does not restore into one if (core.takeAttach()) |req| { @@ -2465,7 +2466,7 @@ fn localSession( g.prepared_images.clearRetainingCapacity(); nc.native_images = true; nc.host = host; - if (fs) |f| f.reset(core); + if (fs) |f| f.reset(nc); core.deinit(); core = nc; shell.core = nc; @@ -2758,7 +2759,10 @@ const StdinFeed = struct { } var fds = [_]posix.pollfd{.{ .fd = 0, .events = posix.POLL.IN, .revents = 0 }}; - _ = posix.poll(&fds, 16) catch return out; + pardes.turn.rest(); + const polled = posix.poll(&fds, 16); + pardes.turn.wake(); + _ = polled catch return out; if ((fds[0].revents & posix.POLL.IN) == 0) { if ((fds[0].revents & (posix.POLL.HUP | posix.POLL.ERR)) != 0) out.eof = true; return out; @@ -3762,7 +3766,11 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { if (s.gui) |g| { var sev = std.mem.zeroes(c.SDL_Event); const ms: c_int = if (timeout_ms != 0) @intCast(timeout_ms) else 16; - if (c.SDL_WaitEventTimeout(&sev, ms)) { + // The wait is the 9P connections' turn with the core. + pardes.turn.rest(); + const got = c.SDL_WaitEventTimeout(&sev, ms); + pardes.turn.wake(); + if (got) { dispatch(g, &in, &sev); while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev); } @@ -3785,7 +3793,7 @@ fn pollFrame(ctx: ?*anyopaque) void { const s = shellOf(ctx); s.reconcilePtys(); const core = s.core; - if (s.fs) |f| if (f.tick(core).pending) s.queue.push(.fs_ready); + if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready); const g = s.gui orelse { if (core.settings.window_opacity_pending) { var unchanged_opacity: u8 = 100; @@ -3923,7 +3931,7 @@ fn gridPollFrame(ctx: ?*anyopaque) void { const s = shellOf(ctx); s.reconcilePtys(); if (s.fs) |f| { - if (f.tick(s.core).count != 0) s.saw_event = true; + if (f.tick().count != 0) s.saw_event = true; } pollCwds(s.core, s.ptys); if (s.core.animationActive()) { @@ -5077,6 +5085,13 @@ fn renderFrame( ); } } + // Body layers first: a notice chip over a tree-sitter context band + // is a tag layer, and instances paint in emission order. + for (surface.bodyLayers()) |*layer| { + if (layer.rows == 0) continue; + const batch_index = paintBatchAt(&paint_plan, layer.viewport.x, layer.viewport.y); + emitBodyLayer(g, instances, &cell_next[batch_index], layer, win_w, win_h, paint_plan.batches[batch_index].track, page, paint_plan.len == 1, false, topbar_pane_border_rgb); + } for (surface.tagLayers()) |*layer| { if (layer.cols == 0) continue; const batch_index = paintBatchAt(&paint_plan, layer.viewport.x, layer.viewport.y); @@ -5092,11 +5107,6 @@ fn renderFrame( emitTagLayer(g, instances, &cell_next[destination], layer, win_w, win_h, if (under) null else track, page, false, track.effect == .dissolve); } } - for (surface.bodyLayers()) |*layer| { - if (layer.rows == 0) continue; - const batch_index = paintBatchAt(&paint_plan, layer.viewport.x, layer.viewport.y); - emitBodyLayer(g, instances, &cell_next[batch_index], layer, win_w, win_h, paint_plan.batches[batch_index].track, page, paint_plan.len == 1, false, topbar_pane_border_rgb); - } for (paint_plan.batches[1..paint_plan.len], 1..) |batch, batch_index| { const track = batch.track.?; const under = track.effect == .vertical and track.phase == .opening; diff --git a/src/host_io.zig b/src/host_io.zig index a7babc74..72e149c9 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -955,6 +955,9 @@ pub fn forkShell( var cwd_buf: [4096]u8 = undefined; const cwd_z: ?[:0]const u8 = if (native_cwd.len == 0) null else dir: { const path = std.fmt.bufPrintSentinel(&cwd_buf, "{s}", .{native_cwd}, 0) catch return error.NameTooLong; + // A shell's directory may be inside a mount this editor serves. + pardes.turn.yield(); + defer pardes.turn.back(); const stat = try std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), path, .{}); if (stat.kind != .directory) return error.NotDir; break :dir path; diff --git a/src/macos.zig b/src/macos.zig index d3b33c55..a7ee3164 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -773,6 +773,10 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { for (&st.ptys, 0..) |*slot, id| if (slot.*) |*pt| startReader(st, pt, @intCast(id)); pardes.lsp.setStatusSink(st, lspStatusSink); + // From here the core is touched only inside the entry points above, + // each of which takes the turn for its own duration; between them the + // 9P connections have it. + pardes.turn.rest(); } fn wakeNinep(ctx: ?*anyopaque) void { @@ -781,6 +785,7 @@ fn wakeNinep(ctx: ?*anyopaque) void { } export fn pardes_deinit() void { + pardes.turn.wake(); const st = &(state orelse return); if (st.ninep) |listener| { listener.deinit(st.gpa); @@ -823,6 +828,8 @@ export fn pardes_deinit() void { } export fn pardes_should_quit() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return true); return st.core.quit; } @@ -890,11 +897,15 @@ test "the animation clock spends real time, not callbacks" { } export fn pardes_animating() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); return st.core.animationActive() or st.rotate_coasting or st.scroll_coasting; } export fn pardes_theme_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const th = if (state) |*st| st.core.theme() else &pardes.themes[0]; const bg = th.bg orelse return color_default; return @as(u32, bg[0]) << 16 | @as(u32, bg[1]) << 8 | bg[2]; @@ -913,6 +924,8 @@ export fn pardes_theme_bg() u32 { /// own (pardes_theme_bg == PARDES_COLOR_DEFAULT) drops the ground entirely, /// whatever percentage is set here. export fn pardes_window_opacity() u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 100); st.core.settings.window_opacity_pending = false; return st.core.settings.window_opacity; @@ -920,6 +933,8 @@ export fn pardes_window_opacity() u8 { /// Public AppKit backdrop strength, independent of background paint opacity. export fn pardes_window_blur() u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); return if (state) |st| st.core.settings.window_blur else 0; } @@ -928,10 +943,14 @@ fn taglineFontPercent(core: ?*const pardes.Pardes) u8 { } export fn pardes_gui_tagline_font_percent() u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); return taglineFontPercent(if (state) |*st| st.core else null); } export fn pardes_tagline_band_offset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h, if (state) |*st| st.core.settings.workspace_tag else true); } @@ -940,16 +959,22 @@ export fn pardes_topbar_pane_border_px(cell_h: u32, tagline_h: u32) u32 { } export fn pardes_tagline_origin_col(col: u16, row: u16) f32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return @floatFromInt(col)); return pardes.taglineOriginColForFrame(st.core, col, row); } export fn pardes_grid_col_at(x: f32, row: u16, body_w: f32, tagline_w: f32) u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return pardes.gridColAt(null, x, row, body_w, tagline_w)); return pardes.gridColAt(st.core, x, row, body_w, tagline_w); } export fn pardes_topbar_pane_border_rgb() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const rgb = pardes.config.gui_topbar_pane_border_rgb orelse fromTheme: { const st = state orelse return color_default; break :fromTheme st.core.chromeTheme().border; @@ -958,11 +983,15 @@ export fn pardes_topbar_pane_border_rgb() u32 { } export fn pardes_tag_active_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = state orelse return color_default; const rgb = st.core.chromeTheme().tag_active_bg; return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; } export fn pardes_tagline_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = state orelse return color_default; const rgb = st.core.chromeTheme().tag_bg; return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; @@ -1008,6 +1037,8 @@ test "the fallback preference order crosses the ABI intact and ends at the bound } export fn pardes_scene() Scene { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return .{}); const seconds = @as(f64, @floatFromInt(st.scene_ns)) / @as(f64, std.time.ns_per_s); return .{ @@ -1018,6 +1049,8 @@ export fn pardes_scene() Scene { } export fn pardes_postprocessor_unavailable() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.disableSceneEffects(); st.core.settings.panel_transition = .off; @@ -1026,6 +1059,8 @@ export fn pardes_postprocessor_unavailable() void { } export fn pardes_panel_animation_failed() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.abandonPanelAnimations(); } @@ -1210,6 +1245,8 @@ fn reloadWatchedFile(st: *State, pane: u8, announce: bool) bool { } export fn pardes_watch_changed(pane: u8, generation: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); if (pane >= watch_slot_count) return; if (st.file_watches.notify(pane, generation)) wake(st); @@ -1265,11 +1302,13 @@ fn drainInbox(st: *State) bool { } export fn pardes_tick() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); st.inbox.wake_pending.store(false, .release); var did = drainInbox(st); if (st.ninep) |listener| { - const drained = listener.tick(st.core); + const drained = listener.tick(); did = did or drained.count != 0; if (drained.pending) wake(st); } @@ -1277,7 +1316,9 @@ export fn pardes_tick() bool { did = true; st.core.perform(effect); } + pardes.turn.settle(); if (restoreCore(st)) did = true; + pardes.turn.restoreSettled(); return did; } @@ -1309,7 +1350,7 @@ fn restoreCore(st: *State) bool { const generation = st.file_watches.stop(st.gpa, id); hostWatchFile(id, generation, null, 0); }; - if (st.ninep) |listener| listener.reset(st.core); + if (st.ninep) |listener| listener.reset(replacement); replacement.host = hostFor(st); st.core.deinit(); st.core = replacement; @@ -1485,6 +1526,8 @@ test "mac Restore cancels a PTY reader waiting for output capacity" { } export fn pardes_animation_tick() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const now: u64 = @intCast(@max(0, monotonicNs())); @@ -1546,6 +1589,8 @@ export fn pardes_animation_tick() bool { } export fn pardes_key(cp_arg: u32, text_ptr: ?[*]const u8, len: usize, mods: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); if (cp_arg > std.math.maxInt(u21)) return; const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; @@ -1559,16 +1604,22 @@ export fn pardes_key(cp_arg: u32, text_ptr: ?[*]const u8, len: usize, mods: u32) } export fn pardes_paste(text_ptr: ?[*]const u8, len: usize) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; st.core.update(.{ .paste = text }); } export fn pardes_mouse(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); mouseWithHit(button_arg, kind_arg, col, row, mods, null, null); } export fn pardes_mouse_pixel(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u32, x: f32, y: f32, bw: f32, bh: f32, tw: f32, th: f32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const source = st.core.presentation.pointerFractional(st.core.screen_w, st.core.screen_h, x / @max(1, bw), y / @max(1, bh)); var hit: ?pardes.Mouse.BodyHit = null; @@ -1620,11 +1671,15 @@ fn mouseWithHit(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u3 } export fn pardes_pointer_leave() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.update(.pointer_leave); } export fn pardes_scroll(delta_rows: f32, delta_cols: f32, col: u16, row: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.scroll_col = col; st.scroll_row = row; @@ -1636,6 +1691,8 @@ export fn pardes_scroll(delta_rows: f32, delta_cols: f32, col: u16, row: u16) vo /// spinning dial. Also drops whatever the last gesture left banked, so the /// first millimetre of a new swipe cannot inherit a nearly-complete row. export fn pardes_scroll_begin() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.scroll_lag = 0; st.scroll_lag_x = 0; @@ -1655,6 +1712,8 @@ export fn pardes_scroll_begin() void { /// momentum simply takes the gesture over, and the tail of that momentum is /// below the fling floor, so its end arms nothing. export fn pardes_scroll_end() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const last = st.scroll_last_ns; st.scroll_last_ns = 0; @@ -1671,6 +1730,8 @@ export fn pardes_scroll_end() void { } export fn pardes_rotate(degrees: f32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); if (degrees == 0) { st.rotate_lag = 0; @@ -1684,6 +1745,8 @@ export fn pardes_rotate(degrees: f32) void { } export fn pardes_rotate_end() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const last = st.rotate_last_ns; st.rotate_last_ns = 0; @@ -1726,6 +1789,8 @@ fn spendRotation(st: *State, degrees: f32) void { } export fn pardes_command(text_ptr: ?[*]const u8, len: usize) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; if (text.len == 0) return; @@ -1733,6 +1798,8 @@ export fn pardes_command(text_ptr: ?[*]const u8, len: usize) void { } export fn pardes_resize(cols_arg: u16, rows_arg: u16, cell_w: u16, cell_h: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); const cols = @max(1, cols_arg); const rows = @max(1, rows_arg); @@ -1747,6 +1814,8 @@ export fn pardes_resize(cols_arg: u16, rows_arg: u16, cell_w: u16, cell_h: u16) } export fn pardes_frame() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); const tz = tracy.zone(@src(), "pardes_frame"); defer tz.end(); @@ -1921,26 +1990,36 @@ fn collectImages(st: *State, surface: *const pardes.Surface) void { } export fn pardes_frame_images() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return @intCast(st.images_len); } export fn pardes_frame_image_list() ?[*]const Image { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.images_len == 0) null else st.images.ptr; } export fn pardes_frame_panel_tracks() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return @intCast(st.panel_tracks_len); } export fn pardes_frame_panel_track_list() ?[*]const PanelTrack { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.panel_tracks_len == 0) null else st.panel_tracks[0..].ptr; } export fn pardes_frame_presented(animated_panels: bool) bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const was_animating = st.core.animationActive(); if (animated_panels) @@ -1951,11 +2030,15 @@ export fn pardes_frame_presented(animated_panels: bool) bool { } export fn pardes_frame_cells() ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.frame_len == 0) null else st.cells.ptr; } export fn pardes_frame_previous_cells() ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.panel_diff_len != st.frame_len or st.panel_diff_len == 0) null @@ -1964,6 +2047,8 @@ export fn pardes_frame_previous_cells() ?[*]const Cell { } export fn pardes_frame_changed_cells() ?[*]const u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); return if (st.panel_diff_len != st.frame_len or st.panel_diff_len == 0) null @@ -1972,16 +2057,22 @@ export fn pardes_frame_changed_cells() ?[*]const u8 { } export fn pardes_frame_cols() u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return st.frame_cols; } export fn pardes_frame_rows() u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return st.frame_rows; } export fn pardes_cursor_x() i32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return -1); if (tagCursorCovered(st.core)) return -1; return if (st.core.surface.cursor) |c| c.x else -1; @@ -2000,6 +2091,8 @@ export fn pardes_tag_layer_limit() u32 { } export fn pardes_tag_layer_value(index: u32, field: u32) u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); if (index >= pardes.MAX_TAG_LAYERS) return 0; const layer = &st.core.surface.tag_layers[index]; @@ -2025,6 +2118,8 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { } export fn pardes_tag_layer_cells(index: u32) ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); if (index >= pardes.MAX_TAG_LAYERS) return null; const layer = &st.core.surface.tag_layers[index]; @@ -2036,6 +2131,8 @@ export fn pardes_tag_layer_cells(index: u32) ?[*]const Cell { } export fn pardes_body_layer_value(index: u32, field: u32) u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); if (index >= pardes.MAX_PANES) return 0; const layer = &st.core.surface.body_layers[index]; @@ -2056,6 +2153,8 @@ export fn pardes_body_layer_value(index: u32, field: u32) u32 { } export fn pardes_body_layer_cells(index: u32) ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); if (index >= pardes.MAX_PANES) return null; const layer = &st.core.surface.body_layers[index]; @@ -2071,27 +2170,37 @@ export fn pardes_body_layer_limit() u32 { } export fn pardes_row_metrics(body_w: u16, body_h: u16, tagline_w: u16, tagline_h: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.update(.{ .resize = .{ .cols = st.core.screen_w, .rows = st.core.screen_h, .cell_pixels = st.core.cell_pixels, .row_metrics = .{ .body_w = @max(1, body_w), .body_h = @max(1, body_h), .tagline_w = @max(1, tagline_w), .tagline_h = @max(1, tagline_h) } } }); } export fn pardes_pointer_shape() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return @intFromEnum(st.core.surface.pointer_shape); } export fn pardes_cursor_y() i32 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return -1); if (tagCursorCovered(st.core)) return -1; return if (st.core.surface.cursor) |c| c.y else -1; } export fn pardes_cursor_bar() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); return if (st.core.surface.cursor) |c| c.bar else false; } export fn pardes_take_haptic() c_int { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return 0); return switch (st.core.takeHaptic()) { .none => 0, @@ -2103,6 +2212,8 @@ export fn pardes_take_haptic() c_int { var font_path_z: [4096:0]u8 = undefined; export fn pardes_font_take(size_hundredths: *u16) ?[*:0]const u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); if (comptime !pardes.font_picker) return null; const want = st.core.takeFontRequest() orelse return null; @@ -2118,6 +2229,8 @@ export fn pardes_font_observe( len: usize, point_hundredths: u16, ) bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const ptr = effective_name orelse return false; if (len == 0 or len > 255 or point_hundredths == 0) return false; @@ -2129,6 +2242,8 @@ export fn pardes_font_ack( len: usize, point_hundredths: u16, ) bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const ptr = effective_name orelse return false; if (len == 0 or len > 255 or point_hundredths == 0) return false; @@ -2136,6 +2251,8 @@ export fn pardes_font_ack( } export fn pardes_font_reject() void { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return); st.core.rejectFont(); } @@ -2143,6 +2260,8 @@ export fn pardes_font_reject() void { var active_path_z: [4096:0]u8 = undefined; export fn pardes_active_path() ?[*:0]const u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return null); const path = activeFilePath(st) orelse return null; if (path.len == 0 or path.len >= active_path_z.len) return null; @@ -2152,6 +2271,8 @@ export fn pardes_active_path() ?[*:0]const u8 { } export fn pardes_active_dirty() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); const st = &(state orelse return false); const pane = st.core.panes[st.core.active] orelse return false; const f = if (pane.file) |*x| x else return false; diff --git a/src/memory.zig b/src/memory.zig index f30e4392..e5394b4f 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -44,7 +44,48 @@ pub const Allocators = struct { pdf: Allocator, }; -var pardes_fallback: std.heap.StackFallbackAllocator(limits.arena.pardes) = undefined; +/// `std.heap.StackFallbackAllocator` with the buffer taken through its +/// lock-free interface. The core's allocator is used from two threads: a 9P +/// connection task answers a request while the editor's own thread is out +/// in a syscall that allocates (`readFileLimit`, `grep`; see `pardes.turn`). +fn SharedStackFallback(comptime size: usize) type { + return struct { + buffer: [size]u8 = undefined, + fallback_allocator: Allocator = undefined, + fixed: std.heap.FixedBufferAllocator = undefined, + + fn get(self: *@This()) Allocator { + self.fixed = .init(self.buffer[0..]); + return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + return self.fixed.threadSafeAllocator().rawAlloc(len, alignment, ra) orelse + self.fallback_allocator.rawAlloc(len, alignment, ra); + } + + fn resize(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, new_len: usize, ra: usize) bool { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.fixed.ownsPtr(buf.ptr)) return self.fixed.threadSafeAllocator().rawResize(buf, alignment, new_len, ra); + return self.fallback_allocator.rawResize(buf, alignment, new_len, ra); + } + + fn remap(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, new_len: usize, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.fixed.ownsPtr(buf.ptr)) return self.fixed.threadSafeAllocator().rawRemap(buf, alignment, new_len, ra); + return self.fallback_allocator.rawRemap(buf, alignment, new_len, ra); + } + + fn free(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, ra: usize) void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.fixed.ownsPtr(buf.ptr)) return self.fixed.threadSafeAllocator().rawFree(buf, alignment, ra); + return self.fallback_allocator.rawFree(buf, alignment, ra); + } + }; +} + +var pardes_fallback: SharedStackFallback(limits.arena.pardes) = .{}; var frame_fallback: std.heap.StackFallbackAllocator(limits.arena.frame) = undefined; var tree_sitter_fallback: std.heap.StackFallbackAllocator(limits.arena.tree_sitter) = undefined; var image_fallback: std.heap.StackFallbackAllocator(limits.arena.image) = undefined; @@ -61,7 +102,6 @@ var pdf_debug: Debug = .init; // One session at a time; free its allocations before deinit. Concurrent LSP workers use the caller's allocator. pub fn init(fallback: Allocator) Allocators { pardes_fallback.fallback_allocator = fallback; - pardes_fallback.get_called = if (std.debug.runtime_safety) false else {}; frame_fallback.fallback_allocator = fallback; frame_fallback.get_called = if (std.debug.runtime_safety) false else {}; tree_sitter_fallback.fallback_allocator = fallback; @@ -112,12 +152,12 @@ test "fixed allocators are separate, spill, and restart" { var allocs = init(std.testing.allocator); const core = try allocs.pardes.alloc(u8, 32); const frame = try allocs.frame.alloc(u8, 32); - try std.testing.expect(pardes_fallback.fixed_buffer_allocator.ownsPtr(core.ptr)); + try std.testing.expect(pardes_fallback.fixed.ownsPtr(core.ptr)); try std.testing.expect(frame_fallback.fixed_buffer_allocator.ownsPtr(frame.ptr)); try std.testing.expect(core.ptr != frame.ptr); const spill = try allocs.pardes.alloc(u8, limits.arena.pardes + 1); - try std.testing.expect(!pardes_fallback.fixed_buffer_allocator.ownsPtr(spill.ptr)); + try std.testing.expect(!pardes_fallback.fixed.ownsPtr(spill.ptr)); allocs.pardes.free(spill); allocs.frame.free(frame); allocs.pardes.free(core); @@ -127,7 +167,7 @@ test "fixed allocators are separate, spill, and restart" { defer deinit(); const restarted = try allocs.pardes.alloc(u8, 32); defer allocs.pardes.free(restarted); - try std.testing.expect(pardes_fallback.fixed_buffer_allocator.ownsPtr(restarted.ptr)); + try std.testing.expect(pardes_fallback.fixed.ownsPtr(restarted.ptr)); } test "memory limits preserve desktop capacities" { diff --git a/src/ninep/testing.zig b/src/ninep/testing.zig index 44329eee..6ea40956 100644 --- a/src/ninep/testing.zig +++ b/src/ninep/testing.zig @@ -30,13 +30,10 @@ pub const Answer = struct { }; pub fn call(p: *Pardes, req: Req) Answer { - p.update(.{ .fs_req = req }); var ans: Answer = .{}; + ans.reply = p.serveFs(req); + ans.bytes = p.fsPayload(ans.reply); while (p.nextEffect()) |e| switch (e) { - .fs_reply => |r| { - ans.reply = r; - ans.bytes = p.fsPayload(r); - }, .save_file, .save_text => ans.saved = true, .watch => |w| ans.watch = w.on, .write => |w| { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 5a0c1e11..b13b1472 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -68,6 +68,22 @@ pub const e_bad_event = "bad event syntax"; /// everywhere, as it is in acme (editors/acme/fsys.c, fsyscreate). pub const features: cloud9.fs.Features = .{ .remove = true }; +/// Whether a request must wait until no step is out in a syscall +/// (`pardes.turn`): what would change a pane such a step still points into. +/// Making a pane and rendering a screen do not -- every yield sits before +/// the mutation of its own step, so the layout and the surface are whole +/// under it -- and a step out there is never waiting on a write of its own, +/// so what parks here is never the syscall's own request. +pub fn needsQuiet(req: Req) bool { + return switch (req.op) { + .write, .setattr => true, + .release => req.remove, + else => false, + }; +} + +/// `needsQuiet`, plus the open that makes a pane: what costs a frame and a +/// wake of the editor. pub fn changesPane(req: Req) bool { return switch (req.op) { .write, .setattr => true, diff --git a/src/panes.zig b/src/panes.zig index f995986b..b3424385 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -3324,11 +3324,28 @@ pub const Image = struct { /// Construct an image pane from a path and optionally transferred dump bytes. /// `raw` must be image_gpa-owned and ownership transfers only on success. + /// Without them the file is read here, not at the first draw: a draw + /// must not go out into the host (`pardes.turn`), and the path may be a + /// mount this editor serves. A file that cannot be read draws blank. pub fn create(p: *pardes.Pardes, id: usize, path: []const u8, raw: []u8) !*pardes.Pane { + var bytes = raw; + var read_here = false; + if (bytes.len == 0) { + // The slot stays ours across the read: another request may + // make a pane meanwhile. + p.reserved_slots[id] = true; + defer p.reserved_slots[id] = false; + if (filesystem.read(p, path)) |from_disk| { + defer p.gpa.free(from_disk); + bytes = try p.image_gpa.dupe(u8, from_disk); + read_here = true; + } else |_| {} + } + errdefer if (read_here) p.image_gpa.free(bytes); const path_copy = try p.image_gpa.dupe(u8, path); errdefer p.image_gpa.free(path_copy); const pane = try p.newDocPane(id); - pane.image = .{ .path = path_copy, .raw = raw }; + pane.image = .{ .path = path_copy, .raw = bytes }; return pane; } @@ -3427,12 +3444,8 @@ pub const Image = struct { fn ensureDecoded(p: *pardes.Pardes, state: *State) void { if (state.tried) return; state.tried = true; - const bytes: []const u8 = if (state.raw.len > 0) - state.raw - else - filesystem.read(p, state.path) catch &.{}; - defer if (state.raw.len == 0) p.gpa.free(bytes); - if (image.decode(p.image_gpa, bytes)) |decoded| { + if (state.raw.len == 0) return; // nothing was readable at open + if (image.decode(p.image_gpa, state.raw)) |decoded| { state.rgba = decoded.rgba; state.iw = decoded.w; state.ih = decoded.h; @@ -3771,9 +3784,15 @@ pub const Pdf = struct { sections_output: ?SectionsOutput = null, outline_reveal_pending: ?pdf.OutlineInternalDestination = null, + /// Read whole and opened from memory (the bridge copies), never from + /// the file itself: MuPDF reads a file lazily at every page, and the + /// path may be a mount this editor serves, which only a read that + /// gives the turn up can come back from (`filesystem.readFile`). pub fn open(gpa: std.mem.Allocator, path: []const u8, page_one_based: usize) !@This() { const local = filesystem.localPath(path) orelse return error.NonLocalPath; - return initDocument(gpa, path, try Document.open(local), page_one_based); + const bytes = try filesystem.readFile(gpa, local); + defer gpa.free(bytes); + return initDocument(gpa, path, try Document.openBytes(bytes), page_one_based); } pub fn openBytes(gpa: std.mem.Allocator, path: []const u8, bytes: []const u8, page_one_based: usize) !@This() { @@ -5219,6 +5238,10 @@ pub const Pdf = struct { page_one_based: usize, ) !*pardes.Pane { if (comptime !enabled) return error.PdfDisabled; + // The slot stays ours across the read: another request may make a + // pane meanwhile. + core.reserved_slots[id] = true; + defer core.reserved_slots[id] = false; var state = if (filesystem.localPath(path) != null) try State.open(core.pdf_gpa, path, page_one_based) else virtual: { @@ -5903,9 +5926,11 @@ pub const Pdf = struct { null, }, .x = text_x, - .y = core.bodyTop(rect), + // Below the notice chips, like an image: a placed page is + // drawn after the cells and would paint a chip out. + .y = core.bodyTop(rect) + pane.notices.len, .w = text_width, - .h = rect.h -| pardes.BOX_H, + .h = (rect.h -| pardes.BOX_H) -| pane.notices.len, .rgba = placed.rgba, .iw = placed.width, // The texture contains the retained band, not the full page. diff --git a/src/pardes.zig b/src/pardes.zig index 0ac16162..cc57127f 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -39,6 +39,148 @@ pub const font_picker = platform == .gui or platform == .macos; pub const hosted = platform == .tty or platform == .gui or platform == .macos; +/// Whose turn it is with the core. The core is single-threaded: the editor's +/// thread has it, and lets go of it in two kinds of gap -- while it waits for +/// input (`rest`, `wake`), and while it is out in the host filesystem in the +/// middle of a step (`yield`, `back`). A 9P connection task takes the turn +/// in those gaps to answer a request (`take`, `give`), which is what lets the +/// editor read its own tree through a mount: the syscall goes out, another +/// thread answers it, the syscall comes back. A step of a connection task's +/// own -- a Look written to `look` -- goes out the same way. +/// +/// `out` counts the steps that are out. While one is, the core reads +/// consistently but that step still holds pointers into it, so nothing may +/// change it: a request that would is parked in the engine (src/9p_io.zig) +/// and retried when the turn is next given up with nothing out, which +/// `parked` remembers to arrange; and the editor's own wake waits for the +/// count to reach zero, since a step of the editor's may change anything. +/// It is never a write of its own that a step waits on out there -- writes +/// come from a shell performing a save between steps -- so a parked request +/// is never the syscall's own. +/// +/// One per process, like the editor it belongs to. A process that never +/// starts it -- a test, the board, the browser -- has no second thread, and +/// every yield is a no-op. +pub var turn: Turn = .{}; + +pub const Turn = struct { + mutex: std.Io.Mutex = .init, + /// Set by `start`; a process that never starts the turn has none. + io: ?std.Io = null, + /// Steps out in a host syscall, from any thread. + out: u32 = 0, + /// A request that changes a pane was parked for want of quiet. + parked: bool = false, + wake_parked: ?*const fn (?*anyopaque) void = null, + wake_ctx: ?*anyopaque = null, + /// Bumped each time the editor has performed what the core asked of it, + /// so a request that asked for something -- a save, a shell -- can be + /// answered once it is done rather than merely queued, the way writing + /// `put` to acme's ctl returns after the file is written. + epoch: u64 = 0, + /// Bumped each time a shell has attempted the Restore the core asked for + /// (`takeRestore`), which lives after `pump` because it swaps the core + /// out from under it; a request that asked for one waits for this. + restores: u64 = 0, + /// Both of the above, and `out` reaching zero. + settled: std.Io.Condition = .init, + + /// The editor's thread takes the turn for good; it has it until `stop`. + pub fn start(t: *Turn, io: std.Io) void { + t.io = io; + t.mutex.lockUncancelable(io); + } + + pub fn stop(t: *Turn) void { + const io = t.io orelse return; + t.io = null; + t.parked = false; + t.mutex.unlock(io); + } + + /// The editor is about to wait for input: anyone may have the core. + pub fn rest(t: *Turn) void { + if (t.io == null) return; + t.release(); + } + + /// The editor takes the turn back -- once every step that is out in a + /// syscall has returned, since a step of the editor's may change what + /// those still point into. + pub fn wake(t: *Turn) void { + const io = t.io orelse return; + t.mutex.lockUncancelable(io); + while (t.out != 0) t.settled.waitUncancelable(io, &t.mutex); + } + + /// Whoever has the turn is about to block in the host in the middle of + /// a step. Nests: a directory listing that resolves each entry yields + /// inside a yield, and only the outermost one lets go. + pub fn yield(t: *Turn) void { + const io = t.io orelse return; + yield_depth += 1; + if (yield_depth != 1) return; + t.out += 1; + t.mutex.unlock(io); + } + + pub fn back(t: *Turn) void { + const io = t.io orelse return; + yield_depth -= 1; + if (yield_depth != 0) return; + t.mutex.lockUncancelable(io); + t.out -= 1; + if (t.out == 0) t.settled.broadcast(io); + } + + /// How many yields this thread is inside of. + threadlocal var yield_depth: u32 = 0; + + /// A connection task takes the turn; answers whether nothing is out + /// mid-step, which is what a request that changes a pane needs. + pub fn take(t: *Turn) bool { + t.mutex.lockUncancelable(t.io.?); + return t.out == 0; + } + + pub fn give(t: *Turn) void { + t.release(); + } + + /// The editor performed the core's effects. + pub fn settle(t: *Turn) void { + const io = t.io orelse return; + t.epoch +%= 1; + t.settled.broadcast(io); + } + + /// With the turn: waits, turn given up meanwhile, until the editor has + /// performed past `epoch`; stopping ends the wait early. + pub fn awaitSettled(t: *Turn, epoch: u64) void { + while (t.epoch == epoch) t.settled.wait(t.io.?, &t.mutex) catch return; + } + + /// The shell attempted the Restore the core asked for, whichever way it + /// went; called at the top of each loop step, when the previous step's + /// attempt is over. + pub fn restoreSettled(t: *Turn) void { + const io = t.io orelse return; + t.restores +%= 1; + t.settled.broadcast(io); + } + + pub fn awaitRestored(t: *Turn, restores: u64) void { + while (t.restores == restores) t.settled.wait(t.io.?, &t.mutex) catch return; + } + + fn release(t: *Turn) void { + const woken = t.out == 0 and t.parked; + if (woken) t.parked = false; + t.mutex.unlock(t.io.?); + if (woken) if (t.wake_parked) |f| f(t.wake_ctx); + } +}; + pub const can_attach = platform == .tty or platform == .gui; pub const terminal_panes = platform != .esp32p4; @@ -4754,7 +4896,6 @@ pub const Event = union(enum) { /// this must not clamp onto and preview the final grid cell. pointer_leave, tick, - fs_req: ctlfs.Req, }; pub const attach_name_max = 256; @@ -4792,7 +4933,6 @@ pub const Effect = union(enum) { /// Write the build-time theme ring below the per-user config directory. /// The pane receives the completion/error message from the native host. dump_themes: struct { pane: u8 }, - fs_reply: ctlfs.Reply, attach: struct { pane: u8, name: Buf(attach_name_max) }, detach: struct { pane: u8 }, quit, @@ -5910,11 +6050,6 @@ pub const Options = struct { ninep_name: []const u8 = "", ninep_tcp: ?[]const u8 = null, ninep_quic: ?[]const u8 = null, - ninep_identity: struct { - socket_path: []const u8 = "", - tcp_address: ?std.Io.net.IpAddress = null, - quic_address: ?std.Io.net.IpAddress = null, - } = .{}, mounts: []const filesystem.Mount = &.{}, config_dir: ?[]const u8 = null, startup_config_path: ?[]const u8 = null, @@ -6182,11 +6317,7 @@ pub const Pardes = struct { .pdf_gpa = pdf_gpa, .tree_sitter_gpa = tree_sitter_gpa, .opts = opts, - .fs = .{ - .socket_path = opts.ninep_identity.socket_path, - .tcp_address = opts.ninep_identity.tcp_address, - .quic_address = opts.ninep_identity.quic_address, - }, + .fs = .{}, .screen_w = opts.cols, .screen_h = opts.rows, .scratch = .init(gpa), @@ -6197,7 +6328,6 @@ pub const Pardes = struct { p.fs.started = ctlfs.events.now(); for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial); p.opts.mounts = &.{}; - p.opts.ninep_identity = .{}; p.boot = Boot.of(opts); switch (p.boot) { .document => { @@ -6310,13 +6440,31 @@ pub const Pardes = struct { return @intCast(std.math.clamp(panes.File.displayWidth(text) + 2, 1, @as(usize, limit))); } + const Printed = struct { left: u16, dropped: usize }; + /// Prints `text` flush with the right edge of the band, and answers the - /// column it started at so a cursor can follow it. - fn printRight(s: *Surface, x: u16, row: u16, w: u16, text: []const u8, style: CellStyle) u16 { - const shown: u16 = @intCast(@min(@as(usize, w), panes.File.displayWidth(text))); - const left = x + w - shown; - _ = s.print(left, row, shown, text, style); - return left; + /// column it started at so a cursor can follow it. Text wider than the + /// band loses its HEAD: the end is the part that says something -- a + /// path's file name, an error's reason -- and `dropped` is how many + /// columns of it went. + fn printRight(s: *Surface, x: u16, row: u16, w: u16, text: []const u8, style: CellStyle) Printed { + const width = panes.File.displayWidth(text); + if (width <= w) { + const left: u16 = @intCast(x + w - width); + _ = s.print(left, row, @intCast(width), text, style); + return .{ .left = left, .dropped = 0 }; + } + // Whole glyphs only: a cut inside a wide one would leave the rest a + // column too wide and clip its LAST glyph instead of the first. + var dropped = width - w; + var start = panes.File.rawAtDisplay(text, dropped); + if (panes.File.rawDisplayCol(text, start) < dropped) { + dropped += 1; + start = panes.File.rawAtDisplay(text, dropped); + } + const left: u16 = @intCast(x + w - (width - dropped)); + _ = s.print(left, row, @intCast(width - dropped), text[start..], style); + return .{ .left = left, .dropped = dropped }; } /// The layout every single-pane boot starts from. @@ -6904,8 +7052,14 @@ pub const Pardes = struct { fn showMessage(p: *Pardes, id: usize, text: []const u8) void { if (id >= MAX_PANES) return; const pane = p.panes[id] orelse return; - pane.msg_len = @intCast(@min(text.len, pane.msg.len)); - @memcpy(pane.msg[0..pane.msg_len], text[0..pane.msg_len]); + // One row of printable text: a language server's multi-line report + // reads as one line, and the cut never leaves half a glyph behind. + var n: usize = @min(text.len, pane.msg.len); + if (n < text.len) { + while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1; + } + for (text[0..n], pane.msg[0..n]) |c, *cell| cell.* = if (c < 0x20 or c == 0x7f) ' ' else c; + pane.msg_len = @intCast(n); } fn logMessage(p: *Pardes, id: usize, text: []const u8) void { @@ -7040,7 +7194,7 @@ pub const Pardes = struct { pub fn postEvent(p: *Pardes, ev: Event) void { switch (ev) { .key => |k| std.debug.assert(k.text.len == 0), - .output, .paste, .lsp_resp, .pipe_resp, .file_changed, .command, .fs_req => unreachable, + .output, .paste, .lsp_resp, .pipe_resp, .file_changed, .command => unreachable, else => {}, } if (p.in_len == p.in_q.len) return; @@ -7173,7 +7327,6 @@ pub const Pardes = struct { }, .theme_file => |t| if (v.watch_theme) |f| f(p.host.ctx, t.generation, t.on), .dump_themes => |d| if (v.dump_themes) |f| f(p.host.ctx, d.pane), - .fs_reply => {}, .attach => |a| { const name = a.name.slice(); @memcpy(p.attach_buf[0..name.len], name); @@ -7194,6 +7347,7 @@ pub const Pardes = struct { if (v.wait_input) |f| f(h.ctx, if (p.animationActive()) layout.Animation.frame_ms else 0); while (p.nextQueued()) |ev| p.update(ev); while (p.nextEffect()) |e| p.perform(e); + turn.settle(); // A quitting frame has already freed what it would draw. if (p.quit) return; if (v.poll_frame) |f| f(h.ctx); @@ -7208,24 +7362,35 @@ pub const Pardes = struct { p.needs_frame = false; } + /// One request of the control filesystem, from whichever thread has the + /// turn (`pardes.turn`). Not an event: it neither sweeps nor resets + /// anything the editor's own step may be in the middle of using, so it + /// can be answered while that step is out in a syscall. Only a request + /// that changes a pane costs a frame, which is why a round trip on a + /// local socket costs microseconds and not a vsync. + pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { + if (!ctlfs.changesPane(req)) return ctlfs.handle(p, req); + p.needs_frame = true; + p.raw_hover_intent = false; + p.cancelLookHover(); + const reply = ctlfs.handle(p, req); + // The request was a whole step of its own, so it settles the way a + // step does: the cursor and scroll reconciled, the scripted panes + // told, and the panes it made announced to /log now rather than at + // the end of whatever the editor does next. + p.sync(); + p.fsReport(); + ctlfs.events.announce(p); + return reply; + } + pub fn update(p: *Pardes, ev: Event) void { - // Only two events cannot change the screen: a tick with nothing - // animating, and a filesystem request that only reads. The second is - // what 9P traffic overwhelmingly is, and answering it used to drag a - // whole vsync-blocked frame behind it -- which is why a round trip on - // a local socket cost a frame instead of a few microseconds. - p.needs_frame = p.needs_frame or switch (ev) { - .tick => false, - .fs_req => |req| ctlfs.changesPane(req), - else => true, - }; + // A tick with nothing animating is the one event that cannot change + // the screen. + p.needs_frame = p.needs_frame or ev != .tick; p.shell_rows.sweep(p.gpa); switch (ev) { .tick => {}, - .fs_req => |req| if (ctlfs.changesPane(req)) { - p.raw_hover_intent = false; - p.cancelLookHover(); - }, .mouse => |m| if (!(m.button == .none and m.kind == .motion)) { p.raw_hover_intent = false; p.cancelLookHover(); @@ -7324,7 +7489,6 @@ pub const Pardes = struct { }, .paste => |bytes| p.applyPaste(bytes), .command => |line| _ = p.executeBuiltinLine(p.active, line), - .fs_req => |r| p.emit(.{ .fs_reply = ctlfs.handle(p, r) }), .pinch => |scale| p.ov_pinch_scale = scale, .touch_scroll => |delta| p.ov_touch_scroll_delta = delta, .pointer_leave => { @@ -12915,11 +13079,7 @@ pub const Pardes = struct { .pdf_gpa = pdf_gpa, .tree_sitter_gpa = tree_sitter_gpa, .opts = opts, - .fs = .{ - .socket_path = opts.ninep_identity.socket_path, - .tcp_address = opts.ninep_identity.tcp_address, - .quic_address = opts.ninep_identity.quic_address, - }, + .fs = .{}, .screen_w = opts.cols, .screen_h = opts.rows, .scratch = .init(gpa), @@ -12934,13 +13094,9 @@ pub const Pardes = struct { p.cell_pixels = old.cell_pixels; p.row_metrics = old.row_metrics; p.native_images = old.native_images; - p.fs.socket_path = old.fs.socket_path; - p.fs.tcp_address = old.fs.tcp_address; - p.fs.quic_address = old.fs.quic_address; } for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial); p.opts.mounts = &.{}; - p.opts.ninep_identity = .{}; var parsed = try dump.readZon(gpa, zon_bytes, "load"); defer parsed.deinit(); const st = parsed.value; @@ -13521,16 +13677,19 @@ pub const Pardes = struct { // right would put it past the pane, off the grid, and past what // the detached wire will encode -- which drops every frame for // as long as the prompt is up. - const left = printRight(s, cx, row, chip -| 1, text, msg_style); + const printed = printRight(s, cx, row, chip -| 1, text, msg_style); if (kind != .prompt or id != p.active) continue; const at = pane.promptAt() orelse continue; const prompt0 = (p.tagPrefix(pane) catch continue).len + at; const col = @as(usize, pane.tag_col); if (col < prompt0) continue; - // The cursor follows the text to wherever it landed. + // The cursor follows the text to wherever it landed; a caret + // in the part a narrow band dropped has nowhere to be. const prompt_col = panes.File.displayWidth(text[0..@min(col - prompt0, text.len)]); - if (left + prompt_col < tx + tw) - s.cursor = .{ .x = left + @as(u16, @intCast(prompt_col)), .y = row, .bar = pane.mode == .insert }; + if (prompt_col < printed.dropped) continue; + const caret = printed.left + (prompt_col - printed.dropped); + if (caret < tx + tw) + s.cursor = .{ .x = @intCast(caret), .y = row, .bar = pane.mode == .insert }; } } @@ -14018,12 +14177,19 @@ pub const Pardes = struct { const chip = r.x + r.w - cx; // Right aligned inside the chip, a blank cell short of its // edge: the same one the grid pass leaves for a prompt caret. + // Wider than the chip, the text loses its head, as on the grid. const room = p.tagCapacity(chip) -| 1; const shown = panes.File.displayWidth(text); - const pad = room -| shown; - const line = try arena.alloc(u8, pad + text.len); + var kept = text; + if (shown > room) { + var start = panes.File.rawAtDisplay(text, shown - room); + if (panes.File.rawDisplayCol(text, start) < shown - room) start = panes.File.rawAtDisplay(text, shown - room + 1); + kept = text[start..]; + } + const pad = room -| panes.File.displayWidth(kept); + const line = try arena.alloc(u8, pad + kept.len); @memset(line[0..pad], ' '); - @memcpy(line[pad..], text); + @memcpy(line[pad..], kept); try p.renderHeaderLayer(arena, NOTICE_LAYER_BASE + id * Pane.Notices.max + i, .notice, @intCast(id), .{ .x = cx, .y = first + @as(u16, @intCast(i)), @@ -14221,8 +14387,12 @@ pub const Pardes = struct { if (pane.hasPdf() and panes.Pdf.draw(p, pane, r, id, tx, tw)) return; if (pane.image) |*iv| { - const image_h = r.h -| BOX_H; - panes.Image.draw(p, iv, @intCast(id), pane.serial, tx, body_y, tw, image_h); + // Below the notice chips: a picture is drawn after the cells (the + // GUI's image pass, kitty's z-order), so a chip over it would be + // painted out. Text gets the overlay; a picture gives up the rows. + const shown = pane.notices.len; + const image_h = (r.h -| BOX_H) -| shown; + panes.Image.draw(p, iv, @intCast(id), pane.serial, tx, body_y + shown, tw, image_h); // thumbless, but the same one column as the real scrollbar below — // that is the whole point of drawing it, and like that one it runs // past the notice bands so the gutter has no notch in it diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 23b7c09b..03ccd3e2 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -727,6 +727,7 @@ fn localSession( if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; frames: while (!core.quit) { + pardes.turn.restoreSettled(); try core.pump(host); if (core.takeRestore()) |rp| blk: { const bytes = filesystem.readRestore(gpa, rp) catch |err| { @@ -760,7 +761,7 @@ fn localSession( _ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false); clearNativeImages(kitty_handles, vx, tty); nc.native_images = vx.caps.kitty_graphics; - if (fs) |f| f.reset(core); + if (fs) |f| f.reset(nc); core.deinit(); core = nc; sh.core = nc; @@ -871,15 +872,21 @@ const Shell = struct { fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { const s = of(ctx); var batch: usize = 0; + // The wait is the 9P connections' turn with the core. if (timeout_ms == 0) { + pardes.turn.rest(); const first = s.loop.nextEvent() catch { + pardes.turn.wake(); s.core.quit = true; return s.reloadWatched(); }; + pardes.turn.wake(); batch = 1; if (s.apply(first)) return s.reloadWatched(); } else { + pardes.turn.rest(); std.Io.sleep(s.io, .fromMilliseconds(timeout_ms), .awake) catch {}; + pardes.turn.wake(); _ = s.apply(.tick); batch = 1; } @@ -994,7 +1001,7 @@ const Shell = struct { fn pollFrame(ctx: ?*anyopaque) void { const s = of(ctx); - if (s.fs) |f| if (f.tick(s.core).pending) { + if (s.fs) |f| if (f.tick().pending) { _ = s.loop.tryPostEvent(.fs_ready) catch {}; }; for (&s.ptys, 0..) |*slot, id| if (slot.*) |pt| { diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index 3eba6639..ec94b509 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -98,9 +98,6 @@ test "transactional restore preserves host capabilities and advances pane identi try std.testing.expect(restored.paneBySerial(pane.serial) == null); try std.testing.expectEqual(p.screen_w, restored.screen_w); try std.testing.expectEqual(p.screen_h, restored.screen_h); - try std.testing.expectEqualStrings(p.fs.socket_path, restored.fs.socket_path); - try std.testing.expectEqualDeep(p.fs.tcp_address, restored.fs.tcp_address); - try std.testing.expectEqualDeep(p.fs.quic_address, restored.fs.quic_address); try std.testing.expect(p.panes[0] == pane); try std.testing.expectEqualStrings("before\n", pane.file.?.content); try std.testing.expectError(error.BadDumpMagic, p.restore( @@ -112,27 +109,6 @@ test "transactional restore preserves host capabilities and advances pane identi try std.testing.expectEqualStrings("/tmp/session.sock", p.fs.socket_path); } -test "same-session identity is available before an initial mounted file is opened" { - if (!filesystem.platform_has_fs) return error.SkipZigTest; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "file.txt", .data = "no socket required\n" }); - var buf: [4096]u8 = undefined; - const len = try tmp.dir.realPathFile(std.testing.io, "file.txt", &buf); - const path = try std.fmt.allocPrint(gpa, "/n/own/os{s}", .{buf[0..len]}); - defer gpa.free(path); - const p = try pardes.Pardes.init(gpa, .{ - .file = path, - .mounts = &.{.{ .name = "own", .dial = "/tmp/not-listening.sock" }}, - .ninep_identity = .{ .socket_path = "/tmp/not-listening.sock" }, - }); - defer p.deinit(); - try std.testing.expectEqualStrings(path, p.panes[0].?.file.?.path); - try std.testing.expectEqualStrings("no socket required\n", p.panes[0].?.file.?.content); - try std.testing.expectEqualStrings("", p.opts.ninep_identity.socket_path); -} - test "filesystem resolves OS first then virtual with explicit mounts and parent paths" { if (!filesystem.platform_has_fs) return error.SkipZigTest; const gpa = std.testing.allocator; diff --git a/test/selfmount.py b/test/selfmount.py new file mode 100644 index 00000000..cc889a93 --- /dev/null +++ b/test/selfmount.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""A session that opens, reads and saves its own 9P tree through a mount. + +The editor runs under `9ns --mntgen`, so /mnt/9p/pardes/ inside its +namespace is its own tree, and is driven over its socket from outside. This +used to hang the editor outright: the realpath, the stat and the read went +out through the mount and came back as 9P requests only the editor's loop +could answer, while that loop was blocked making them. Now the connection's +task answers them while the editor waits (pardes.turn). + +Needs 9ns (cloud9) on PATH or in ~/.local/bin, and a runtime directory; it +skips, loudly, without them. +""" +import fcntl +import os +from pathlib import Path +import pty +import shutil +import signal +import struct +import sys +import termios +import time + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from ninep import Client + + +def run(binary): + ns = shutil.which('9ns') or str(Path.home() / '.local/bin/9ns') + runtime = os.environ.get('XDG_RUNTIME_DIR') + if not os.path.exists(ns) or not runtime: + print('selfmount: skipped (needs 9ns and XDG_RUNTIME_DIR)') + return 0 + name = 'selfmount%d' % os.getpid() + sock = f'{runtime}/pardes-9p-{name}.sock' + fixture = Path(f'/tmp/{name}.txt') + fixture.write_bytes(b'initial\n') + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} + env.update(PARDES_NOTIME='1', TERM='xterm-256color', PARDES_DUMP=f'/tmp/{name}.dump.zon') + for language in ['RS', 'C', 'GO', 'TS', 'PY']: + env['PARDES_LSP_' + language] = '' + pid, master = pty.fork() + if pid == 0: + os.execve(ns, ['9ns', '--mntgen', '--', binary, '--tty', '--9p=' + name, str(fixture)], env) + fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack('HHHH', 30, 100, 0, 0)) + os.set_blocking(master, False) + tail = bytearray() + + def drain(): + try: + while True: + chunk = os.read(master, 65536) + if not chunk: + return + tail.extend(chunk[-2000:]) + except OSError: + pass + + failures = [] + + def check(condition, what): + print(('ok ' if condition else 'FAIL ') + what) + if not condition: + failures.append(what) + + try: + deadline = time.monotonic() + 15 + while not os.path.exists(sock): + drain() + if time.monotonic() > deadline: + raise TimeoutError('socket never appeared: ' + tail.decode(errors='replace')[-400:]) + time.sleep(.02) + time.sleep(.3) + mount = f'/mnt/9p/pardes/{name}' + with Client(sock) as client: + index = client.read('/index').decode() + rows = [row.split(maxsplit=3) for row in index.splitlines()] + first = rows[0][0] + # A Look at the tree's own index: realpath, stat and read all go + # out through 9ns and back in, and the write returns when the + # pane is open. + started = time.monotonic() + client.write('/look', (mount + '/index\n').encode()) + took = time.monotonic() - started + check(took < 5, f'look at the mounted index returned ({took:.2f}s)') + rows = [row.split(maxsplit=3) for row in client.read('/index').decode().splitlines()] + opened = [row for row in rows if len(row) == 4 and row[3] == mount + '/index'] + check(len(opened) == 1, 'a pane opened on the mounted index') + if opened: + body = client.read(f'/pane/{opened[0][0]}/body').decode() + check(body.startswith(index.splitlines()[0]), 'its body is the index as served') + # A Look at pane 1's body through the mount, an edit of the copy, + # and a Save: the save writes back through the mount into pane 1, + # and the exec returns once it has. + client.write('/look', f'{mount}/pane/{first}/body\n'.encode()) + rows = [row.split(maxsplit=3) for row in client.read('/index').decode().splitlines()] + mirror = [row for row in rows if len(row) == 4 and row[3] == f'{mount}/pane/{first}/body'] + check(len(mirror) == 1, 'a pane opened on the mounted body') + if mirror: + pane = mirror[0][0] + client.write(f'/pane/{pane}/addr', b'#0,#0') + client.write(f'/pane/{pane}/data', b'HELLO ') + client.write(f'/pane/{pane}/exec', b'Save\n') + check(client.read(f'/pane/{first}/body') == b'HELLO initial\n', f'Save wrote back through the mount into pane {first}') + text = ''.join(cell[0] for cell in client.screen()['cells']) + check('saved ' + mount in text, 'the editor reported the save') + client.write('/exec', b'Msg still here\n') + text = ''.join(cell[0] for cell in client.screen()['cells']) + check('still here' in text, 'the editor answers after all of that') + finally: + os.kill(pid, signal.SIGTERM) + time.sleep(.2) + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + os.waitpid(pid, 0) + for path in (fixture, Path(f'/tmp/{name}.dump.zon')): + path.unlink(missing_ok=True) + print('selfmount: ' + ('ok' if not failures else f'{len(failures)} failed')) + return 0 if not failures else 1 + + +if __name__ == '__main__': + sys.exit(run(str(Path(sys.argv[1]).resolve()))) diff --git a/test/snapshots/images.golden b/test/snapshots/images.golden index a1b78556..74b5f873 100644 --- a/test/snapshots/images.golden +++ b/test/snapshots/images.golden @@ -54,29 +54,29 @@ == style term-palette grid=150x31 |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, |6: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-72 #becfc4,#26362d, 73-74 #dfbce5,#26362d, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|7: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p5, 29-30 p8,p4, 31-31 p4,p8, 32-35 p8,p4, 36-37 p4,p8, 38-39 p8,p4, 40-40 p4,p8, 41-42 p8,p4, 43-43 p4,p8, 44-46 p8,p4, 47-47 p12,p8, 48-65 d,#0d1410, 66-66 d,#1d2824, 67-73 #b2c3b8,#1d2824, 74-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-27 d,#0d1410, 28-30 p8,p4, 31-33 p4,p8, 34-34 p8,p4, 35-36 p4,p8, 37-37 p8,p4, 38-41 p4,p8, 42-42 p8,p4, 43-43 p4,p8, 44-44 p8,p12, 45-46 p12,p8, 47-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p4, 29-29 p4,p8, 30-30 p8,p4, 31-31 p4,p8, 32-32 p8,p4, 33-33 p4,p8, 34-35 p8,p4, 36-37 p4,p8, 38-38 p8,p5, 39-41 p8,p4, 42-42 p4,p8, 43-44 p12,p8, 45-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|10: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 p8,p4, 30-34 p4,p8, 35-36 p8,p4, 37-38 p4,p8, 39-39 p8,p4, 40-40 p4,p8, 41-41 p12,p8, 42-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|11: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p4,p8, 29-29 p8,p4, 30-31 p4,p8, 32-32 p8,p4, 33-33 p4,p8, 34-34 p8,p4, 35-36 p4,p8, 37-37 p8,p4, 38-38 p8,p12, 39-39 p12,p8, 40-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|12: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p4, 29-31 p4,p8, 32-35 p8,p4, 36-36 p4,p8, 37-37 p12,p8, 38-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|13: 0-0 d,#152019, 1-27 d,#0d1410, 28-32 p8,p4, 33-33 p4,p8, 34-34 p8,p12, 35-36 p12,p8, 37-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|14: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p4, 29-29 p4,p8, 30-30 p8,p4, 31-32 p4,p8, 33-33 p12,p8, 34-34 p8,p12, 35-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-27 d,#0d1410, 28-29 p4,p8, 30-30 p8,p12, 31-32 p12,p8, 33-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-27 d,#0d1410, 28-28 p8,p12, 29-29 p12,p8, 30-47 p12,p12, 48-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-65 d,#0d1410, 66-66 d,#1d2824, 67-73 #b2c3b8,#1d2824, 74-74 d,#1d2824, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|8: 0-0 d,#152019, 1-28 d,#0d1410, 29-31 p8,p4, 32-33 p4,p8, 34-37 p8,p4, 38-38 p4,p8, 39-44 p8,p4, 45-45 p8,p12, 46-46 p12,p8, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|9: 0-0 d,#152019, 1-28 d,#0d1410, 29-29 p8,p4, 30-30 p4,p8, 31-35 p8,p4, 36-36 p5,p8, 37-37 p8,p4, 38-38 p4,p8, 39-41 p8,p4, 42-42 p4,p8, 43-43 p8,p12, 44-45 p12,p8, 46-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|10: 0-0 d,#152019, 1-28 d,#0d1410, 29-30 p8,p4, 31-32 p4,p8, 33-40 p8,p4, 41-41 p8,p12, 42-43 p12,p8, 44-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|11: 0-0 d,#152019, 1-28 d,#0d1410, 29-31 p8,p4, 32-32 p4,p8, 33-34 p8,p4, 35-37 p4,p8, 38-38 p8,p4, 39-39 p8,p12, 40-41 p12,p8, 42-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|12: 0-0 d,#152019, 1-28 d,#0d1410, 29-36 p8,p4, 37-37 p8,p12, 38-39 p12,p8, 40-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|13: 0-0 d,#152019, 1-28 d,#0d1410, 29-30 p4,p8, 31-34 p8,p4, 35-35 p8,p12, 36-36 p12,p8, 37-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|14: 0-0 d,#152019, 1-28 d,#0d1410, 29-29 p4,p8, 30-31 p8,p4, 32-32 p4,p8, 33-33 p8,p12, 34-35 p12,p8, 36-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|15: 0-0 d,#152019, 1-28 d,#0d1410, 29-29 p4,p8, 30-30 p8,p4, 31-31 p8,p12, 32-32 p12,p8, 33-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, +|16: 0-0 d,#152019, 1-28 d,#0d1410, 29-29 p8,p12, 30-30 p12,p8, 31-46 p12,p12, 47-74 d,#0d1410, 75-75 d,#608269, 76-76 d,#0d1410, 77-149 #e5eee5,#0d1410, == snap no-ascii grid=150x31 cursor=11,8 |3: ls ls |6: img petscii:off palette:terminal ascii:off /tmp/pardes-snap/images/cwd/p -|7: ███╱█🬻██🬺██🬻███╱██🬴▄ Ascii -|8: 🬬██╱███╱🬻🬝🬻🬬████🬝🬵█ -|9: █╲█🬴████╲╱█🬝██▟▄█ -|10: ██╲╱╲█🬝█████╱🬵 -|11: ╱█████████🬝▄ -|12: █│█████🬝🬝🬹 -|13: ██████🬝▄█ -|14: 🬜🬬██🬸▄╲ -|15: 🬺█🬝🬵█ -|16: 🬝▄ +|7: Ascii +|8: █🬝█╲███▙🬸🬬🬻█████🬝🬵 +|9: ███████🬻██🬸█🬝█🬝▄█ +|10: ████████████🬝▄█ +|11: ███🬸██████🬝▄█ +|12: ████████🬝🬵█ +|13: ╱█████🬝▄ +|14: █🬬█╲🬝🬵█ +|15: 🬺█🬝🬵 +|16: 🬝▄ == snap tag-edit grid=400x31 cursor=87,6 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol diff --git a/test/snapshots/msg.golden b/test/snapshots/msg.golden index 653e9772..1d5b4cc2 100644 --- a/test/snapshots/msg.golden +++ b/test/snapshots/msg.golden @@ -48,3 +48,7 @@ |2: /tmp/pardes-snap/msg/cwd/a.txt * Save Tty Collapse Del |3: 1 AGAIN hand-written report |5: 3 Msg hand-written report +== snap msgtail grid=70x17 cursor=32,7 +|3: 6789 0123456789 0123456789 0123456789 0123456789 0123456789 THE-END +|6: 4 Msg 0123456789 0123456789 0123456789 0123456789 0123456789 012↩ +|7: 3456789 0123456789 THE-END diff --git a/test/snapshots/msg.snap b/test/snapshots/msg.snap index c8a0a265..5252508a 100644 --- a/test/snapshots/msg.snap +++ b/test/snapshots/msg.snap @@ -89,3 +89,15 @@ key x key tab stable 700 15000 snap msgbuiltin +# A message wider than the pane keeps its TAIL, not its head: the end of a +# message is the part that says something -- a path's file name, an error's +# reason -- so the head is what a narrow pane goes without. +key j +key o +text Msg 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 THE-END +key esc +settle 100 +key x +key tab +stable 700 15000 +snap msgtail diff --git a/test/snapshots/tagbottomimage.golden b/test/snapshots/tagbottomimage.golden index e7100114..0136e1a0 100644 --- a/test/snapshots/tagbottomimage.golden +++ b/test/snapshots/tagbottomimage.golden @@ -35,30 +35,30 @@ |3: pic.ppm |4: |5: /tmp/pardes-snap/tagbottomimage/cwd Tty Save Mode Filter Collapse Del -|6: 4*🬹~F~N🬰|G🬏▚Y~KF🬴s>T&zZ/🬻iTY=`S~╳bkZR37v🬦🬵d4QHZ8X▛▟ -|8: ^🬪🬛$}DrydNU&wsz=`*r🬒🬓🬳🬟*Y🬴G6🬧f🬮/>t🬧u🬲1Rg1t🬝🬻█ -|9: ▖#_{🬗X@🬢&$s'C%*=w@🬆▀wq%🬡d┼a┼m─>🬭🬜A▀A🬲H]p🬝🬹 -|10: %?WX🬕f🬩*TA8n╱┼E▘🬭Y#qo~XVE▐(╳▀H4^[mj🬗=🬒🬕▟█ -|11: ]Z🬷eb~Oyl3=SL▙a🬱🬉~MPMz}FMu<🬝▚>3&▖🬷WS🬝~█ -|12: EF-🬑y🬔!r🬙🬐╳O🬩▐%Qj─4za/?/\a🬜"🬖🬈🬛🬟A🬙🬝▄ -|13: 🬃N@xzOnczIK=t0@🬖j5🬮🬧65▟{🬮🬉🬄🬩zQ9/🬝🬻 -|14: ╲${&%@"#ctt▀Cr5F;🬐ARM╱uej╳75🬹9▛🬻 -|15: h^🬜"🬈🬨▜╲|W🬊🬦k6^🬰🬶rZ─▄\z9🬎🬉4^🬎🬻 -|16: 🬆f│Q_V🬗wGx🬱=5▛5*&V🬟🬄ZrXGz2🬝🬻█ -|17: !🬷W🬐(🬭]7x_>▗er🬯~▚di🬬4jY:🬝▟ -|18: gU~🬧3▙bjr\C#kKMpffAjps🬝🬻 -|19: *🬯G"🬣▟d🬮▀zJ🬪EHV▟╳9}y▛▄ -|20: ``))~RyJ🬴jA~w=hLpX🬝🬻█ -|21: 4x▀J"TG7=y-QZ🬙╲~▛🬻 -|22: 🬯/+╳f9ZG🬕+{QN_🬝🬹 -|23: E<'─🬫pS!"n4&🬝~ -|24: m$dx"!2🬳&{🬝🬻 -|25: *8f🬩▙Jb🬒🬝🬻█ -|26: m🬩7CiN🬎🬹 -|27: pG╲L🬝🬻 -|28: 🬡L🬝▄ -|29: 🬝~ +|6: Tagbottom +|7: {DbgY🬲s▜M^#▐FUJ[zNq=🬝g/y╱?V@🬱🬙▌UK╱🬍("🬕KJ8hSo🬝🬻 +|8: tX🬆s>🬌`🬵 Date: Tue, 22 Sep 2026 17:43:57 -0300 Subject: Repaint PDF highlights by row, send rasters by shared memory, and animate messages PDF highlights (hover preview, search, selection) are baked into page rasters, and any change re-rendered the whole page with MuPDF; the TTY then re-sent it as base64 (4.7 MB a page), the GUI as a new texture. Worse, a pointer motion over a PDF invalidated the page even when no preview was shown, so every motion paid that. Now: - A raster whose baked highlight set equals the wanted one is left alone. - A highlighted page keeps its clean rows (before highlights and tint); a change repaints only the rows of quads that differ, running MuPDF's highlight pass (pardes_pdf_paint_highlights) over those clean rows and tinting them: the operations a full render performs, so the pixels are identical. MuPDF band renders are NOT bit-identical to a whole page (edge rows, resampled images), so they are never used to patch; the comment claiming otherwise is corrected. - ImagePlace.patch hands shells the changed rows; the GUI uploads just those rows into the texture it holds. - The TTY probes kitty shared memory (t=s) with an id vaxis never reaches and sends rasters as a /dev/shm name when the terminal reads it; direct base64 otherwise (ssh). - Shells that take row patches (GUI, TTY with shm) repaint a selection while it is dragged instead of only on release. Latency elsewhere: - TTY: an animating frame no longer sleeps 16 ms blind; a tick thread posts into the input queue, so input inside the frame is handled at once. - TTY and GUI: queued pointer motions coalesce to the last. - GUI: a skipped swapchain image re-arms the frame (3 retries); animations still tick while nothing presents. - Editing: the line index is carried across an edit instead of rebuilt from a scan of the whole file per keystroke. Messages fall into their row (ease-in; the GUI slides the band out from under the tagline, a terminal fades it), stay until the next input as before, linger MessageLinger ms (default 800), and dissolve (ease-out). MessageAnimation toggles it; both are settings, in Config and startup files. The snapshot harness pins the old behaviour. The detached server now ticks animations. A restored terminal comes back live: the old screen and scrollback (dumped as clean VT by ghostty's formatter, replayed at the new size; older dumps fall back to their rendered text), a dim "restored history" marker, then a new shell in the directory it was in. Right-click on a line number in a file pane looks at that line (a sticky context header's number included). Measured with an external pty driver (TTY), an in-process fence trace (GUI, PARDES_TEST_LATENCY), and test/pdf_pointer_bench.zig (pixel identity against the baseline and a whole-page oracle); balanced A/A/B rounds, paired per-round statistics. Messages stack: each event gets its own row and its own fall, linger and dissolve; a line keeps its row until it leaves and a new one fills the first free row. Announcements and statuses are replaced in place, not stacked. MessageFall, MessageDissolve and DumpDir are settings Config reports. Co-Authored-By: Claude Opus 5.5 (1M context) --- build.zig | 19 ++ docs/config.md | 24 ++- src/config.zig | 66 +++++- src/detached/server.zig | 14 +- src/dump.zig | 19 +- src/fs.zig | 4 +- src/gui/gui.zig | 110 ++++++++-- src/macos.zig | 4 +- src/panes.zig | 484 ++++++++++++++++++++++++++++++++++++++++-- src/pardes.zig | 433 +++++++++++++++++++++++++++++++++++-- src/pdf.zig | 67 ++++++ src/pdf_bridge.c | 228 ++++++++++++++++---- src/pdf_bridge.h | 46 +++- src/tag_layer.zig | 4 + src/tty/tty.zig | 148 +++++++++++-- test/output.zig | 3 +- test/panes.zig | 37 ++++ test/pdf_pointer_bench.zig | 224 +++++++++++++++++++ test/snapshot.zig | 4 +- test/snapshots/builtins.snap | 4 + test/snapshots/dump.golden | 3 + test/snapshots/load.golden | 18 +- test/snapshots/restore.golden | 6 +- 23 files changed, 1815 insertions(+), 154 deletions(-) create mode 100644 test/pdf_pointer_bench.zig (limited to 'src/fs.zig') diff --git a/build.zig b/build.zig index 562ed89f..7010c863 100644 --- a/build.zig +++ b/build.zig @@ -142,6 +142,7 @@ pub fn build(b: *std.Build) void { const mupdf_check = b.step("mupdf-check", "compile, link, render, and search docs/design.pdf with MuPDF"); const pdf_bench_step = b.step("pdf-bench", "benchmark real MuPDF page rendering (-- [--json] [--reps N] [--warmup N] [--path FILE] [--page N] [--pages N])"); const pdf_sections_bench_step = b.step("pdf-sections-bench", "benchmark PDF outline/sections paths in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N])"); + const pdf_pointer_bench_step = b.step("pdf-pointer-bench", "time PDF hover and selection gestures and prove their pixels (-Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] [--cell WxH])"); const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])"); if (!enable_mupdf) mupdf_check.dependOn(&b.addFail("mupdf-check is unavailable with -Dmupdf=false").step); @@ -151,6 +152,8 @@ pub fn build(b: *std.Build) void { pdf_sections_bench_step.dependOn(&b.addFail("pdf-sections-bench is unavailable with -Dmupdf=false").step); if (!enable_mupdf) pdf_scroll_bench_step.dependOn(&b.addFail("pdf-scroll-bench is unavailable with -Dmupdf=false").step); + if (!enable_mupdf) + pdf_pointer_bench_step.dependOn(&b.addFail("pdf-pointer-bench is unavailable with -Dmupdf=false").step); const shaders_step = b.step("shaders", "refresh paired shaders/prebuilt/*.spv + *.glsl snapshots (glslc)"); const update_shaders = b.addUpdateSourceFiles(); @@ -482,6 +485,22 @@ pub fn build(b: *std.Build) void { run_pdf_sections_bench.setCwd(b.path(".")); pdf_sections_bench_step.dependOn(&run_pdf_sections_bench.step); + const pdf_pointer_bench = b.addExecutable(.{ + .name = "pardes-pdf-pointer-bench", + .root_module = b.createModule(.{ + .target = target, + .optimize = .ReleaseFast, + .root_source_file = b.path("test/pdf_pointer_bench.zig"), + .link_libc = true, + }), + }); + pdf_pointer_bench.root_module.addImport("pardes", core_module); + pdf_pointer_bench.root_module.addImport("mupdf", mupdf_mod); + const run_pdf_pointer_bench = b.addRunArtifact(pdf_pointer_bench); + if (b.args) |args| run_pdf_pointer_bench.addArgs(args); + run_pdf_pointer_bench.setCwd(b.path(".")); + pdf_pointer_bench_step.dependOn(&run_pdf_pointer_bench.step); + const pdf_scroll_bench = b.addExecutable(.{ .name = "pardes-pdf-scroll-bench", .root_module = b.createModule(.{ diff --git a/docs/config.md b/docs/config.md index 8eff79a8..27818b5b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -115,6 +115,16 @@ compact screen. Hiding it preserves your custom column commands. name before it runs; it is on by default, and the builtins that own the message row themselves (`Msg`) never announce. Turning it off leaves the row to the messages a builtin chooses to write. +`MessageAnimation` toggles how a message comes and goes; it is on by default. +A message eases down into its row (graphical frontends slide it out from under +the tagline; a terminal fades it in), stays until the next key or click as it +always has, then lingers for `MessageLinger` milliseconds (default 800) before +it dissolves into the page. `MessageFall` (default 180) and `MessageDissolve` +(default 300) set how long the fall and the dissolve take, also in +milliseconds; each timing is at most 60000, and `Config` reports all three. `MessageLinger 0` with +`MessageAnimation off` restores the old behaviour, a message cleared by the +very input that follows it. An updated line on a row already showing one swaps +its text in place rather than falling again. `SyntaxBold` toggles bold syntax keywords; it is off by default. These settings are shared by GUI and TTY, and `Config` reports their current states. Like `Colors` and `Wrap`, these commands take no argument and invert @@ -573,8 +583,18 @@ control all yield null, and the flag has to work anyway. Neither is a question asked at runtime — a binary that shelled out to `git` would describe whatever tree it was standing in rather than the one it came from. -`Restore a.dump` first looks for the relative path in the default dump directory -(`$XDG_DATA_HOME/pardes`, or `~/.local/share/pardes`). If it is absent, Restore +`Restore a.dump` first looks for the relative path in the dump directory: +`DumpDir ` when set (a leading `~/` is your home; bare `DumpDir` returns +to the default), else `$XDG_DATA_HOME/pardes` or `~/.local/share/pardes`. +`Config` reports the directory in effect as `DumpDir `, so the line can +be fed back as configuration. If it is absent, Restore uses the argument as a path as before. Absolute paths and argument-free Restore retain their existing behavior. `Dump` still honors `$PARDES_DUMP` and otherwise writes a timestamped file in the default directory. + +A restored terminal comes back live: its recorded output (the last MiB of it) +is replayed as history, a dim `── restored history ──` line marks where it +ends, and a new shell starts below it in the directory the old one was in. A +view left scrolled back stays where it was. Only the shell is new; nothing the +old one was running is restarted. The web shell, which has no ptys, still +shows the history alone. diff --git a/src/config.zig b/src/config.zig index 98bbf3f4..527c3752 100644 --- a/src/config.zig +++ b/src/config.zig @@ -102,6 +102,11 @@ pub const leader_path = paths: { table.set(.TaglineSize, null); } if (pardes.platform == .gui) table.set(.Pet, null); + table.set(.MessageAnimation, null); + table.set(.MessageLinger, null); + table.set(.MessageFall, null); + table.set(.MessageDissolve, null); + table.set(.DumpDir, null); if (builtins.capabilities.window_opacity) table.set(.WindowOpacity, null); if (builtins.capabilities.window_blur) table.set(.WindowBlur, null); if (builtins.capabilities.panel_transitions) { @@ -269,6 +274,10 @@ pub const wheel_cols: i32 = 4; pub const look_preview_delay_frames: ?u16 = 2; +/// The longest any message timing (MessageLinger, MessageFall, +/// MessageDissolve) may be set to, in milliseconds. +pub const message_ms_max: u16 = 60_000; + // Tag fonts keep body-cell geometry; valid sizes are 1...100 percent. pub const gui_tagline_font_percent: u8 = 82; comptime { @@ -558,6 +567,17 @@ pub const Runtime = struct { syntax_bold: bool = false, /// Builtins announce themselves on the message row. verbose: bool = true, + /// A message falls into its row and dissolves out of it. + message_animation: bool = true, + /// How long a message stays after the key or click that dismisses it. + message_linger_ms: u16 = 800, + /// How long its ease-in fall into the row takes. + message_fall_ms: u16 = 180, + /// How long its ease-out dissolve takes. + message_dissolve_ms: u16 = 300, + /// Where Dump writes and a relative Restore looks; empty is the default + /// ($XDG_DATA_HOME/pardes, else ~/.local/share/pardes). + dump_dir: Text(limits.host_path_cap) = .{}, window_opacity: u8 = 100, window_blur: u8 = 0, window_opacity_pending: bool = true, @@ -655,7 +675,10 @@ pub const Runtime = struct { pub const Capability = std.meta.FieldEnum(Capabilities); - pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, column_tags, syntax_bold, verbose }; + /// The message timings a setting word sets, each in milliseconds. + pub const MessageTime = enum { linger, fall, dissolve }; + + pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, column_tags, syntax_bold, verbose, message_animation }; pub const Scene = std.meta.FieldEnum(layout.SceneEffect); pub const Action = union(enum) { @@ -666,6 +689,8 @@ pub const Runtime = struct { tagline_size, window_opacity, window_blur, + message_ms: MessageTime, + dump_dir, transition: layout.Transition, scene: Scene, }; @@ -679,7 +704,7 @@ pub const Runtime = struct { return switch (setting.action) { // A toggle flips when it is a bare tagline word and SETS when // it is given `on` or `off`, so the report is configuration. - .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .toggle => true, + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .dump_dir, .toggle => true, else => false, }; } @@ -703,6 +728,11 @@ pub const Runtime = struct { .{ .word = "ColumnTags", .action = .{ .toggle = .column_tags } }, .{ .word = "SyntaxBold", .action = .{ .toggle = .syntax_bold } }, .{ .word = "Verbose", .action = .{ .toggle = .verbose } }, + .{ .word = "MessageAnimation", .action = .{ .toggle = .message_animation } }, + .{ .word = "MessageLinger", .action = .{ .message_ms = .linger } }, + .{ .word = "MessageFall", .action = .{ .message_ms = .fall } }, + .{ .word = "MessageDissolve", .action = .{ .message_ms = .dissolve } }, + .{ .word = "DumpDir", .action = .dump_dir }, .{ .word = "Theme", .action = .theme }, .{ .word = "Shell", .action = .shell }, .{ .word = "Font", .action = .font, .availability = .font_picker }, @@ -827,6 +857,17 @@ pub const Runtime = struct { if (percent > 100) return false; state.window_blur = percent; }, + // Bare, it returns to the default directory. + .dump_dir => if (!state.dump_dir.set(std.mem.trim(u8, argument orelse "", " \t\r\n"))) return false, + .message_ms => |which| { + const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); + for (text) |byte| if (!std.ascii.isDigit(byte)) return false; + const ms = std.fmt.parseInt(u16, text, 10) catch return false; + if (ms > message_ms_max) return false; + switch (which) { + inline else => |w| @field(state, "message_" ++ @tagName(w) ++ "_ms") = ms, + } + }, .transition => |effect| state.toggleTransition(effect), .scene => |effect| switch (effect) { inline else => |field| { @@ -847,6 +888,9 @@ pub const Runtime = struct { compiled_default_shell: []const u8, gui_shader_source_mode: ?[]const u8 = null, hover_delay_frames: ?u16, + /// Where dumps go when `DumpDir` is unset; empty without a host + /// filesystem. + default_dump_dir: []const u8 = "", native_images: bool, capabilities: Capabilities, state: *const Runtime, @@ -895,6 +939,13 @@ pub const Runtime = struct { else try out.print("{s} unsupported\n", .{setting.word}); }, + .dump_dir => { + const dir = if (state.dump_dir.len > 0) state.dump_dir.get() else context.default_dump_dir; + try out.print("{s} {s}\n", .{ setting.word, if (dir.len > 0) dir else "(none)" }); + }, + .message_ms => |which| try out.print("{s} {d}\n", .{ setting.word, switch (which) { + inline else => |w| @field(state, "message_" ++ @tagName(w) ++ "_ms"), + } }), .shell => { const chosen = state.shell.requested.get(); try out.print( @@ -993,7 +1044,7 @@ pub const Runtime = struct { for (settings[i + 1 ..]) |later| try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); try std.testing.expectEqual(switch (setting.action) { - .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .toggle => true, + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .dump_dir, .toggle => true, else => false, }, setting.takesArg()); } @@ -1152,6 +1203,8 @@ pub const Runtime = struct { .tagline_size => "73", .window_opacity => "85", .window_blur => "40", + .message_ms => "1500", + .dump_dir => "~/dumps", else => null, }; try std.testing.expect(apply(&state, setting, argument)); @@ -1170,11 +1223,18 @@ pub const Runtime = struct { .column_tags => "ColumnTags off\n", .syntax_bold => "SyntaxBold on\n", .verbose => "Verbose off\n", + .message_animation => "MessageAnimation off\n", }, .shell => "Shell requested (new panes) fish\n", .tagline_size => "TaglineSize 73\n", .window_opacity => "WindowOpacity 85 (pending)\n", .window_blur => "WindowBlur 40\n", + .dump_dir => "DumpDir ~/dumps\n", + .message_ms => |which| switch (which) { + .linger => "MessageLinger 1500\n", + .fall => "MessageFall 1500\n", + .dissolve => "MessageDissolve 1500\n", + }, .transition => |transition| switch (transition) { .off => unreachable, .slide => "Panel transition PanelSlide\n", diff --git a/src/detached/server.zig b/src/detached/server.zig index 3e98fc9d..6959e577 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -536,7 +536,7 @@ pub const Session = struct { fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const s = of(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; + const path = pardes.dump.outPath(&pbuf, s.core.settings.dump_dir.get()) orelse return; filesystem.write(s.core, path, bytes) catch |err| return s.core.reportError(0, "dump", err); s.core.setLastDump(path); } @@ -809,8 +809,11 @@ pub const Session = struct { // The wait is the 9P connections' turn with the core. if (n == 0) { pardes.turn.rest(); - defer pardes.turn.wake(); - return nap(if (timeout_ms == 0) 16 else timeout_ms); + nap(if (timeout_ms == 0) 16 else timeout_ms); + pardes.turn.wake(); + // An animating frame's wait is the frame: tick it. + if (timeout_ms != 0) s.core.update(.tick); + return; } var timeout: c_int = if (timeout_ms == 0) -1 else @intCast(@min(timeout_ms, std.math.maxInt(c_int))); if (s.nextWake(now)) |due| timeout = if (timeout < 0) due else @min(timeout, due); @@ -819,6 +822,9 @@ pub const Session = struct { const ready = libc.poll(&fds, @intCast(n), timeout); pardes.turn.wake(); if (ready > 0) s.dispatch(fds[0..n], src[0..n]); + // Animating, the frame's time is up: advance it. There is no other + // tick in a detached session, and without it an animation never ends. + if (timeout_ms != 0 and monotonicMs() -| now >= timeout_ms) s.core.update(.tick); _ = s.drainCompletions(true); s.expire(monotonicMs()); s.harvest(); @@ -1156,7 +1162,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void try session.core.pump(h); if (session.core.quit) break; if (session.core.takeRestore()) |path| restore: { - const bytes = filesystem.readRestore(gpa, path) catch |err| { + const bytes = filesystem.readRestore(gpa, path, session.core.settings.dump_dir.get()) catch |err| { session.core.reportError(session.core.active, "Restore", err); break :restore; }; diff --git a/src/dump.zig b/src/dump.zig index 89abd995..ff5d2166 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -11,11 +11,11 @@ const log = std.log.scoped(.dump); /// pins it for deterministic goldens); else $XDG_DATA_HOME|~/.local/share /// /pardes/pardes-.zon — timestamped so dumps never overwrite each other. /// Creates the pardes dir (parents assumed; a failure surfaces at open). -pub fn outPath(buf: *[1024:0]u8) ?[:0]const u8 { +pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { if (std.c.getenv("PARDES_DUMP")) |p| return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null; var dir_buf: [900]u8 = undefined; - const dir = defaultDirectory(&dir_buf) orelse return null; + const dir = directory(&dir_buf, dir_setting) orelse return null; var dz: [901:0]u8 = undefined; @memcpy(dz[0..dir.len], dir); dz[dir.len] = 0; @@ -32,6 +32,15 @@ pub fn outPath(buf: *[1024:0]u8) ?[:0]const u8 { ds.getSecondsIntoMinute(), }, 0) catch null; } +/// Where dumps go and relative Restore names are looked up: the `DumpDir` +/// setting when set (a leading `~/` is the home directory), else the default. +pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { + if (dir_setting.len == 0) return defaultDirectory(buf); + if (std.mem.startsWith(u8, dir_setting, "~/")) if (std.c.getenv("HOME")) |h| + return std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.span(h), dir_setting[2..] }) catch null; + return std.fmt.bufPrint(buf, "{s}", .{dir_setting}) catch null; +} + /// The standard dump directory, without creating it or generating a filename. pub fn defaultDirectory(buf: []u8) ?[]const u8 { if (std.c.getenv("XDG_DATA_HOME")) |x| @@ -69,8 +78,14 @@ pub const PaneKind = enum { pub const Terminal = struct { cwd: []const u8 = "", + /// The rendered scrollback and screen as plain text, one row per line. stream: []const u8 = "", stream_b64: []const u8 = "", + /// `stream_b64` is the emulator's primary screen and scrollback as clean + /// VT (ghostty's formatter), which replays to what the screen showed. + /// Absent (older dumps), it is the raw tail of the pty's output, which + /// replays faithfully only if it holds the whole session at one size. + stream_is_screen: bool = false, cursor: Cursor = .{}, }; diff --git a/src/fs.zig b/src/fs.zig index 85eae825..84ab3b95 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1104,9 +1104,9 @@ pub fn readFile(gpa: std.mem.Allocator, path: []const u8) ![]u8 { /// Restore first tries a relative argument under the default dump directory, /// then preserves the ordinary file lookup. Absolute paths remain verbatim. -pub fn readRestore(gpa: std.mem.Allocator, path: []const u8) ![]u8 { +pub fn readRestore(gpa: std.mem.Allocator, path: []const u8, dir_setting: []const u8) ![]u8 { var dir_buf: [4096]u8 = undefined; - const dir = @import("dump.zig").defaultDirectory(&dir_buf); + const dir = @import("dump.zig").directory(&dir_buf, dir_setting); return readRestoreIn(gpa, path, dir); } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 17bdb46f..7f28124c 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2111,8 +2111,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u } var win_flags: c.SDL_WindowFlags = c.SDL_WINDOW_RESIZABLE; if (!test_mode) win_flags |= c.SDL_WINDOW_HIGH_PIXEL_DENSITY; - // A latency run renders to the capture texture; keep it off the desktop. - if (latency_fd >= 0) win_flags |= c.SDL_WINDOW_HIDDEN; + // A test run renders to the capture texture; keep it off the desktop. + if (test_mode) win_flags |= c.SDL_WINDOW_HIDDEN; const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); // Background-only opacity needs per-pixel alpha; whole-window compositor // opacity would dim the text as well. SDL requires this flag at creation. @@ -2353,6 +2353,7 @@ fn localSession( } else try pardes.Pardes.init(allocs.pardes, opts); defer core.deinit(); core.native_images = true; + core.native_image_patches = true; observeGuiFont(g, core); syncTaglineFont(g, core); @@ -2448,7 +2449,7 @@ fn localSession( } } if (core.takeRestore()) |rp| blk: { - const bytes = filesystem.readRestore(gpa, rp) catch |err| { + const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); break :blk; }; @@ -2473,6 +2474,7 @@ fn localSession( g.presented_images.clearRetainingCapacity(); g.prepared_images.clearRetainingCapacity(); nc.native_images = true; + nc.native_image_patches = true; nc.host = host; if (fs) |f| f.reset(nc); core.deinit(); @@ -3591,6 +3593,7 @@ const Shell = struct { test_mode: bool = false, feed: StdinFeed = .{}, presented: bool = false, + skipped_presents: u8 = 0, surface: ?*pardes.Surface = null, animation_clock: AnimationClock = .{}, saw_event: bool = false, @@ -3774,14 +3777,29 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { var in: Input = .{ .core = core }; if (s.gui) |g| { var sev = std.mem.zeroes(c.SDL_Event); - const ms: c_int = if (timeout_ms != 0) @intCast(timeout_ms) else 16; + // A latency trace is fed on stdin, whose poll below paces the loop: + // waiting here too would make every tick cost two frames. + const ms: c_int = if (latency_fd >= 0) 0 else if (timeout_ms != 0) @intCast(timeout_ms) else 16; // The wait is the 9P connections' turn with the core. pardes.turn.rest(); const got = c.SDL_WaitEventTimeout(&sev, ms); pardes.turn.wake(); if (got) { - dispatch(g, &in, &sev); - while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev); + // A run of queued motions is one move to its last position (the + // handler reads only absolute x/y and held buttons): acting on + // each would repeat hover and selection work the next undoes. + var motion: ?c.SDL_Event = null; + while (true) { + if (sev.type == c.SDL_EVENT_MOUSE_MOTION) { + motion = sev; + } else { + if (motion) |*m| dispatch(g, &in, m); + motion = null; + dispatch(g, &in, &sev); + } + if (!c.SDL_PollEvent(&sev)) break; + } + if (motion) |*m| dispatch(g, &in, m); } } if (s.test_mode) { @@ -3913,6 +3931,10 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { log.err("render: {t}", .{err}); break :blk false; }; + // A skipped swapchain image would otherwise hide this input's frame until + // the next event. A few retries only: a minimized window never gets one. + s.skipped_presents = if (s.presented) 0 else s.skipped_presents +| 1; + if (!s.presented and s.skipped_presents <= 3) core.present_skipped = true; if (g.scene_target_failed) { g.scene_failures +|= 1; log.err("scene target unavailable (attempt {d}/3)", .{g.scene_failures}); @@ -3926,7 +3948,12 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { fn postPresent(ctx: ?*anyopaque) void { const s = shellOf(ctx); const g = s.gui orelse return; - if (!s.presented) return; + if (!s.presented) { + // No image (a minimized window): time still passes, so a lingering + // message or a hover wait runs out instead of redrawing forever. + if (s.animation_clock.due(s.core.animationActive(), c.SDL_GetTicksNS())) s.core.update(.tick); + return; + } const frame = s.surface orelse return; refreshPresentedPointer(g, s.core); finishPresentedAnimationFrame( @@ -4030,7 +4057,7 @@ fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) vo fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const s = shellOf(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; + const path = pardes.dump.outPath(&pbuf, s.core.settings.dump_dir.get()) orelse return; filesystem.write(s.core, path, bytes) catch |err| return s.core.reportError(0, "dump", err); s.core.setLastDump(path); } @@ -4533,6 +4560,23 @@ fn uploadNativeTexture( const byte_len = validImageBytes(place) orelse return error.BadImage; const key = place.cacheKey(); if (g.native_images.contains(key)) return; + if (comptime pardes.pdf_enabled) if (place.patch) |patch| patch: { + // The core changed only these rows since a revision we still hold: + // write them into that texture rather than sending the whole page. + var base = key; + base.revision = patch.from; + if (patch.y + patch.h > place.ih) break :patch; + const texture = g.native_images.get(base) orelse break :patch; + const row = place.iw * 4; + try uploadTextureRows(g, cmd, texture, place.rgba[patch.y * row ..][0 .. patch.h * row], place.iw, patch.y, patch.h); + try g.native_images.put(gpa, key, texture); + _ = g.native_images.remove(base); + // A transition snapshot of the last frame follows its texture. + for (g.presented_images.items) |*saved| if (saved.key.eql(base)) { + saved.key = key; + }; + return; + }; var tex_info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); tex_info.type = c.SDL_GPU_TEXTURETYPE_2D; @@ -4545,39 +4589,51 @@ fn uploadNativeTexture( tex_info.sample_count = c.SDL_GPU_SAMPLECOUNT_1; const texture = c.SDL_CreateGPUTexture(g.device, &tex_info) orelse return error.GpuCreate; errdefer c.SDL_ReleaseGPUTexture(g.device, texture); + try uploadTextureRows(g, cmd, texture, place.rgba[0..byte_len], place.iw, 0, place.ih); + try g.native_images.put(gpa, key, texture); +} +/// Copy `rows` rows of RGBA, `width` pixels each, into `texture` at row `y`. +fn uploadTextureRows( + g: *Gui, + cmd: *c.SDL_GPUCommandBuffer, + texture: *c.SDL_GPUTexture, + rgba: []const u8, + width: usize, + y: usize, + rows: usize, +) !void { var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, - .size = byte_len, + .size = @intCast(rgba.len), .props = 0, }; const transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate; defer c.SDL_ReleaseGPUTransferBuffer(g.device, transfer); const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, transfer, false) orelse return error.GpuMap); - @memcpy(mapped[0..byte_len], place.rgba); + @memcpy(mapped[0..rgba.len], rgba); c.SDL_UnmapGPUTransferBuffer(g.device, transfer); const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = transfer, .offset = 0, - .pixels_per_row = @intCast(place.iw), - .rows_per_layer = @intCast(place.ih), + .pixels_per_row = @intCast(width), + .rows_per_layer = @intCast(rows), }; const dst = c.SDL_GPUTextureRegion{ .texture = texture, .mip_level = 0, .layer = 0, .x = 0, - .y = 0, + .y = @intCast(y), .z = 0, - .w = @intCast(place.iw), - .h = @intCast(place.ih), + .w = @intCast(width), + .h = @intCast(rows), .d = 1, }; c.SDL_UploadToGPUTexture(copy, &src, &dst, false); c.SDL_EndGPUCopyPass(copy); - try g.native_images.put(gpa, key, texture); } fn appendPreparedImage( @@ -5442,16 +5498,30 @@ fn emitTagLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const p const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * bw; const background: pardes.Cell = .{ .default = false, .style = .{ .bg = .{ .rgb = layer.bg } } }; - emitInstance(g, instances, next.*, 0, layer.viewport.y, .{ .w = right - left, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, track, .body, &background, old_layer, false, page); + // A band sliding into place is drawn offset and cut at its row's top, so + // it comes out from under whatever is above it. + const slide = layer.slide * bh; + const top = @as(f32, @floatFromInt(layer.viewport.y)) * bh; + emitInstance(g, instances, next.*, 0, layer.viewport.y, .{ .w = right - left, .h = bh, .x_off = left, .y_off = slide }, win_w, win_h, track, .body, &background, old_layer, false, page); + if (slide != 0) clipInstanceTop(&instances[next.*], top, win_h); next.* += 1; for (0..tagLayerCellCount(g, layer)) |col| { const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.col == col else false; - emitInstance(g, instances, next.*, @intCast(col), layer.viewport.y, .{ .w = tw, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, track, .tagline, &layer.cells[col], old_layer, cursor, page); + emitInstance(g, instances, next.*, @intCast(col), layer.viewport.y, .{ .w = tw, .h = bh, .x_off = left, .y_off = slide }, win_w, win_h, track, .tagline, &layer.cells[col], old_layer, cursor, page); clipInstanceRight(&instances[next.*], right, win_w); + if (slide != 0) clipInstanceTop(&instances[next.*], top, win_h); next.* += 1; } } +fn clipInstanceTop(instance: *CellInstance, top: f32, win_h: f32) void { + const limit = 1 - top / win_h * 2; + if (instance.y0 <= limit) return; + const fraction = std.math.clamp((limit - instance.y1) / (instance.y0 - instance.y1), 0, 1); + instance.v0 = instance.v1 + (instance.v0 - instance.v1) * fraction; + instance.y0 = @max(instance.y1, limit); +} + fn bodyLayerAt(surface: *const pardes.Surface, col: u16, row: u16) ?*const pardes.BodyLayer { return bodyLayerIn(surface.bodyLayers(), col, row); } @@ -6436,7 +6506,9 @@ fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, t } fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32) !void { - if (g.capture_dir.len == 0) return; + // 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) { diff --git a/src/macos.zig b/src/macos.zig index a7ee3164..c359eb3f 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1325,7 +1325,7 @@ export fn pardes_tick() bool { fn restoreCore(st: *State) bool { if (st.core.quit) return false; const path = st.core.takeRestore() orelse return false; - const bytes = filesystem.readRestore(st.gpa, path) catch |err| { + const bytes = filesystem.readRestore(st.gpa, path, st.core.settings.dump_dir.get()) catch |err| { st.core.reportError(st.core.active, "Restore", err); return false; }; @@ -2431,7 +2431,7 @@ fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) vo fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const st = hostState(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; + const path = pardes.dump.outPath(&pbuf, st.core.settings.dump_dir.get()) orelse return; filesystem.write(st.core, path, bytes) catch |err| return st.core.reportError(0, "dump", err); st.core.setLastDump(path); } diff --git a/src/panes.zig b/src/panes.zig index b3424385..8d4330e9 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -183,6 +183,20 @@ pub const Pane = struct { tty_filter: bool = false, msg: [256]u8 = undefined, msg_len: u16 = 0, + /// Where the newest message line is in its life. + msg_life: MessageLife = .{}, + /// The row (among the notice rows) the newest line holds for its life. + msg_slot: u8 = 0, + /// Earlier message lines still on screen, oldest first, each running its + /// own life: a new message stacks under them instead of replacing them. + msg_older: [message_stack]OlderMessage = undefined, + msg_older_len: u8 = 0, + /// The newest line is a builtin announcing itself in this step: what + /// the step says next replaces it rather than stacking under it. + msg_announcement: bool = false, + /// The newest line is a status (progress, a server's state): the next + /// line replaces it rather than stacking under it. + msg_status: bool = false, /// The transient lines this pane shows between its body and its tagline: /// a builtin's message, the pending leader chord, a prompt waiting for /// input. Rebuilt every frame from the state that owns each one, so a @@ -192,30 +206,102 @@ pub const Pane = struct { /// reserves rows for sticky context headers. notices: Notices = .{}, + pub const MessagePhase = enum { entering, shown, lingering, leaving }; + /// One message line's animation: falling in, shown, lingering after the + /// key or click that dismissed it, dissolving. `frame` counts animation + /// frames within the phase. + pub const MessageLife = struct { + phase: MessagePhase = .shown, + frame: u16 = 0, + /// Dismissed while still falling: it lingers once it has landed. + dismissed: bool = false, + }; + /// Older message lines kept on screen under a new one. + pub const message_stack = 3; + pub const OlderMessage = struct { + text: [256]u8 = undefined, + len: u16 = 0, + life: MessageLife = .{}, + slot: u8 = 0, + + pub fn slice(line: *const OlderMessage) []const u8 { + return line.text[0..line.len]; + } + }; + + /// Move the newest line onto the stack of older ones, dropping the oldest + /// when it is full; the newest slot is left empty for what arrives. + pub fn pushOlderMessage(pane: *Pane) void { + if (pane.msg_older_len == message_stack) { + std.mem.copyForwards(OlderMessage, pane.msg_older[0 .. message_stack - 1], pane.msg_older[1..]); + pane.msg_older_len -= 1; + } + pane.msg_older[pane.msg_older_len] = .{ .text = pane.msg, .len = pane.msg_len, .life = pane.msg_life, .slot = pane.msg_slot }; + pane.msg_older_len += 1; + pane.msg_len = 0; + pane.msg_life = .{}; + } + + /// The first row no older line holds. A line keeps its row until it + /// leaves, and a new one fills the first gap: nothing on screen moves. + pub fn freeMessageSlot(pane: *const Pane) u8 { + var used: u8 = 0; + for (pane.msg_older[0..pane.msg_older_len]) |line| used |= @as(u8, 1) << @intCast(line.slot); + var slot: u8 = 0; + while (used & (@as(u8, 1) << @intCast(slot)) != 0) slot += 1; + return slot; + } + + pub fn removeOlderMessage(pane: *Pane, i: usize) void { + std.mem.copyForwards(OlderMessage, pane.msg_older[i .. pane.msg_older_len - 1], pane.msg_older[i + 1 .. pane.msg_older_len]); + pane.msg_older_len -= 1; + } + pub const Notices = struct { /// Painted bottom-up in this order, so a prompt keeps the row nearest /// the tagline that it has always had, and its cursor with it. - pub const Kind = enum { message, leader, prompt }; - pub const max = @typeInfo(Kind).@"enum".fields.len; + /// `older` is an earlier message line still on screen; `index` says + /// which (`Pane.msg_older`). + pub const Kind = enum { older, message, leader, prompt }; + pub const max = @typeInfo(Kind).@"enum".fields.len - 1 + message_stack; kinds: [max]Kind = undefined, + index: [max]u8 = @splat(0), + /// Each band's row below the body's top: message lines keep theirs, + /// so a band that leaves leaves a gap rather than moving the rest. + row: [max]u8 = @splat(0), /// Where each band's chip starts, as an absolute grid column. A chip /// is only as wide as its own text, so the rest of the row underneath /// is ordinary body text and a click there has to reach it. left: [max]u16 = @splat(std.math.maxInt(u16)), len: u8 = 0, + /// A band on the next row after every band so far. pub fn push(n: *Notices, kind: Kind) void { + n.pushAt(kind, 0, n.span()); + } + + pub fn pushAt(n: *Notices, kind: Kind, index: u8, row: u8) void { if (n.len >= max) return; n.kinds[n.len] = kind; + n.index[n.len] = index; + n.row[n.len] = row; n.left[n.len] = std.math.maxInt(u16); n.len += 1; } /// Is this cell inside the chip drawn for band `i`? Nothing else on /// that row belongs to the notice. - pub fn covers(n: *const Notices, i: usize, col: u16) bool { - return i < n.len and col >= n.left[i]; + pub fn covers(n: *const Notices, row: usize, col: u16) bool { + for (0..n.len) |i| if (n.row[i] == row) return col >= n.left[i]; + return false; + } + + /// Rows from the body's top down to the last band's. + pub fn span(n: *const Notices) u8 { + var rows: u8 = 0; + for (n.row[0..n.len]) |row| rows = @max(rows, row + 1); + return rows; } pub fn slice(n: *const Notices) []const Kind { @@ -1327,7 +1413,15 @@ pub const File = struct { 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)); - try std.testing.expectEqual(@as(usize, 0), file.line_starts.len); + // An edit carries a built index forward; it must equal a fresh one. + if (file.line_starts.len > 0) { + const carried = file.line_starts; + defer p.gpa.free(carried); + 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); @@ -1546,6 +1640,80 @@ pub const File = struct { return starts; } + /// The line index of `new` from `old`'s: an edit replaces one span, so + /// line starts before it stand, starts after it shift, and only the span + /// is scanned. Rebuilding scanned the whole file on every keystroke. + fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8) ![]usize { + const n = @min(old.len, new.len); + var head: usize = 0; + while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; + while (head < n and old[head] == new[head]) head += 1; + var tail: usize = 0; + while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; + while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; + // A start s follows the newline at s-1: kept while that newline is in + // the common head, shifted while it is in the common tail. + const kept = std.sort.upperBound(usize, starts, head, struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order); + const old_tail_at = old.len - tail; + const moved = starts.len - std.sort.upperBound(usize, starts, old_tail_at, struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order); + const middle = new[head .. new.len - tail]; + const out = try gpa.alloc(usize, kept + std.mem.count(u8, middle, "\n") + moved); + @memcpy(out[0..kept], starts[0..kept]); + var i = kept; + var off: usize = 0; + while (std.mem.indexOfScalarPos(u8, middle, off, '\n')) |nl| { + off = nl + 1; + out[i] = head + off; + i += 1; + } + for (starts[starts.len - moved ..]) |start| { + out[i] = start + new.len - old.len; + i += 1; + } + return out; + } + + test "edited line index equals a rebuilt one" { + const gpa = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(7); + 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)]); + for (0..2000) |_| { + var old_state: State = undefined; + old_state.content = text.items; + old_state.line_starts = &.{}; + const starts = try lineIndex(gpa, &old_state); + defer gpa.free(starts); + // one random replace, like any edit through setContent + const at = r.uintAtMost(usize, text.items.len); + const del = r.uintAtMost(usize, @min(8, text.items.len - at)); + var ins: [8]u8 = undefined; + const ins_len = r.uintAtMost(usize, 8); + for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)]; + const old = try gpa.dupe(u8, text.items); + defer gpa.free(old); + try text.replaceRange(gpa, at, del, ins[0..ins_len]); + const edited = try editedLineStarts(gpa, starts, old, text.items); + defer gpa.free(edited); + var fresh_state: State = undefined; + fresh_state.content = text.items; + fresh_state.line_starts = &.{}; + const fresh = try lineIndex(gpa, &fresh_state); + defer gpa.free(fresh); + try std.testing.expectEqualSlices(usize, fresh, edited); + } + } + /// 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); @@ -1760,12 +1928,13 @@ pub const File = struct { reportEdit(p, f, new); if (f.mini) |*mini| mini.deinit(p.gpa); f.mini = null; + const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new) catch &.{} else &.{}; p.gpa.free(f.content); f.content = new; f.revision +%= 1; f.mtime = pardes.ctlfs.events.now(); if (f.line_starts.len > 0) p.gpa.free(f.line_starts); - f.line_starts = &.{}; + f.line_starts = starts; if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); f.highlights = &.{}; f.highlight_start = 0; @@ -2864,7 +3033,10 @@ pub const Output = struct { pub fn openConfig(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); + var dir_buf: [1024]u8 = undefined; + const host_fs = comptime (pardes.platform != .web and pardes.platform != .esp32p4); try config.Runtime.writeReport(&out.writer, .{ + .default_dump_dir = if (host_fs) (pardes.dump.defaultDirectory(&dir_buf) orelse "") else "", .startup_config_path = p.opts.startup_config_path, .platform = @tagName(pardes.platform), .theme_name = p.theme().name, @@ -3599,6 +3771,9 @@ pub const Pdf = struct { const Page = struct { page: usize, items: []const Highlight }; pages: [3]Page = undefined, len: usize = 0, + /// Repaint whenever the set changes, not only when a page's raster was + /// invalidated (`HighlightInput.live`). + live: bool = false, pub fn forPage(highlights: @This(), page: usize) []const Highlight { for (highlights.pages[0..highlights.len]) |group| @@ -3612,6 +3787,7 @@ pub const Pdf = struct { hover_page: ?usize = null, hover_color: [3]u8, selection_color: [3]u8, + live: bool = false, } else void; pub fn buildHighlights( @@ -3623,7 +3799,7 @@ pub const Pdf = struct { const search_len = if (state.search_results) |results| results.quads.len else 0; const selection_len = if (state.selection) |selection| selection.quads.len else 0; const items = try arena.alloc(Highlight, input.hover_quads.len + search_len + selection_len); - var result: Highlights = .{}; + var result: Highlights = .{ .live = input.live }; var n: usize = 0; // Hover, search and selection can belong to three different pages. // Group them once so raster rendering can borrow a contiguous slice. @@ -3721,6 +3897,19 @@ pub const Pdf = struct { decorated: bool = false, tint_key: ?TintKey = null, revision: u32 = 0, + /// `rgba` before its highlights and tint, kept once the page has been + /// highlighted: a highlight change repaints rows from it instead of + /// rendering the page again. + clean: []u8 = &.{}, + /// The highlights baked into `rgba` (gpa-owned), so a change repaints + /// only the rows of the quads that differ. + baked: []Highlight = &.{}, + /// `baked` is a true record (false after a render could not copy it). + baked_valid: bool = false, + /// Page rows changed since revision `patch_from`, the one last handed + /// to a shell; 0 when the pixels were replaced wholesale since. + patch_from: u32 = 0, + patch_rows: pdf.Document.Rows = .{ .start = 0, .end = 0 }, } else void; pub const SectionsOutput = if (enabled) struct { @@ -3894,6 +4083,8 @@ pub const Pdf = struct { } fn retireRaster(state: *@This(), gpa: std.mem.Allocator, raster: *Raster) void { + if (raster.clean.len > 0) gpa.free(raster.clean); + gpa.free(raster.baked); state.retireRgba(gpa, raster.rgba); raster.* = .{}; } @@ -4138,8 +4329,11 @@ pub const Pdf = struct { pub fn deinit(state: *@This(), gpa: std.mem.Allocator) void { gpa.free(state.path); - for (state.rasters[0..state.rasters_len]) |raster| + for (state.rasters[0..state.rasters_len]) |raster| { if (raster.rgba.len > 0) gpa.free(raster.rgba); + if (raster.clean.len > 0) gpa.free(raster.clean); + gpa.free(raster.baked); + } for (state.spare[0..state.spare_len]) |rgba| gpa.free(rgba); gpa.free(state.page_sizes); gpa.free(state.page_starts); @@ -4614,16 +4808,27 @@ pub const Pdf = struct { const slot = raster.?; const page_highlights = highlights.forPage(page); const decorated = page_highlights.len > 0; - const stale = !slot.tried or !slot.request_valid or - !slot.request.eql(request) or slot.decorated != decorated or + const base_stale = !slot.request_valid or !slot.request.eql(request) or slot.tint_key == null or !slot.tint_key.?.eql(tint_key) or slot.rgba.len == 0 or slot.band_h == 0; - const uncovered = !stale and uncovered: { + const uncovered = !base_stale and uncovered: { const want = wantedBand(state, viewport, page, slotShape(slot), is_flinging); break :uncovered slot.band_y > want.y or slot.band_y + slot.band_h < want.y + want.height; }; - if (!stale and !uncovered) continue; + if (!base_stale and !uncovered) { + if (slot.tried and slot.decorated == decorated and + !(highlights.live and !sameHighlights(slot.baked, page_highlights))) continue; + // Invalidated, but it already shows exactly these highlights + // (a preview withdrawn that was never drawn, on every pointer + // move over a page): nothing to render. + if (slot.baked_valid and sameHighlights(slot.baked, page_highlights)) { + slot.tried = true; + continue; + } + // Only the highlights moved: repaint their rows in place. + if (repaintHighlights(state, gpa, slot, request, tint_key, page_highlights)) continue; + } slot.tried = true; slot.request = request; @@ -4640,15 +4845,27 @@ pub const Pdf = struct { { const tz_render = tracy.zone(@src(), "pdf.render_into"); defer tz_render.end(); + // A highlighted page keeps its clean rows for repaints. + const keep_clean = pardes.platform != .macos and (decorated or slot.clean.len > 0); state.document.renderIntoAtWithPaper( page, request, shape, want, - page_highlights, + if (keep_clean) &.{} else page_highlights, fresh, pardes.platform == .macos, ) catch break :filled false; + if (slot.clean.len != 0 and (!keep_clean or slot.clean.len != fresh.len)) { + gpa.free(slot.clean); + slot.clean = &.{}; + } + if (keep_clean) { + if (slot.clean.len == 0) slot.clean = gpa.alloc(u8, fresh.len) catch &.{}; + if (slot.clean.len == fresh.len) @memcpy(slot.clean, fresh); + state.document.paintHighlightsAt(page, request, shape, want, page_highlights, fresh) catch + break :filled false; + } } const tz_tint = tracy.zone(@src(), "pdf.tint"); defer tz_tint.end(); @@ -4658,6 +4875,9 @@ pub const Pdf = struct { }; if (!filled) { state.retireRgba(gpa, fresh); + // `clean` may already hold the band that failed. + if (slot.clean.len > 0) gpa.free(slot.clean); + slot.clean = &.{}; continue; } @@ -4669,6 +4889,18 @@ pub const Pdf = struct { slot.band_h = want.height; slot.decorated = decorated; slot.tint_key = tint_key; + if (gpa.dupe(Highlight, page_highlights)) |copy| { + gpa.free(slot.baked); + slot.baked = copy; + slot.baked_valid = true; + } else |_| { + // Unrecorded highlights cannot be compared or diffed. + slot.baked_valid = false; + if (slot.clean.len > 0) gpa.free(slot.clean); + slot.clean = &.{}; + } + slot.patch_from = 0; + slot.patch_rows = .{ .start = 0, .end = 0 }; state.next_raster_revision +%= 1; if (state.next_raster_revision == 0) state.next_raster_revision = 1; slot.revision = state.next_raster_revision; @@ -4676,6 +4908,114 @@ pub const Pdf = struct { state.trimSpares(gpa); } + /// Repaint only the rows where the old and new highlights differ: the + /// clean rows kept from the page's last render, MuPDF's highlight pass + /// (the whole new set) over them, the per-pixel tint — the operations a + /// full render performs, in its order, on fewer rows and without running + /// the page again. False leaves the slot for the full path. + fn repaintHighlights( + state: *State, + gpa: std.mem.Allocator, + slot: *Raster, + request: RenderRequest, + tint_key: TintKey, + page_highlights: []const Highlight, + ) bool { + const tz = tracy.zone(@src(), "pdf.repaint_highlights"); + defer tz.end(); + if (slot.clean.len != slot.rgba.len or !slot.baked_valid) return false; + if (sameHighlights(slot.baked, page_highlights)) { + slot.tried = true; + return true; + } + const baked = gpa.dupe(Highlight, page_highlights) catch return false; + const changed = changedHighlights(gpa, slot.baked, page_highlights) catch { + gpa.free(baked); + return false; + }; + defer gpa.free(changed); + var dirty = state.document.highlightRows(slot.page, request, changed) catch { + gpa.free(baked); + return false; + }; + slot.tried = true; + dirty.start = @max(dirty.start, slot.band_y); + dirty.end = @min(dirty.end, slot.band_y + slot.band_h); + if (dirty.start < dirty.end) { + const shape = slotShape(slot); + const band = shape.band(dirty.start, dirty.end - dirty.start); + const offset = (dirty.start - slot.band_y) * shape.stride; + const out = slot.rgba[offset..][0..band.len]; + @memcpy(out, slot.clean[offset..][0..band.len]); + // On failure the rows are half-made: let the full path redo them. + state.document.paintHighlightsAt(slot.page, request, shape, band, page_highlights, out) catch { + gpa.free(baked); + slot.tried = false; + return false; + }; + pdf.tintRgba(out, tint_key.mode, tint_key.colors) catch { + gpa.free(baked); + slot.tried = false; + return false; + }; + slot.patch_rows = unionRows(slot.patch_rows, dirty); + state.next_raster_revision +%= 1; + if (state.next_raster_revision == 0) state.next_raster_revision = 1; + slot.revision = state.next_raster_revision; + } + gpa.free(slot.baked); + slot.baked = baked; + slot.decorated = page_highlights.len > 0; + return true; + } + + fn sameHighlights(a: []const Highlight, b: []const Highlight) bool { + return std.mem.eql(u8, std.mem.sliceAsBytes(a), std.mem.sliceAsBytes(b)); + } + + /// The highlights in one set and not the other, as multisets (a quad + /// painted twice blends twice). When only the order changed, blending + /// order did, so everything counts. + // ponytail: quadratic match; past 64k comparisons every quad counts. + fn changedHighlights(gpa: std.mem.Allocator, old: []const Highlight, new: []const Highlight) ![]Highlight { + const out = try gpa.alloc(Highlight, old.len + new.len); + errdefer gpa.free(out); + var n: usize = 0; + if (old.len * new.len <= 1 << 16) { + const matched = try gpa.alloc(bool, new.len); + defer gpa.free(matched); + @memset(matched, false); + for (old) |h| { + for (new, matched) |candidate, *used| { + if (!used.* and std.mem.eql(u8, std.mem.asBytes(&h), std.mem.asBytes(&candidate))) { + used.* = true; + break; + } + } else { + out[n] = h; + n += 1; + } + } + for (new, matched) |h, used| if (!used) { + out[n] = h; + n += 1; + }; + } + if (n == 0) { + @memcpy(out[0..old.len], old); + @memcpy(out[old.len..], new); + return out; + } + // Freed by length: hand back exactly what the caller will free. + return gpa.realloc(out, n); + } + + fn unionRows(a: pdf.Document.Rows, b: pdf.Document.Rows) pdf.Document.Rows { + if (a.start >= a.end) return b; + if (b.start >= b.end) return a; + return .{ .start = @min(a.start, b.start), .end = @max(a.end, b.end) }; + } + pub fn renderFrame( state: *State, gpa: std.mem.Allocator, @@ -5837,6 +6177,7 @@ pub const Pdf = struct { .hover_page = hover_page, .hover_color = if (link_hover) core.theme().box else selection_color, .selection_color = selection_color, + .live = core.native_image_patches, }; } @@ -5907,6 +6248,16 @@ pub const Pdf = struct { const visible_end = visible.first + visible.len; while (page < visible_end) : (page += 1) { const placed = placedRaster(state, view, page) orelse continue; + const slot = rasterForPage(state, page).?; + const patch: ?pardes.ImagePatch = if (slot.patch_from != 0 and + slot.patch_rows.start < slot.patch_rows.end) + .{ + .from = slot.patch_from, + .y = @intCast(slot.patch_rows.start - slot.band_y), + .h = @intCast(slot.patch_rows.end - slot.patch_rows.start), + } + else + null; if (!core.appendImagePlace(.{ .pane = @intCast(pane_id), .serial = pane.serial, @@ -5928,14 +6279,18 @@ pub const Pdf = struct { .x = text_x, // Below the notice chips, like an image: a placed page is // drawn after the cells and would paint a chip out. - .y = core.bodyTop(rect) + pane.notices.len, + .y = core.bodyTop(rect) + pane.notices.span(), .w = text_width, - .h = (rect.h -| pardes.BOX_H) -| pane.notices.len, + .h = (rect.h -| pardes.BOX_H) -| pane.notices.span(), .rgba = placed.rgba, .iw = placed.width, // The texture contains the retained band, not the full page. .ih = placed.band_height, + .patch = patch, })) break; + // A shell now holds (or will fetch whole) this revision. + slot.patch_from = slot.revision; + slot.patch_rows = .{ .start = 0, .end = 0 }; placed_any = true; } if (!placed_any) return false; @@ -6439,9 +6794,15 @@ pub const Terminal = struct { return pane; } - /// Rebuild a dump's dead terminal emulator. Registration and tag/cwd policy - /// stay with the core; raw VT replay and viewport restoration belong here. - pub fn restore(p: *Pardes, src: dump.Pane) !*Pane { + /// Where a restored terminal's history ends and its new shell begins. + pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; + + /// Rebuild a dump's terminal emulator from its recorded output. `live`: a + /// shell will be spawned into it, so the history is marked off from what + /// that shell prints and the pane waits for it like any new terminal. + /// Registration and tag/cwd policy stay with the core; raw VT replay and + /// viewport restoration belong here. + pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { const terminal = src.terminal.?; if (comptime !enabled) { const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); @@ -6450,12 +6811,28 @@ pub const Terminal = struct { pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; return pane; } - const bytes = if (terminal.stream_b64.len > 0) + // An older dump's raw output tail cannot come back live: cut off mid + // redraw, or written at sizes the pane no longer has, it replays as + // garbage. Its rendered text can. + const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; + const bytes = if (legacy_text) + try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") + else if (terminal.stream_b64.len > 0) try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) else &.{}; const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - if (bytes.len > 0) { + if (live) { + if (bytes.len > 0) { + ingest(pane, bytes); + ingest(pane, restored_banner); + } + followOutput(pane); + // A view left scrolled back stays on what it was showing: the + // banner's line breaks scrolled a full screen by that many more. + if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); + armShellSpawn(pane); + } else if (bytes.len > 0) { ingest(pane, bytes); followOutput(pane); if (src.scroll > 0) @@ -6613,7 +6990,7 @@ pub const Terminal = struct { .cols = pane.cols, .rows = pane.rows, .terminal = .{ .stream_b64 = encoded }, - }); + }, false); defer gpa.destroy(restored); defer deinitEmulator(restored, gpa); const before = try screenTextAlloc(pane, gpa); @@ -6624,6 +7001,58 @@ pub const Terminal = struct { try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); } + test "a restored terminal keeps its history above a marker and gets a shell where it was" { + if (comptime !enabled or 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"); + try p.dumpState(); + const restored = try Pardes.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.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 "an older dump comes back live from its rendered text, not its raw output tail" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + // A tail cut mid-redraw: relative moves from a cursor it never set. + const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); + defer gpa.free(tail); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = 40, + .rows = 12, + .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, + }, true); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + defer deinitPendingCommand(restored); + const text = try screenTextAlloc(restored, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); + } + /// Record and parse one live pty read, invalidate its motion surface, and /// follow it only when the body (possibly parked under a tag edit) is raw. pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { @@ -7247,6 +7676,16 @@ pub const Terminal = struct { overlay.text = new; } + /// The shell's screen and scrollback (the primary screen, even under a + /// full-screen program) as VT that replays to what was shown: styled + /// text, soft-wrapped lines rejoined so they reflow at another width. + fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { + const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; + var out: std.Io.Writer.Allocating = .init(arena); + try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); + return out.written(); + } + /// Serialize terminal-only state; the core supplies shared pane metadata. pub fn dumpPane( pane: *Pane, @@ -7318,7 +7757,8 @@ pub const Terminal = struct { .terminal = .{ .cwd = try arena.dupe(u8, pane.cwdSlice()), .stream = stream[0..len], - .stream_b64 = try dump.encodeBytes(arena, try replayBytes(pane, arena)), + .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), + .stream_is_screen = true, .cursor = .{ .col = pane.terminal.?.vt.screens.active.cursor.x, .row = pane.terminal.?.vt.screens.active.cursor.y, diff --git a/src/pardes.zig b/src/pardes.zig index cc57127f..fae14f47 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -2722,8 +2722,16 @@ test "Msg writes the transient row by hand, bare or with text, and input ends it try std.testing.expect(p.executeBuiltinLine(2, "Msg")); try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); - // A message is exactly as old as your last input. + // Input starts its exit: it lingers, dissolves, and is gone. p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); + for (0..200) |_| p.update(.tick); + try std.testing.expectEqualStrings("", row(p, 2)); + // ...and with neither linger nor animation it is as old as your last input. + try std.testing.expect(p.executeBuiltinLine(2, "MessageAnimation off")); + try std.testing.expect(p.executeBuiltinLine(2, "MessageLinger 0")); + try std.testing.expect(p.executeBuiltinLine(2, "Msg gone")); + p.update(.{ .key = .{ .cp = 'h' } }); try std.testing.expectEqualStrings("", row(p, 2)); // Longer than the row's buffer is CUT, never refused and never overrun: @@ -2735,6 +2743,151 @@ test "Msg writes the transient row by hand, bare or with text, and input ends it try std.testing.expectEqual(p.panes[2].?.msg.len, row(p, 2).len); } +test "a message falls in, lingers past the input that dismisses it, and dissolves" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[p.active].?; + try std.testing.expect(p.settings.message_animation); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageLinger 160")); + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + try std.testing.expect(p.animationActive()); + // An ease-in fall: starts a whole row up, lands exactly on it. + const start = p.messageMotion(pane.msg_life); + try std.testing.expectEqual(@as(f32, -1), start.slide); + var last = start.slide; + for (0..Pardes.messageFrames(p.settings.message_fall_ms)) |_| { + p.needs_frame = false; + p.update(.tick); + // Every tick that moves it owes a frame, the landing one included. + try std.testing.expect(p.needs_frame); + const now = p.messageMotion(pane.msg_life); + try std.testing.expect(now.slide >= last); + last = now.slide; + } + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expectEqual(@as(f32, 0), p.messageMotion(pane.msg_life).slide); + try std.testing.expect(!p.animationActive()); + // Shown until input, like always; the same line again does not re-enter. + for (0..100) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + // Input (a key that announces nothing): 160 ms of lingering (ten frames), unaffected by more input... + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + for (0..9) |_| { + p.update(.tick); + p.update(.{ .key = .{ .cp = 'h' } }); + } + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + p.update(.tick); + // ...then an ease-out dissolve toward nothing, and gone. + try std.testing.expectEqual(Pane.MessagePhase.leaving, pane.msg_life.phase); + var alpha: f32 = 1; + for (0..Pardes.messageFrames(p.settings.message_dissolve_ms)) |_| { + const now = p.messageMotion(pane.msg_life).alpha; + try std.testing.expect(now <= alpha); + alpha = now; + p.needs_frame = false; + p.update(.tick); + } + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); + try std.testing.expect(!p.animationActive()); + // The tick that clears it still owes the frame that shows it gone. + try std.testing.expect(p.needs_frame); + + // Dismissed mid-fall: it lands, then lingers. + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg again")); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + p.update(.tick); + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + for (0..Pardes.messageFrames(p.settings.message_fall_ms)) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + // Shown again while lingering: fresh, so it stays; a status update to a + // line on screen swaps its text in place instead of falling again. + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg again")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + p.setStatus(p.active, "progress 50%"); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expectEqualStrings("progress 50%", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + // The fall and the dissolve are timings of their own, in milliseconds. + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageFall 48")); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageDissolve 0")); + try std.testing.expectEqual(@as(u16, 3), Pardes.messageFrames(p.settings.message_fall_ms)); + try std.testing.expectEqual(@as(u16, 1), Pardes.messageFrames(p.settings.message_dissolve_ms)); + // The Config report reads back as configuration. + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageAnimation")); + try std.testing.expect(!p.settings.message_animation); + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg plain")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); +} + +test "messages stack, oldest on top, each on its own timing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[p.active].?; + try std.testing.expect(p.executeBuiltinLine(p.active, "Verbose off")); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageLinger 160")); + // `Verbose off` announced itself before it took effect. + pane.msg_len = 0; + pane.msg_life = .{}; + const fall = Pardes.messageFrames(p.settings.message_fall_ms); + p.setMessage(p.active, "first"); + for (0..fall) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + // A second message stacks under the first instead of replacing it. + p.setMessage(p.active, "second"); + try std.testing.expectEqual(@as(u8, 1), pane.msg_older_len); + try std.testing.expectEqualStrings("first", pane.msg_older[0].slice()); + try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + p.collectNotices(pane, p.rects[p.active], p.active); + try std.testing.expectEqual(Pane.Notices.Kind.older, pane.notices.kinds[0]); + try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[1]); + // One key dismisses both, but each runs its own clock: the first starts + // lingering now, the second only once it has landed. + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_older[0].life.phase); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + const linger = Pardes.messageFrames(p.settings.message_linger_ms); + const dissolve = Pardes.messageFrames(p.settings.message_dissolve_ms); + for (0..linger + dissolve) |_| p.update(.tick); + // The first is gone; the second, a fall later, is still dissolving. + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(Pane.MessagePhase.leaving, pane.msg_life.phase); + for (0..fall) |_| p.update(.tick); + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); + try std.testing.expect(!p.animationActive()); + // A status ticking in place does not pile up. + p.setStatus(p.active, "lsp 10%"); + p.setStatus(p.active, "lsp 20%"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + // Lines keep their rows: when the top one leaves, the one under it does + // not move up, and the next message fills the gap instead. + p.setMessage(p.active, "top"); + p.setMessage(p.active, "under"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older[0].slot); + try std.testing.expectEqual(@as(u8, 1), pane.msg_slot); + pane.removeOlderMessage(0); + p.collectNotices(pane, p.rects[p.active], p.active); + try std.testing.expectEqual(@as(u8, 1), pane.notices.row[0]); + try std.testing.expectEqual(@as(u8, 2), pane.notices.span()); + p.setMessage(p.active, "fills"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_slot); + try std.testing.expectEqual(@as(u8, 1), pane.msg_older[0].slot); + // The stack keeps the newest few. + for ([_][]const u8{ "a", "b", "c", "d", "e" }) |text| p.setMessage(p.active, text); + try std.testing.expectEqual(@as(u8, Pane.message_stack), pane.msg_older_len); + try std.testing.expectEqualStrings("b", pane.msg_older[0].slice()); + try std.testing.expectEqualStrings("e", pane.msg[0..pane.msg_len]); +} + test "Font keeps requested and acknowledged faces as separate plain state" { if (comptime !font_picker) return; // there is no Font builtin on tty or web const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); @@ -3774,6 +3927,8 @@ pub const NativePlacement = if (pdf_enabled) struct { paper_bg: ?[3]u8 = null, } else struct {}; +pub const ImagePatch = struct { from: u32, y: u32, h: u32 }; + pub const ImagePlace = struct { pane: u8, /// Pane slots are reused. This identity makes a cached GPU texture or @@ -3787,6 +3942,10 @@ pub const ImagePlace = struct { rgba: []const u8, iw: usize, ih: usize, + /// Rows [y, y+h) of `rgba` are the only ones that differ from the + /// same pane page at revision `from`: a shell still holding that one may + /// update just these rows instead of taking the whole image again. + patch: ?ImagePatch = null, pub fn cacheKey(place: ImagePlace) ImageCacheKey { if (comptime pdf_enabled) @@ -6194,6 +6353,10 @@ pub const Pardes = struct { chrome_animation: ChromeAnimation = ChromeAnimation.init(initial_chrome), animate_theme_changes: bool = false, native_images: bool = false, + /// The shell can take a changed image a few rows at a time (a texture row + /// upload, a shared-memory hand-off), so a PDF selection is repainted as + /// it is dragged instead of once on release. + native_image_patches: bool = false, quit: bool = false, haptic: HapticSlot = if (platform == .macos) .none else {}, drag: Drag = .none, @@ -6250,6 +6413,9 @@ pub const Pardes = struct { /// Is there a frame worth drawing? Cleared once one is presented, set by /// anything that can change what is on screen. The first frame always is. needs_frame: bool = true, + /// Set by a shell whose present was skipped (no swapchain image): the + /// frame is still owed, and the next pump draws it again. + present_skipped: bool = false, /// Builtins announce themselves on the message row. Off while startup /// configuration is applied: those lines are nobody clicking, and should /// not leave the row holding the name of the last one. @@ -7040,16 +7206,18 @@ pub const Pardes = struct { } }; + /// A status updates the message line in place (a progress count does not + /// pile up); a message is an event, and stacks. pub fn setStatus(p: *Pardes, id: usize, text: []const u8) void { - p.showMessage(id, text); + p.showMessage(id, text, false); } pub fn setMessage(p: *Pardes, id: usize, text: []const u8) void { p.logMessage(id, text); - p.showMessage(id, text); + p.showMessage(id, text, true); } - fn showMessage(p: *Pardes, id: usize, text: []const u8) void { + fn showMessage(p: *Pardes, id: usize, text: []const u8, stack: bool) void { if (id >= MAX_PANES) return; const pane = p.panes[id] orelse return; // One row of printable text: a language server's multi-line report @@ -7058,8 +7226,158 @@ pub const Pardes = struct { if (n < text.len) { while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1; } + const same = pane.msg_len == n and for (text[0..n], pane.msg[0..n]) |c, have| { + if ((if (c < 0x20 or c == 0x7f) ' ' else c) != have) break false; + } else true; + // A new event moves the line on screen up the stack, where it keeps + // its own timing, and falls in below it. + // Only an event stacks on an event: an announcement or a status + // stands in for whatever comes next. + if (stack and pane.msg_len > 0 and !same and !pane.msg_announcement and !pane.msg_status) + pane.pushOlderMessage(); + if (pane.msg_len == 0) pane.msg_slot = pane.freeMessageSlot(); + pane.msg_announcement = false; + pane.msg_status = !stack; + const arrives = pane.msg_len == 0 or pane.msg_life.phase == .leaving; for (text[0..n], pane.msg[0..n]) |c, *cell| cell.* = if (c < 0x20 or c == 0x7f) ' ' else c; pane.msg_len = @intCast(n); + p.needs_frame = true; + if (arrives) { + pane.msg_life = .{ .phase = if (p.settings.message_animation and n > 0) .entering else .shown }; + } else if (pane.msg_life.phase == .lingering or + (pane.msg_life.phase == .entering and !p.settings.message_animation)) + { + // The same line again, or a status update: fresh, so it stays. + pane.msg_life = .{}; + } else { + pane.msg_life.dismissed = false; + } + } + + /// The key or click that used to clear the message row now starts each + /// line's exit: it stays `message_linger_ms`, then dissolves. A line + /// already on its way out keeps its own timing. + fn dismissMessage(p: *Pardes, pane: *Pane) void { + if (pane.msg_len > 0 and p.dismissLine(&pane.msg_life)) { + pane.msg_len = 0; + pane.msg_life = .{}; + } + var i: usize = 0; + while (i < pane.msg_older_len) { + if (p.dismissLine(&pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1; + } + } + + /// Start one line's exit; true when it is gone at once (no linger, no + /// animation). + fn dismissLine(p: *const Pardes, life: *Pane.MessageLife) bool { + switch (life.phase) { + .lingering, .leaving => return false, + // A falling line lands first, then lingers -- unless falling was + // just turned off, and nothing will land it. + .entering => if (p.settings.message_animation) { + life.dismissed = true; + return false; + }, + .shown => {}, + } + life.frame = 0; + if (p.settings.message_linger_ms > 0) { + life.phase = .lingering; + } else if (p.settings.message_animation) { + life.phase = .leaving; + } else return true; + return false; + } + + /// One animation frame of every message line. Each one that moves owes + /// a frame, the one that finishes included: a tick asks for none itself. + fn advanceMessages(p: *Pardes) void { + for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.msg_len > 0 and pane.msg_life.phase != .shown) { + p.needs_frame = true; + if (p.advanceLine(&pane.msg_life)) { + pane.msg_len = 0; + pane.msg_life = .{}; + } + } + var i: usize = 0; + while (i < pane.msg_older_len) { + if (pane.msg_older[i].life.phase != .shown) p.needs_frame = true; + if (p.advanceLine(&pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1; + } + } + } + + /// One frame of one line's life; true once it has left. + fn advanceLine(p: *const Pardes, life: *Pane.MessageLife) bool { + if (life.phase == .shown) return false; + life.frame +|= 1; + switch (life.phase) { + .shown => {}, + .entering => if (life.frame >= messageFrames(p.settings.message_fall_ms)) { + life.* = .{ .phase = if (life.dismissed) .lingering else .shown }; + }, + .lingering => if (life.frame >= messageFrames(p.settings.message_linger_ms)) { + if (!p.settings.message_animation) return true; + life.* = .{ .phase = .leaving }; + }, + .leaving => if (life.frame >= messageFrames(p.settings.message_dissolve_ms)) return true, + } + return false; + } + + /// Is any message line moving (and so owed ticks)? + fn messagesAnimating(pane: *const Pane) bool { + if (pane.msg_len > 0 and pane.msg_life.phase != .shown) return true; + for (pane.msg_older[0..pane.msg_older_len]) |line| if (line.life.phase != .shown) return true; + return false; + } + + /// How present a message is (1 = fully) and how far above its row it + /// still is (rows), eased: an ease-in fall, an ease-out dissolve. + const MessageMotion = struct { alpha: f32 = 1, slide: f32 = 0 }; + + /// Animation frames a message timing lasts; at least one. + pub fn messageFrames(ms: u16) u16 { + return @intCast(@max(1, (@as(u32, ms) + layout.Animation.frame_ms - 1) / layout.Animation.frame_ms)); + } + + fn messageMotion(p: *const Pardes, life: Pane.MessageLife) MessageMotion { + const fall_frames = messageFrames(p.settings.message_fall_ms); + const dissolve_frames = messageFrames(p.settings.message_dissolve_ms); + return switch (life.phase) { + .shown, .lingering => .{ .alpha = 1, .slide = 0 }, + .entering => blk: { + const t = @as(f32, @floatFromInt(@min(life.frame, fall_frames))) / @as(f32, @floatFromInt(fall_frames)); + const eased = t * t; + break :blk .{ .alpha = eased, .slide = eased - 1 }; + }, + .leaving => blk: { + const t = @as(f32, @floatFromInt(@min(life.frame, dissolve_frames))) / @as(f32, @floatFromInt(dissolve_frames)); + break :blk .{ .alpha = (1 - t) * (1 - t), .slide = 0 }; + }, + }; + } + + /// The life of the message line notice `i` shows, if it shows one. + fn noticeLife(pane: *const Pane, i: usize) ?Pane.MessageLife { + return switch (pane.notices.kinds[i]) { + .message => pane.msg_life, + .older => pane.msg_older[pane.notices.index[i]].life, + .leader, .prompt => null, + }; + } + + fn blendRgb(from: [3]u8, to: [3]u8, amount: f32) [3]u8 { + var out: [3]u8 = undefined; + for (&out, from, to) |*o, a, b| { + const af: f32 = @floatFromInt(a); + const bf: f32 = @floatFromInt(b); + o.* = @intFromFloat(@round(bf + (af - bf) * std.math.clamp(amount, 0, 1))); + } + return out; } fn logMessage(p: *Pardes, id: usize, text: []const u8) void { @@ -7358,8 +7676,11 @@ pub const Pardes = struct { _ = p.frame_arena.reset(.retain_capacity); const surface = try p.render(p.frame_arena.allocator()); if (v.present) |f| f(h.ctx, surface); + // Settled before post_present: a shell ticks there, and what that + // tick moves owes the next frame. + p.needs_frame = p.present_skipped; + p.present_skipped = false; if (v.post_present) |f| f(h.ctx); - p.needs_frame = false; } /// One request of the control filesystem, from whichever thread has the @@ -7389,6 +7710,10 @@ pub const Pardes = struct { // the screen. p.needs_frame = p.needs_frame or ev != .tick; p.shell_rows.sweep(p.gpa); + // An announcement stands in only until its own step says more. + for (p.panes) |slot| if (slot) |pane| { + pane.msg_announcement = false; + }; switch (ev) { .tick => {}, .mouse => |m| if (!(m.button == .none and m.kind == .motion)) { @@ -7415,10 +7740,11 @@ pub const Pardes = struct { switch (ev) { .key, .mouse => { for (p.panes) |slot| { - if (slot) |pane| pane.msg_len = 0; + if (slot) |pane| p.dismissMessage(pane); } p.clip_pending = null; }, + .tick => p.advanceMessages(), else => {}, } if (p.fs.listeners != 0) p.fs.origin = switch (ev) { @@ -11462,7 +11788,7 @@ pub const Pardes = struct { // A notice chip is chrome: it sits OVER the body's top rows, so a // click inside one belongs to nobody. The rest of those rows is // ordinary body text and still answers normally. - if (!on_tag and row >= body_y and row - body_y < p.panes[id].?.notices.len and + if (!on_tag and row >= body_y and row - body_y < p.panes[id].?.notices.span() and p.panes[id].?.notices.covers(row - body_y, col)) return null; if (!on_tag) if (body_hit) |supplied| { const mapped_hit = p.bodyHitForPane(id, supplied, false) orelse return null; @@ -12252,6 +12578,21 @@ pub const Pardes = struct { } } else { const clk = pane.sel[b]; + // A right-click on a line NUMBER looks at that line of + // this file -- a sticky context header's number included, + // since the row map holds each header's own source line. + if (s.button == config.look_button and clk.r0 >= BOX_H and clk.r0 == clk.r1 and + clk.c0 == clk.c1 and clk.c0 >= 0 and pane.mode != .tty) + if (pane.file) |f| if (f.output == null and clk.c0 < panes.File.gutterWidth(pane)) { + const line = pane.wrapAt(clk.r0 - BOX_H).line; + if (line >= 0) { + pane.sel[b].state = .none; + var buf: [48]u8 = undefined; + const target = std.fmt.bufPrint(&buf, "@p{d}:{d}", .{ s.id, @as(usize, @intCast(line)) + 1 }) catch return; + p.runBuiltin(config.look_cmd, s.id, "", target); + return; + } + }; var operand = p.pointerOperand(pane, clk); if (operand.expanded) |expanded| pane.sel[b] = expanded @@ -12876,8 +13217,10 @@ pub const Pardes = struct { // A builtin says its own name before it runs, so a tagline click is // legible even when what it did is invisible. Whatever the builtin // then says for itself replaces the announcement. - if (p.announce and p.settings.verbose and builtins.registry.announces(b)) + if (p.announce and p.settings.verbose and builtins.registry.announces(b)) { p.setMessage(id, @tagName(b)); + pane.msg_announcement = true; + } const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg }; builtins.registry.dispatch(b, c); } @@ -13121,10 +13464,16 @@ pub const Pardes = struct { const pane: *Pane = switch (src.kind) { .terminal => terminal: { const t = src.terminal.?; - const restored = try panes.Terminal.restore(p, src); + // A host that runs shells gets them back: the old history + // above a new shell in the directory it was in. The web + // shell and an isolated build only ever replay it. + const live = comptime (terminal_panes and platform != .web and !isolated); + const revive = live and t.cwd.len <= effect_path_cap; + const restored = try panes.Terminal.restore(p, src, revive); p.installPane(i, restored); try restored.setOwnedCwd(t.cwd); if (std.mem.startsWith(u8, src.tag, "TTY ")) restored.mode = .tty; + if (revive) p.emit(.{ .spawn = .{ .pane = @intCast(i), .cwd = .from(t.cwd) } }); break :terminal restored; }, .file => try panes.File.restore(p, i, src), @@ -13487,6 +13836,9 @@ pub const Pardes = struct { /// core work belongs in this one predicate so TTY and GUI mature it alike. pub fn animationActive(p: *const Pardes) bool { if (p.chrome_animation.isActive() or p.look_hover_wait != null) return true; + for (p.panes) |slot| if (slot) |pane| { + if (messagesAnimating(pane)) return true; + }; const scene = p.settings.scene_effects; if (scene.crt or scene.ripple or scene.glitch) return true; return p.presentation.animating(); @@ -13653,7 +14005,7 @@ pub const Pardes = struct { const first = p.bodyTop(r); var leader_buf: [16]u8 = undefined; for (pane.notices.slice(), 0..) |kind, i| { - const row = first + @as(u16, @intCast(i)); + const row = first + @as(u16, pane.notices.row[i]); // Every notice is painted on the canonical grid as well as // emitted as a tag layer: the grid is what a terminal client // draws, and a band it cannot see is a message it never gets. @@ -13661,6 +14013,7 @@ pub const Pardes = struct { // drawn twice there. const text = switch (kind) { .message => pane.msg[0..pane.msg_len], + .older => pane.msg_older[pane.notices.index[i]].slice(), .leader => p.leaderText(&leader_buf), .prompt => blk: { const at = pane.promptAt() orelse continue; @@ -13671,13 +14024,24 @@ pub const Pardes = struct { if (chip == 0) continue; const cx = tx + tw - chip; pane.notices.left[i] = cx; - s.fill(cx, row, chip, 1, .{ .bg = msg_style.bg, .font_role = .tagline }); + // A message coming or going blends toward the page it sits + // on; a grid cannot move it by less than a row. + var style = msg_style; + if (noticeLife(pane, i)) |life| { + // No page colour to fade to (a terminal's own default): + // the text dissolves into its chip instead. + const alpha = p.messageMotion(life).alpha; + const page = th.bg orelse chrome.tag_bg; + style.fg = .{ .rgb = blendRgb(chrome.tag_fg, page, alpha) }; + style.bg = .{ .rgb = blendRgb(chrome.tag_bg, page, alpha) }; + } + s.fill(cx, row, chip, 1, .{ .bg = style.bg, .font_role = .tagline }); // One column short of the chip's right edge: a prompt's caret // sits AFTER its last character the moment it opens, and flush // right would put it past the pane, off the grid, and past what // the detached wire will encode -- which drops every frame for // as long as the prompt is up. - const printed = printRight(s, cx, row, chip -| 1, text, msg_style); + const printed = printRight(s, cx, row, chip -| 1, text, style); if (kind != .prompt or id != p.active) continue; const at = pane.promptAt() orelse continue; const prompt0 = (p.tagPrefix(pane) catch continue).len + at; @@ -14166,6 +14530,7 @@ pub const Pardes = struct { for (pane.notices.slice(), 0..) |kind, i| { const text = switch (kind) { .message => pane.msg[0..pane.msg_len], + .older => pane.msg_older[pane.notices.index[i]].slice(), .leader => p.leaderText(&leader_buf), // A prompt is an editing line with a cursor in it, so it // stays on the grid where the cursor can sit on a cell. @@ -14190,12 +14555,19 @@ pub const Pardes = struct { const line = try arena.alloc(u8, pad + kept.len); @memset(line[0..pad], ' '); @memcpy(line[pad..], kept); - try p.renderHeaderLayer(arena, NOTICE_LAYER_BASE + id * Pane.Notices.max + i, .notice, @intCast(id), .{ + // A pixel shell slides the message in whole and only fades + // it on the way out. + const motion: MessageMotion = if (noticeLife(pane, i)) |life| p.messageMotion(life) else .{}; + const fade = if (motion.slide == 0) motion.alpha else 1; + const page = p.theme().bg orelse chrome.tag_bg; + const layer_index = NOTICE_LAYER_BASE + id * Pane.Notices.max + i; + try p.renderHeaderLayer(arena, layer_index, .notice, @intCast(id), .{ .x = cx, - .y = first + @as(u16, @intCast(i)), + .y = first + @as(u16, pane.notices.row[i]), .w = chip, .h = BOX_H, - }, line, chrome.tag_bg, chrome.tag_fg); + }, line, blendRgb(chrome.tag_bg, page, fade), blendRgb(chrome.tag_fg, page, fade)); + p.surface.tag_layers[layer_index].slide = motion.slide; } } if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { @@ -14221,6 +14593,7 @@ pub const Pardes = struct { layer.cols = columns; layer.bg = bg; layer.cursor = null; + layer.slide = 0; var surface: Surface = .{ .cols = columns, .rows = 1, .cells = layer.cells }; // A notice band carries a PANE id, not a column index, so it must not // answer to the column being edited -- that would scroll and select @@ -14270,7 +14643,10 @@ pub const Pardes = struct { fn collectNotices(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { pane.notices.len = 0; if (r.w <= config.GUTTER or r.h <= BOX_H) return; - if (pane.msg_len > 0) pane.notices.push(.message); + // Oldest message line on top, so lines already up do not move when a + // new one lands under them; when rows run out the oldest go first. + for (pane.msg_older[0..pane.msg_older_len], 0..) |line, i| pane.notices.pushAt(.older, @intCast(i), line.slot); + if (pane.msg_len > 0) pane.notices.pushAt(.message, 0, pane.msg_slot); if (id == p.active and p.leader_on) pane.notices.push(.leader); if (pane.promptAt()) |at| { if (pane.tagSlice()[@min(at, pane.tag_tail_len)..].len > 0) pane.notices.push(.prompt); @@ -14281,11 +14657,26 @@ pub const Pardes = struct { // into blind. A two-row pane spends its only body row on one notice, // which is what the single shared row used to do anyway. const room: u8 = @intCast(@min(@as(u16, Pane.Notices.max), r.h - BOX_H)); - if (pane.notices.len > room) { - const drop = pane.notices.len - room; - for (0..room) |i| pane.notices.kinds[i] = pane.notices.kinds[i + drop]; - pane.notices.len = room; + const n = &pane.notices; + if (n.span() <= room) return; + // Too short for the gaps: close them up in screen order, and if even + // that does not fit, the top bands go. + var i: usize = 1; + while (i < n.len) : (i += 1) { + var j = i; + while (j > 0 and n.row[j - 1] > n.row[j]) : (j -= 1) { + std.mem.swap(Pane.Notices.Kind, &n.kinds[j - 1], &n.kinds[j]); + std.mem.swap(u8, &n.index[j - 1], &n.index[j]); + std.mem.swap(u8, &n.row[j - 1], &n.row[j]); + } + } + const drop = n.len -| room; + for (0..n.len - drop) |k| { + n.kinds[k] = n.kinds[k + drop]; + n.index[k] = n.index[k + drop]; + n.row[k] = @intCast(k); } + n.len -= @intCast(drop); } fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize) !void { @@ -14390,7 +14781,7 @@ pub const Pardes = struct { // Below the notice chips: a picture is drawn after the cells (the // GUI's image pass, kitty's z-order), so a chip over it would be // painted out. Text gets the overlay; a picture gives up the rows. - const shown = pane.notices.len; + const shown = pane.notices.span(); const image_h = (r.h -| BOX_H) -| shown; panes.Image.draw(p, iv, @intCast(id), pane.serial, tx, body_y + shown, tw, image_h); // thumbless, but the same one column as the real scrollbar below — diff --git a/src/pdf.zig b/src/pdf.zig index 712750dc..de5e6d86 100644 --- a/src/pdf.zig +++ b/src/pdf.zig @@ -1017,6 +1017,73 @@ pub const Document = struct { ) != c.PARDES_PDF_OK) return error.RenderFailed; } + /// Only the highlight pass of `renderIntoAtWithPaper`, over `rgba`, which + /// holds `band` of this page as that render left it before highlighting + /// (opaque paper). Rendering with highlights equals rendering without and + /// then this, row for row: the render draws highlights over the finished + /// page, and so does this. + pub fn paintHighlightsAt( + document: *Document, + page: usize, + request: RenderRequest, + raster: Raster, + band: Raster.Band, + highlights: []const Highlight, + rgba: []u8, + ) !void { + if (rgba.len != band.len) return error.BadPixmap; + if (band.height == 0 or band.y + band.height > raster.height) + return error.BadPixmap; + const bounded = try boundedRequest(document, page, request); + if (highlights.len > c.PARDES_PDF_MAX_RESULT_QUADS) return error.RenderFailed; + if (c.pardes_pdf_paint_highlights( + document.handle, + @intCast(page), + bounded.dpi, + bounded.minimum_width, + bounded.minimum_height, + bounded.max_dimension, + if (highlights.len == 0) null else @ptrCast(highlights.ptr), + highlights.len, + rgba.ptr, + rgba.len, + @intCast(raster.width), + @intCast(raster.height), + @intCast(raster.stride), + @intCast(band.y), + @intCast(band.height), + ) != c.PARDES_PDF_OK) return error.RenderFailed; + } + + pub const Rows = struct { start: usize, end: usize }; + + /// The rows of `request`'s raster that painting `highlights` can touch, + /// by the transform the render itself uses (rotation included). Empty + /// when nothing would paint. + pub fn highlightRows( + document: *Document, + page: usize, + request: RenderRequest, + highlights: []const Highlight, + ) !Rows { + const bounded = try boundedRequest(document, page, request); + var row_start: c_int = 0; + var row_end: c_int = 0; + if (c.pardes_pdf_highlight_rows( + document.handle, + @intCast(page), + bounded.dpi, + bounded.minimum_width, + bounded.minimum_height, + bounded.max_dimension, + if (highlights.len == 0) null else @ptrCast(highlights.ptr), + highlights.len, + &row_start, + &row_end, + ) != c.PARDES_PDF_OK) return error.RenderFailed; + return .{ .start = @intCast(row_start), .end = @intCast(row_end) }; + } + const BoundedRequest = struct { dpi: c_int, minimum_width: c_int, diff --git a/src/pdf_bridge.c b/src/pdf_bridge.c index 976ed838..2c723dbb 100644 --- a/src/pdf_bridge.c +++ b/src/pdf_bridge.c @@ -572,6 +572,55 @@ pardes_pdf_measure_render( return PARDES_PDF_OK; } +/* The highlight pass of a render: fills over whatever the pixmap holds. */ +static void +pardes_pdf_fill_highlights(fz_context *ctx, pardes_pdf_document *document, + fz_device *device, const pardes_pdf_highlight *highlights, size_t highlight_count) +{ + fz_path *path = NULL; + size_t i; + + fz_var(path); + fz_try(ctx) + { + for (i = 0; i < highlight_count; ++i) { + fz_quad quad; + float color[3]; + float alpha; + + if (!pardes_pdf_valid_quad(highlights[i].quad)) + fz_throw(ctx, FZ_ERROR_ARGUMENT, + "PDF highlight contains a non-finite point"); + if (highlights[i].rgba[3] == 0) + continue; + + /* Kind is semantic metadata; caller-supplied RGBA is final. */ + (void)highlights[i].kind; + quad = pardes_pdf_quad_to_page(document, highlights[i].quad); + color[0] = highlights[i].rgba[0] / 255.0f; + color[1] = highlights[i].rgba[1] / 255.0f; + color[2] = highlights[i].rgba[2] / 255.0f; + alpha = highlights[i].rgba[3] / 255.0f; + + path = fz_new_path(ctx); + fz_moveto(ctx, path, quad.ul.x, quad.ul.y); + fz_lineto(ctx, path, quad.ur.x, quad.ur.y); + fz_lineto(ctx, path, quad.lr.x, quad.lr.y); + fz_lineto(ctx, path, quad.ll.x, quad.ll.y); + fz_closepath(ctx, path); + fz_fill_path(ctx, device, path, 0, fz_identity, + fz_device_rgb(ctx), color, alpha, + fz_default_color_params); + fz_drop_path(ctx, path); + path = NULL; + } + } + fz_always(ctx) + fz_drop_path(ctx, path); + fz_catch(ctx) + fz_rethrow(ctx); +} + int pardes_pdf_render_into( pardes_pdf_document *document, @@ -594,10 +643,8 @@ pardes_pdf_render_into( fz_context *ctx; fz_pixmap *pixmap = NULL; fz_device *device = NULL; - fz_path *path = NULL; fz_matrix ctm; fz_irect bbox; - size_t i; if (document == NULL || page_number < 0 || page_number >= document->page_count || dpi < 1 || @@ -614,7 +661,6 @@ pardes_pdf_render_into( ctx = document->ctx; fz_var(pixmap); fz_var(device); - fz_var(path); fz_try(ctx) { pardes_pdf_render_geometry(document, page_number, dpi, @@ -627,10 +673,12 @@ pardes_pdf_render_into( * The BAND: rows [band_y, band_y + band_height) of the page raster, * and nothing else. A pixmap's bbox IS the draw device's clip, so the * page runs under the same CTM it would for a full raster and MuPDF - * discards everything outside these rows. Every row inside them is - * therefore bit-identical to the same row of the full-page raster — - * "band rows equal full-page rows" in pdf.zig proves it, because the - * whole point of a band is that the reader cannot tell. + * discards everything outside these rows. The rows are NOT always + * bit-identical to the full page's: rows at the band's edges, and a + * resampled image anywhere in it, can differ (measured on + * docs/registry.pdf and docs/design.pdf). Good enough for a band that + * is only shown while flinging; never use a band to patch rows into a + * whole-page raster -- `pardes_pdf_paint_highlights` exists for that. */ bbox.y0 += band_y; bbox.y1 = bbox.y0 + band_height; @@ -674,43 +722,12 @@ pardes_pdf_render_into( if (highlight_count != 0) { device = fz_new_draw_device(ctx, ctm, pixmap); - for (i = 0; i < highlight_count; ++i) { - fz_quad quad; - float color[3]; - float alpha; - - if (!pardes_pdf_valid_quad(highlights[i].quad)) - fz_throw(ctx, FZ_ERROR_ARGUMENT, - "PDF highlight contains a non-finite point"); - if (highlights[i].rgba[3] == 0) - continue; - - /* Kind is semantic metadata; caller-supplied RGBA is final. */ - (void)highlights[i].kind; - quad = pardes_pdf_quad_to_page(document, highlights[i].quad); - color[0] = highlights[i].rgba[0] / 255.0f; - color[1] = highlights[i].rgba[1] / 255.0f; - color[2] = highlights[i].rgba[2] / 255.0f; - alpha = highlights[i].rgba[3] / 255.0f; - - path = fz_new_path(ctx); - fz_moveto(ctx, path, quad.ul.x, quad.ul.y); - fz_lineto(ctx, path, quad.ur.x, quad.ur.y); - fz_lineto(ctx, path, quad.lr.x, quad.lr.y); - fz_lineto(ctx, path, quad.ll.x, quad.ll.y); - fz_closepath(ctx, path); - fz_fill_path(ctx, device, path, 0, fz_identity, - fz_device_rgb(ctx), color, alpha, - fz_default_color_params); - fz_drop_path(ctx, path); - path = NULL; - } + pardes_pdf_fill_highlights(ctx, document, device, highlights, highlight_count); fz_close_device(ctx, device); } } fz_always(ctx) { - fz_drop_path(ctx, path); fz_drop_device(ctx, device); /* Drops only the wrapper: caller-owned samples remain untouched. */ fz_drop_pixmap(ctx, pixmap); @@ -742,6 +759,139 @@ pardes_pdf_render_into( return PARDES_PDF_OK; } +int +pardes_pdf_paint_highlights( + pardes_pdf_document *document, + int page_number, + int dpi, + int minimum_width, + int minimum_height, + int max_dimension, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + unsigned char *samples, + size_t samples_len, + int width, + int height, + int stride, + int band_y, + int band_height) +{ + fz_context *ctx; + fz_pixmap *pixmap = NULL; + fz_device *device = NULL; + fz_matrix ctm; + fz_irect bbox; + + if (document == NULL || page_number < 0 || + page_number >= document->page_count || dpi < 1 || + minimum_width < 0 || minimum_height < 0 || max_dimension < 1 || + (highlight_count != 0 && highlights == NULL) || + highlight_count > PARDES_PDF_MAX_RESULT_QUADS || samples == NULL || + width < 1 || height < 1 || width > INT_MAX / 4 || stride != width * 4 || + band_y < 0 || band_height < 1 || band_y > height - band_height || + (size_t)band_height > SIZE_MAX / (size_t)stride || + samples_len != (size_t)stride * (size_t)band_height) + return PARDES_PDF_ERROR; + if (highlight_count == 0) + return PARDES_PDF_OK; + + ctx = document->ctx; + fz_var(pixmap); + fz_var(device); + fz_try(ctx) + { + pardes_pdf_render_geometry(document, page_number, dpi, + minimum_width, minimum_height, max_dimension, &ctm, &bbox); + if (fz_irect_width(bbox) != width || fz_irect_height(bbox) != height) + fz_throw(ctx, FZ_ERROR_ARGUMENT, + "PDF raster layout changed between measure and paint"); + bbox.y0 += band_y; + bbox.y1 = bbox.y0 + band_height; + pixmap = fz_new_pixmap_with_bbox_and_data( + ctx, fz_device_rgb(ctx), bbox, NULL, 1, samples); + device = fz_new_draw_device(ctx, ctm, pixmap); + pardes_pdf_fill_highlights(ctx, document, device, highlights, highlight_count); + fz_close_device(ctx, device); + } + fz_always(ctx) + { + fz_drop_device(ctx, device); + fz_drop_pixmap(ctx, pixmap); + } + fz_catch(ctx) + { + fz_report_error(ctx); + return PARDES_PDF_ERROR; + } + return PARDES_PDF_OK; +} + +int +pardes_pdf_highlight_rows( + pardes_pdf_document *document, + int page_number, + int dpi, + int minimum_width, + int minimum_height, + int max_dimension, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + int *row_start, + int *row_end) +{ + fz_context *ctx; + fz_matrix ctm; + fz_irect bbox; + float y0 = 0, y1 = 0; + int any = 0; + size_t i; + + if (row_start == NULL || row_end == NULL) + return PARDES_PDF_ERROR; + *row_start = *row_end = 0; + if (document == NULL || page_number < 0 || + page_number >= document->page_count || dpi < 1 || + minimum_width < 0 || minimum_height < 0 || max_dimension < 1 || + (highlight_count != 0 && highlights == NULL)) + return PARDES_PDF_ERROR; + + ctx = document->ctx; + fz_try(ctx) + { + pardes_pdf_render_geometry(document, page_number, dpi, + minimum_width, minimum_height, max_dimension, &ctm, &bbox); + for (i = 0; i < highlight_count; ++i) { + fz_rect r; + if (highlights[i].rgba[3] == 0 || + !pardes_pdf_valid_quad(highlights[i].quad)) + continue; + r = fz_rect_from_quad(fz_transform_quad( + pardes_pdf_quad_to_page(document, highlights[i].quad), ctm)); + if (!any || r.y0 < y0) y0 = r.y0; + if (!any || r.y1 > y1) y1 = r.y1; + any = 1; + } + } + fz_catch(ctx) + { + fz_report_error(ctx); + return PARDES_PDF_ERROR; + } + if (any) { + /* + * Antialiasing covers the pixel a fractional edge falls in, and the + * rasterizer paints row floor(y1) even for a zero-height quad. + */ + int lo = (int)floorf(y0) - bbox.y0; + int hi = (int)floorf(y1) + 1 - bbox.y0; + int h = fz_irect_height(bbox); + *row_start = lo < 0 ? 0 : (lo > h ? h : lo); + *row_end = hi < *row_start ? *row_start : (hi > h ? h : hi); + } + return PARDES_PDF_OK; +} + int pardes_pdf_page_text( pardes_pdf_document *document, diff --git a/src/pdf_bridge.h b/src/pdf_bridge.h index cda426aa..e3514437 100644 --- a/src/pdf_bridge.h +++ b/src/pdf_bridge.h @@ -222,8 +222,9 @@ int pardes_pdf_measure_render( * MuPDF wraps but never owns or frees samples. Every successful pixel is * opaque unless transparent_paper is nonzero. That mode preserves content * coverage and returns straight-alpha RGBA over an unpainted page. - * The CTM does not depend on the band, so a band's rows are bit-identical to - * the same rows of the whole page: it is a clip, not a different rendering. + * The CTM does not depend on the band, so a band is a clip of the same + * rendering -- but not a bit-exact one: its edge rows and resampled images can + * differ from the whole page's (see pardes_pdf_render_into). */ int pardes_pdf_render_into( pardes_pdf_document *document, @@ -244,6 +245,47 @@ int pardes_pdf_render_into( int transparent_paper ); +/* + * The highlight pass of `pardes_pdf_render_into` alone, over caller-supplied + * rows of that page's opaque raster: render_into(h) == paint(render_into({}), h) + * row for row, because a render draws its highlights over the finished page. + */ +int pardes_pdf_paint_highlights( + pardes_pdf_document *document, + int page, + int dpi, + int minimum_width, + int minimum_height, + int max_dimension, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + unsigned char *samples, + size_t samples_len, + int width, + int height, + int stride, + int band_y, + int band_height +); + +/* + * The raster rows [*row_start, *row_end) that painting `highlights` can touch + * under the same request, in the coordinates `pardes_pdf_render_into` bands + * use. An empty set (or only transparent ones) yields start == end == 0. + */ +int pardes_pdf_highlight_rows( + pardes_pdf_document *document, + int page, + int dpi, + int minimum_width, + int minimum_height, + int max_dimension, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + int *row_start, + int *row_end +); + int pardes_pdf_page_text( pardes_pdf_document *document, int page, diff --git a/src/tag_layer.zig b/src/tag_layer.zig index 0fb2297d..f8cc6eca 100644 --- a/src/tag_layer.zig +++ b/src/tag_layer.zig @@ -26,6 +26,10 @@ pub const Layer = struct { bg: [3]u8 = .{ 0, 0, 0 }, cells: []pardes.Cell = &.{}, cursor: ?struct { col: u16, bar: bool = false } = null, + /// Vertical offset in rows (negative: above its viewport), for a band + /// that is moving into place. A pixel shell draws it offset and clipped + /// to the rows below the viewport's top; the grid has no such thing. + slide: f32 = 0, pub fn capacity(layer: *const Layer, metrics: pardes.RowMetrics) u16 { return @intCast(@min(std.math.maxInt(u16), @max(1, @as(u32, layer.viewport.w) * @max(1, metrics.body_w) / @max(1, metrics.tagline_w)))); diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 03ccd3e2..5976852f 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -21,6 +21,56 @@ extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); +/// The terminal answered the shared-memory probe (`kittyShmProbe`): it can +/// read a raster from a POSIX shm object, so a page costs a name on the wire +/// instead of its whole base64 body. Set by the input reader, which sees the +/// reply before vaxis' parser swallows every graphics APC alike. +var kitty_shm = std.atomic.Value(bool).init(false); +/// Only a reply that arrives while the probe is out counts. The id is one +/// vaxis' own image numbering (1, 2, ...) never reaches, because a terminal +/// answers every transmission `i=;OK` and one of those must not pass. +var kitty_shm_probing = std.atomic.Value(bool).init(false); +const kitty_shm_probe_id = 0x7fff_fff1; +var kitty_shm_serial: u32 = 0; + +fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { + return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); +} + +/// Write `bytes` to a fresh shm object; the terminal unlinks it after reading. +fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool { + const fd = libc.shm_open(name, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }), @as(c_uint, 0o600)); + if (fd < 0) return false; + defer _ = libc.close(fd); + if (libc.ftruncate(fd, @intCast(bytes.len)) != 0) { + _ = libc.shm_unlink(name); + return false; + } + var off: usize = 0; + while (off < bytes.len) { + const n = libc.write(fd, bytes[off..].ptr, bytes.len - off); + if (n <= 0) { + _ = libc.shm_unlink(name); + return false; + } + off += @intCast(n); + } + return true; +} + +/// Ask with a 1x1 RGB image in shm whether the terminal reads that medium. A +/// remote terminal cannot see our shm and answers an error (or nothing). +fn kittyShmProbe(w: *std.Io.Writer) void { + var buf: [64]u8 = undefined; + const name = kittyShmName(&buf, 0) catch return; + if (!kittyShmWrite(name, &.{ 0, 0, 0 })) return; + var b64: [64]u8 = undefined; + const enc = std.base64.standard.Encoder.encode(&b64, name); + kitty_shm_probing.store(true, .release); + w.print("\x1b_Gi={d},s=1,v=1,a=q,t=s,f=24;{s}\x1b\\", .{ kitty_shm_probe_id, enc }) catch return; + w.flush() catch {}; +} + pub const Command = struct { pub var value: union(enum) { nop, @@ -81,6 +131,13 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { const received = try tty.read(buf[carried..]); if (received == 0) return; const end = carried + received; + if (kitty_shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { + kitty_shm_probing.store(false, .release); + kitty_shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); + // Answered either way: a terminal that could not read it left it. + var name_buf: [64]u8 = undefined; + if (kittyShmName(&name_buf, 0)) |name| _ = libc.shm_unlink(name) else |_| {} + }; var parse_end = end; var lead = end; while (lead > 0 and buf[lead - 1] & 0xc0 == 0x80) lead -= 1; @@ -717,6 +774,7 @@ fn localSession( try startInput(loop, input_cache); defer if (attached.* == null) stopInput(loop); (try std.Thread.spawn(.{}, winchWatch, .{ loop, vx, tty })).detach(); + (try std.Thread.spawn(.{}, tickWatch, .{ io, loop })).detach(); if (fs) |f| try f.watch(loop, wakeFs); try vx.queryTerminalSend(tty.writer()); @@ -726,11 +784,20 @@ fn localSession( }; if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; + // A terminal unlinks what it reads; whatever it never read (the probe + // unanswered, a transmission lost with the terminal) is ours to remove. + defer { + var name_buf: [64]u8 = undefined; + var n: u32 = 0; + while (n <= kitty_shm_serial) : (n += 1) { + if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} + } + } frames: while (!core.quit) { pardes.turn.restoreSettled(); try core.pump(host); if (core.takeRestore()) |rp| blk: { - const bytes = filesystem.readRestore(gpa, rp) catch |err| { + const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); break :blk; }; @@ -872,29 +939,39 @@ const Shell = struct { fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { const s = of(ctx); var batch: usize = 0; - // The wait is the 9P connections' turn with the core. - if (timeout_ms == 0) { - pardes.turn.rest(); - const first = s.loop.nextEvent() catch { - pardes.turn.wake(); - s.core.quit = true; - return s.reloadWatched(); - }; - pardes.turn.wake(); - batch = 1; - if (s.apply(first)) return s.reloadWatched(); - } else { - pardes.turn.rest(); - std.Io.sleep(s.io, .fromMilliseconds(timeout_ms), .awake) catch {}; + // The wait is the 9P connections' turn with the core. Animating, the + // frame's tick arrives through the same queue (`tickWatch`). + if (timeout_ms != 0) tick_request.set(s.io); + pardes.turn.rest(); + const first = s.loop.nextEvent() catch { pardes.turn.wake(); - _ = s.apply(.tick); - batch = 1; - } - while (s.in_paste or batch < 64) { - const ev = (s.loop.tryEvent() catch null) orelse break; + s.core.quit = true; + return s.reloadWatched(); + }; + pardes.turn.wake(); + batch = 1; + // A run of queued motions is one move to its last cell: each would + // otherwise redo hover and selection work the next one undoes. + var motion: ?@TypeOf(Command.value) = null; + var ev = first; + while (true) { + if (ev == .mouse and (ev.mouse.type == .motion or ev.mouse.type == .drag)) { + if (motion) |m| if (m.mouse.button != ev.mouse.button or m.mouse.type != ev.mouse.type or + @as(u3, @bitCast(m.mouse.mods)) != @as(u3, @bitCast(ev.mouse.mods))) + { + _ = s.apply(m); + }; + motion = ev; + } else { + if (motion) |m| _ = s.apply(m); + motion = null; + if (s.apply(ev)) break; + } + if (!s.in_paste and batch >= 64) break; + ev = (s.loop.tryEvent() catch null) orelse break; batch += 1; - if (s.apply(ev)) break; } + if (motion) |m| _ = s.apply(m); s.reloadWatched(); } @@ -1001,6 +1078,7 @@ const Shell = struct { fn pollFrame(ctx: ?*anyopaque) void { const s = of(ctx); + s.core.native_image_patches = kitty_shm.load(.acquire); if (s.fs) |f| if (f.tick().pending) { _ = s.loop.tryPostEvent(.fs_ready) catch {}; }; @@ -1013,6 +1091,7 @@ const Shell = struct { s.caps_pending = false; s.vx.enableDetectedFeatures(s.tty.writer()) catch {}; s.core.native_images = s.vx.caps.kitty_graphics; + if (s.vx.caps.kitty_graphics) kittyShmProbe(s.tty.writer()); s.vx.queueRefresh(); } } @@ -1039,6 +1118,16 @@ const Shell = struct { if (!kittyImageRepresentable(place)) continue; } const key = place.cacheKey(); + if (!s.kitty.contains(key) and vx.caps.kitty_graphics and kitty_shm.load(.acquire)) shm: { + var buf: [64]u8 = undefined; + kitty_shm_serial +%= 1; + const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; + if (!kittyShmWrite(name, place.rgba)) break :shm; + if (vx.transmitLocalImagePath(s.gpa, s.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| + s.kitty.put(key, handle) catch vx.freeImage(s.tty.writer(), handle.id) + else + _ = libc.shm_unlink(name); + } if (!s.kitty.contains(key) and vx.caps.kitty_graphics) { const enc = std.base64.standard.Encoder; if (s.gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| { @@ -1160,7 +1249,7 @@ const Shell = struct { fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const s = of(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; + const path = pardes.dump.outPath(&pbuf, s.core.settings.dump_dir.get()) orelse return; filesystem.write(s.core, path, bytes) catch |err| return s.core.reportError(0, "dump", err); s.core.setLastDump(path); } @@ -1415,6 +1504,21 @@ fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { } } +/// Set by an animating frame's wait: post one `.tick` a frame from now. The +/// tick joins the input queue, so a key or a click that lands inside the +/// frame is handled at once instead of after a blind sleep. +var tick_request: std.Io.Event = .unset; + +fn tickWatch(io: std.Io, loop: *Loop) void { + while (true) { + tick_request.waitUncancelable(io); + tick_request.reset(); + var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, pardes.layout.Animation.frame_ms) * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + loop.postEvent(.tick) catch {}; + } +} + fn wakeFs(ctx: ?*anyopaque) void { const loop: *Loop = @ptrCast(@alignCast(ctx.?)); _ = loop.tryPostEvent(.fs_ready) catch {}; diff --git a/test/output.zig b/test/output.zig index ad33954f..7c80e105 100644 --- a/test/output.zig +++ b/test/output.zig @@ -1089,7 +1089,8 @@ test "identical result refresh keeps warm content caches without allocation" { try std.testing.expectEqual(revision + 1, file.revision); try std.testing.expectEqualStrings("short\n", file.content); try std.testing.expectEqualStrings("changed", file.output.?.arg()); - try std.testing.expectEqual(@as(usize, 0), file.line_starts.len); + // The warm index is carried through the edit, not dropped. + try std.testing.expectEqualSlices(usize, &.{ 0, 6 }, file.line_starts); try std.testing.expectEqual(@as(usize, 0), file.highlights.len); try std.testing.expect(file.syntax_dirty); try std.testing.expect(!result.vsel.active and !result.select); diff --git a/test/panes.zig b/test/panes.zig index 8e71e69d..2d3aed43 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -394,6 +394,42 @@ const BodyHitTests = struct { } }; +const LineNumberLookTests = struct { + test "right-click on a line number looks at that line, sticky context headers included" { + if (!syntax.enabled) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); + defer p.deinit(); + p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; + const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ " // body\n" ** 60 ++ " }\n};\n"); + try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); + pane.scrollBy(30); + var frame = std.heap.ArenaAllocator.init(p.gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const layer = &p.surface.body_layers[0]; + try std.testing.expect(layer.context_rows >= 2); + // A header row's number is its declaration's own source line, not the + // body line it sits over (`pub fn work(` is line 1); a body row's is + // its own. + try std.testing.expectEqual(@as(i32, 1), pane.wrapAt(1).line); + const rows = [_]u16{ 1, pane.context_rows + 3 }; + for (rows) |row| { + // Each Look recentres the view; come back under the headers. + pane.scrollBy(30 - pane.scroll()); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const expected = pane.wrapAt(row).line; + var press = BodyHitTests.mouse(&p.surface.body_layers[0], row, 1, .press); + press.button = .right; + var release = BodyHitTests.mouse(&p.surface.body_layers[0], row, 1, .release); + release.button = .right; + p.update(.{ .mouse = press }); + p.update(.{ .mouse = release }); + try std.testing.expectEqual(expected, pane.cur_row); + } + } +}; + const TreeContextTests = struct { const source = "const Box = struct {\n" ++ " pub fn work(\n" ++ @@ -4069,6 +4105,7 @@ test { _ = TagNameTintTests; _ = TreeContextTests; _ = BodyHitTests; + _ = LineNumberLookTests; _ = TtySelectionTests; _ = ClickCursorTests; _ = JumpSelectionTests; diff --git a/test/pdf_pointer_bench.zig b/test/pdf_pointer_bench.zig new file mode 100644 index 00000000..f1d61229 --- /dev/null +++ b/test/pdf_pointer_bench.zig @@ -0,0 +1,224 @@ +//! Pointer gestures over a native PDF pane: hovering words (the Look preview +//! highlight), and dragging a selection to its release. +//! +//! zig build pdf-pointer-bench -Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] +//! [--cell WxH] [--scroll NOTCHES] [--verify 1] [--live 1] +//! +//! Every frame is timed the way a shell pump spends it: the event through +//! `Pardes.update`, one `render()` into a reset arena, the effect drain. A +//! hover step is its motion frame plus every tick frame the preview animates +//! before settling, which is when the highlight lands. Stdout is CSV, +//! `label,scenario:kind,round,ns`, one row per frame and one per step +//! (`kind=step`), for an external statistics pass. +//! +//! `visual` hashes every presented raster in full, with its placement, on the +//! frame each step settles on. It is the no-regression proof: a change to how highlights +//! are painted may change what it costs, never one presented pixel. +const std = @import("std"); +const pardes = @import("pardes"); +const pdf = @import("mupdf"); + +pub const std_options: std.Options = .{ .log_level = .err }; + +const gpa = std.heap.smp_allocator; +const cols: u16 = 120; +const rows: u16 = 40; + +const Config = struct { + path: []const u8 = "docs/design.pdf", + label: []const u8 = "run", + reps: usize = 5, + /// Wheel notches before the gestures, off the sparse title page. + scroll: usize = 40, + /// 8x16 is the Kitty policy's cell; the SDL shell's is closer to 16x35. + cell_w: u16 = 8, + cell_h: u16 = 16, + /// Re-render every raster that claims to hold the current highlights and + /// compare it row by row: exactness without a baseline build. + verify: bool = false, + /// A shell that takes row patches: selections repaint while dragged. + live: bool = false, +}; + +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + var config: Config = .{}; + var i: usize = 1; + while (i + 1 < args.len) : (i += 2) { + const value = args[i + 1]; + if (std.mem.eql(u8, args[i], "--path")) config.path = value else if (std.mem.eql(u8, args[i], "--label")) config.label = value else if (std.mem.eql(u8, args[i], "--reps")) config.reps = try std.fmt.parseUnsigned(usize, value, 10) else if (std.mem.eql(u8, args[i], "--scroll")) config.scroll = try std.fmt.parseUnsigned(usize, value, 10) else if (std.mem.eql(u8, args[i], "--verify")) config.verify = std.mem.eql(u8, value, "1") else if (std.mem.eql(u8, args[i], "--live")) config.live = std.mem.eql(u8, value, "1") else if (std.mem.eql(u8, args[i], "--cell")) { + var it = std.mem.splitScalar(u8, value, 'x'); + config.cell_w = try std.fmt.parseUnsigned(u16, it.next() orelse "", 10); + config.cell_h = try std.fmt.parseUnsigned(u16, it.next() orelse "", 10); + } else return error.UnknownOption; + } + if (i != args.len) return error.MissingValue; + + var visual: ?u64 = null; + for (0..config.reps) |round| { + const got = try measure(config, round); + if (visual) |want| if (want != got) { + std.debug.print("pdf-pointer-bench: visual changed between rounds: {x} vs {x}\n", .{ want, got }); + return error.Unstable; + }; + visual = got; + } + std.debug.print("pdf-pointer-bench {s}: visual={x:0>16}\n", .{ config.label, visual.? }); +} + +const Run = struct { + core: *pardes.Pardes, + arena: std.heap.ArenaAllocator, + config: Config, + round: usize, + visual: u64 = 0x7061_7264_6573_5050, + step_ns: u64 = 0, + frames: usize = 0, + steps: usize = 0, + last: ?*const pardes.Surface = null, + + fn frame(run: *Run, scenario: []const u8, kind: []const u8, event: pardes.Event) !void { + const started = nowNs(); + run.core.update(event); + while (run.core.nextEffect()) |_| {} + _ = run.arena.reset(.retain_capacity); + const surface = try run.core.render(run.arena.allocator()); + while (run.core.nextEffect()) |_| {} + const elapsed = nowNs() - started; + run.step_ns += elapsed; + run.frames += 1; + print("{s},{s}:{s},{d},{d}\n", .{ run.config.label, scenario, kind, run.round, elapsed }); + run.last = surface; + if (run.config.verify) try verify(run.core, run.arena.allocator()); + } + + /// The step, then the tick frames its animation asks for (a hover's + /// preview arrives on one of them), as a pump with nothing else queued. + fn step(run: *Run, scenario: []const u8, kind: []const u8, event: pardes.Event) !void { + run.step_ns = 0; + try run.frame(scenario, kind, event); + var ticks: usize = 0; + while (run.core.animationActive() and ticks < 32) : (ticks += 1) + try run.frame(scenario, "tick", .tick); + print("{s},{s}:step,{d},{d}\n", .{ run.config.label, scenario, run.round, run.step_ns }); + // Only the settled frame is the invariant: how many frames a preview + // takes to arrive is a setting (look_preview_delay_frames). + run.observe(run.last.?); + run.steps += 1; + } + + fn observe(run: *Run, surface: *const pardes.Surface) void { + for (surface.images[0..surface.nimages]) |maybe| { + const place = maybe orelse continue; + run.visual = mix(run.visual, [_]u64{ place.pane, place.x, place.y, place.w, place.h, place.native.page, place.iw, place.ih }); + if (place.native.geometry) |g| run.visual = mix(run.visual, [_]u64{ g.src.x, g.src.y, g.src.w, g.src.h, g.dst.x, g.dst.y, g.dst.w, g.dst.h }); + run.visual = std.hash.Wyhash.hash(run.visual, place.rgba); + } + } +}; + +var verify_failures: usize = 0; + +fn verify(core: *pardes.Pardes, arena: std.mem.Allocator) !void { + const Pdf = pardes.panes.Pdf; + const pane = core.panes[0] orelse return; + const state = &(pane.pdf orelse return); + const highlights = try Pdf.buildHighlights(state, arena, Pdf.highlightInput(core, 0, pane)); + for (state.rasters[0..state.rasters_len]) |*r| { + if (!r.valid or r.rgba.len == 0 or r.tint_key == null) continue; + const want = highlights.forPage(r.page); + if (comptime !@hasField(@TypeOf(r.*), "baked")) return else if (!std.mem.eql(u8, std.mem.sliceAsBytes(want), std.mem.sliceAsBytes(r.baked))) continue; + const shape = try state.document.measureRenderAt(r.page, r.request); + // The oracle is the WHOLE page: a band's own edge rows can differ. + const whole = try arena.alloc(u8, shape.len); + try state.document.renderIntoAtWithPaper(r.page, r.request, shape, shape.wholePage(), want, whole, false); + try pdf.tintRgba(whole, r.tint_key.?.mode, r.tint_key.?.colors); + const fresh = whole[r.band_y * shape.stride ..][0 .. r.band_h * shape.stride]; + var first: ?usize = null; + var last: usize = 0; + var count: usize = 0; + for (0..r.band_h) |y| { + const row = fresh[y * shape.stride ..][0..shape.stride]; + if (std.mem.eql(u8, row, r.rgba[y * shape.stride ..][0..shape.stride])) continue; + if (first == null) first = y; + last = y; + count += 1; + } + if (first) |f| { + verify_failures += 1; + if (verify_failures <= 20) std.debug.print("verify: page {d} rows {d}..{d} ({d} differ), highlights {d}, band {d}+{d}\n", .{ r.page, f + r.band_y, last + r.band_y, count, want.len, r.band_y, r.band_h }); + } + } +} + +fn measure(config: Config, round: usize) !u64 { + const core = try pardes.Pardes.init(gpa, .{ .file = config.path, .cols = cols, .rows = rows }); + defer core.deinit(); + core.native_images = true; + if (comptime @hasField(pardes.Pardes, "native_image_patches")) core.native_image_patches = config.live; + var run: Run = .{ .core = core, .arena = .init(gpa), .config = config, .round = round }; + defer run.arena.deinit(); + const cell: pardes.CellPixels = .{ .w = config.cell_w, .h = config.cell_h }; + core.update(.{ .resize = .{ .cols = cols, .rows = rows, .cell_pixels = cell } }); + _ = try core.render(run.arena.allocator()); + const pane = core.panes[0] orelse return error.NoPane; + if (pane.pdf == null) return error.NotPdf; + const rect = core.rects[0]; + const mid_col = rect.x + rect.w / 2; + const mid_row = rect.y + rect.h / 2; + for (0..config.scroll) |_| { + core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mid_col, .row = mid_row } }); + _ = run.arena.reset(.retain_capacity); + _ = try core.render(run.arena.allocator()); + while (core.nextEffect()) |_| {} + } + + const top = rect.y + 4; + const bottom = rect.y + rect.h -| 3; + const left = rect.x + 4; + const right = rect.x + rect.w -| 4; + + // Hover: walk four rows of the body, a word-ish stride at a time. + var row: u16 = top; + while (row < bottom) : (row += (bottom - top) / 4) { + var col: u16 = left; + while (col < right) : (col += 3) + try run.step("hover", "motion", .{ .mouse = .{ .button = .none, .kind = .motion, .col = col, .row = row } }); + } + // Leave the page so the last preview is withdrawn like a real exit. + try run.step("hover", "leave", .pointer_leave); + + // Select: press, drag across three lines, release; five times down the page. + row = top; + while (row + 3 < bottom) : (row += (bottom - top) / 5) { + try run.step("select", "press", .{ .mouse = .{ .button = .left, .kind = .press, .col = left, .row = row } }); + var n: u16 = 1; + while (n <= 24) : (n += 1) { + const col = left + (right - left) * (n % 8) / 8; + try run.step("select", "drag", .{ .mouse = .{ .button = .left, .kind = .drag, .col = col, .row = row + n / 8 } }); + } + try run.step("select", "release", .{ .mouse = .{ .button = .left, .kind = .release, .col = right, .row = row + 3 } }); + } + return mix(run.visual, @as(u64, run.steps)); +} + +fn print(comptime format: []const u8, args: anytype) void { + var buf: [256]u8 = undefined; + const line = std.fmt.bufPrint(&buf, format, args) catch return; + _ = std.c.write(1, line.ptr, line.len); +} + +fn mix(seed: u64, value: anytype) u64 { + var copy = value; + return std.hash.Wyhash.hash(seed, std.mem.asBytes(©)); +} + +fn nowNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +comptime { + _ = pdf.Document; +} diff --git a/test/snapshot.zig b/test/snapshot.zig index 7cc5eb91..bdabb56e 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -569,7 +569,9 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const try mkdir(arena, config_home, false); const pardes_config = try std.fmt.allocPrint(arena, "{s}/pardes", .{config_home}); try mkdir(arena, pardes_config, false); - try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/init", .{pardes_config}, 0), "Shell bash\n"); + // Messages leave the moment they are dismissed, as goldens have always + // recorded: a linger or a dissolve is time, and time cannot be a golden. + try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/init", .{pardes_config}, 0), "Shell bash\nMessageAnimation off\nMessageLinger 0\n"); _ = setenv("TERM", "xterm-256color", 1); _ = setenv("LC_ALL", "C", 1); // a wall clock cannot live in a golden; everything that would print one diff --git a/test/snapshots/builtins.snap b/test/snapshots/builtins.snap index cd47209f..02547b91 100644 --- a/test/snapshots/builtins.snap +++ b/test/snapshots/builtins.snap @@ -19,6 +19,10 @@ wheel up 110 50 wheel up 110 50 wheel up 110 50 wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 wait 10000 Look enter, right-click wait 10000 Exec tab, middle-click wait 10000 Filter diff --git a/test/snapshots/dump.golden b/test/snapshots/dump.golden index 8f920136..e466dbf1 100644 --- a/test/snapshots/dump.golden +++ b/test/snapshots/dump.golden @@ -38,6 +38,7 @@ .cwd = "/tmp/pardes-snap/dump/cwd", .stream = "ls\nd.txt\n", .stream_b64 = + .stream_is_screen = true, .cursor = .{ .col = 2, .row = 2 }, }, .file = null, @@ -57,6 +58,7 @@ .cwd = "/tmp/pardes-snap/dump/cwd", .stream = "ls\nd.txt\n", .stream_b64 = + .stream_is_screen = true, .cursor = .{ .col = 2, .row = 2 }, }, .file = null, @@ -76,6 +78,7 @@ .cwd = "/tmp/pardes-snap/dump/cwd", .stream = "ls\nd.txt\n", .stream_b64 = + .stream_is_screen = true, .cursor = .{ .col = 2, .row = 2 }, }, .file = null, diff --git a/test/snapshots/load.golden b/test/snapshots/load.golden index 994ab83e..32024cec 100644 --- a/test/snapshots/load.golden +++ b/test/snapshots/load.golden @@ -2,10 +2,10 @@ |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/load/cwd Tty Save Mode Filter /tmp/pardes-snap/load/cwd Tty Save Mode Filter -| echo LOAD''MARK; seq 1 40; echo E''ND ls +| $ echo LOAD''MARK; seq 1 40; echo E''ND $ ls | LOADMARK d.txt -| 1 -| 2 +| 1 $ +| 2 ── restored history ── | 3 | 4 | 5 @@ -17,8 +17,10 @@ | 11 | 12 | /tmp/pardes-snap/load/cwd Tty Save Mode Filter -| ls +| $ ls | d.txt +| $ +| ── restored history ── == style loaded grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, |1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-49 d,#26362d, 50-51 #ffffff,#887455, 52-52 d,#1d2824, 53-84 #b2c3b8,#1d2824, 85-99 d,#1d2824, @@ -26,8 +28,8 @@ |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-73 #e5eee5,#0d1410,f 74-99 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, |8: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |9: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |10: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, @@ -41,8 +43,8 @@ |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-23 #e5eee5,#0d1410,f 24-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |23: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |24: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |25: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, diff --git a/test/snapshots/restore.golden b/test/snapshots/restore.golden index 11d92288..01b52984 100644 --- a/test/snapshots/restore.golden +++ b/test/snapshots/restore.golden @@ -6,9 +6,7 @@ | $ echo KEEP''ME | KEEPME | $ -== snap restored grid=100x31 cursor=4,6 +== snap restored grid=100x31 cursor=4,8 |0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill |2: /tmp/pardes-snap/restore/cwd Tty Save Mode Filter Collapse Del -|3: ls -|4: echo KEEP''ME -|6: +|7: ── restored history ── -- cgit v1.3 From 542dd489149e33915d19878a277e23b3a9c0b070 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 17:41:55 -0300 Subject: Record /log whether or not anyone reads it, with the editor's messages in it /log is now one ring (64 KiB, 4 KiB on the board) that records new, del, rename and save, and a msg line for everything the editor says. An open freezes it, so cat log shows what happened lately and ends; writing follow to that same open makes reads past it wait for newer records, and a follower the ring outran reads lost N first. The message log keeps the pane's serial, not its reusable slot. A test now fails when the tree serves a file /README never mentions; it caught pty/status, now documented along with typing through pty/data. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 3 +- docs/fs.md | 18 +++- src/fs-help.txt | 9 +- src/fs.zig | 10 +- src/memory.zig | 2 + src/ninep/events.zig | 190 ++++++++++++++++++++++++++++++++------ src/ninep/screen.zig | 8 +- src/ninep/tree.zig | 46 +++++++-- src/panes.zig | 2 +- src/pardes.zig | 19 ++-- test/fs.py | 24 +++-- test/panes.zig | 1 + 12 files changed, 266 insertions(+), 66 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 2e065819..2867ed18 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -46,7 +46,8 @@ $m/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, $m/status pid, version, panes $m/look write a line = a right click on it at the active pane $m/exec write a line = a middle click: an editor command word, or a shell line -$m/log one record per read: new|del|rename|save ; reads park +$m/log recent events, then EOF: new|del|rename|save , msg + (exec 3<>$m/log; echo follow >&3; cat <&3 waits for new ones) $m/screen the rendered screen as JSON, frozen per open $m/listeners this session's dial addresses $m/pane/new open it to make a pane, read names it; rmdir $m/pane/ closes it diff --git a/docs/fs.md b/docs/fs.md index 335ee4e6..a0dd86fa 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -76,7 +76,8 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. /status pid, version and pane count /look write a line: a right click on it at the active pane; read: the serials it touched /exec write a line: a middle click; read the same serials -/log one line per editor event: new|del|rename|save ; reads park +/log recent events, one a line: new|del|rename|save , msg ; + write follow to that open to wait for more /screen rendered screen JSON; frozen per open handle /listeners the session's dial addresses /pane/new open it to make a pane; the read answers that pane's serial @@ -173,8 +174,9 @@ pane. Truncating `tag` clears the part of the tag you may edit. Stats report real lengths for `index`, `status`, `look`, `exec`, `listeners`, `name`, `body`, `tag`, `sel`, `ctl`, the range files and the flag files, and -for `log`, `event` and `pty/data` the length of the record a read would -answer, which is zero when nothing is waiting. Modes are 0644/0666 (0444 for +for `event` and `pty/data` the length of the record a read would +answer, which is zero when nothing is waiting; for `log`, the text an open +would freeze now. Modes are 0644/0666 (0444 for read-only files, 0222 for write-only); mtime is the pane's last edit or the process start. The qid version of `body`, `data` and `xdata` is the pane's revision, so a stat sees an edit land without reading the text; every other @@ -182,8 +184,14 @@ file leaves it zero rather than promise a version it cannot keep. Directory entries carry no sizes, and neither does `/screen`, which has no length until an open renders its frame; stat the entry. -`/log` records `new`, `del`, `rename` and `save` while at least one client -holds it open; a read parks until a record arrives. `/screen` returns JSON with +`/log` is one ring (64 KiB) that records whether or not anyone reads it: +`new`, `del`, `rename` and `save `, and `msg ` +for every line the editor says, builtins announcing themselves included. +Control characters in a record become spaces, so a record is one line. An +open freezes the ring's text the way `/screen` freezes a frame: reads walk it +and end. Writing `follow` to that same open makes reads past it park for the +next record, one per read; a follower the ring outran reads `lost N` first. +Closing the open is the only way back, as with rio's `consctl`. `/screen` returns JSON with `cols`, `rows`, `cursor`, a `styles` table, and row-major `cells` of `[grapheme, style_index]`. Each open freezes one frame until close. A terminal `body` freezes its history on the first read of each open handle; diff --git a/src/fs-help.txt b/src/fs-help.txt index 7f55b3af..dca2c14e 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -5,7 +5,8 @@ index one line per pane: serial, kind (text|term|pdf|image), dirty flag, n status pid, version and pane count look write a line: a right click on it at the active pane; read: the serials it touched exec write a line: a middle click, an editor command word or a shell line; read the same -log one line per editor event (new/del/rename/save ); reads wait +log recent events, one a line: new/del/rename/save , and + msg for what the editor said; write follow to wait screen rendered screen as JSON, frozen from open to close listeners the session's dial addresses pane/new open it to make a pane; the read answers that pane's serial @@ -26,9 +27,10 @@ Below, $m is the mount point (PARDES_MOUNT in a Tty9p shell; 9ns and 9p work too echo '#0,#5' > $m/pane/$n/addr; printf NEW >> $m/pane/$n/data replace bytes 0..5 cp $m/pane/$n/addr $m/pane/$n/dot; cat $m/pane/$n/sel select the range, read it cat $m/pane/$n/dirty; echo 0 > $m/pane/$n/dirty is it modified? say it is not - cat $m/log block until a pane is made, renamed, saved or closed + exec 3<>$m/log; echo follow >&3; cat <&3 what happened lately, then wait for more cat $m/pane/$n/event hold it open to own that pane's clicks echo exec > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT + printf 'ls\r' > $m/pane/$n/pty/data type into a terminal; pty/status: cols rows busy Pitfalls, one each: Each open of pane/new makes another pane; two reads of one fid name the same one. @@ -39,6 +41,5 @@ Pitfalls, one each: Writing body appends; open it with truncation to replace; writes are whole UTF-8 sequences. Truncating tag clears the part you may edit; truncating dot or addr empties it. A terminal's body is a history snapshot frozen per open; pty/data is the live stream. - screen is frozen per open handle as well; reopen it for a fresh frame. - A failing command is reported in the editor, not as a write error; a bad line fails the write. + A failing command is reported in the editor and in log, not as a write error; a bad line fails the write. pane//ctl reads acme's window status line and takes one verb, get, which reloads from disk. diff --git a/src/fs.zig b/src/fs.zig index 84ab3b95..fef4ffe1 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -308,8 +308,10 @@ 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", "/n/self/log" }) |path| + 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)); @@ -1240,9 +1242,9 @@ pub const Namespace = struct { panes: [MAX_PANES]tree.pane.State = @splat(.{}), listeners: u16 = 0, origin: u8 = 'K', - /// The editor-wide event stream, recorded only while /log is held open. - log: tree.events.Queue = .{}, - log_readers: u16 = 0, + /// The editor-wide event ring: panes made, renamed, saved and closed, and + /// what the editor said. Recorded whether or not anyone reads /log. + log: tree.events.Queue = .{ .cap = limits.log_bytes }, /// What the last look or exec created or touched, answered by reading /// either of those files. results: [MAX_PANES]u32 = undefined, diff --git a/src/memory.zig b/src/memory.zig index b8a64a1a..7b6ee2c0 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -17,6 +17,8 @@ pub const limits = struct { pub const wrap_rows = if (board) 128 else 256; pub const undo_max = if (board) 16 else 256; pub const message_log = if (board) 16 else 128; + /// /log's ring, which records whether or not anyone reads it. + pub const log_bytes: usize = if (board) 4 * KiB else 64 * KiB; pub const max_tag_tail: usize = if (board) 512 else 4096; pub const host_path_cap: usize = if (board) 0 else 4095; /// -Dembed-sources: the editor serves its own sources under /src. diff --git a/src/ninep/events.zig b/src/ninep/events.zig index d94fb54d..472a114f 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -25,6 +25,10 @@ pub fn now() u32 { pub const Queue = struct { buf: std.ArrayList(u8) = .empty, head: usize = 0, + cap: usize = queue_cap, + /// Records pushed out of the front to make room: the sequence number of + /// the oldest one still held. + dropped: u64 = 0, pub fn deinit(q: *Queue, gpa: std.mem.Allocator) void { q.buf.deinit(gpa); @@ -33,9 +37,10 @@ pub const Queue = struct { pub fn push(q: *Queue, gpa: std.mem.Allocator, record: []const u8) void { if (record.len > std.math.maxInt(u32)) return; - while (q.buf.items.len - q.head + record.len + 4 > queue_cap) { + while (q.buf.items.len - q.head + record.len + 4 > q.cap) { if (q.peek() == null) return; q.pop(); + q.dropped += 1; } q.compact(); var head: [4]u8 = undefined; @@ -136,15 +141,114 @@ pub fn announce(p: *Pardes) void { } } -/// Records ` ` while a reader holds /log open. +/// Records ` `. pub fn noteLog(p: *Pardes, kind: LogKind, pane: *Pane) void { - if (p.fs.log_readers == 0) return; var buf: [4096 + 64]u8 = undefined; const name = pane_files.nameOf(pane); - const record = std.fmt.bufPrint(&buf, "{s} {d} {s}\n", .{ @tagName(kind), pane.serial, name[0..@min(name.len, 4096)] }) catch return; + pushLog(p, std.fmt.bufPrint(&buf, "{s} {d} {s}\n", .{ @tagName(kind), pane.serial, name[0..@min(name.len, 4096)] }) catch return); +} + +/// Records `msg ` for what the editor said, `-` for no pane. +pub fn noteMessage(p: *Pardes, serial: u32, text: []const u8) void { + var buf: [pardes.LoggedMessage.cap + 32]u8 = undefined; + pushLog(p, (if (serial == 0) + std.fmt.bufPrint(&buf, "msg - {s}\n", .{text}) + else + std.fmt.bufPrint(&buf, "msg {d} {s}\n", .{ serial, text })) catch return); +} + +/// The log is one ring that records whether or not anyone reads it. A record +/// is one line: a newline in a message or a name would read as two records. +fn pushLog(p: *Pardes, record: []u8) void { + for (record[0 .. record.len - 1]) |*c| if (c.* < ' ') { + c.* = ' '; + }; p.fs.log.push(p.gpa, record); } +/// An open freezes the ring's text, so `cat log` answers what happened lately +/// and ends; `next` is where a follower picks up after it. +pub fn openLog(p: *Pardes, req: Req) Reply { + for (&p.fs.snapshots, 0..) |*slot, i| { + if (slot.node != 0) continue; + var text: std.ArrayList(u8) = .empty; + var at = p.fs.log.head; + const items = p.fs.log.buf.items; + var n: u64 = 0; + while (at + 4 <= items.len) : (n += 1) { + const len = std.mem.readInt(u32, items[at..][0..4], .little); + text.appendSlice(p.gpa, items[at + 4 ..][0..len]) catch { + text.deinit(p.gpa); + return Reply.fail(req.tag, E.NOMEM); + }; + at += 4 + len; + } + const bytes = text.toOwnedSlice(p.gpa) catch return Reply.fail(req.tag, E.NOMEM); + slot.* = .{ .node = req.node, .bytes = bytes, .next = p.fs.log.dropped + n }; + return .{ .tag = req.tag, .handle = @intCast(i + 1) }; + } + return Reply.fail(req.tag, E.NFILE); +} + +/// Past the frozen text, a following open reads newer records one per read, +/// parked until one arrives; one that fell behind the ring hears `lost N`. +pub fn readLog(p: *Pardes, req: Req) Reply { + if (req.handle == 0 or req.handle > p.fs.snapshots.len) return Reply.fail(req.tag, E.INVAL); + const slot = &p.fs.snapshots[req.handle - 1]; + if (slot.node != req.node) return Reply.fail(req.tag, E.INVAL); + const frozen = slot.bytes orelse &.{}; + const out = p.fs.stage(p.gpa); + if (!slot.follow or req.off < frozen.len) { + const off = @min(req.off, frozen.len); + const len = @min(frozen.len - off, req.size); + out.appendSlice(p.gpa, frozen[off..][0..len]) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; + } + const q = &p.fs.log; + if (slot.next < q.dropped) { + out.print(p.gpa, "lost {d}\n", .{q.dropped - slot.next}) catch return Reply.fail(req.tag, E.NOMEM); + slot.next = q.dropped; + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; + } + // ponytail: walks the ring from its oldest record; it holds at most log_bytes. + var at = q.head; + var seq = q.dropped; + while (at + 4 <= q.buf.items.len) : (seq += 1) { + const len = std.mem.readInt(u32, q.buf.items[at..][0..4], .little); + if (seq == slot.next) { + if (req.size < len) return Reply.fail(req.tag, E.INVAL); + out.appendSlice(p.gpa, q.buf.items[at + 4 ..][0..len]) catch return Reply.fail(req.tag, E.NOMEM); + slot.next += 1; + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; + } + at += 4 + len; + } + return .{ .tag = req.tag, .status = .again }; +} + +/// `follow`, written to an open of the log, makes that open wait for newer +/// records instead of ending; closing it is the way back. +pub fn writeLog(p: *Pardes, req: Req) Reply { + if (req.handle == 0 or req.handle > p.fs.snapshots.len) return Reply.fail(req.tag, E.INVAL); + const slot = &p.fs.snapshots[req.handle - 1]; + if (slot.node != req.node) return Reply.fail(req.tag, E.INVAL); + if (!std.mem.eql(u8, std.mem.trim(u8, req.data, " \t\r\n"), "follow")) return Reply.fail(req.tag, E.INVAL); + slot.follow = true; + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +/// The length a stat reports: the text an open would freeze now. +pub fn logLen(q: *const Queue) u64 { + var n: u64 = 0; + var at = q.head; + while (at + 4 <= q.buf.items.len) { + const len = std.mem.readInt(u32, q.buf.items[at..][0..4], .little); + n += len; + at += 4 + len; + } + return n; +} + // ---- per-pane event records ---- pub const max_record_text = 256; @@ -517,49 +621,81 @@ test "writing an event record back performs the action it names" { try testing.expectEqual(@as(u8, 'F'), p.fs.origin); } -test "the log parks until a pane is created, renamed, saved or deleted" { +test "the log records whether or not anyone reads, and an open that follows waits" { const gpa = testing.allocator; const p = try withFile(gpa, "logged\n"); defer p.deinit(); const log = @intFromEnum(tree.TopFile.log); - _ = try th.newPane(p); - try testing.expect(p.fs.log.empty()); + var expected: [4200]u8 = undefined; - const opened = call(p, .{ .tag = 1, .op = .open, .node = log }); - try testing.expectEqual(Status.ok, opened.reply.status); - try testing.expectEqual(@as(u16, 1), p.fs.log_readers); - try testing.expectEqual(Status.again, rd(p, log, 0, 4096).reply.status); + // Nobody holds /log open, and the pane is recorded anyway. + const early = try th.newPane(p); + const early_line = try std.fmt.bufPrint(&expected, "new {d} {s}\n", .{ early, pane_files.nameOf(p.panes[p.paneBySerial(early).?].?) }); + const early_owned = try gpa.dupe(u8, early_line); + defer gpa.free(early_owned); + + // A plain open answers what happened so far, and ends: `cat log` never hangs. + const plain = call(p, .{ .tag = 1, .op = .open, .node = log }); + try testing.expectEqual(Status.ok, plain.reply.status); + const first = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = plain.reply.handle, .size = 8192 }); + try testing.expect(std.mem.endsWith(u8, first.bytes, early_owned)); + const past = call(p, .{ .tag = 3, .op = .read, .node = log, .handle = plain.reply.handle, .off = first.bytes.len, .size = 8192 }); + try testing.expectEqual(Status.ok, past.reply.status); + try testing.expectEqual(@as(usize, 0), past.bytes.len); + _ = call(p, .{ .tag = 4, .op = .release, .node = log, .handle = plain.reply.handle }); + + // `follow` on an open makes it wait past what it froze, one record a read. + const f = call(p, .{ .tag = 5, .op = .open, .node = log }); + const fh = f.reply.handle; + const frozen = call(p, .{ .tag = 6, .op = .read, .node = log, .handle = fh, .size = 8192 }).bytes.len; + try testing.expectEqual(Status.err, call(p, .{ .tag = 7, .op = .write, .node = log, .handle = fh, .data = "tail\n" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = log, .handle = fh, .data = "follow\n" }).reply.status); + const rdf = struct { + fn next(pp: *Pardes, node: u64, h: u32, off: u64) th.Answer { + return call(pp, .{ .tag = 9, .op = .read, .node = node, .handle = h, .off = off, .size = 8192 }); + } + }; + try testing.expectEqual(Status.again, rdf.next(p, log, fh, frozen).reply.status); const serial = try th.newPane(p); const id = p.paneBySerial(serial).?; - var expected: [4200]u8 = undefined; try testing.expectEqualStrings( try std.fmt.bufPrint(&expected, "new {d} {s}\n", .{ serial, pane_files.nameOf(p.panes[id].?) }), - rd(p, log, 0, 4096).bytes, + rdf.next(p, log, fh, frozen).bytes, ); try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/logged.txt\n").reply.status); try testing.expectEqualStrings( try std.fmt.bufPrint(&expected, "rename {d} /tmp/logged.txt\n", .{serial}), - rd(p, log, 0, 4096).bytes, + rdf.next(p, log, fh, frozen).bytes, ); - const saving = wr(p, Node.of(serial, .exec), "Save\n"); - try testing.expectEqual(Status.ok, saving.reply.status); - try testing.expect(saving.saved); - p.perform(.{ .save_file = .{ .pane = @intCast(id) } }); + // What the editor says is in the same stream, one line even when the + // message had several. + p.setMessage(id, "save: two\nlines"); try testing.expectEqualStrings( - try std.fmt.bufPrint(&expected, "save {d} /tmp/logged.txt\n", .{serial}), - rd(p, log, 0, 4096).bytes, + try std.fmt.bufPrint(&expected, "msg {d} save: two lines\n", .{serial}), + rdf.next(p, log, fh, frozen).bytes, ); + // A builtin announces itself on the message row, so the log says which ran. try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "Del\n").reply.status); + try testing.expectEqualStrings( + try std.fmt.bufPrint(&expected, "msg {d} Del\n", .{serial}), + rdf.next(p, log, fh, frozen).bytes, + ); try testing.expectEqualStrings( try std.fmt.bufPrint(&expected, "del {d} /tmp/logged.txt\n", .{serial}), - rd(p, log, 0, 4096).bytes, + rdf.next(p, log, fh, frozen).bytes, ); - try testing.expectEqual(Status.again, rd(p, log, 0, 4096).reply.status); + try testing.expectEqual(Status.again, rdf.next(p, log, fh, frozen).reply.status); - _ = call(p, .{ .tag = 2, .op = .release, .node = log, .handle = opened.reply.handle }); - try testing.expectEqual(@as(u16, 0), p.fs.log_readers); - _ = try th.newPane(p); - try testing.expect(p.fs.log.empty()); - try testing.expectEqual(@as(usize, 0), p.fs.log.buf.capacity); + // A follower the ring outran hears how much it missed, then carries on. + var filler: [200]u8 = @splat('x'); + for (0..p.fs.log.cap / filler.len + 8) |i| { + _ = std.fmt.bufPrint(&filler, "{d:0>6}", .{i}) catch unreachable; // a repeat would collapse + p.setMessage(0, &filler); + } + const lost = rdf.next(p, log, fh, frozen).bytes; + try testing.expect(std.mem.startsWith(u8, lost, "lost ")); + try testing.expect(std.mem.startsWith(u8, rdf.next(p, log, fh, frozen).bytes, "msg ")); + _ = call(p, .{ .tag = 10, .op = .release, .node = log, .handle = fh }); + for (p.fs.snapshots) |slot| try testing.expect(slot.node == 0); } diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 60fb5951..245a31ef 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -11,7 +11,13 @@ const Req = tree.Req; const Reply = tree.Reply; const E = tree.E; -pub const Snapshot = struct { node: u64 = 0, bytes: ?[]const u8 = null }; +pub const Snapshot = struct { + node: u64 = 0, + bytes: ?[]const u8 = null, + /// /log only: this open waits for records after `bytes`, from `next`. + follow: bool = false, + next: u64 = 0, +}; pub const snapshot_slots = 32; pub fn render(p: *Pardes) ![]u8 { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index aca8d109..f98429ab 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -117,8 +117,8 @@ pub const TopFile = enum(u4) { pub fn mode(f: TopFile) u16 { return switch (f) { .root, .pane => 0o755, - .look, .exec => 0o666, - .README, .index, .status, .log, .screen, .listeners, .new => 0o444, + .look, .exec, .log => 0o666, + .README, .index, .status, .screen, .listeners, .new => 0o444, }; } @@ -375,7 +375,7 @@ fn topSize(p: *Pardes, f: TopFile) u64 { .README => fs.help.len, .status => ctl.statusLen(p), .look, .exec => ctl.resultsLen(p), - .log => events.pending(&p.fs.log), + .log => events.logLen(&p.fs.log), .listeners => screen.listenersLen(p), }; } @@ -497,7 +497,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { .top => |f| switch (f) { .new => return .{ .tag = req.tag, .handle = makePane(p) orelse return Reply.fail(req.tag, E.NFILE) }, .screen => return screen.openSnapshot(p, req, true), - .log => p.fs.log_readers +|= 1, + .log => return events.openLog(p, req), else => {}, }, .pane => |t| { @@ -543,10 +543,7 @@ fn releaseHandle(p: *Pardes, req: Req) Reply { if (screen.releaseSnapshot(p, req)) return .{ .tag = req.tag }; const target = Node.target(req.node) orelse return .{ .tag = req.tag }; switch (target) { - .top => |f| if (f == .log and p.fs.log_readers > 0) { - p.fs.log_readers -= 1; - if (p.fs.log_readers == 0) p.fs.log.clearAndFree(p.gpa); - }, + .top => {}, .pane => |t| { if (t.file != .event and t.file != .pty_data) return .{ .tag = req.tag }; const id = p.paneBySerial(t.serial) orelse return .{ .tag = req.tag }; @@ -597,7 +594,7 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { }, .status => ctl.readStatus(p, req), .look, .exec => ctl.readResults(p, req), - .log => events.readQueue(p, req, &p.fs.log), + .log => events.readLog(p, req), .screen => screen.readSnapshot(p, req, null), .listeners => screen.readListeners(p, req), // The serial the open handed this fid, so that two reads of one @@ -623,6 +620,7 @@ fn write(p: *Pardes, req: Req, target: Target) Reply { switch (target) { .top => |f| return switch (f) { .look, .exec => ctl.command(p, req, null, f == .exec), + .log => events.writeLog(p, req), else => Reply.fail(req.tag, E.PERM), }, .pane => |t| { @@ -730,6 +728,36 @@ test "filesystem pane creation and truncation cancel Look hover" { } } +test "README names every file the tree serves" { + // /README is the whole manual a client gets; a file it never mentions + // is one nobody can find without reading this source. + const words = struct { + fn has(name: []const u8) bool { + var it = std.mem.tokenizeAny(u8, fs.help, " \t\n,.:;()'\"$<>|=/"); + while (it.next()) |w| if (std.mem.eql(u8, w, name)) return true; + return false; + } + }; + inline for (@typeInfo(TopFile).@"enum".fields) |f| { + const t: TopFile = @enumFromInt(f.value); + if (t != .root and !words.has(t.fileName())) { + std.debug.print("README does not mention /{s}\n", .{t.fileName()}); + return error.Undocumented; + } + } + inline for (@typeInfo(PaneFile).@"enum".fields) |f| { + const t: PaneFile = @enumFromInt(f.value); + const ok = if (t == .dir) true else if (t.inPty() and t != .pty) + std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @enumFromInt(f.value)).fileName()) != null + else + words.has(t.fileName()); + if (!ok) { + std.debug.print("README does not mention pane file {s}\n", .{@tagName(t)}); + return error.Undocumented; + } + } +} + test "readdir lists the root and a pane directory without creating anything" { const gpa = testing.allocator; const p = try withFile(gpa, "hello\n"); diff --git a/src/panes.zig b/src/panes.zig index 0b4204aa..156d443a 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -3072,7 +3072,7 @@ pub const Output = struct { errdefer out.deinit(); var i: usize = 0; while (p.messageLog(i)) |m| : (i += 1) { - if (m.pane != 0xff) try out.writer.print("{d}: ", .{m.pane}); + if (m.serial != 0) try out.writer.print("{d}: ", .{m.serial}); try out.writer.writeAll(m.slice()); if (m.repeats > 1) try out.writer.print(" (x{d})", .{m.repeats}); try out.writer.writeByte('\n'); diff --git a/src/pardes.zig b/src/pardes.zig index ca09caa1..6d294230 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -672,9 +672,11 @@ test "the message log keeps what the row forgets, and collapses repeats" { // The same text from a DIFFERENT pane is a different event: one pane's // failure must not be recorded as another's. - p.setMessage(1, "save: AccessDenied"); + p.newScratchBelow(0); + const other = p.active; + p.setMessage(other, "save: AccessDenied"); try std.testing.expectEqual(@as(usize, 3), p.messages_len); - try std.testing.expectEqual(@as(u8, 1), p.messageLog(2).?.pane); + try std.testing.expectEqual(p.panes[other].?.serial, p.messageLog(2).?.serial); // Progress is NOT logged: it arrives several times a second for a whole // index and would push everything else out (`setStatus`). @@ -6254,8 +6256,10 @@ pub const LoggedMessage = struct { pub const cap = 256; text: [cap]u8 = undefined, len: u16 = 0, - /// Which pane said it, or 0xff for one said to no pane in particular. - pane: u8 = 0xff, + /// The serial of the pane that said it, or 0 for none in particular. A + /// serial, not a slot: slots are reused, so an old line would name + /// whichever pane took the slot since. + serial: u32 = 0, /// How many times in a row. Saturating: a key held down against the same /// refusal is one event, not four hundred. repeats: u16 = 0, @@ -7432,11 +7436,11 @@ pub const Pardes = struct { fn logMessage(p: *Pardes, id: usize, text: []const u8) void { if (text.len == 0) return; - const pane: u8 = if (id < MAX_PANES) @intCast(id) else 0xff; + const serial: u32 = if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; const kept = text[0..@min(text.len, LoggedMessage.cap)]; if (p.messages_len > 0) { const last = &p.messages[(p.messages_head + limits.message_log - 1) % limits.message_log]; - if (last.pane == pane and + if (last.serial == serial and std.mem.eql(u8, Message.body(last.slice()), Message.body(kept))) { // The NEWEST wording wins, so the row carries the latest clock @@ -7447,10 +7451,11 @@ pub const Pardes = struct { return; } } + ctlfs.events.noteMessage(p, serial, kept); const slot = &p.messages[p.messages_head]; slot.len = @intCast(kept.len); @memcpy(slot.text[0..slot.len], kept); - slot.pane = pane; + slot.serial = serial; slot.repeats = 1; p.messages_head = (p.messages_head + 1) % limits.message_log; p.messages_len = @min(p.messages_len + 1, limits.message_log); diff --git a/test/fs.py b/test/fs.py index 33bcdfa9..48104e3f 100644 --- a/test/fs.py +++ b/test/fs.py @@ -185,7 +185,11 @@ def discovery(binary, embedded=False): # An open of /pane/new makes a pane and the read names it; each # open makes another. A stat makes none, which is why new can be # listed at all: ls -l stats every name a listing gave it. - log = client.open('/log') + # /log answers the recent past and ends; `follow` written to the + # same open makes its reads past that wait for new records. + log = client.open('/log', 2) + frozen = len(client.read_fid(log)) + client.rpc(118, struct.pack(' Date: Sun, 27 Sep 2026 18:07:06 -0300 Subject: Run a line at a terminal's prompt through pty/run and read how it ended /pane//pty/run takes factotum's rpc shape: write one line on an open, read the answer on that same open. The answer is exit N once the command ended and the shell is back at a prompt; busy at once when a command runs, text is typed at the prompt, or the shell has not drawn its first prompt; error not run when the shell refused the line without running it (fish on a syntax error keeps it on the prompt, so it is taken back with Ctrl-U); error shell gone when the pane closes or its shell is replaced; error no prompt marks for a shell pardes could not instrument. The end comes from the shell's OSC 133 marks. ghostty parses D's exit status and drops it, so the stream now runs through a handler that wraps ghostty's and follows prompt -> input -> running -> done. The marks pardes injects into bash and fish carry aid=pardes and only those count, so fish 4's own marks (which doubled ours), a nested shell's, and a stray 133;D in printed output are ignored. Checked end to end against real bash and fish: false, exit 7, a syntax error, sleep, busy while running, and the pane closing mid-command. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 2 + docs/fs.md | 17 ++- src/fs-help.txt | 4 +- src/fs.zig | 1 + src/host_io.zig | 14 +-- src/ninep/events.zig | 10 +- src/ninep/pane.zig | 8 +- src/ninep/pty.zig | 210 +++++++++++++++++++++++++++++++++++++- src/ninep/tree.zig | 9 +- src/panes.zig | 74 +++++++++++++- src/pardes.zig | 5 + test/fs.py | 39 +++++++ 12 files changed, 371 insertions(+), 22 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 81853c3e..47a83f13 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -46,6 +46,8 @@ $m/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, $m/status pid, version, panes $m/look write a line = a right click on it at the active pane $m/exec write a line = a middle click: an editor command word, or a shell line +$m/pane//pty/run write one line, read `exit N` / `busy` / `error ...` on the same open: + exec 3<>$m/pane/$n/pty/run; echo make >&3; cat <&3 $m/log recent events, then EOF: new|del|rename|save , msg (exec 3<>$m/log; echo follow >&3; cat <&3 waits for new ones; tail -f does not) $m/screen the rendered screen as JSON, frozen per open diff --git a/docs/fs.md b/docs/fs.md index 9d95b36e..d46e3d21 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -194,7 +194,22 @@ Control characters in a record become spaces, so a record is one line. An open freezes the ring's text the way `/screen` freezes a frame: reads walk it and end. Writing `follow` to that same open makes reads past it park for the next record, one per read; a follower the ring outran reads `lost N` first. -Closing the open is the only way back, as with rio's `consctl`. A record +Closing the open is the only way back, as with rio's `consctl`. + +`pty/run` runs one line at a terminal's prompt and answers how it ended, on +the same open (factotum's `rpc` shape): write the line, then read `exit N` +once the command has ended and the shell is back at a prompt. It reads +`busy` at once when a command is running, text is typed at the prompt or the +shell has not drawn its first prompt; `error not run` when the shell refused +the line without running it (a fish syntax error; the line is taken back off +the prompt); `error shell gone` when the pane closed or its shell was +replaced; `error no prompt marks` for a shell pardes could not instrument. +It relies on the OSC 133 marks pardes injects into bash and fish, tagged +`aid=pardes` so fish's own marks and a nested shell's are ignored. A second +line on an open whose command still runs fails the write. `exec zsh` or a +continuation prompt never reports an end; cancel the read. A read of `run` +waits in pardes, so through 9ns it needs 9ns's concurrent requests or it +holds up the rest of the mount. A record longer than a read comes in pieces, so a shell's `read` loop works. `tail -f` never writes `follow`, so it sees nothing new: use the follow open instead. `/screen` returns JSON with `cols`, `rows`, `cursor`, a `styles` table, and row-major `cells` of diff --git a/src/fs-help.txt b/src/fs-help.txt index db046946..cc682cf7 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -30,11 +30,11 @@ Below, $m is the mount point (PARDES_MOUNT in a Tty9p shell; 9ns and 9p work too exec 3<>$m/log; echo follow >&3; cat <&3 what happened lately, then wait for more cat $m/pane/$n/event hold it open to own that pane's clicks echo exec > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT + exec 3<>$m/pane/$n/pty/run; echo make >&3; cat <&3 exit N, busy or error, once back at a prompt printf 'ls\r' > $m/pane/$n/pty/data type into a terminal; pty/status: cols rows busy Pitfalls, one each: - Each open of pane/new makes another pane; two reads of one fid name the same one. - Only that open creates: ls, stat, find and every other read leave the tree alone. + Each open of pane/new makes another pane (ls, stat, find never do); a reread names the same. rmdir closes a pane even when it is dirty; index and pane//dirty show the flag. addr, dot and limit read the same pair of offsets they take, so cp between them works. dirty, mark and scroll read "0" or "1" and take "0" or "1"; truncating limit lifts it. diff --git a/src/fs.zig b/src/fs.zig index fef4ffe1..c35322b6 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1238,6 +1238,7 @@ pub const Namespace = struct { node_name: [16]u8 = undefined, os_paths: std.ArrayList(OsPath) = .empty, snapshots: [tree.screen.snapshot_slots]tree.screen.Snapshot = @splat(.{}), + runs: [tree.pty.run_slots]tree.pty.Run = @splat(.{}), out: std.ArrayList(u8) = .empty, panes: [MAX_PANES]tree.pane.State = @splat(.{}), listeners: u16 = 0, diff --git a/src/host_io.zig b/src/host_io.zig index f0a8d637..fcd2225b 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -588,9 +588,9 @@ pub const Shell = struct { const bash_rc = \\[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc" - \\PS1='\[\e]133;A;cl=line\a\]'"$PS1"'\[\e]133;B\a\]' - \\PROMPT_COMMAND='printf "\e]133;D;%s\a" "$?"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}" - \\trap 'printf "\e]133;C\a"' DEBUG + \\PS1='\[\e]133;A;cl=line;aid=pardes\a\]'"$PS1"'\[\e]133;B;aid=pardes\a\]' + \\PROMPT_COMMAND='printf "\e]133;D;%s;aid=pardes\a" "$?"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}" + \\trap 'printf "\e]133;C;aid=pardes\a"' DEBUG \\ ; @@ -598,15 +598,15 @@ pub const Shell = struct { const fish_rc = \\functions -c fish_prompt __pardes_user_prompt \\function fish_prompt - \\ printf '\e]133;A;cl=line\a' + \\ printf '\e]133;A;cl=line;aid=pardes\a' \\ __pardes_user_prompt - \\ printf '\e]133;B\a' + \\ printf '\e]133;B;aid=pardes\a' \\end \\function __pardes_preexec --on-event fish_preexec - \\ printf '\e]133;C\a' + \\ printf '\e]133;C;aid=pardes\a' \\end \\function __pardes_postexec --on-event fish_postexec - \\ printf '\e]133;D;%s\a' $status + \\ printf '\e]133;D;%s;aid=pardes\a' $status \\end \\ ; diff --git a/src/ninep/events.zig b/src/ninep/events.zig index ebd1cd2c..fa0a4975 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -128,6 +128,7 @@ pub fn noteInstall(p: *Pardes, id: usize) void { /// A pane leaving; one never announced leaves silently. pub fn noteRetire(p: *Pardes, id: usize, pane: *Pane) void { if (id >= MAX_PANES) return; + tree.pty.shellGone(p, id); if (p.fs.panes[id].unannounced) { p.fs.panes[id].unannounced = false; return; @@ -168,10 +169,11 @@ fn pushLog(p: *Pardes, record: []u8) void { c.* = ' '; }; // One record larger than the ring would push every other out and then - // not fit itself; cut it to what fits instead. - const fit = @min(record.len, p.fs.log.cap - 4); - record[fit - 1] = '\n'; - p.fs.log.push(p.gpa, record[0..fit]); + // not fit itself; cut it to what fits instead, on a character boundary. + var end = @min(record.len, p.fs.log.cap - 4) - 1; + while (end > 0 and record[end] & 0xC0 == 0x80) end -= 1; + record[end] = '\n'; + p.fs.log.push(p.gpa, record[0 .. end + 1]); } /// An open freezes the ring's text, so `cat log` answers what happened lately diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 40d292c0..61073a55 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -41,6 +41,10 @@ pub const State = struct { tag_snap: std.ArrayList(u8) = .empty, pty_readers: u16 = 0, pty_out: events.Queue = .{}, + /// The pty/run open waiting on this shell's current command. + run: ?u8 = null, + /// The host started a shell it could not teach to mark its prompts. + unmarked: bool = false, /// Installed during this update; /log hears about it once the update ends /// and the pane has its file, name and place. unannounced: bool = false, @@ -225,7 +229,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { .pty_status => pty.status_len, .pty_ctl => pty.ctlLen(pane), .pty_data => events.pending(&pf.pty_out), - .dir, .errors, .pty => 0, + .dir, .errors, .pty, .pty_run => 0, }; } @@ -293,6 +297,7 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .pty_status => pty.readStatus(p, req, id, pane), .pty_data => pty.readData(p, req, pf), .pty_ctl => pty.readCtl(p, req, pane), + .pty_run => pty.readRun(p, req), .dir, .errors, .pty => Reply.fail(req.tag, E.PERM), }; } @@ -386,6 +391,7 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply Reply.fail(req.tag, E.IO), .pty_ctl => pty.writeCtl(p, req, id), .pty_data => pty.writeData(p, req, id), + .pty_run => pty.writeRun(p, req, id, pane), .dir, .pty, .pty_status => Reply.fail(req.tag, E.PERM), }; } diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index b34bd59d..c7a32fbf 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -15,6 +15,7 @@ pub fn fileNamed(name: []const u8) ?PaneFile { if (std.mem.eql(u8, name, "ctl")) return .pty_ctl; if (std.mem.eql(u8, name, "status")) return .pty_status; if (std.mem.eql(u8, name, "data")) return .pty_data; + if (std.mem.eql(u8, name, "run")) return .pty_run; return null; } @@ -101,6 +102,147 @@ pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return tree.stagedReply(p, req); } +// ---- run: one command line in, how it ended out ---- +// +// factotum's rpc shape (factotum(4)): write a request on an open, read the +// answer on that same open, so the open is what ties a result to its +// command. The shell's own OSC 133 marks say when the command started (C) +// and ended (D, with its status); pardes injects them into bash and fish. + +pub const run_slots = 8; + +pub const Run = struct { + /// 0 is a free slot. + node: u64 = 0, + phase: enum { idle, sent, done } = .idle, + /// The shell's command count its C must reach for the end to be ours. + want: u32 = 0, + /// The shell's prompt count when the line went: a newer prompt with no + /// C for it means the shell never ran the line. + prompts: u32 = 0, + /// The refused line was taken back off the prompt. + cleared: bool = false, + answer: [48]u8 = undefined, + len: u8 = 0, +}; + +fn runOf(p: *Pardes, req: Req) ?*Run { + if (req.handle == 0 or req.handle > run_slots) return null; + const slot = &p.fs.runs[req.handle - 1]; + return if (slot.node == req.node) slot else null; +} + +pub fn openRun(p: *Pardes, req: Req, serial: u32) Reply { + _ = serial; + for (&p.fs.runs, 0..) |*slot, i| { + if (slot.node != 0) continue; + slot.* = .{ .node = req.node }; + return .{ .tag = req.tag, .handle = @intCast(i + 1) }; + } + return Reply.fail(req.tag, E.NFILE); +} + +fn answer(slot: *Run, comptime fmt: []const u8, args: anytype) void { + slot.len = @intCast((std.fmt.bufPrint(&slot.answer, fmt ++ "\n", args) catch unreachable).len); + slot.phase = .done; + pardes.turn.parked = true; // wake the read waiting on it +} + +pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { + const slot = runOf(p, req) orelse return Reply.fail(req.tag, E.INVAL); + if (slot.phase == .sent) return tree.failText(req.tag, 16, tree.e_in_use); + const line = std.mem.trimEnd(u8, req.data, "\r\n"); + if (line.len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); + for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); + const pf = &p.fs.panes[id]; + const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); + const marks = &state.stream.handler; + if (pf.unmarked) { + answer(slot, "error no prompt marks", .{}); + } else if (pf.run != null or !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) { + // Something is running, someone has typed at the prompt, or the + // shell has not drawn its first one yet: sending now would type into + // the middle of it. + answer(slot, "busy", .{}); + } else { + slot.want = marks.started +% 1; + slot.prompts = marks.prompts; + p.emitWrite(id, line); + p.emitWrite(id, "\r"); + slot.phase = .sent; + pf.run = @intCast(slot - &p.fs.runs[0]); + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +pub fn readRun(p: *Pardes, req: Req) Reply { + const slot = runOf(p, req) orelse return Reply.fail(req.tag, E.INVAL); + switch (slot.phase) { + .idle => return .{ .tag = req.tag, .payload = .{ .staged = 0 } }, + .sent => return .{ .tag = req.tag, .status = .again }, + .done => {}, + } + const text = slot.answer[0..slot.len]; + const off = @min(req.off, text.len); + const n = @min(text.len - off, req.size); + p.fs.stage(p.gpa).appendSlice(p.gpa, text[off..][0..n]) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } }; +} + +pub fn releaseRun(p: *Pardes, req: Req) Reply { + const slot = runOf(p, req) orelse return .{ .tag = req.tag }; + const idx: u8 = @intCast(slot - &p.fs.runs[0]); + // The command runs on in the shell; nobody is waiting for it any more. + for (&p.fs.panes) |*pf| if (pf.run == idx) { + pf.run = null; + }; + slot.* = .{}; + return .{ .tag = req.tag }; +} + +/// After each chunk of a terminal's output: once the command the run sent +/// has ended and the shell is back at a prompt, the run answers how. Waiting +/// for the prompt means whoever reads the answer can send the next command +/// at once instead of finding the shell still drawing it. +pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { + if (comptime !pardes.panes.Terminal.enabled) return; + const state = pane.terminal orelse return; + const pf = &p.fs.panes[id]; + const slot = &p.fs.runs[pf.run orelse return]; + const marks = &state.stream.handler; + if (marks.phase != .input) return; + // ponytail: a prompt redrawn before the command starts (a resize in that + // instant) reads as not run; a per-command id in the marks would tell. + if (marks.started != slot.want and marks.prompts != slot.prompts) { + // fish keeps a refused line on the prompt for editing; it is the one + // this run typed into an empty prompt, so take it back (Ctrl-U), and + // answer once it is gone so the next line finds the prompt clear. + if (!pardes.panes.Terminal.promptInputEmpty(pane)) { + if (!slot.cleared) p.emitWrite(id, "\x15"); + slot.cleared = true; + return; + } + answer(slot, "error not run", .{}); + pf.run = null; + return; + } + const done = marks.finished orelse return; + if (done.seq != slot.want) return; + if (done.status) |status| answer(slot, "exit {d}", .{status}) else answer(slot, "exit", .{}); + pf.run = null; +} + +/// The pane closed or its shell was replaced: the command's end will never +/// be reported, so the run says so instead of waiting forever. +pub fn shellGone(p: *Pardes, id: usize) void { + const pf = &p.fs.panes[id]; + const idx = pf.run orelse return; + answer(&p.fs.runs[idx], "error shell gone", .{}); + pf.run = null; +} + +const e_bad_line = "bad command line"; + pub fn readData(p: *Pardes, req: Req, pf: *pane_files.State) Reply { if (pf.pty_out.empty()) return .{ .tag = req.tag, .status = .again }; const out = p.fs.stage(p.gpa); @@ -186,10 +328,11 @@ test "a terminal pane's pty/ holds exactly ctl, status and data" { try testing.expect(th.nameAt(files, "pty").?.dir); const inside = th.dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf); - try testing.expectEqual(@as(usize, 3), inside.len); + try testing.expectEqual(@as(usize, 4), inside.len); try testing.expectEqualStrings("ctl", inside[0].name); try testing.expectEqualStrings("status", inside[1].name); try testing.expectEqualStrings("data", inside[2].name); + try testing.expectEqualStrings("run", inside[3].name); for (inside) |d| try testing.expect(!d.dir); try testing.expectEqual(Node.of(serial, .pty_data), inside[2].node); @@ -386,6 +529,71 @@ test "pty/data writes at the shell and reads the raw stream" { try testing.expectEqualStrings("still", rd(p, data, 0, 64).bytes); } +test "run answers how its command ended once the shell is back at a prompt" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const node = Node.of(serialOf(p), .pty_run); + const out = struct { + fn put(pp: *Pardes, bytes: []const u8) void { + pp.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); + while (pp.nextEffect()) |_| {} + } + }; + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + + // Before its first prompt the shell cannot take a line: busy, at once. + const early = call(p, .{ .tag = 1, .op = .open, .node = node }); + _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = early.reply.handle, .data = "true\n" }); + try testing.expectEqualStrings("busy\n", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = early.reply.handle, .size = 64 }).bytes); + _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = early.reply.handle }); + + out.put(p, prompt); + const r = call(p, .{ .tag = 5, .op = .open, .node = node }); + const h = r.reply.handle; + const sent = call(p, .{ .tag = 6, .op = .write, .node = node, .handle = h, .data = "make\n" }); + try testing.expectEqualStrings("make\r", sent.pty()); + try testing.expectEqual(Status.again, call(p, .{ .tag = 7, .op = .read, .node = node, .handle = h, .size = 64 }).reply.status); + // A second line on the same open while the first runs is refused. + try testing.expectEqual(Status.err, call(p, .{ .tag = 8, .op = .write, .node = node, .handle = h, .data = "ls\n" }).reply.status); + + // Untagged marks (fish's own, a nested shell's, a file being printed) + // and bash's C from its PROMPT_COMMAND trap change nothing. + out.put(p, "\x1b]133;D;9\x07\x1b]133;C;aid=pardes\x07building\r\n"); + out.put(p, "\x1b]133;C;aid=pardes\x07\x1b]133;D;2;aid=pardes\x07"); + try testing.expectEqual(Status.again, call(p, .{ .tag = 9, .op = .read, .node = node, .handle = h, .size = 64 }).reply.status); + out.put(p, prompt); + try testing.expectEqualStrings("exit 2\n", call(p, .{ .tag = 10, .op = .read, .node = node, .handle = h, .size = 64 }).bytes); + // The answer stays for a re-read until the open closes. + try testing.expectEqualStrings("exit 2\n", call(p, .{ .tag = 11, .op = .read, .node = node, .handle = h, .size = 64 }).bytes); + _ = call(p, .{ .tag = 12, .op = .release, .node = node, .handle = h }); + + // Typed text on the prompt line: busy, rather than typing into it. + out.put(p, "ls -"); + const typed = call(p, .{ .tag = 13, .op = .open, .node = node }); + _ = call(p, .{ .tag = 14, .op = .write, .node = node, .handle = typed.reply.handle, .data = "true\n" }); + try testing.expectEqualStrings("busy\n", call(p, .{ .tag = 15, .op = .read, .node = node, .handle = typed.reply.handle, .size = 64 }).bytes); + _ = call(p, .{ .tag = 16, .op = .release, .node = node, .handle = typed.reply.handle }); + out.put(p, "\x08\x08\x08\x08\x1b[K"); + + // A line the shell refuses without running it (fish on a syntax error): + // a fresh prompt and no C. Waiting for a D would wait forever. + const refused = call(p, .{ .tag = 21, .op = .open, .node = node }); + _ = call(p, .{ .tag = 22, .op = .write, .node = node, .handle = refused.reply.handle, .data = "(exit 7)\n" }); + out.put(p, "\r\nfish: command substitutions not allowed\r\n" ++ prompt); + try testing.expectEqualStrings("error not run\n", call(p, .{ .tag = 23, .op = .read, .node = node, .handle = refused.reply.handle, .size = 64 }).bytes); + _ = call(p, .{ .tag = 24, .op = .release, .node = node, .handle = refused.reply.handle }); + + // The pane going away while a command runs ends the wait. + out.put(p, "\r\n" ++ prompt); + const gone = call(p, .{ .tag = 17, .op = .open, .node = node }); + _ = call(p, .{ .tag = 18, .op = .write, .node = node, .handle = gone.reply.handle, .data = "sleep 9\n" }); + try p.removePane(0, null); + try testing.expectEqualStrings("error shell gone\n", call(p, .{ .tag = 19, .op = .read, .node = node, .handle = gone.reply.handle, .size = 64 }).bytes); + _ = call(p, .{ .tag = 20, .op = .release, .node = node, .handle = gone.reply.handle }); + for (p.fs.runs) |slot| try testing.expect(slot.node == 0); +} + test "the pty queue drops the oldest at its cap" { const gpa = testing.allocator; const p = try withTerm(gpa); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index a85a1873..0d328594 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -167,6 +167,7 @@ pub const PaneFile = enum(u5) { pty_ctl, pty_status, pty_data, + pty_run, pub fn fileName(f: PaneFile) []const u8 { return switch (f) { @@ -174,6 +175,7 @@ pub const PaneFile = enum(u5) { .pty_ctl => "ctl", .pty_status => "status", .pty_data => "data", + .pty_run => "run", else => @tagName(f), }; } @@ -193,7 +195,7 @@ pub const PaneFile = enum(u5) { pub fn inPty(f: PaneFile) bool { return switch (f) { - .pty, .pty_ctl, .pty_status, .pty_data => true, + .pty, .pty_ctl, .pty_status, .pty_data, .pty_run => true, else => false, }; } @@ -531,6 +533,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { pf.event_reader = pf.event_reader or reader; if (reader) return .{ .tag = req.tag, .handle = reader_handle }; }, + .pty_run => return pty.openRun(p, req, t.serial), .pty_data => if (reads(req.omode)) { if (pf.pty_readers > 0) return failText(req.tag, e_busy, e_in_use); pf.pty_readers = 1; @@ -569,6 +572,8 @@ fn releaseHandle(p: *Pardes, req: Req) Reply { switch (target) { .top => {}, .pane => |t| { + // A run's open outlives its pane: it still holds the answer. + if (t.file == .pty_run) return pty.releaseRun(p, req); if (t.file != .event and t.file != .pty_data) return .{ .tag = req.tag }; const id = p.paneBySerial(t.serial) orelse return .{ .tag = req.tag }; const pf = &p.fs.panes[id]; @@ -633,6 +638,8 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { .root, .pane => Reply.fail(req.tag, E.PERM), }, .pane => |t| { + // A run's answer outlives the pane it ran in. + if (t.file == .pty_run and req.handle != 0) return pty.readRun(p, req); const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); const pn = p.panes[id].?; if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); diff --git a/src/panes.zig b/src/panes.zig index 156d443a..3b1bb1b4 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -6502,7 +6502,59 @@ pub const Terminal = struct { pub const history_max = if (enabled) 64 else 8; pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; - pub const StreamSlot = if (enabled) ghostty_vt.TerminalStream else void; + pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; + + /// The `aid` pardes's injected bash and fish marks carry (host_io.zig). + pub const prompt_aid = "pardes"; + + /// ghostty's handler, plus where the shell is in its command cycle as + /// its OSC 133 marks tell it: ghostty parses D's exit status and drops + /// it, and /pane//pty/run waits on exactly that. Only marks carrying + /// pardes's own `aid` move it, so fish's native marks, a nested shell's + /// and a stray `133;D` in some file being printed all pass it by. + pub const MarkedHandler = if (enabled) struct { + inner: ghostty_vt.TerminalStream.Handler, + phase: enum { none, prompt, input, running } = .none, + /// Counts commands started (C at the input phase). + started: u32 = 0, + /// Counts prompts drawn (B), so a line the shell refused without + /// running (a fish syntax error: no C, no D, a new prompt) shows. + prompts: u32 = 0, + /// The newest command to end: which one, and its status if given. + finished: ?struct { seq: u32, status: ?i32 } = null, + + const Action = ghostty_vt.TerminalStream.Action; + + pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { + if (comptime action == .semantic_prompt) mark: { + const aid = value.readOption(.aid) orelse break :mark; + if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; + switch (value.action) { + .fresh_line_new_prompt => self.phase = .prompt, + .end_prompt_start_input => { + self.phase = .input; + self.prompts +%= 1; + }, + // bash's DEBUG trap also fires on its own PROMPT_COMMAND, + // outside the input phase; only a C that ends input counts + .end_input_start_output => if (self.phase == .input) { + self.phase = .running; + self.started +%= 1; + }, + .end_command => if (self.phase == .running) { + self.phase = .none; + self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; + }, + else => {}, + } + } + self.inner.vt(action, value); + } + + pub fn deinit(self: *@This()) void { + self.inner.deinit(); + } + } else void; pub const Replay = struct { bytes: [1024 * 1024]u8 = undefined, @@ -6784,12 +6836,12 @@ pub const Terminal = struct { .rows = rows, .max_scrollback = 16 * 1024 * 1024, }); - state.stream = state.vt.vtStream(); + state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); state.replay.head = 0; state.replay.len = 0; state.reply_len = 0; - state.stream.handler.effects.write_pty = ptyReport; - state.stream.handler.effects.device_attributes = ptyDeviceAttrs; + state.stream.handler.inner.effects.write_pty = ptyReport; + state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; pane.terminal = state; pane.tty_filter = true; return pane; @@ -6938,7 +6990,7 @@ pub const Terminal = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; const state = pane.terminal.?; - try std.testing.expect(state.stream.handler.terminal == &state.vt); + 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; @@ -7294,6 +7346,18 @@ pub const Terminal = struct { state.vt.screens.active.cursor.semantic_content == .input; } + /// At a prompt with nothing typed on its line, wherever the cursor is + /// (someone may have typed and pressed Ctrl-A). fish suggests nothing on + /// an empty line, so its autosuggestions never make this false. + pub fn promptInputEmpty(pane: *const Pane) bool { + if (comptime !enabled) return false; + if (!promptInputReady(pane)) return false; + const cursor = &pane.terminal.?.vt.screens.active.cursor; + for (cursor.page_pin.cells(.all)) |cell| + if (cell.semantic_content == .input and !cell.isEmpty()) return false; + return true; + } + /// Encode one key for the program that owns a raw terminal and queue its pty /// write, respecting the application's keyboard protocol and terminal modes. pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { diff --git a/src/pardes.zig b/src/pardes.zig index 06bc81ed..29a9ab3a 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -7024,6 +7024,10 @@ pub const Pardes = struct { } pub fn acknowledgeShell(p: *Pardes, id: usize, executable: []const u8, prompt_marks: bool) void { + if (id < MAX_PANES) { + ctlfs.pty.shellGone(p, id); // a respawn replaced whatever ran + p.fs.panes[id].unmarked = !prompt_marks; + } if (id < MAX_PANES) panes.Terminal.shellSpawned(p, id, prompt_marks); if (p.settings.shell.effective.set(executable)) p.settings.shell.pending = false; @@ -7848,6 +7852,7 @@ pub const Pardes = struct { const pane = p.panes[o.pane] orelse return; ctlfs.events.notePtyOutput(p, o.pane, o.bytes); panes.Terminal.feedOutput(p, pane, o.bytes); + ctlfs.pty.noteMarks(p, o.pane, pane); }, .eof => |e| p.removePane(e.pane, null) catch |err| { if (p.panes[e.pane]) |pane| pane.mode = .normal; diff --git a/test/fs.py b/test/fs.py index 1332c319..ff085a55 100644 --- a/test/fs.py +++ b/test/fs.py @@ -290,8 +290,47 @@ def discovery(binary, embedded=False): print('9P discovery: listing/stat/find are inert; new, remove, look, exec, name, sel and log behave') +def run_file(binary): + """pty/run: a line in, how it ended out, on the same open.""" + def run(c, serial, line): + fid = c.open(f'/pane/{serial}/pty/run', 2) + try: + c.rpc(118, struct.pack(' Date: Sun, 27 Sep 2026 19:37:05 -0300 Subject: pty/run answers with the command's output; pin cloud9 with 9ns concurrency and E.BUSY The answer is now the header line (exit N, or exit N cut M when only the last 64 KiB were kept, or exit N cut when its start scrolled out of the history), then what the command printed: the screen text between its C and D marks, which the marks handler pins so scrolling keeps them. Also from review: a plain /log open honours its offset until follow is written, so tail -n and less work; whitespace-only run lines are refused. cloud9 is pinned at 82d8152c: 9ns keeps up to 32 requests in flight per mount so a waiting read no longer freezes the rest of it, and E.BUSY replaces the errno pardes spelled locally. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 2 +- build.zig.zon | 4 +-- docs/fs.md | 9 ++++- src/fs-help.txt | 2 +- src/fs.zig | 1 + src/ninep/events.zig | 11 ++++-- src/ninep/pty.zig | 75 ++++++++++++++++++++++++++++++++------- src/ninep/tree.zig | 6 ++-- src/panes.zig | 37 +++++++++++++++++++ test/fs.py | 1 + 10 files changed, 124 insertions(+), 24 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 47a83f13..354932b3 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -46,7 +46,7 @@ $m/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, $m/status pid, version, panes $m/look write a line = a right click on it at the active pane $m/exec write a line = a middle click: an editor command word, or a shell line -$m/pane//pty/run write one line, read `exit N` / `busy` / `error ...` on the same open: +$m/pane//pty/run write one line, read `exit N` + its output, or `busy` / `error ...`, on the same open: exec 3<>$m/pane/$n/pty/run; echo make >&3; cat <&3 $m/log recent events, then EOF: new|del|rename|save , msg (exec 3<>$m/log; echo follow >&3; cat <&3 waits for new ones; tail -f does not) diff --git a/build.zig.zon b/build.zig.zon index 31649350..f0167c34 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,8 +9,8 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#eb1a104f385f375a74319695e1a59f6f82e6384e", - .hash = "cloud9-0.1.0-yt86qiixGgCCjOhSDJ6tijGR7zj_zLT8mjvuUqrkeG9_", + .url = "git+https://git.sr.ht/~gbrls/cloud9#82d8152cd15ea3ddd238caec2072bc2a1327a578", + .hash = "cloud9-0.1.0-yt86qs2zHQAlKvzjBVAZ0ghQwRwWwRtvfE2r-6zUES4X", }, // ZLS as a LIBRARY, not a language server: src/lsp_zls.zig imports the // `zls` module its build.zig publishes and calls the analyser in diff --git a/docs/fs.md b/docs/fs.md index d46e3d21..90849a58 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -198,7 +198,14 @@ Closing the open is the only way back, as with rio's `consctl`. `pty/run` runs one line at a terminal's prompt and answers how it ended, on the same open (factotum's `rpc` shape): write the line, then read `exit N` -once the command has ended and the shell is back at a prompt. It reads +once the command has ended and the shell is back at a prompt, followed by +what it printed. The output is what the screen showed between the command's +start and end marks: stderr interleaved, `\r` progress collapsed to its last +state, no colour; a full-screen program (vim, less) leaves none, and rows a +program redrew above its start are missed. Only its last 64 KiB are kept, +from a line start, and the header then reads `exit N cut M` (M bytes left +out), or `exit N cut` when its start scrolled out of the history. The header +is always the whole first line. It reads `busy` at once when a command is running, text is typed at the prompt or the shell has not drawn its first prompt; `error not run` when the shell refused the line without running it (a fish syntax error; the line is taken back off diff --git a/src/fs-help.txt b/src/fs-help.txt index cc682cf7..5f890d66 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -30,7 +30,7 @@ Below, $m is the mount point (PARDES_MOUNT in a Tty9p shell; 9ns and 9p work too exec 3<>$m/log; echo follow >&3; cat <&3 what happened lately, then wait for more cat $m/pane/$n/event hold it open to own that pane's clicks echo exec > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT - exec 3<>$m/pane/$n/pty/run; echo make >&3; cat <&3 exit N, busy or error, once back at a prompt + exec 3<>$m/pane/$n/pty/run; echo make >&3; cat <&3 exit N then its output; or busy, or error printf 'ls\r' > $m/pane/$n/pty/data type into a terminal; pty/status: cols rows busy Pitfalls, one each: diff --git a/src/fs.zig b/src/fs.zig index c35322b6..8e2c52a1 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1262,6 +1262,7 @@ pub const Namespace = struct { for (st.os_paths.items) |entry| gpa.free(entry.path); st.os_paths.deinit(gpa); for (st.snapshots) |snapshot| if (snapshot.bytes) |bytes| gpa.free(bytes); + for (&st.runs) |*slot| slot.reset(gpa, 0); for (&st.panes) |*pf| pf.deinit(gpa); st.log.deinit(gpa); st.out.deinit(gpa); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 20cdeda4..bd5fecf3 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -209,10 +209,12 @@ pub fn readLog(p: *Pardes, req: Req) Reply { const frozen = slot.bytes orelse &.{}; const out = p.fs.stage(p.gpa); if (!slot.follow or slot.pos < frozen.len) { - const off = @min(slot.pos, frozen.len); + // Until `follow`, the frozen text is a file like any other: `tail -n` + // seeks near its end, `less` seeks back. After it, a stream. + const off = @min(if (slot.follow) slot.pos else req.off, frozen.len); const len = @min(frozen.len - off, req.size); out.appendSlice(p.gpa, frozen[off..][0..len]) catch return Reply.fail(req.tag, E.NOMEM); - slot.pos += len; + slot.pos = off + len; return .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; } const q = &p.fs.log; @@ -671,6 +673,8 @@ test "the log records whether or not anyone reads, and an open that follows wait const past = call(p, .{ .tag = 3, .op = .read, .node = log, .handle = plain.reply.handle, .off = first.bytes.len, .size = 8192 }); try testing.expectEqual(Status.ok, past.reply.status); try testing.expectEqual(@as(usize, 0), past.bytes.len); + const tail = call(p, .{ .tag = 3, .op = .read, .node = log, .handle = plain.reply.handle, .off = first.bytes.len - early_owned.len, .size = 8192 }); + try testing.expectEqualStrings(early_owned, tail.bytes); _ = call(p, .{ .tag = 4, .op = .release, .node = log, .handle = plain.reply.handle }); // `follow` on an open makes it wait past what it froze, one record a read. @@ -680,7 +684,8 @@ test "the log records whether or not anyone reads, and an open that follows wait try testing.expectEqual(Status.err, call(p, .{ .tag = 7, .op = .write, .node = log, .handle = fh, .data = "tail\n" }).reply.status); try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = log, .handle = fh, .data = "follow\n" }).reply.status); // A stream: after `echo follow >&3` a shell reads at offset 7, and gets - // what comes next, not the frozen text from byte 7. + // what comes next, not the frozen text from byte 7. Before `follow` the + // offset is honoured, so `tail -n` works (checked below on `plain`). const rdf = struct { fn next(pp: *Pardes, node: u64, h: u32, off: u64) th.Answer { return call(pp, .{ .tag = 9, .op = .read, .node = node, .handle = h, .off = off, .size = 8192 }); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index ec2e18e5..a689d87f 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -111,6 +111,10 @@ pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { pub const run_slots = 32; +/// The most of a command's output an answer carries: its last this-many +/// bytes, since that is where a failure says what went wrong. +pub const output_cap = 64 * 1024; + pub const Run = struct { /// 0 is a free slot. node: u64 = 0, @@ -129,9 +133,17 @@ pub const Run = struct { /// `exec 3<>run` shares one offset between the write and the read, so /// the offset a read arrives with means nothing (acme's event file and /// Plan 9's kprint read the same way). - read: u8 = 0, + read: usize = 0, + /// The first line: how it ended. answer: [48]u8 = undefined, len: u8 = 0, + /// Then what the command printed, gpa-owned. + output: []u8 = &.{}, + + pub fn reset(slot: *Run, gpa: std.mem.Allocator, node: u64) void { + gpa.free(slot.output); + slot.* = .{ .node = node }; + } }; fn runOf(p: *Pardes, req: Req) ?*Run { @@ -158,9 +170,10 @@ fn answer(slot: *Run, comptime fmt: []const u8, args: anytype) void { pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { const slot = runOf(p, req) orelse return Reply.fail(req.tag, E.INVAL); - if (slot.phase == .sent) return tree.failText(req.tag, 16, tree.e_in_use); - slot.* = .{ .node = slot.node }; // a new line on this open: a new answer + if (slot.phase == .sent) return tree.failText(req.tag, E.BUSY, tree.e_in_use); + slot.reset(p.gpa, slot.node); // a new line on this open: a new answer const line = std.mem.trimEnd(u8, req.data, "\r\n"); + if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); if (line.len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); const pf = &p.fs.panes[id]; @@ -196,11 +209,21 @@ pub fn readRun(p: *Pardes, req: Req) Reply { .sent => return .{ .tag = req.tag, .status = .again }, .done => {}, } - const text = slot.answer[slot.read..slot.len]; - const n = @min(text.len, req.size); - p.fs.stage(p.gpa).appendSlice(p.gpa, text[0..n]) catch return Reply.fail(req.tag, E.NOMEM); - slot.read += @intCast(n); - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } }; + // The answer line, then the output: one stream, read from `read` on. + const out = p.fs.stage(p.gpa); + var at = slot.read; + for ([_][]const u8{ slot.answer[0..slot.len], slot.output }) |part| { + if (at >= part.len) { + at -= part.len; + continue; + } + const n = @min(part.len - at, req.size - out.items.len); + out.appendSlice(p.gpa, part[at..][0..n]) catch return Reply.fail(req.tag, E.NOMEM); + at = 0; + if (out.items.len == req.size) break; + } + slot.read += out.items.len; + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; } pub fn releaseRun(p: *Pardes, req: Req) Reply { @@ -210,7 +233,7 @@ pub fn releaseRun(p: *Pardes, req: Req) Reply { for (&p.fs.panes) |*pf| if (pf.run == idx) { pf.run = null; }; - slot.* = .{}; + slot.reset(p.gpa, 0); return .{ .tag = req.tag }; } @@ -268,7 +291,33 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { } const done = marks.finished orelse return; if (done.seq != slot.want) return; - if (done.status) |status| answer(slot, "exit {d}", .{status}) else answer(slot, "exit", .{}); + const printed = pardes.panes.Terminal.commandOutput(pane, p.gpa) catch null; + defer if (printed) |text| p.gpa.free(text); + const scrolled_out = if (state.stream.handler.out_start) |pin| pin.garbage else false; + // Keep the tail, cut at a line start so the first line kept is whole. + var keep: []const u8 = printed orelse ""; + if (keep.len > output_cap) { + keep = keep[keep.len - output_cap ..]; + if (std.mem.indexOfScalar(u8, keep, '\n')) |nl| keep = keep[nl + 1 ..]; + } + const cut = (if (printed) |text| text.len else 0) - keep.len; + const status = done.status orelse 0; + // The header is the whole first line, so a count there can never be + // mistaken for output; `cut` with no count: its start scrolled away. + if (printed == null or scrolled_out) + answer(slot, "exit {d} cut", .{status}) + else if (cut > 0) + answer(slot, "exit {d} cut {d}", .{ status, cut }) + else + answer(slot, "exit {d}", .{status}); + if (keep.len > 0) { + const nl = @intFromBool(keep[keep.len - 1] != '\n'); + if (p.gpa.alloc(u8, keep.len + nl)) |owned| { + @memcpy(owned[0..keep.len], keep); + if (nl == 1) owned[keep.len] = '\n'; + slot.output = owned; + } else |_| {} + } pf.run = null; } @@ -605,7 +654,8 @@ test "run answers how its command ended once the shell is back at a prompt" { out.put(p, prompt); // A shell's `exec 3<>run; echo make >&3; cat <&3` reads at the offset // its write left (5): the answer is a stream and comes whole anyway. - try testing.expectEqualStrings("exit 2\n", call(p, .{ .tag = 10, .op = .read, .node = node, .handle = h, .off = 5, .size = 64 }).bytes); + // The answer is how it ended, then what it printed. + try testing.expectEqualStrings("exit 2\nbuilding\n", call(p, .{ .tag = 10, .op = .read, .node = node, .handle = h, .off = 5, .size = 64 }).bytes); try testing.expectEqual(@as(usize, 0), call(p, .{ .tag = 11, .op = .read, .node = node, .handle = h, .size = 64 }).bytes.len); _ = call(p, .{ .tag = 12, .op = .release, .node = node, .handle = h }); @@ -619,7 +669,8 @@ test "run answers how its command ended once the shell is back at a prompt" { try testing.expectEqualStrings("busy\n", call(p, .{ .tag = 34, .op = .read, .node = node, .handle = nested.reply.handle, .size = 64 }).bytes); _ = call(p, .{ .tag = 35, .op = .release, .node = node, .handle = nested.reply.handle }); out.put(p, "logout\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt); - try testing.expectEqualStrings("exit 0\n", call(p, .{ .tag = 36, .op = .read, .node = node, .handle = outer.reply.handle, .size = 64 }).bytes); + const ssh = call(p, .{ .tag = 36, .op = .read, .node = node, .handle = outer.reply.handle, .size = 64 }).bytes; + try testing.expect(std.mem.startsWith(u8, ssh, "exit 0\n") and std.mem.indexOf(u8, ssh, "remote$ logout\n") != null); _ = call(p, .{ .tag = 37, .op = .release, .node = node, .handle = outer.reply.handle }); // Typed text on the prompt line: busy, rather than typing into it. diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 0d328594..e8bcad2f 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -68,8 +68,6 @@ pub const e_in_use = "file in use"; /// Handles that mark an open as the one reading `event` or `pty/data`, so the /// release knows to give the file up; other opens get `open_handle`. const open_handle: u32 = 1; -// ponytail: EBUSY spelled locally; use E.BUSY once cloud9 names it and pardes bumps the pin. -const e_busy: u16 = 16; const reader_handle: u32 = 2; fn reads(omode: u8) bool { @@ -527,7 +525,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { // the stream; the second is refused rather than robbed. .event => { const reader = reads(req.omode); - if (reader and pf.event_reader) return failText(req.tag, e_busy, e_in_use); + if (reader and pf.event_reader) return failText(req.tag, E.BUSY, e_in_use); pf.readers +|= 1; p.fs.listeners +|= 1; pf.event_reader = pf.event_reader or reader; @@ -535,7 +533,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { }, .pty_run => return pty.openRun(p, req, t.serial), .pty_data => if (reads(req.omode)) { - if (pf.pty_readers > 0) return failText(req.tag, e_busy, e_in_use); + if (pf.pty_readers > 0) return failText(req.tag, E.BUSY, e_in_use); pf.pty_readers = 1; return .{ .tag = req.tag, .handle = reader_handle }; }, diff --git a/src/panes.zig b/src/panes.zig index 410492b8..68e03a04 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -6526,11 +6526,26 @@ pub const Terminal = struct { /// The newest prompt continues an unfinished line (bash's PS2, marked /// `k=c`): the shell still holds the start of the command. continuation: bool = false, + /// Where the newest command's output began (its C) and ended (its + /// D) on the primary screen, pinned so scrolling keeps them. + out_start: ?*ghostty_vt.Pin = null, + out_end: ?*ghostty_vt.Pin = null, + /// The newest command to end: which one, and its status if given. finished: ?struct { seq: u32, status: ?i32 } = null, const Action = ghostty_vt.TerminalStream.Action; + /// Move one of the output pins to the cursor. Only the primary screen + /// is pinned: a command's own full-screen display is not its output. + fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { + const screen = self.inner.terminal.screens.get(.primary) orelse return; + if (slot.*) |old| screen.pages.untrackPin(old); + slot.* = null; + if (!now or self.inner.terminal.screens.active_key != .primary) return; + slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; + } + pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { if (comptime action == .semantic_prompt) mark: { const aid = value.readOption(.aid) orelse break :mark; @@ -6549,10 +6564,13 @@ pub const Terminal = struct { .end_input_start_output => if (self.phase == .input) { self.phase = .running; self.started +%= 1; + self.pinCursor(&self.out_start, true); + self.pinCursor(&self.out_end, false); }, .end_command => if (self.phase == .running) { self.phase = .none; self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; + self.pinCursor(&self.out_end, true); } else { self.declined +%= 1; }, @@ -7357,6 +7375,25 @@ pub const Terminal = struct { state.vt.screens.active.cursor.semantic_content == .input; } + /// What the newest finished command printed: the screen text between its + /// C and D marks, owned by the caller. When its start has scrolled out of + /// the history, ghostty moved that pin to the oldest row it kept (and + /// flagged it `garbage`), so this is the part that survived. + pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator) ![:0]const u8 { + if (comptime enabled) printed: { + const state = pane.terminal orelse break :printed; + const start = state.stream.handler.out_start orelse break :printed; + const end = state.stream.handler.out_end orelse break :printed; + if (end.garbage) break :printed; + const screen = state.vt.screens.get(.primary) orelse break :printed; + // D is where the next prompt begins: the output ends a cell before. + const last = end.leftWrap(1) orelse break :printed; + if (start.eql(end.*) or last.before(start.*)) break :printed; + return try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(start.*, last, false) }); + } + return try gpa.dupeZ(u8, ""); // it printed nothing + } + /// At a prompt with nothing typed on its line: no input left of the /// cursor and none under it (text typed and then Ctrl-A'd starts at the /// cursor). Nothing further right counts: that is where fish draws a diff --git a/test/fs.py b/test/fs.py index d44f417d..b4b0315b 100644 --- a/test/fs.py +++ b/test/fs.py @@ -310,6 +310,7 @@ def run_file(binary): assert time.monotonic() < deadline, 'the shell never reached a prompt' time.sleep(.05) assert run(client, term, b'false\n') == b'exit 1\n' + assert run(client, term, b'printf "one\\ntwo\\n"\n') == b'exit 0\none\ntwo\n' # then what it printed assert run(client, term, b'sh -c "exit 7"\n') == b'exit 7\n' assert run(client, term, b'fi\n') == b'error not run\n' # a syntax error runs nothing assert run(client, term, b"echo 'open\n") == b'error not run\n' # nor does an open quote -- cgit v1.3 From 28c814aa5cfea23e8950ef007916ffc5d089288d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 20:09:02 -0300 Subject: Hold a read that has nothing yet and answer it when its file has news A following log, event, pty/data or a pty/run before its answer used to answer .again and wait for a wakeAll, which only the parked-write path asked for, so the band-aid had every queue push set turn.parked. Now the core keeps such a read (ctlfs.hold) and, as the turn is given up after anything that queued a record, ran a command out or closed a pane, answers it on its own connection, the way factotum answers the log reads it keeps and acme an event read. Only a read the engine still holds parked is answered, because cloud9 tells the backend nothing of a Tflush, so a flushed read spends no record. Co-Authored-By: Claude Opus 5.5 --- docs/cloud9.md | 6 ++- docs/fs.md | 12 ++++- src/9p_io.zig | 145 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/fs.zig | 6 +++ src/ninep/events.zig | 10 ++-- src/ninep/pty.zig | 18 +++---- src/ninep/tree.zig | 31 +++++++++++ src/pardes.zig | 5 ++ 8 files changed, 217 insertions(+), 16 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/cloud9.md b/docs/cloud9.md index 6eb76238..8d4b6b44 100644 --- a/docs/cloud9.md +++ b/docs/cloud9.md @@ -21,7 +21,11 @@ turn with the core (`pardes.turn`) while the editor waits for input or is out in a syscall. A request that would change a pane while the editor is mid-step is parked with `Status.again` -- the engine parks reads, writes, opens, truncations, clunks and removes -- and retried by `Runner.wakeAll` when the -editor next rests. `src/9p_quic.zig` selects the existing `pardes-9p` ALPN for +editor next rests. A read with nothing yet parks the same way, but is never +retried for news: the core holds it (`ctlfs.hold`) and `answerHeld` answers +it on its connection through `Conn.reply`'s engine, under the connection's +lock and only while the engine still holds that tag parked, since cloud9 does +not tell the backend about a Tflush. `src/9p_quic.zig` selects the existing `pardes-9p` ALPN for cloud9's optional OpenSSL transport; QUIC still runs on the poll loop in `src/9p_io.zig` on the editor's thread, since cloud9's QUIC adapter is nonblocking-descriptor based rather than `std.Io` based. diff --git a/docs/fs.md b/docs/fs.md index 90849a58..0d6ffcda 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -192,10 +192,20 @@ pane is being made can precede that pane's `new`; panes present at boot are recorded before anything else. Control characters in a record become spaces, so a record is one line. An open freezes the ring's text the way `/screen` freezes a frame: reads walk it -and end. Writing `follow` to that same open makes reads past it park for the +and end. Writing `follow` to that same open makes reads past it wait for the next record, one per read; a follower the ring outran reads `lost N` first. Closing the open is the only way back, as with rio's `consctl`. +A read with nothing to give yet -- a following `log`, `event`, `pty/data`, a +`pty/run` before its answer -- is held, the way factotum holds its log's reads +(security/auth/factotum/log.c) and acme an event read: the core keeps it, and +whoever next has news for it (a record, output, a run's answer, the pane +closing, which answers "No such file or directory") answers it on the connection it +came on as the turn is given up. Nothing else parked is retried for it. A +read the client flushed meanwhile is dropped unanswered, so no record is +spent on it. An open waits with one read at a time, as acme's window keeps +one `eventx`. QUIC connections still retry their parked reads each tick. + `pty/run` runs one line at a terminal's prompt and answers how it ended, on the same open (factotum's `rpc` shape): write the line, then read `exit N` once the command has ended and the shell is back at a prompt, followed by diff --git a/src/9p_io.zig b/src/9p_io.zig index 7e09fb27..6182ca75 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -227,6 +227,9 @@ pub const Listener = struct { const restores = pardes.turn.restores; const reply = core.serveFs(req); if (req.op == .release and quiet) l.collectOs(); + // A read with nothing yet stays parked in the engine, and the core + // keeps it to answer when what it waits on has something. + if (reply.status == .again and req.op == .read) pardes.ctlfs.hold(core, req, conn); if (!pardes.ctlfs.changesPane(req)) return conn.reply(&reply, core.fsPayload(reply)); // The editor draws the change and performs what it asked for; when // it asked for something -- a save, a shell, a watch -- the answer @@ -246,6 +249,43 @@ pub const Listener = struct { conn.reply(&reply, ""); } + /// With the turn, as it is given up: answers each read the core holds + /// whose file now has something, on the connection that asked, with no + /// retry of anything else parked there. Only a read its engine still + /// holds parked is answered: Tflush drops one without a word to the + /// backend, and a `retry` takes one out to ask again, and a record spent + /// on either would be lost to the reader that comes next. + fn answerHeld(ctx: ?*anyopaque) void { + if (comptime !supported) return; + const l = of(ctx); + if (l.stopping.load(.acquire)) return; + const core = l.core; + if (!core.fs.news) return; + core.fs.news = false; + for (&core.fs.held) |*slot| { + const held = slot.* orelse continue; + const conn: *Runner.Conn = @ptrCast(@alignCast(held.asker)); + conn.lock(); + const parked: ?bool = for (conn.engine.slots) |sl| { + if (sl.used and sl.req.tag == held.req.tag) break sl.parked; + } else null; + // Gone (flushed, answered, hung up) it is forgotten; out being + // asked again, the asking answers it. + if (parked != true) { + if (parked == null) slot.* = null; + conn.unlock(); + continue; + } + const reply = core.serveFs(held.req); + if (reply.status != .again) { + slot.* = null; + conn.engine.reply(&reply, core.fsPayload(reply)); + } + conn.unlock(); + conn.flush(); + } + } + /// The turn was given up quiet with a request parked: every connection /// retries what it parked. fn wakeParked(ctx: ?*anyopaque) void { @@ -641,6 +681,7 @@ pub const Listener = struct { pardes.turn.wake(); } pardes.turn.wake_parked = null; + pardes.turn.answer_held = null; pardes.turn.stop(); if (l.path_len != 0) { var z: [sun_path_len:0]u8 = undefined; @@ -672,6 +713,7 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: [ l.* = .{ .io = io, .core = core }; pardes.turn.start(io); pardes.turn.wake_parked = Listener.wakeParked; + pardes.turn.answer_held = Listener.answerHeld; pardes.turn.wake_ctx = l; l.runner.init(.{ .io = io, @@ -1312,6 +1354,109 @@ test "a change waits while the editor is out mid-step, a read does not, and the try testing.expectEqualStrings("after\n", pane.file.?.content); } +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 directory: [64:0]u8 = undefined; + _ = try std.fmt.bufPrintSentinel(&directory, "/tmp/pardes-held-XXXXXX", .{}, 0); + if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; + defer _ = rmdir(&directory); + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + defer { + if (old_runtime) |v| { + _ = setenv("XDG_RUNTIME_DIR", v, 1); + gpa.free(v); + } else _ = unsetenv("XDG_RUNTIME_DIR"); + } + try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); + + 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 = listen(testing.io, gpa, p, "held", "", null, null) orelse return error.ListenFailed; + defer { + l.reset(p); + l.deinit(gpa); + } + // 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 = Client.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 heldNow = struct { + fn check(core: *pardes.Pardes) !void { + const deadline = Client.nowMs() + Client.budget_ms; + while (Client.nowMs() < deadline) { + pardes.turn.wake(); + const any = for (core.fs.held) |slot| { + if (slot != null) break true; + } else false; + pardes.turn.rest(); + if (any) return; + Client.nap(1); + } + return error.Timeout; + } + }; + + // Flushed while held, a read is gone from the engine without the core + // hearing of it; the record logged next must reach the read after it. + const flushed = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); + try s.flush(); + try heldNow.check(p); + _ = 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); + pardes.turn.wake(); + p.setMessage(0, "after the flush"); + pardes.turn.rest(); + try testing.expect(std.mem.indexOf(u8, (try s.ask(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }, &remote)).read, "after the flush") != null); + + // Held, a read is answered by the record that arrives, on its own + // connection, with no retry of every parked request asked for. + const waiting = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }); + try s.flush(); + try heldNow.check(p); + 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); + s.drop(1); + pardes.turn.wake(); + const left = for (p.fs.held) |slot| { + if (slot != null) break true; + } else false; + pardes.turn.rest(); + try testing.expect(!left); +} + extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; extern "c" fn unsetenv(name: [*:0]const u8) c_int; diff --git a/src/fs.zig b/src/fs.zig index 8e2c52a1..50a446dc 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1243,6 +1243,12 @@ pub const Namespace = struct { panes: [MAX_PANES]tree.pane.State = @splat(.{}), listeners: u16 = 0, origin: u8 = 'K', + /// Reads that found nothing yet, one per open that can wait: the log's + /// and a run's opens, and one event and one pty/data reader a pane. + held: [tree.screen.snapshot_slots + tree.pty.run_slots + 2 * MAX_PANES]?tree.Held = @splat(null), + /// Something a held read may be waiting on changed since they were last + /// answered: a record queued, a run answered, a pane gone. + news: bool = false, /// The editor-wide event ring: panes made, renamed, saved and closed, and /// what the editor said. Recorded whether or not anyone reads /log. log: tree.events.Queue = .{ .cap = limits.log_bytes }, diff --git a/src/ninep/events.zig b/src/ninep/events.zig index bd5fecf3..6b8c744e 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -50,10 +50,6 @@ pub const Queue = struct { q.buf.shrinkRetainingCapacity(q.buf.items.len - 4); return; }; - // A read parked on this queue is retried only when the turn is next - // given up with `parked` set; without it a follower sleeps until some - // unrelated request happens to park. - pardes.turn.parked = true; } pub fn peek(q: *const Queue) ?[]const u8 { @@ -105,7 +101,7 @@ pub fn pending(q: *const Queue) u64 { return record.len; } -/// One record per read; `.again` parks the read until a record arrives. +/// One record per read; `.again` holds the read until a record arrives. pub fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply { const record = q.peek() orelse return .{ .tag = req.tag, .status = .again }; if (req.size < record.len) return Reply.fail(req.tag, E.INVAL); @@ -129,6 +125,7 @@ pub fn noteInstall(p: *Pardes, id: usize) void { pub fn noteRetire(p: *Pardes, id: usize, pane: *Pane) void { if (id >= MAX_PANES) return; tree.pty.shellGone(p, id); + p.fs.news = true; // a read held on its event or pty/data hears it went if (p.fs.panes[id].unannounced) { p.fs.panes[id].unannounced = false; return; @@ -174,6 +171,7 @@ fn pushLog(p: *Pardes, record: []u8) void { while (end > 0 and record[end] & 0xC0 == 0x80) end -= 1; record[end] = '\n'; p.fs.log.push(p.gpa, record[0 .. end + 1]); + p.fs.news = true; } /// An open freezes the ring's text, so `cat log` answers what happened lately @@ -384,6 +382,7 @@ pub fn noteAction( var buf: [max_record_text + 64]u8 = undefined; const record = formatRecord(&buf, p.fs.origin, action, q0, q1, flag, text); p.fs.panes[id].events.push(p.gpa, record); + p.fs.news = true; return true; } @@ -397,6 +396,7 @@ pub fn notePtyOutput(p: *Pardes, id: usize, bytes: []const u8) void { pf.pty_out.push(p.gpa, bytes[off..][0..n]); off += n; } + p.fs.news = true; } const EventRecord = struct { action: Action, q0: u32, q1: u32 }; diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index a689d87f..2a38f1f0 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -162,10 +162,10 @@ pub fn openRun(p: *Pardes, req: Req, serial: u32) Reply { return Reply.fail(req.tag, E.NFILE); } -fn answer(slot: *Run, comptime fmt: []const u8, args: anytype) void { +fn answer(p: *Pardes, slot: *Run, comptime fmt: []const u8, args: anytype) void { slot.len = @intCast((std.fmt.bufPrint(&slot.answer, fmt ++ "\n", args) catch unreachable).len); slot.phase = .done; - pardes.turn.parked = true; // wake the read waiting on it + p.fs.news = true; // the read held on it can be answered } pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { @@ -180,7 +180,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); const marks = &state.stream.handler; if (pf.unmarked) { - answer(slot, "error no prompt marks", .{}); + answer(p, slot, "error no prompt marks", .{}); } else if (pf.run != null or marks.phase != .input or !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) { @@ -189,7 +189,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // the middle of it. The phase is pardes's own marks: a nested // shell's prompt (ssh, a shell with its own integration) looks like // an empty prompt to ghostty but is not the shell this run knows. - answer(slot, "busy", .{}); + answer(p, slot, "busy", .{}); } else { slot.want = marks.started +% 1; slot.prompts = marks.prompts; @@ -285,7 +285,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { .kept_line => {}, } if (!empty) return; - answer(slot, "error not run", .{}); + answer(p, slot, "error not run", .{}); pf.run = null; return; } @@ -305,11 +305,11 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { // The header is the whole first line, so a count there can never be // mistaken for output; `cut` with no count: its start scrolled away. if (printed == null or scrolled_out) - answer(slot, "exit {d} cut", .{status}) + answer(p, slot, "exit {d} cut", .{status}) else if (cut > 0) - answer(slot, "exit {d} cut {d}", .{ status, cut }) + answer(p, slot, "exit {d} cut {d}", .{ status, cut }) else - answer(slot, "exit {d}", .{status}); + answer(p, slot, "exit {d}", .{status}); if (keep.len > 0) { const nl = @intFromBool(keep[keep.len - 1] != '\n'); if (p.gpa.alloc(u8, keep.len + nl)) |owned| { @@ -326,7 +326,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { pub fn shellGone(p: *Pardes, id: usize) void { const pf = &p.fs.panes[id]; const idx = pf.run orelse return; - answer(&p.fs.runs[idx], "error shell gone", .{}); + answer(p, &p.fs.runs[idx], "error shell gone", .{}); pf.run = null; } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index e8bcad2f..3ebea669 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -107,6 +107,32 @@ pub fn changesPane(req: Req) bool { pub const out_reserve = 4 * 1024; +/// A read that found nothing yet (`.again`), kept to be answered when what it +/// waits on has something, the way factotum keeps its log's waiting reads +/// and answers them on append (security/auth/factotum/log.c:4-52) and acme +/// an event read (editors/acme/xfid.c:994). `asker` is the connection it +/// came on, which only the listener knows (src/9p_io.zig, `answerHeld`). +pub const Held = struct { asker: *anyopaque, req: Req }; + +/// Keeps a read that answered `.again`. An open waits with one read at a +/// time, as acme's window keeps one `eventx`: a newer read on the same open +/// takes the place of the older. +pub fn hold(p: *Pardes, req: Req, asker: *anyopaque) void { + var free: ?*?Held = null; + for (&p.fs.held) |*slot| { + const held = slot.* orelse { + if (free == null) free = slot; + continue; + }; + if (held.req.node == req.node and held.req.handle == req.handle) { + slot.* = .{ .asker = asker, .req = req }; + return; + } + } + // One slot per open that can wait, so a free one is always there. + if (free) |slot| slot.* = .{ .asker = asker, .req = req }; +} + // ---- nodes ---- pub const TopFile = enum(u4) { @@ -559,6 +585,11 @@ fn remove(p: *Pardes, req: Req) Reply { } fn release(p: *Pardes, req: Req) Reply { + // A read held on this open goes with it: a hangup pays its releases + // before the connection's slot is reused, so none outlives its asker. + for (&p.fs.held) |*slot| if (slot.*) |held| { + if (held.req.node == req.node and held.req.handle == req.handle) slot.* = null; + }; // The handle's bookkeeping runs whether or not the removal is allowed. const done = releaseHandle(p, req); return if (req.remove) remove(p, req) else done; diff --git a/src/pardes.zig b/src/pardes.zig index 29a9ab3a..a38eb837 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -72,6 +72,8 @@ pub const Turn = struct { /// A request that changes a pane was parked for want of quiet. parked: bool = false, wake_parked: ?*const fn (?*anyopaque) void = null, + /// Answers the reads the core holds, with the turn, as it is given up. + answer_held: ?*const fn (?*anyopaque) void = null, wake_ctx: ?*anyopaque = null, /// Bumped each time the editor has performed what the core asked of it, /// so a request that asked for something -- a save, a shell -- can be @@ -174,6 +176,9 @@ pub const Turn = struct { } fn release(t: *Turn) void { + // Whatever the holder just did may be what a held read waits for, + // and answering it takes the core, so before letting go. + if (t.answer_held) |f| f(t.wake_ctx); const woken = t.out == 0 and t.parked; if (woken) t.parked = false; t.mutex.unlock(t.io.?); -- cgit v1.3 From acd9e032a147f4aa7ad49110dc2f4fb945e7a9bb Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 20:14:04 -0300 Subject: Keep a pane's filesystem state on the Pane instead of a slot-indexed table addr, limit, the event queue and its readers, pty/data's queue, a waiting run and the /log announcement flag lived in p.fs.panes[slot], reset when the pane went; a reused slot is how the bug class came in. acme keeps the same state on its Window (editors/acme/dat.h:226-266), so now Pane.fs holds it: announced, retired (noteRetire, which still answers a waiting run and drops the listener count first) and freed with the pane itself. Co-Authored-By: Claude Opus 5.5 --- src/fs.zig | 14 +----------- src/ninep/addr.zig | 12 +++++------ src/ninep/events.zig | 49 ++++++++++++++++++++---------------------- src/ninep/pane.zig | 60 ++++++++++++++++++++++++++-------------------------- src/ninep/pty.zig | 33 ++++++++++++++--------------- src/ninep/tree.zig | 6 +++--- src/panes.zig | 5 +++++ src/pardes.zig | 23 +++++++++++--------- test/fs_bench.zig | 4 ++-- test/output.zig | 4 ++-- test/panes.zig | 2 +- 11 files changed, 102 insertions(+), 110 deletions(-) (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index 50a446dc..c2e88b10 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -586,7 +586,7 @@ test "virtual body writes can read their input from the same pane" { try write(p, path, pane.file.?.content); try std.testing.expectEqualStrings("same pane contents\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 2), pane.file.?.history.undo_len); - const events = &p.fs.panes[p.active].events; + const events = &p.panes[p.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")); @@ -1240,7 +1240,6 @@ pub const Namespace = struct { snapshots: [tree.screen.snapshot_slots]tree.screen.Snapshot = @splat(.{}), runs: [tree.pty.run_slots]tree.pty.Run = @splat(.{}), out: std.ArrayList(u8) = .empty, - panes: [MAX_PANES]tree.pane.State = @splat(.{}), listeners: u16 = 0, origin: u8 = 'K', /// Reads that found nothing yet, one per open that can wait: the log's @@ -1269,7 +1268,6 @@ pub const Namespace = struct { st.os_paths.deinit(gpa); for (st.snapshots) |snapshot| if (snapshot.bytes) |bytes| gpa.free(bytes); for (&st.runs) |*slot| slot.reset(gpa, 0); - for (&st.panes) |*pf| pf.deinit(gpa); st.log.deinit(gpa); st.out.deinit(gpa); } @@ -1292,16 +1290,6 @@ pub const Namespace = struct { st.out.ensureTotalCapacity(gpa, tree.out_reserve) catch {}; return &st.out; } - - pub fn forget(st: *Namespace, gpa: std.mem.Allocator, id: usize) void { - if (id >= MAX_PANES) return; - st.listeners -= @min(st.listeners, st.panes[id].readers); - st.panes[id].deinit(gpa); - } - - pub fn scripted(st: *const Namespace, id: usize) bool { - return id < MAX_PANES and st.panes[id].readers != 0; - } }; pub fn unmount(p: *Pardes, name: []const u8) !void { diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index 566e2364..e41d306e 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -247,13 +247,13 @@ test "the address language, form by form" { _ = th.wr(p, addr, "1"); _ = th.wr(p, addr, "."); - try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 4), p.fs.panes[0].addr.q1); + try testing.expectEqual(@as(u32, 0), p.panes[0].?.fs.addr.q0); + try testing.expectEqual(@as(u32, 4), p.panes[0].?.fs.addr.q1); _ = th.wr(p, addr, "$"); _ = th.wr(p, addr, "?o?"); - try testing.expectEqual(@as(u32, 6), p.fs.panes[0].addr.q0); // the `o` in "two" - try testing.expectEqual(@as(u32, 7), p.fs.panes[0].addr.q1); + try testing.expectEqual(@as(u32, 6), p.panes[0].?.fs.addr.q0); // the `o` in "two" + try testing.expectEqual(@as(u32, 7), p.panes[0].?.fs.addr.q1); // limit is its own file: copying addr onto it bounds the search, and // truncating it lifts the bound again. @@ -264,12 +264,12 @@ test "the address language, form by form" { const pair = th.rd(p, addr, 0, 64).bytes; @memcpy(copied[0..pair.len], pair); _ = th.wr(p, limit, copied[0..pair.len]); - try testing.expectEqual(@as(u32, 4), p.fs.panes[0].limit.?.q1); + try testing.expectEqual(@as(u32, 4), p.panes[0].?.fs.limit.?.q1); try testing.expectEqualStrings(" 0 4 ", th.rd(p, limit, 0, 64).bytes); _ = th.wr(p, addr, "#0"); try testing.expectEqual(E.INVAL, th.wr(p, addr, "/three/").errno()); _ = th.call(p, .{ .tag = 6, .op = .setattr, .node = limit, .truncate = true }); - try testing.expect(p.fs.panes[0].limit == null); + try testing.expect(p.panes[0].?.fs.limit == null); _ = th.wr(p, addr, "#0"); try testing.expectEqual(Status.ok, th.wr(p, addr, "/three/").reply.status); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 6b8c744e..78945c5c 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -115,19 +115,14 @@ pub fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply { pub const LogKind = enum { new, del, rename, save }; -/// A pane installed now is announced by `announce` once the update that made -/// it has finished, when its name is known. -pub fn noteInstall(p: *Pardes, id: usize) void { - if (id < MAX_PANES) p.fs.panes[id].unannounced = true; -} - -/// A pane leaving; one never announced leaves silently. -pub fn noteRetire(p: *Pardes, id: usize, pane: *Pane) void { - if (id >= MAX_PANES) return; - tree.pty.shellGone(p, id); +/// A pane leaving, before its state goes with it; one never announced +/// leaves silently. +pub fn noteRetire(p: *Pardes, pane: *Pane) void { + tree.pty.shellGone(p, pane); p.fs.news = true; // a read held on its event or pty/data hears it went - if (p.fs.panes[id].unannounced) { - p.fs.panes[id].unannounced = false; + p.fs.listeners -|= pane.fs.readers; + if (pane.fs.unannounced) { + pane.fs.unannounced = false; return; } noteLog(p, .del, pane); @@ -135,11 +130,11 @@ pub fn noteRetire(p: *Pardes, id: usize, pane: *Pane) void { /// Called at the end of every update: reports the panes installed by it. pub fn announce(p: *Pardes) void { - for (p.panes, 0..) |slot, id| { - const pf = &p.fs.panes[id]; - if (!pf.unannounced) continue; - pf.unannounced = false; - if (slot) |pane| noteLog(p, .new, pane); + for (p.panes) |slot| { + const pane = slot orelse continue; + if (!pane.fs.unannounced) continue; + pane.fs.unannounced = false; + noteLog(p, .new, pane); } } @@ -346,7 +341,8 @@ pub fn diffSpan(old: []const u8, new: []const u8) Span { } pub fn noteReplace(p: *Pardes, id: usize, on_tag: bool, old: []const u8, new: []const u8) void { - if (!p.fs.scripted(id)) return; + const pane = p.panes[id] orelse return; + if (pane.fs.readers == 0) return; const span = diffSpan(old, new); if (span.removed == 0 and span.inserted == 0) return; if (span.removed > 0) _ = noteAction( @@ -378,17 +374,18 @@ pub fn noteAction( flag: u32, text: []const u8, ) bool { - if (!p.fs.scripted(id)) return false; + const pane = p.panes[id] orelse return false; + if (pane.fs.readers == 0) return false; var buf: [max_record_text + 64]u8 = undefined; const record = formatRecord(&buf, p.fs.origin, action, q0, q1, flag, text); - p.fs.panes[id].events.push(p.gpa, record); + pane.fs.events.push(p.gpa, record); p.fs.news = true; return true; } pub fn notePtyOutput(p: *Pardes, id: usize, bytes: []const u8) void { if (id >= MAX_PANES or bytes.len == 0) return; - const pf = &p.fs.panes[id]; + const pf = &(p.panes[id] orelse return).fs; if (pf.pty_readers == 0) return; var off: usize = 0; while (off < bytes.len) { @@ -486,7 +483,7 @@ test "event records are acme's bytes, one per read, and .again when empty" { const event = Node.of(serial, .event); _ = noteAction(p, 0, .body_exec, 1, 4, flag_builtin, "sg "); - try testing.expect(p.fs.panes[0].events.empty()); + try testing.expect(p.panes[0].?.fs.events.empty()); const h = call(p, .{ .tag = 10, .op = .open, .node = event }); try testing.expect(h.reply.handle != 0); @@ -570,19 +567,19 @@ test "one event reader at a time, and a writer still holds the pane" { try testing.expectEqualStrings(tree.e_in_use, second.reply.ename); const writer = call(p, .{ .tag = 13, .op = .open, .node = event, .omode = 1 }); try testing.expectEqual(Status.ok, writer.reply.status); - try testing.expectEqual(@as(u16, 2), p.fs.panes[0].readers); + try testing.expectEqual(@as(u16, 2), p.panes[0].?.fs.readers); try testing.expectEqual(@as(u16, 2), p.fs.listeners); _ = call(p, .{ .tag = 14, .op = .release, .node = event, .handle = writer.reply.handle }); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].readers); - try testing.expect(p.fs.scripted(0)); + try testing.expectEqual(@as(u16, 1), p.panes[0].?.fs.readers); + try testing.expect(p.panes[0].?.fs.readers != 0); _ = call(p, .{ .tag = 15, .op = .release, .node = Node.of(serialOf(p), .body) }); try testing.expectEqual(@as(u16, 1), p.fs.listeners); _ = call(p, .{ .tag = 16, .op = .release, .node = event, .handle = reader.reply.handle }); try testing.expectEqual(@as(u16, 0), p.fs.listeners); - try testing.expect(!p.fs.scripted(0)); + try testing.expect(p.panes[0].?.fs.readers == 0); _ = call(p, .{ .tag = 17, .op = .release, .node = event }); try testing.expectEqual(@as(u16, 0), p.fs.listeners); // Once it closed, the next reader gets in. diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 61073a55..b07ee038 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -186,7 +186,7 @@ pub fn wholeUtf8(data: []const u8) usize { return data.len; } -pub fn spliceBody(p: *Pardes, id: usize, pane: *Pane, q0: usize, q1: usize, bytes: []const u8) ?usize { +pub fn spliceBody(p: *Pardes, pane: *Pane, q0: usize, q1: usize, bytes: []const u8) ?usize { const f = fileOf(pane) orelse return null; const take = if (bytes.len == 0) 0 else wholeUtf8(bytes); const lo = @min(q0, f.content.len); @@ -195,7 +195,7 @@ pub fn spliceBody(p: *Pardes, id: usize, pane: *Pane, q0: usize, q1: usize, byte @memcpy(new[0..lo], f.content[0..lo]); @memcpy(new[lo..][0..take], bytes[0..take]); @memcpy(new[lo + take ..], f.content[hi..]); - if (!p.fs.panes[id].nomark) panes.File.pushUndo(p, pane); + if (!pane.fs.nomark) panes.File.pushUndo(p, pane); panes.File.setContent(p, f, new); return take; } @@ -208,7 +208,7 @@ pub const range_len: u64 = 24; pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pane = p.panes[id] orelse return 0; - const pf = &p.fs.panes[id]; + const pf = &pane.fs; return switch (f) { .body, .data, .xdata => bodyOf(pane).len, .tag => tagOf(p, pane).len, @@ -265,7 +265,7 @@ pub fn indexLen(p: *Pardes) u64 { // ---- reads ---- pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { - const pf = &p.fs.panes[id]; + const pf = &pane.fs; return switch (file) { .name => name: { const out = p.fs.stage(p.gpa); @@ -379,10 +379,10 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .body => writeBody(p, req, id, pane), .tag => writeTag(p, req, pane), .ctl => ctl.writePane(p, req, pane), - .addr, .dot, .limit => writeRange(p, req, id, pane, file), - .data, .xdata => writeData(p, req, id, pane), - .sel => writeSel(p, req, id, pane), - .dirty, .mark, .scroll => writeFlag(p, req, id, pane, file), + .addr, .dot, .limit => writeRange(req, pane, file), + .data, .xdata => writeData(p, req, pane), + .sel => writeSel(p, req, pane), + .dirty, .mark, .scroll => writeFlag(p, req, pane, file), .look, .exec => ctl.command(p, req, pane.serial, file == .exec), .event => events.writeEvent(p, req, id), .errors => if (appendErrors(p, id, req.data)) |took| @@ -404,9 +404,9 @@ fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } const at = bodyOf(pane).len; - const take = spliceBody(p, id, pane, at, at, req.data) orelse + const take = spliceBody(p, pane, at, at, req.data) orelse return Reply.fail(req.tag, E.NOMEM); - if (!p.fs.panes[id].noscroll) showOffset(pane, at + take); + if (!pane.fs.noscroll) showOffset(pane, at + take); return .{ .tag = req.tag, .written = @intCast(take) }; } @@ -422,14 +422,14 @@ fn writeTag(p: *Pardes, req: Req, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } -fn writeData(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { +fn writeData(p: *Pardes, req: Req, pane: *Pane) Reply { if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); - const pf = &p.fs.panes[id]; + const pf = &pane.fs; clampAddr(pf, bodyOf(pane).len); const q0: usize = pf.addr.q0; const q1: usize = @max(q0, @as(usize, pf.addr.q1)); const before = dotOf(pane); - const take = spliceBody(p, id, pane, q0, q1, req.data) orelse + const take = spliceBody(p, pane, q0, q1, req.data) orelse return Reply.fail(req.tag, E.NOMEM); setDot(pane, shiftBy(before, clip(q0), clip(q1 - q0), clip(take))); pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }; @@ -437,12 +437,12 @@ fn writeData(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } -fn writeSel(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { +fn writeSel(p: *Pardes, req: Req, pane: *Pane) Reply { if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); const d = dotOf(pane); const q0: usize = d.q0; const q1: usize = @max(q0, @as(usize, d.q1)); - const take = spliceBody(p, id, pane, q0, q1, req.data) orelse + const take = spliceBody(p, pane, q0, q1, req.data) orelse return Reply.fail(req.tag, E.NOMEM); setDot(pane, .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }); return .{ .tag = req.tag, .written = @intCast(take) }; @@ -470,8 +470,8 @@ fn rangeOf(pf: *State, text: []const u8, data: []const u8) ?State.Range { return if (a.i < expr.len) null else r; } -fn writeRange(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { - const pf = &p.fs.panes[id]; +fn writeRange(req: Req, pane: *Pane, file: PaneFile) Reply { + const pf = &pane.fs; const text = bodyOf(pane); clampAddr(pf, text.len); const r = rangeOf(pf, text, req.data) orelse return tree.failText(req.tag, E.INVAL, tree.e_bad_addr); @@ -495,9 +495,9 @@ fn flagOf(data: []const u8) ?bool { return null; } -fn writeFlag(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply { +fn writeFlag(p: *Pardes, req: Req, pane: *Pane, file: PaneFile) Reply { const on = flagOf(req.data) orelse return Reply.fail(req.tag, E.INVAL); - const pf = &p.fs.panes[id]; + const pf = &pane.fs; switch (file) { .dirty => { const f = fileOf(pane) orelse return Reply.fail(req.tag, E.INVAL); @@ -569,13 +569,13 @@ pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { if (text.len == 0) return 0; const pane = p.panes[id] orelse return null; const dir = dirOf(pane); - for (p.panes, 0..) |slot, i| { + for (p.panes) |slot| { const q = slot orelse continue; const qf = fileOf(q) orelse continue; const o = qf.output orelse continue; if (std.meta.activeTag(o.from) != .errors) continue; if (!std.mem.eql(u8, std.fs.path.dirname(qf.path) orelse "", dir)) continue; - return spliceBody(p, i, q, qf.content.len, qf.content.len, text); + return spliceBody(p, q, qf.content.len, qf.content.len, text); } const free = p.freeSlot() orelse return null; const content = p.gpa.dupe(u8, text) catch return null; @@ -590,11 +590,11 @@ pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { /// Truncation empties whatever the file holds: the body, the tag's editable /// tail (acme's `cleartag`), a range. Every other setattr just answers fresh /// attributes. -pub fn truncate(p: *Pardes, id: usize, pane: *Pane, file: PaneFile) tree.Status { - const pf = &p.fs.panes[id]; +pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { + const pf = &pane.fs; switch (file) { .body, .data, .xdata => if (fileOf(pane) != null) { - _ = spliceBody(p, id, pane, 0, bodyOf(pane).len, "") orelse return .err; + _ = spliceBody(p, pane, 0, bodyOf(pane).len, "") orelse return .err; pf.addr = .{}; setDot(pane, .{}); }, @@ -753,8 +753,8 @@ test "data and xdata read from addr, move it, and write through it" { _ = wr(p, addr, "#0"); try testing.expectEqualStrings("one", rd(p, data, 0, 3).bytes); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); + try testing.expectEqual(@as(u32, 3), p.panes[0].?.fs.addr.q0); + try testing.expectEqual(@as(u32, 3), p.panes[0].?.fs.addr.q1); _ = wr(p, addr, "1"); try testing.expectEqualStrings("one\n", rd(p, xdata, 0, 100).bytes); @@ -765,7 +765,7 @@ test "data and xdata read from addr, move it, and write through it" { const w = wr(p, data, "ONE\n"); try testing.expectEqual(@as(u32, 4), w.reply.written); try testing.expectEqualStrings("ONE\ntwo\n", p.panes[0].?.file.?.content); - try testing.expectEqual(@as(u32, 4), p.fs.panes[0].addr.q0); + try testing.expectEqual(@as(u32, 4), p.panes[0].?.fs.addr.q0); } test "data never splits a grapheme, in either direction" { @@ -802,8 +802,8 @@ test "sel reads the selection and writing sel replaces it" { _ = wr(p, addr_node, "#0"); _ = wr(p, addr_node, " 0 3 "); - try testing.expectEqual(@as(u32, 0), p.fs.panes[0].addr.q0); - try testing.expectEqual(@as(u32, 3), p.fs.panes[0].addr.q1); + try testing.expectEqual(@as(u32, 0), p.panes[0].?.fs.addr.q0); + try testing.expectEqual(@as(u32, 3), p.panes[0].?.fs.addr.q1); // A truncation empties dot; an address expression addresses it. _ = call(p, .{ .tag = 9, .op = .setattr, .node = dot, .truncate = true }); @@ -823,7 +823,7 @@ test "the flag files read and write the state acme kept behind ctl verbs" { defer p.deinit(); const serial = serialOf(p); const pane = p.panes[0].?; - const pf = &p.fs.panes[0]; + const pf = &p.panes[0].?.fs; const dirty = Node.of(serial, .dirty); const mark = Node.of(serial, .mark); const scroll = Node.of(serial, .scroll); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 2a38f1f0..ddb7bcd1 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -176,7 +176,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); if (line.len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); - const pf = &p.fs.panes[id]; + const pf = &pane.fs; const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); const marks = &state.stream.handler; if (pf.unmarked) { @@ -230,8 +230,8 @@ pub fn releaseRun(p: *Pardes, req: Req) Reply { const slot = runOf(p, req) orelse return .{ .tag = req.tag }; const idx: u8 = @intCast(slot - &p.fs.runs[0]); // The command runs on in the shell; nobody is waiting for it any more. - for (&p.fs.panes) |*pf| if (pf.run == idx) { - pf.run = null; + for (p.panes) |live| if (live) |pane| if (pane.fs.run == idx) { + pane.fs.run = null; }; slot.reset(p.gpa, 0); return .{ .tag = req.tag }; @@ -244,7 +244,7 @@ pub fn releaseRun(p: *Pardes, req: Req) Reply { pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { if (comptime !pardes.panes.Terminal.enabled) return; const state = pane.terminal orelse return; - const pf = &p.fs.panes[id]; + const pf = &pane.fs; const slot = &p.fs.runs[pf.run orelse return]; const marks = &state.stream.handler; if (marks.phase != .input) return; @@ -323,11 +323,10 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { /// The pane closed or its shell was replaced: the command's end will never /// be reported, so the run says so instead of waiting forever. -pub fn shellGone(p: *Pardes, id: usize) void { - const pf = &p.fs.panes[id]; - const idx = pf.run orelse return; +pub fn shellGone(p: *Pardes, pane: *Pane) void { + const idx = pane.fs.run orelse return; answer(p, &p.fs.runs[idx], "error shell gone", .{}); - pf.run = null; + pane.fs.run = null; } const e_bad_line = "bad command line"; @@ -388,7 +387,7 @@ test "a pane that is not a terminal has no pty/ at all" { .op = .open, .node = Node.of(serial, .pty_data), }).errno()); - try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); + try testing.expectEqual(@as(u16, 0), p.panes[0].?.fs.pty_readers); var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); @@ -574,18 +573,18 @@ test "pty/data writes at the shell and reads the raw stream" { p.update(.{ .output = .{ .pane = 0, .bytes = "unwatched" } }); while (p.nextEffect()) |_| {} - try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.items.len); + try testing.expectEqual(@as(usize, 0), p.panes[0].?.fs.pty_out.buf.items.len); try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); // An open that only writes is not a reader: nothing queues for it. const writer = call(p, .{ .tag = 4, .op = .open, .node = data, .omode = 1 }); - try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); + try testing.expectEqual(@as(u16, 0), p.panes[0].?.fs.pty_readers); _ = call(p, .{ .tag = 4, .op = .release, .node = data, .handle = writer.reply.handle }); const reader = call(p, .{ .tag = 5, .op = .open, .node = data }); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers); + try testing.expectEqual(@as(u16, 1), p.panes[0].?.fs.pty_readers); try testing.expectEqual(@as(u16, 0), p.fs.listeners); - try testing.expect(!p.fs.scripted(0)); + try testing.expect(p.panes[0].?.fs.readers == 0); p.update(.{ .output = .{ .pane = 0, .bytes = "hello" } }); while (p.nextEffect()) |_| {} @@ -603,8 +602,8 @@ test "pty/data writes at the shell and reads the raw stream" { p.update(.{ .output = .{ .pane = 0, .bytes = "orphan" } }); while (p.nextEffect()) |_| {} _ = call(p, .{ .tag = 6, .op = .release, .node = data, .handle = reader.reply.handle }); - try testing.expectEqual(@as(u16, 0), p.fs.panes[0].pty_readers); - try testing.expectEqual(@as(usize, 0), p.fs.panes[0].pty_out.buf.capacity); + try testing.expectEqual(@as(u16, 0), p.panes[0].?.fs.pty_readers); + try testing.expectEqual(@as(usize, 0), p.panes[0].?.fs.pty_out.buf.capacity); try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); // A second reader would take half the stream from the first: refused. @@ -612,7 +611,7 @@ test "pty/data writes at the shell and reads the raw stream" { const second = call(p, .{ .tag = 8, .op = .open, .node = data, .omode = 2 }); try testing.expectEqual(Status.err, second.reply.status); try testing.expectEqualStrings(tree.e_in_use, second.reply.ename); - try testing.expectEqual(@as(u16, 1), p.fs.panes[0].pty_readers); + try testing.expectEqual(@as(u16, 1), p.panes[0].?.fs.pty_readers); p.update(.{ .output = .{ .pane = 0, .bytes = "still" } }); while (p.nextEffect()) |_| {} try testing.expectEqualStrings("still", rd(p, data, 0, 64).bytes); @@ -732,7 +731,7 @@ test "the pty queue drops the oldest at its cap" { const rest: [4096]u8 = @splat('B'); events.notePtyOutput(p, 0, &oldest); for (0..events.queue_cap / rest.len + 4) |_| events.notePtyOutput(p, 0, &rest); - const q = &p.fs.panes[0].pty_out; + const q = &p.panes[0].?.fs.pty_out; try testing.expect(q.buf.items.len - q.head <= events.queue_cap); var seen: usize = 0; diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 3ebea669..f08d20c8 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -543,7 +543,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { .pane => |t| { const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); const pn = p.panes[id].?; - const pf = &p.fs.panes[id]; + const pf = &pn.fs; if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); switch (t.file) { .body => if (pn.isTerminal()) return screen.openSnapshot(p, req, false), @@ -605,7 +605,7 @@ fn releaseHandle(p: *Pardes, req: Req) Reply { if (t.file == .pty_run) return pty.releaseRun(p, req); if (t.file != .event and t.file != .pty_data) return .{ .tag = req.tag }; const id = p.paneBySerial(t.serial) orelse return .{ .tag = req.tag }; - const pf = &p.fs.panes[id]; + const pf = &p.panes[id].?.fs; if (t.file == .pty_data) { if (req.handle != reader_handle or pf.pty_readers == 0) return .{ .tag = req.tag }; pf.pty_readers -= 1; @@ -626,7 +626,7 @@ fn setattr(p: *Pardes, req: Req, target: Target) Reply { if (req.truncate) switch (target) { .pane => |t| { const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - if (pane.truncate(p, id, p.panes[id].?, t.file) != .ok) return Reply.fail(req.tag, E.NOMEM); + if (pane.truncate(p, p.panes[id].?, t.file) != .ok) return Reply.fail(req.tag, E.NOMEM); }, .top => {}, }; diff --git a/src/panes.zig b/src/panes.zig index 68e03a04..08310830 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -103,6 +103,11 @@ pub const Pane = struct { terminal: ?*Terminal.State = null, gpa: std.mem.Allocator, serial: u32 = 0, + /// What the control filesystem keeps of this pane -- addr and limit, the + /// event queue and its readers, a run waiting on the shell -- lives and + /// dies with it, as acme keeps the same on its Window + /// (editors/acme/dat.h:226-266). + fs: pardes.ctlfs.pane.State = .{}, mode: Mode = .normal, vweight: f32 = 1, /// A folded pane keeps its expansion weight, but occupies only its tag row. diff --git a/src/pardes.zig b/src/pardes.zig index a38eb837..7ae9cf32 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -6826,8 +6826,7 @@ pub const Pardes = struct { const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf(); for (p.panes, 0..) |slot, id| if (slot == pane) { if (watched) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); - ctlfs.events.noteRetire(p, id, pane); - p.fs.forget(p.gpa, id); + ctlfs.events.noteRetire(p, pane); // ...and so do bytes still queued for the pty it no longer has. p.dropPendingWrite(id); }; @@ -6854,6 +6853,7 @@ pub const Pardes = struct { for (pane.ed_redo[0..pane.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); panes.Terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); + pane.fs.deinit(p.gpa); p.gpa.destroy(pane); } @@ -6872,7 +6872,9 @@ pub const Pardes = struct { pane.serial = p.next_serial; p.rects[id] = .{}; p.panes[id] = pane; - ctlfs.events.noteInstall(p, id); + // /log hears of it once the update that made it ends, when it has + // its file, name and place (`ctlfs.events.announce`). + pane.fs.unannounced = true; } pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { @@ -7029,10 +7031,10 @@ pub const Pardes = struct { } pub fn acknowledgeShell(p: *Pardes, id: usize, executable: []const u8, prompt_marks: bool) void { - if (id < MAX_PANES) { - ctlfs.pty.shellGone(p, id); // a respawn replaced whatever ran - p.fs.panes[id].unmarked = !prompt_marks; - } + if (id < MAX_PANES) if (p.panes[id]) |pane| { + ctlfs.pty.shellGone(p, pane); // a respawn replaced whatever ran + pane.fs.unmarked = !prompt_marks; + }; if (id < MAX_PANES) panes.Terminal.shellSpawned(p, id, prompt_marks); if (p.settings.shell.effective.set(executable)) p.settings.shell.pending = false; @@ -7913,9 +7915,9 @@ pub const Pardes = struct { if (p.fs.listeners == 0) return; for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; - if (!p.fs.scripted(id)) continue; + if (pane.fs.readers == 0) continue; const tag = p.tagText(p.scratch.allocator(), pane) catch continue; - const snap = &p.fs.panes[id].tag_snap; + const snap = &pane.fs.tag_snap; if (std.mem.eql(u8, snap.items, tag)) continue; if (snap.capacity != 0 or snap.items.len != 0) ctlfs.events.noteReplace(p, id, true, snap.items, tag); @@ -12462,7 +12464,8 @@ pub const Pardes = struct { operand: PointerOperand, chorded: bool, ) bool { - if (!p.fs.scripted(id)) return false; + const scripted = p.panes[id] orelse return false; + if (scripted.fs.readers == 0) return false; const is_look = cmd == config.look_cmd; const action: ctlfs.events.Action = if (is_look) (if (on_tag) .tag_look else .body_look) diff --git a/test/fs_bench.zig b/test/fs_bench.zig index 74b7b5da..00601ca3 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -285,7 +285,7 @@ pub fn main(init: std.process.Init) !void { const initial_bytes = pane.file.?.content.len; key_body_bytes = initial_bytes; if (scripted) { - keys.core.fs.panes[keys.file_id].readers = 1; + keys.core.panes[keys.file_id].?.fs.readers = 1; keys.core.fs.listeners = 1; } counting.allocations = 0; @@ -297,7 +297,7 @@ pub fn main(init: std.process.Init) !void { const elapsed = nowNs() - start; if (pane.file.?.content.len != initial_bytes + key_reps or pane.cur_col != key_reps or !std.mem.allEqual(u8, pane.file.?.content[0..key_reps], 'x')) return error.MissingKeystroke; - const events = &keys.core.fs.panes[keys.file_id].events; + const events = &keys.core.panes[keys.file_id].?.fs.events; if (scripted) for (0..key_reps) |i| { var buf: [64]u8 = undefined; const expected = try std.fmt.bufPrint(&buf, "KI{d} {d} 0 1 x\n", .{ i, i + 1 }); diff --git a/test/output.zig b/test/output.zig index 7c80e105..cda5f556 100644 --- a/test/output.zig +++ b/test/output.zig @@ -1082,7 +1082,7 @@ test "identical result refresh keeps warm content caches without allocation" { try std.testing.expectEqual(id, source.search_pane.?); try std.testing.expectEqual(@as(usize, 1), source.search_row.?); try std.testing.expectEqual(result.serial, p.look_walk_owner.?); - try std.testing.expect(p.fs.panes[id].events.empty()); + try std.testing.expect(p.panes[id].?.fs.events.empty()); } try panes.Output.fillResults(p, 0, "/tmp", .{ .query = .references }, "changed", try p.gpa.dupe(u8, "short\n"), null); @@ -1099,7 +1099,7 @@ test "identical result refresh keeps warm content caches without allocation" { try std.testing.expectEqual(@as(usize, 0), file.scroll); try std.testing.expectEqual(@as(i32, 0), result.hscroll); try std.testing.expect(source.search_row == null); - const events = &p.fs.panes[id].events; + const events = &p.panes[id].?.fs.events; try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "KD")); events.pop(); try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "KI")); diff --git a/test/panes.zig b/test/panes.zig index 2f307cb5..e865641f 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -946,7 +946,7 @@ const ClickCursorTests = struct { defer _ = pardes.ctlfs.handle(p, .{ .tag = 0, .op = .release, .node = event_node, .handle = opened.handle }); for ([_]pardes.Mouse.Button{ .middle, .right }) |button| { - const events = &p.fs.panes[0].events; + const events = &p.panes[0].?.fs.events; while (!events.empty()) events.pop(); click(p, button, x + 2, y + 2); const selected = events.peek() orelse return error.MissingSelectionGesture; -- cgit v1.3 From 7dc3891ed574d6e96548f592b09b0f8abc87ae2a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 20:20:27 -0300 Subject: Keep what each open holds in one table of open records Snapshots (and /log's cursor), runs, and the reader_handle constants for event and pty/data each reused the open handle and each validated handle and node on its own. Now p.fs.opens is one table of 64 records, each the node it was opened on and a tagged union of what it holds, like lib9p's per-fid aux and acme's Fid (editors/acme/dat.h:373-385): one lookup (openOf), one release, ENFILE when full. A held read lives in its open's record, so it goes with the release. Opens that hold nothing answer handle 0 and take no record. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 7 +- src/9p_io.zig | 22 ++--- src/fs.zig | 17 ++-- src/ninep/events.zig | 67 ++++++++------- src/ninep/pane.zig | 7 +- src/ninep/pty.zig | 63 ++++---------- src/ninep/screen.zig | 79 +++++------------- src/ninep/tree.zig | 231 ++++++++++++++++++++++++++++++++------------------- 8 files changed, 243 insertions(+), 250 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 0d6ffcda..64ac9ba1 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -232,8 +232,11 @@ never writes `follow`, so it sees nothing new: use the follow open instead. `/sc `cols`, `rows`, `cursor`, a `styles` table, and row-major `cells` of `[grapheme, style_index]`. Each open freezes one frame until close. A terminal `body` freezes its history on the first read of each open handle; -`pty/data` streams live output. Screen and terminal-body snapshots share 32 -handle slots, released on close or disconnect. +`pty/data` streams live output. An open that holds something between open +and close -- a frozen screen, terminal body or log, a run, an `event` or +`pty/data` open -- takes one of 64 records (lib9p's per-fid aux, acme's +Fid), released on close or disconnect; past that such an open fails with +`ENFILE`. Other opens hold nothing and are not counted. `-Dembed-sources=true` embeds the editor's sources and serves them under `/src` (and `/shaders` on GUI builds). `EffectCode ` lists the current diff --git a/src/9p_io.zig b/src/9p_io.zig index 6182ca75..7c366aa8 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -229,7 +229,9 @@ pub const Listener = struct { if (req.op == .release and quiet) l.collectOs(); // A read with nothing yet stays parked in the engine, and the core // keeps it to answer when what it waits on has something. - if (reply.status == .again and req.op == .read) pardes.ctlfs.hold(core, req, conn); + if (reply.status == .again and req.op == .read) if (pardes.ctlfs.openOf(core, req)) |o| { + o.held = .{ .asker = conn, .req = req }; + }; if (!pardes.ctlfs.changesPane(req)) return conn.reply(&reply, core.fsPayload(reply)); // The editor draws the change and performs what it asked for; when // it asked for something -- a save, a shell, a watch -- the answer @@ -262,8 +264,8 @@ pub const Listener = struct { const core = l.core; if (!core.fs.news) return; core.fs.news = false; - for (&core.fs.held) |*slot| { - const held = slot.* orelse continue; + for (&core.fs.opens) |*o| { + const held = o.held orelse continue; const conn: *Runner.Conn = @ptrCast(@alignCast(held.asker)); conn.lock(); const parked: ?bool = for (conn.engine.slots) |sl| { @@ -272,13 +274,13 @@ pub const Listener = struct { // Gone (flushed, answered, hung up) it is forgotten; out being // asked again, the asking answers it. if (parked != true) { - if (parked == null) slot.* = null; + if (parked == null) o.held = null; conn.unlock(); continue; } const reply = core.serveFs(held.req); if (reply.status != .again) { - slot.* = null; + o.held = null; conn.engine.reply(&reply, core.fsPayload(reply)); } conn.unlock(); @@ -1280,7 +1282,7 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r l.reset(p); try testing.expectEqual(@as(usize, 0), l.runner.count()); for (&l.conns, 0..) |conn, i| try testing.expect(!l.live(@intCast(i)) and !conn.draining); - for (p.fs.snapshots) |snapshot| try testing.expect(snapshot.node == 0); + for (p.fs.opens) |o| try testing.expect(o.node == 0); } }; } @@ -1409,8 +1411,8 @@ test "a held read is answered when the log has news, and a flushed one spends no const deadline = Client.nowMs() + Client.budget_ms; while (Client.nowMs() < deadline) { pardes.turn.wake(); - const any = for (core.fs.held) |slot| { - if (slot != null) break true; + const any = for (core.fs.opens) |o| { + if (o.held != null) break true; } else false; pardes.turn.rest(); if (any) return; @@ -1450,8 +1452,8 @@ test "a held read is answered when the log has news, and a flushed one spends no try testing.expect(std.mem.indexOf(u8, answered.result.read, "while held") != null); s.drop(1); pardes.turn.wake(); - const left = for (p.fs.held) |slot| { - if (slot != null) break true; + const left = for (p.fs.opens) |o| { + if (o.held != null) break true; } else false; pardes.turn.rest(); try testing.expect(!left); diff --git a/src/fs.zig b/src/fs.zig index c2e88b10..4f395b1c 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -321,7 +321,7 @@ test "virtual writes enforce permissions even when contents are empty" { 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.snapshots) |snapshot| try std.testing.expect(snapshot.node == 0); + 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" { @@ -480,10 +480,7 @@ test "bounded reads release terminal snapshots after success and size refusal" { 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.snapshots) |snapshot| { - try std.testing.expectEqual(@as(u64, 0), snapshot.node); - try std.testing.expect(snapshot.bytes == null); - } + 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" { @@ -1237,14 +1234,11 @@ pub const Namespace = struct { mounts: std.ArrayList(Mount) = .empty, node_name: [16]u8 = undefined, os_paths: std.ArrayList(OsPath) = .empty, - snapshots: [tree.screen.snapshot_slots]tree.screen.Snapshot = @splat(.{}), - runs: [tree.pty.run_slots]tree.pty.Run = @splat(.{}), + /// What each open holds between its open and its release. + opens: [tree.open_slots]tree.Open = @splat(.{}), out: std.ArrayList(u8) = .empty, listeners: u16 = 0, origin: u8 = 'K', - /// Reads that found nothing yet, one per open that can wait: the log's - /// and a run's opens, and one event and one pty/data reader a pane. - held: [tree.screen.snapshot_slots + tree.pty.run_slots + 2 * MAX_PANES]?tree.Held = @splat(null), /// Something a held read may be waiting on changed since they were last /// answered: a record queued, a run answered, a pane gone. news: bool = false, @@ -1266,8 +1260,7 @@ pub const Namespace = struct { st.mounts.deinit(gpa); for (st.os_paths.items) |entry| gpa.free(entry.path); st.os_paths.deinit(gpa); - for (st.snapshots) |snapshot| if (snapshot.bytes) |bytes| gpa.free(bytes); - for (&st.runs) |*slot| slot.reset(gpa, 0); + for (&st.opens) |*o| o.deinit(gpa); st.log.deinit(gpa); st.out.deinit(gpa); } diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 78945c5c..8f66cf3a 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -169,37 +169,42 @@ fn pushLog(p: *Pardes, record: []u8) void { p.fs.news = true; } +/// What an open of /log holds. +pub const LogOpen = struct { + /// The ring's text when it was opened. + bytes: []const u8 = &.{}, + /// This open waits for records after `bytes`, from `next`. + follow: bool = false, + next: u64 = 0, + /// How much of record `next` a short read already took. + part: u32 = 0, + /// How much of `bytes` this open has read. Reads walk it as a stream once + /// following and ignore their offset, since `exec 3<>log; echo follow + /// >&3` leaves the shared offset past the word it wrote. + pos: u64 = 0, +}; + /// An open freezes the ring's text, so `cat log` answers what happened lately /// and ends; `next` is where a follower picks up after it. -pub fn openLog(p: *Pardes, req: Req) Reply { - for (&p.fs.snapshots, 0..) |*slot, i| { - if (slot.node != 0) continue; - var text: std.ArrayList(u8) = .empty; - var at = p.fs.log.head; - const items = p.fs.log.buf.items; - var n: u64 = 0; - while (at + 4 <= items.len) : (n += 1) { - const len = std.mem.readInt(u32, items[at..][0..4], .little); - text.appendSlice(p.gpa, items[at + 4 ..][0..len]) catch { - text.deinit(p.gpa); - return Reply.fail(req.tag, E.NOMEM); - }; - at += 4 + len; - } - const bytes = text.toOwnedSlice(p.gpa) catch return Reply.fail(req.tag, E.NOMEM); - slot.* = .{ .node = req.node, .bytes = bytes, .next = p.fs.log.dropped + n }; - return .{ .tag = req.tag, .handle = @intCast(i + 1) }; +pub fn freezeLog(p: *Pardes) !LogOpen { + var text: std.ArrayList(u8) = .empty; + errdefer text.deinit(p.gpa); + var at = p.fs.log.head; + const items = p.fs.log.buf.items; + var n: u64 = 0; + while (at + 4 <= items.len) : (n += 1) { + const len = std.mem.readInt(u32, items[at..][0..4], .little); + try text.appendSlice(p.gpa, items[at + 4 ..][0..len]); + at += 4 + len; } - return Reply.fail(req.tag, E.NFILE); + return .{ .bytes = try text.toOwnedSlice(p.gpa), .next = p.fs.log.dropped + n }; } /// Past the frozen text, a following open reads newer records one per read, -/// parked until one arrives; one that fell behind the ring hears `lost N`. +/// held until one arrives; one that fell behind the ring hears `lost N`. pub fn readLog(p: *Pardes, req: Req) Reply { - if (req.handle == 0 or req.handle > p.fs.snapshots.len) return Reply.fail(req.tag, E.INVAL); - const slot = &p.fs.snapshots[req.handle - 1]; - if (slot.node != req.node) return Reply.fail(req.tag, E.INVAL); - const frozen = slot.bytes orelse &.{}; + const slot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.log; + const frozen = slot.bytes; const out = p.fs.stage(p.gpa); if (!slot.follow or slot.pos < frozen.len) { // Until `follow`, the frozen text is a file like any other: `tail -n` @@ -243,9 +248,7 @@ pub fn readLog(p: *Pardes, req: Req) Reply { /// `follow`, written to an open of the log, makes that open wait for newer /// records instead of ending; closing it is the way back. pub fn writeLog(p: *Pardes, req: Req) Reply { - if (req.handle == 0 or req.handle > p.fs.snapshots.len) return Reply.fail(req.tag, E.INVAL); - const slot = &p.fs.snapshots[req.handle - 1]; - if (slot.node != req.node) return Reply.fail(req.tag, E.INVAL); + const slot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.log; if (!std.mem.eql(u8, std.mem.trim(u8, req.data, " \t\r\n"), "follow")) return Reply.fail(req.tag, E.INVAL); slot.follow = true; return .{ .tag = req.tag, .written = @intCast(req.data.len) }; @@ -386,7 +389,7 @@ pub fn noteAction( pub fn notePtyOutput(p: *Pardes, id: usize, bytes: []const u8) void { if (id >= MAX_PANES or bytes.len == 0) return; const pf = &(p.panes[id] orelse return).fs; - if (pf.pty_readers == 0) return; + if (!pf.pty_reader) return; var off: usize = 0; while (off < bytes.len) { const n = @min(bytes.len - off, queue_cap / 2); @@ -745,7 +748,7 @@ test "the log records whether or not anyone reads, and an open that follows wait try testing.expect(std.mem.startsWith(u8, lost, "lost ")); try testing.expect(std.mem.startsWith(u8, rdf.next(p, log, fh, frozen).bytes, "msg ")); _ = call(p, .{ .tag = 10, .op = .release, .node = log, .handle = fh }); - for (p.fs.snapshots) |slot| try testing.expect(slot.node == 0); + for (p.fs.opens) |o| try testing.expect(o.node == 0); // A record bigger than the whole ring is cut to fit, not dropped with // everything else pushed out ahead of it. @@ -759,12 +762,12 @@ test "the log records whether or not anyone reads, and an open that follows wait _ = call(p, .{ .tag = 13, .op = .release, .node = log, .handle = cut.reply.handle }); } -test "opens of the log share the snapshot slots, and a closed one frees its slot" { +test "opens of the log share the open records, and a closed one frees its record" { const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); const log = @intFromEnum(tree.TopFile.log); - var handles: [tree.screen.snapshot_slots]u32 = undefined; + var handles: [tree.open_slots]u32 = undefined; for (&handles) |*h| h.* = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = log }).errno()); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = handles[5] }); @@ -772,5 +775,5 @@ test "opens of the log share the snapshot slots, and a closed one frees its slot try testing.expectEqual(Status.ok, again.reply.status); handles[5] = again.reply.handle; for (handles) |h| _ = call(p, .{ .tag = 5, .op = .release, .node = log, .handle = h }); - for (p.fs.snapshots) |slot| try testing.expect(slot.node == 0); + for (p.fs.opens) |o| try testing.expect(o.node == 0); } diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index b07ee038..c03cd776 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -32,6 +32,7 @@ pub const State = struct { /// `cat addr` answer what was written. addr: Range = .{}, limit: ?Range = null, + /// Opens of `event`, which hold the pane scripted. readers: u16 = 0, /// One of `readers` reads `event`; a second reading open is refused. event_reader: bool = false, @@ -39,9 +40,11 @@ pub const State = struct { nomark: bool = false, noscroll: bool = false, tag_snap: std.ArrayList(u8) = .empty, - pty_readers: u16 = 0, + /// An open reads pty/data, so output queues for it; a second is refused. + pty_reader: bool = false, pty_out: events.Queue = .{}, - /// The pty/run open waiting on this shell's current command. + /// The open record (tree.zig) of the pty/run waiting on this shell's + /// current command. run: ?u8 = null, /// The host started a shell it could not teach to mark its prompts. unmarked: bool = false, diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index ddb7bcd1..706163e5 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -109,15 +109,12 @@ pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // command. The shell's own OSC 133 marks say when the command started (C) // and ended (D, with its status); pardes injects them into bash and fish. -pub const run_slots = 32; - /// The most of a command's output an answer carries: its last this-many /// bytes, since that is where a failure says what went wrong. pub const output_cap = 64 * 1024; +/// What an open of run holds (tree.zig's open records). pub const Run = struct { - /// 0 is a free slot. - node: u64 = 0, phase: enum { idle, sent, done } = .idle, /// The shell's command count its C must reach for the end to be ours. want: u32 = 0, @@ -139,29 +136,8 @@ pub const Run = struct { len: u8 = 0, /// Then what the command printed, gpa-owned. output: []u8 = &.{}, - - pub fn reset(slot: *Run, gpa: std.mem.Allocator, node: u64) void { - gpa.free(slot.output); - slot.* = .{ .node = node }; - } }; -fn runOf(p: *Pardes, req: Req) ?*Run { - if (req.handle == 0 or req.handle > run_slots) return null; - const slot = &p.fs.runs[req.handle - 1]; - return if (slot.node == req.node) slot else null; -} - -pub fn openRun(p: *Pardes, req: Req, serial: u32) Reply { - _ = serial; - for (&p.fs.runs, 0..) |*slot, i| { - if (slot.node != 0) continue; - slot.* = .{ .node = req.node }; - return .{ .tag = req.tag, .handle = @intCast(i + 1) }; - } - return Reply.fail(req.tag, E.NFILE); -} - fn answer(p: *Pardes, slot: *Run, comptime fmt: []const u8, args: anytype) void { slot.len = @intCast((std.fmt.bufPrint(&slot.answer, fmt ++ "\n", args) catch unreachable).len); slot.phase = .done; @@ -169,9 +145,11 @@ fn answer(p: *Pardes, slot: *Run, comptime fmt: []const u8, args: anytype) void } pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { - const slot = runOf(p, req) orelse return Reply.fail(req.tag, E.INVAL); + const slot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.run; if (slot.phase == .sent) return tree.failText(req.tag, E.BUSY, tree.e_in_use); - slot.reset(p.gpa, slot.node); // a new line on this open: a new answer + // A new line on this open: a new answer. + p.gpa.free(slot.output); + slot.* = .{}; const line = std.mem.trimEnd(u8, req.data, "\r\n"); if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); if (line.len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); @@ -197,13 +175,13 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { p.emitWrite(id, line); p.emitWrite(id, "\r"); slot.phase = .sent; - pf.run = @intCast(slot - &p.fs.runs[0]); + pf.run = @intCast(req.handle - 1); } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } pub fn readRun(p: *Pardes, req: Req) Reply { - const slot = runOf(p, req) orelse return Reply.fail(req.tag, E.INVAL); + const slot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.run; switch (slot.phase) { .idle => return .{ .tag = req.tag, .payload = .{ .staged = 0 } }, .sent => return .{ .tag = req.tag, .status = .again }, @@ -226,17 +204,6 @@ pub fn readRun(p: *Pardes, req: Req) Reply { return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; } -pub fn releaseRun(p: *Pardes, req: Req) Reply { - const slot = runOf(p, req) orelse return .{ .tag = req.tag }; - const idx: u8 = @intCast(slot - &p.fs.runs[0]); - // The command runs on in the shell; nobody is waiting for it any more. - for (p.panes) |live| if (live) |pane| if (pane.fs.run == idx) { - pane.fs.run = null; - }; - slot.reset(p.gpa, 0); - return .{ .tag = req.tag }; -} - /// After each chunk of a terminal's output: once the command the run sent /// has ended and the shell is back at a prompt, the run answers how. Waiting /// for the prompt means whoever reads the answer can send the next command @@ -245,7 +212,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { if (comptime !pardes.panes.Terminal.enabled) return; const state = pane.terminal orelse return; const pf = &pane.fs; - const slot = &p.fs.runs[pf.run orelse return]; + const slot = &p.fs.opens[pf.run orelse return].what.run; const marks = &state.stream.handler; if (marks.phase != .input) return; // ponytail: a prompt redrawn before the command starts (a resize in that @@ -325,7 +292,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { /// be reported, so the run says so instead of waiting forever. pub fn shellGone(p: *Pardes, pane: *Pane) void { const idx = pane.fs.run orelse return; - answer(p, &p.fs.runs[idx], "error shell gone", .{}); + answer(p, &p.fs.opens[idx].what.run, "error shell gone", .{}); pane.fs.run = null; } @@ -387,7 +354,7 @@ test "a pane that is not a terminal has no pty/ at all" { .op = .open, .node = Node.of(serial, .pty_data), }).errno()); - try testing.expectEqual(@as(u16, 0), p.panes[0].?.fs.pty_readers); + try testing.expect(!p.panes[0].?.fs.pty_reader); var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); @@ -578,11 +545,11 @@ test "pty/data writes at the shell and reads the raw stream" { // An open that only writes is not a reader: nothing queues for it. const writer = call(p, .{ .tag = 4, .op = .open, .node = data, .omode = 1 }); - try testing.expectEqual(@as(u16, 0), p.panes[0].?.fs.pty_readers); + try testing.expect(!p.panes[0].?.fs.pty_reader); _ = call(p, .{ .tag = 4, .op = .release, .node = data, .handle = writer.reply.handle }); const reader = call(p, .{ .tag = 5, .op = .open, .node = data }); - try testing.expectEqual(@as(u16, 1), p.panes[0].?.fs.pty_readers); + try testing.expect(p.panes[0].?.fs.pty_reader); try testing.expectEqual(@as(u16, 0), p.fs.listeners); try testing.expect(p.panes[0].?.fs.readers == 0); @@ -602,7 +569,7 @@ test "pty/data writes at the shell and reads the raw stream" { p.update(.{ .output = .{ .pane = 0, .bytes = "orphan" } }); while (p.nextEffect()) |_| {} _ = call(p, .{ .tag = 6, .op = .release, .node = data, .handle = reader.reply.handle }); - try testing.expectEqual(@as(u16, 0), p.panes[0].?.fs.pty_readers); + try testing.expect(!p.panes[0].?.fs.pty_reader); try testing.expectEqual(@as(usize, 0), p.panes[0].?.fs.pty_out.buf.capacity); try testing.expectEqual(Status.again, rd(p, data, 0, 64).reply.status); @@ -611,7 +578,7 @@ test "pty/data writes at the shell and reads the raw stream" { const second = call(p, .{ .tag = 8, .op = .open, .node = data, .omode = 2 }); try testing.expectEqual(Status.err, second.reply.status); try testing.expectEqualStrings(tree.e_in_use, second.reply.ename); - try testing.expectEqual(@as(u16, 1), p.panes[0].?.fs.pty_readers); + try testing.expect(p.panes[0].?.fs.pty_reader); p.update(.{ .output = .{ .pane = 0, .bytes = "still" } }); while (p.nextEffect()) |_| {} try testing.expectEqualStrings("still", rd(p, data, 0, 64).bytes); @@ -717,7 +684,7 @@ test "run answers how its command ended once the shell is back at a prompt" { try p.removePane(0, null); try testing.expectEqualStrings("error shell gone\n", call(p, .{ .tag = 19, .op = .read, .node = node, .handle = gone.reply.handle, .size = 64 }).bytes); _ = call(p, .{ .tag = 20, .op = .release, .node = node, .handle = gone.reply.handle }); - for (p.fs.runs) |slot| try testing.expect(slot.node == 0); + for (p.fs.opens) |o| try testing.expect(o.node == 0); } test "the pty queue drops the oldest at its cap" { diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 89ca369b..f72043d4 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -1,5 +1,5 @@ -//! /screen, /listeners and the snapshot handles that freeze a screen or a -//! terminal history between open and close. +//! /screen, /listeners and the snapshots that freeze a screen or a terminal +//! history between open and close (tree.zig's open records hold them). const std = @import("std"); const pardes = @import("../pardes.zig"); const panes = @import("../panes.zig"); @@ -11,21 +11,6 @@ const Req = tree.Req; const Reply = tree.Reply; const E = tree.E; -pub const Snapshot = struct { - node: u64 = 0, - bytes: ?[]const u8 = null, - /// /log only: this open waits for records after `bytes`, from `next`. - follow: bool = false, - next: u64 = 0, - /// How much of record `next` a short read already took. - part: u32 = 0, - /// /log only: how much of `bytes` this open has read. Reads walk it as a - /// stream and ignore their offset, since `exec 3<>log; echo follow >&3` - /// leaves the shared offset past the word it wrote. - pos: u64 = 0, -}; -pub const snapshot_slots = 32; - pub fn render(p: *Pardes) ![]u8 { var arena: std.heap.ArenaAllocator = .init(p.gpa); defer arena.deinit(); @@ -58,26 +43,13 @@ pub fn render(p: *Pardes) ![]u8 { return out.toOwnedSlice(); } -/// A screen freezes at open; a terminal body freezes at its first read. -pub fn openSnapshot(p: *Pardes, req: Req, of_screen: bool) Reply { - for (&p.fs.snapshots, 0..) |*slot, i| { - if (slot.node != 0) continue; - const bytes = if (of_screen) render(p) catch return Reply.fail(req.tag, E.NOMEM) else null; - slot.* = .{ .node = req.node, .bytes = bytes }; - return .{ .tag = req.tag, .handle = @intCast(i + 1) }; - } - return Reply.fail(req.tag, E.NFILE); -} - pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { - if (req.handle == 0 or req.handle > p.fs.snapshots.len) return Reply.fail(req.tag, E.INVAL); - const snapshot = &p.fs.snapshots[req.handle - 1]; - if (snapshot.node == 0 or snapshot.node != req.node) return Reply.fail(req.tag, E.INVAL); - if (snapshot.bytes == null) { + const snapshot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.snapshot; + if (snapshot.* == null) { const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); - snapshot.bytes = panes.Terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); + snapshot.* = panes.Terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); } - const bytes = snapshot.bytes.?; + const bytes = snapshot.*.?; const off = @min(req.off, bytes.len); const len = @min(bytes.len - off, req.size); const out = p.fs.stage(p.gpa); @@ -85,16 +57,6 @@ pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { return .{ .tag = req.tag, .payload = .{ .staged = @intCast(len) } }; } -/// True when the handle named a snapshot, which is now released. -pub fn releaseSnapshot(p: *Pardes, req: Req) bool { - if (req.handle == 0 or req.handle > p.fs.snapshots.len) return false; - const snapshot = &p.fs.snapshots[req.handle - 1]; - if (snapshot.node != req.node) return false; - if (snapshot.bytes) |bytes| p.gpa.free(bytes); - snapshot.* = .{}; - return true; -} - const listeners_cap = 512; fn listenersText(p: *Pardes, buf: []u8) []const u8 { @@ -199,7 +161,7 @@ test "an empty terminal body snapshot stays empty while output continues" { const node = Node.of(serialOf(p), .body); const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); try testing.expectEqualStrings("", call(p, .{ .tag = 2, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); - try testing.expect(p.fs.snapshots[opened.reply.handle - 1].bytes != null); + try testing.expect(p.fs.opens[opened.reply.handle - 1].what.snapshot != null); p.update(.{ .output = .{ .pane = 0, .bytes = "new output" } }); while (p.nextEffect()) |_| {} try testing.expectEqualStrings("", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); @@ -214,15 +176,15 @@ test "terminal body snapshots are lazy bounded and released after the pane close const p = try withTerm(gpa); defer p.deinit(); const node = Node.of(serialOf(p), .body); - var handles: [snapshot_slots]u32 = undefined; + var handles: [tree.open_slots]u32 = undefined; for (&handles) |*opened_handle| { const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); try testing.expectEqual(Status.ok, opened.reply.status); opened_handle.* = opened.reply.handle; } - for (p.fs.snapshots) |snapshot| { - try testing.expectEqual(node, snapshot.node); - try testing.expect(snapshot.bytes == null); + for (p.fs.opens) |o| { + try testing.expectEqual(node, o.node); + try testing.expect(o.what.snapshot == null); } try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = node }).errno()); const scratch = try th.newPane(p); @@ -235,26 +197,23 @@ test "terminal body snapshots are lazy bounded and released after the pane close const failed = call(p, .{ .tag = 3, .op = .read, .node = node, .handle = handles[0], .size = 32 }); p.gpa = gpa; try testing.expectEqual(E.NOMEM, failed.errno()); - try testing.expect(p.fs.snapshots[handles[0] - 1].bytes == null); + try testing.expect(p.fs.opens[handles[0] - 1].what.snapshot == null); const first = call(p, .{ .tag = 4, .op = .read, .node = node, .handle = handles[0], .size = 32 }); try testing.expectEqualStrings("latest output", first.bytes); - const saved = p.fs.snapshots[handles[0] - 1].bytes.?; + const saved = p.fs.opens[handles[0] - 1].what.snapshot.?; failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); p.gpa = failing.allocator(); const second = call(p, .{ .tag = 5, .op = .read, .node = node, .handle = handles[0], .off = 7, .size = 32 }); p.gpa = gpa; try testing.expectEqualStrings("output", second.bytes); try testing.expect(!failing.has_induced_failure); - try testing.expectEqual(saved.ptr, p.fs.snapshots[handles[0] - 1].bytes.?.ptr); + try testing.expectEqual(saved.ptr, p.fs.opens[handles[0] - 1].what.snapshot.?.ptr); try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .read, .node = screen_node, .handle = handles[0], .size = 32 }).errno()); _ = call(p, .{ .tag = 7, .op = .release, .node = screen_node, .handle = handles[0] }); - try testing.expectEqual(node, p.fs.snapshots[handles[0] - 1].node); + try testing.expectEqual(node, p.fs.opens[handles[0] - 1].node); try p.removePane(0, null); for (handles) |opened_handle| _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = opened_handle }); - for (p.fs.snapshots) |snapshot| { - try testing.expectEqual(@as(u64, 0), snapshot.node); - try testing.expect(snapshot.bytes == null); - } + for (p.fs.opens) |o| try testing.expectEqual(@as(u64, 0), o.node); } test "screen snapshots preserve rendered cells and styles until their handle is released" { @@ -263,7 +222,7 @@ test "screen snapshots preserve rendered cells and styles until their handle is defer p.deinit(); const opened = call(p, .{ .tag = 1, .op = .open, .node = screen_node }); try testing.expectEqual(Status.ok, opened.reply.status); - const snapshot = p.fs.snapshots[opened.reply.handle - 1].bytes.?; + const snapshot = p.fs.opens[opened.reply.handle - 1].what.snapshot.?; const original = try gpa.dupe(u8, snapshot); defer gpa.free(original); const parsed = try std.json.parseFromSlice(std.json.Value, gpa, original, .{}); @@ -276,7 +235,7 @@ test "screen snapshots preserve rendered cells and styles until their handle is _ = wr(p, Node.of(serialOf(p), .body), "changed\n"); const newer = call(p, .{ .tag = 2, .op = .open, .node = screen_node }); try testing.expectEqual(Status.ok, newer.reply.status); - try testing.expect(!std.mem.eql(u8, original, p.fs.snapshots[newer.reply.handle - 1].bytes.?)); + try testing.expect(!std.mem.eql(u8, original, p.fs.opens[newer.reply.handle - 1].what.snapshot.?)); var off: usize = 0; while (off < original.len) { const result = call(p, .{ .tag = 3, .op = .read, .node = screen_node, .handle = opened.reply.handle, .off = off, .size = 13 }); @@ -286,7 +245,7 @@ test "screen snapshots preserve rendered cells and styles until their handle is } _ = call(p, .{ .tag = 4, .op = .release, .node = screen_node, .handle = opened.reply.handle }); _ = call(p, .{ .tag = 5, .op = .release, .node = screen_node, .handle = newer.reply.handle }); - for (p.fs.snapshots) |slot| try testing.expect(slot.node == 0); + for (p.fs.opens) |o| try testing.expect(o.node == 0); } test "screen inspection preserves acknowledged presentation and the next real frame" { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index f08d20c8..bc32ad33 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -65,11 +65,6 @@ pub const e_bad_event = "bad event syntax"; /// (windows/rio/xfid.c:25), which 9ns turns into EBUSY. pub const e_in_use = "file in use"; -/// Handles that mark an open as the one reading `event` or `pty/data`, so the -/// release knows to give the file up; other opens get `open_handle`. -const open_handle: u32 = 1; -const reader_handle: u32 = 2; - fn reads(omode: u8) bool { return omode & 3 != 1; // OWRITE is the one access mode that never reads } @@ -107,30 +102,59 @@ pub fn changesPane(req: Req) bool { pub const out_reserve = 4 * 1024; -/// A read that found nothing yet (`.again`), kept to be answered when what it -/// waits on has something, the way factotum keeps its log's waiting reads -/// and answers them on append (security/auth/factotum/log.c:4-52) and acme -/// an event read (editors/acme/xfid.c:994). `asker` is the connection it -/// came on, which only the listener knows (src/9p_io.zig, `answerHeld`). -pub const Held = struct { asker: *anyopaque, req: Req }; - -/// Keeps a read that answered `.again`. An open waits with one read at a -/// time, as acme's window keeps one `eventx`: a newer read on the same open -/// takes the place of the older. -pub fn hold(p: *Pardes, req: Req, asker: *anyopaque) void { - var free: ?*?Held = null; - for (&p.fs.held) |*slot| { - const held = slot.* orelse { - if (free == null) free = slot; - continue; - }; - if (held.req.node == req.node and held.req.handle == req.handle) { - slot.* = .{ .asker = asker, .req = req }; - return; +// ---- opens ---- + +/// What one open holds from its open to its release, the way lib9p hangs a +/// server's own state off each fid (`Fid.aux`) and acme keeps it on its Fid +/// (editors/acme/dat.h:373-385). An open that holds something answers its +/// record's index plus one as the handle; one that holds nothing answers 0. +pub const Open = struct { + /// The node it was opened on, which every use checks; 0 is a free record. + node: u64 = 0, + what: union(enum) { + /// /screen's frame from the open, a terminal body's history from its + /// first read. + snapshot: ?[]const u8, + log: events.LogOpen, + run: pty.Run, + /// An open of a pane's event, holding the pane scripted; `true` for + /// the one that reads it. + event: bool, + /// The one open reading a pane's pty/data. + pty_data, + } = .{ .snapshot = null }, + /// A read that found nothing yet (`.again`), kept to be answered when + /// this open's file has something, the way factotum keeps its log's + /// waiting reads and answers them on append (security/auth/factotum/ + /// log.c:4-52) and acme an event read (editors/acme/xfid.c:994). One at a + /// time, as acme's window keeps one `eventx`: a newer read takes the + /// place of the older. The listener fills it in and answers it + /// (src/9p_io.zig, `answerHeld`). + held: ?Held = null, + + /// `asker` is the connection the read came on, which only the listener + /// knows. + pub const Held = struct { asker: *anyopaque, req: Req }; + + pub fn deinit(o: *Open, gpa: std.mem.Allocator) void { + switch (o.what) { + .snapshot => |bytes| if (bytes) |b| gpa.free(b), + .log => |log| gpa.free(log.bytes), + .run => |run| gpa.free(run.output), + .event, .pty_data => {}, } + o.* = .{}; } - // One slot per open that can wait, so a free one is always there. - if (free) |slot| slot.* = .{ .asker = asker, .req = req }; +}; + +/// Records for 64 opens at once; one more that would hold something fails. +pub const open_slots = 64; + +/// The record a request's handle names, when it was opened on that node. +pub fn openOf(p: *Pardes, req: Req) ?*Open { + if (req.handle == 0 or req.handle > p.fs.opens.len) return null; + const o = &p.fs.opens[req.handle - 1]; + return if (o.node == req.node) o else null; } // ---- nodes ---- @@ -533,41 +557,57 @@ fn makePane(p: *Pardes) ?u32 { } fn open(p: *Pardes, req: Req, target: Target) Reply { - switch (target) { + var pane_of: ?*Pane = null; + const what: @FieldType(Open, "what") = switch (target) { .top => |f| switch (f) { .new => return .{ .tag = req.tag, .handle = makePane(p) orelse return Reply.fail(req.tag, E.NFILE) }, - .screen => return screen.openSnapshot(p, req, true), - .log => return events.openLog(p, req), - else => {}, + .screen => .{ .snapshot = null }, + .log => .{ .log = .{} }, + else => return .{ .tag = req.tag }, }, - .pane => |t| { - const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); - const pn = p.panes[id].?; - const pf = &pn.fs; + .pane => |t| what: { + const pn = p.panes[p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT)].?; if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); - switch (t.file) { - .body => if (pn.isTerminal()) return screen.openSnapshot(p, req, false), + pane_of = pn; + const reader = reads(req.omode); + break :what switch (t.file) { + .body => if (pn.isTerminal()) .{ .snapshot = null } else return .{ .tag = req.tag }, // Reads of these consume, so two readers would each see half // the stream; the second is refused rather than robbed. - .event => { - const reader = reads(req.omode); - if (reader and pf.event_reader) return failText(req.tag, E.BUSY, e_in_use); - pf.readers +|= 1; - p.fs.listeners +|= 1; - pf.event_reader = pf.event_reader or reader; - if (reader) return .{ .tag = req.tag, .handle = reader_handle }; - }, - .pty_run => return pty.openRun(p, req, t.serial), - .pty_data => if (reads(req.omode)) { - if (pf.pty_readers > 0) return failText(req.tag, E.BUSY, e_in_use); - pf.pty_readers = 1; - return .{ .tag = req.tag, .handle = reader_handle }; - }, - else => {}, - } + .event => if (reader and pn.fs.event_reader) return failText(req.tag, E.BUSY, e_in_use) else .{ .event = reader }, + .pty_data => if (!reader) return .{ .tag = req.tag } else if (pn.fs.pty_reader) return failText(req.tag, E.BUSY, e_in_use) else .pty_data, + .pty_run => .{ .run = .{} }, + else => return .{ .tag = req.tag }, + }; + }, + }; + const i = for (p.fs.opens, 0..) |o, i| { + if (o.node == 0) break i; + } else return Reply.fail(req.tag, E.NFILE); + const o = &p.fs.opens[i]; + o.* = .{ .node = req.node, .what = what }; + switch (o.what) { + // A screen freezes at open; a terminal body at its first read. + .snapshot => |*bytes| if (pane_of == null) { + bytes.* = screen.render(p) catch { + o.* = .{}; + return Reply.fail(req.tag, E.NOMEM); + }; }, + .log => |*log| log.* = events.freezeLog(p) catch { + o.* = .{}; + return Reply.fail(req.tag, E.NOMEM); + }, + .event => |reader| { + const pn = pane_of.?; + pn.fs.readers +|= 1; + p.fs.listeners +|= 1; + pn.fs.event_reader = pn.fs.event_reader or reader; + }, + .pty_data => pane_of.?.fs.pty_reader = true, + .run => {}, } - return .{ .tag = req.tag, .handle = open_handle }; + return .{ .tag = req.tag, .handle = @intCast(i + 1) }; } /// Tremove closes a pane. Nothing else in the tree can be removed, and this @@ -585,41 +625,36 @@ fn remove(p: *Pardes, req: Req) Reply { } fn release(p: *Pardes, req: Req) Reply { - // A read held on this open goes with it: a hangup pays its releases - // before the connection's slot is reused, so none outlives its asker. - for (&p.fs.held) |*slot| if (slot.*) |held| { - if (held.req.node == req.node and held.req.handle == req.handle) slot.* = null; - }; // The handle's bookkeeping runs whether or not the removal is allowed. - const done = releaseHandle(p, req); - return if (req.remove) remove(p, req) else done; + releaseHandle(p, req); + return if (req.remove) remove(p, req) else .{ .tag = req.tag }; } -fn releaseHandle(p: *Pardes, req: Req) Reply { - if (screen.releaseSnapshot(p, req)) return .{ .tag = req.tag }; - const target = Node.target(req.node) orelse return .{ .tag = req.tag }; - switch (target) { - .top => {}, - .pane => |t| { - // A run's open outlives its pane: it still holds the answer. - if (t.file == .pty_run) return pty.releaseRun(p, req); - if (t.file != .event and t.file != .pty_data) return .{ .tag = req.tag }; - const id = p.paneBySerial(t.serial) orelse return .{ .tag = req.tag }; - const pf = &p.panes[id].?.fs; - if (t.file == .pty_data) { - if (req.handle != reader_handle or pf.pty_readers == 0) return .{ .tag = req.tag }; - pf.pty_readers -= 1; - if (pf.pty_readers == 0) pf.pty_out.clearAndFree(p.gpa); - return .{ .tag = req.tag }; - } - if (pf.readers == 0) return .{ .tag = req.tag }; - if (req.handle == reader_handle) pf.event_reader = false; - pf.readers -= 1; +/// Gives up what the open held, a read held on it included: a hangup pays +/// its releases before the connection's slot is reused, so none outlives +/// the connection it came on. +fn releaseHandle(p: *Pardes, req: Req) void { + const o = openOf(p, req) orelse return; + const t = Node.target(req.node).?; + const of: ?*Pane = if (t == .pane) (if (p.paneBySerial(t.pane.serial)) |id| p.panes[id] else null) else null; + if (of) |pn| switch (o.what) { + .event => |reader| { + if (reader) pn.fs.event_reader = false; + pn.fs.readers -|= 1; p.fs.listeners -|= 1; - if (pf.readers == 0) pf.tag_snap.clearAndFree(p.gpa); + if (pn.fs.readers == 0) pn.fs.tag_snap.clearAndFree(p.gpa); }, - } - return .{ .tag = req.tag }; + .pty_data => { + pn.fs.pty_reader = false; + pn.fs.pty_out.clearAndFree(p.gpa); + }, + // The command runs on in the shell; nobody is waiting for it any more. + .run => if (pn.fs.run == @as(u8, @intCast(req.handle - 1))) { + pn.fs.run = null; + }, + .snapshot, .log => {}, + }; + o.deinit(p.gpa); } fn setattr(p: *Pardes, req: Req, target: Target) Reply { @@ -997,6 +1032,34 @@ test "opening /pane/new makes a pane and removing one closes it" { try testing.expectEqual(E.NOENT, th.rmdir(p, Node.of(serial, .dir)).errno()); } +test "every open that holds something is one record, named by its handle only on its own node" { + const p = try th.withTerm(testing.allocator); + defer p.deinit(); + const serial = serialOf(p); + const log = @intFromEnum(TopFile.log); + const event = Node.of(serial, .event); + const run = Node.of(serial, .pty_run); + const logged = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; + const reader = call(p, .{ .tag = 2, .op = .open, .node = event }).reply.handle; + const ran = call(p, .{ .tag = 3, .op = .open, .node = run }).reply.handle; + try testing.expect(logged != 0 and reader != 0 and ran != 0); + try testing.expect(logged != reader and reader != ran and logged != ran); + // An open that holds nothing takes no record. + try testing.expectEqual(@as(u32, 0), call(p, .{ .tag = 4, .op = .open, .node = Node.of(serial, .addr) }).reply.handle); + + // A handle is refused on any other node, and releasing it there gives + // nothing up. + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 5, .op = .read, .node = run, .handle = logged, .size = 64 }).errno()); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .write, .node = log, .handle = ran, .data = "follow\n" }).errno()); + _ = call(p, .{ .tag = 7, .op = .release, .node = log, .handle = reader }); + try testing.expectEqualStrings(e_in_use, call(p, .{ .tag = 8, .op = .open, .node = event }).reply.ename); + + for ([_]u64{ log, event, run }, [_]u32{ logged, reader, ran }) |node, h| + _ = call(p, .{ .tag = 9, .op = .release, .node = node, .handle = h }); + for (p.fs.opens) |o| try testing.expect(o.node == 0); + try testing.expectEqual(@as(u16, 0), p.fs.listeners); +} + test "directories walk to their parents" { const p = try withFile(testing.allocator, "contents\n"); defer p.deinit(); -- cgit v1.3 From d2d31742b3381a4c550baabd55852489b91dc277 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:12:37 -0300 Subject: Move the Mini namespace out of panes.zig into Mini.zig Pure move: the body of `pub const Mini = struct { ... }` is now the file Mini.zig, dedented, with the imports it uses; panes.zig keeps `pub const Mini = @import("Mini.zig");` so every `panes.Mini.x` caller is unchanged. Output.resetBody becomes pub because Mini calls it from another file now. Mini.zig joins the embedded source list in fs.zig. Co-Authored-By: Claude Opus 5.5 --- src/Mini.zig | 314 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/fs.zig | 1 + src/panes.zig | 307 +------------------------------------------------------- 3 files changed, 317 insertions(+), 305 deletions(-) create mode 100644 src/Mini.zig (limited to 'src/fs.zig') diff --git a/src/Mini.zig b/src/Mini.zig new file mode 100644 index 00000000..bc93f678 --- /dev/null +++ b/src/Mini.zig @@ -0,0 +1,314 @@ +//! The Mini minimap: a file drawn four rows to a cell in braille dots. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const modal = @import("modal.zig"); +const filesystem = @import("fs.zig"); +const syntax = @import("syntax.zig"); +const File = panes.File; +const Output = panes.Output; + +pub const max_input_bytes = 4 * 1024 * 1024; +pub const max_output_bytes = 4 * 1024 * 1024; + +pub const State = struct { + source: []u8, + colors: []u8, + + pub fn deinit(state: *State, gpa: std.mem.Allocator) void { + gpa.free(state.source); + gpa.free(state.colors); + state.* = undefined; + } +}; + +pub const Result = struct { + content: []u8, + colors: []u8, + + pub fn deinit(result: Result, gpa: std.mem.Allocator) void { + gpa.free(result.content); + gpa.free(result.colors); + } +}; + +const Row = struct { + text: []const u8 = "", + base: usize = 0, + at: usize = 0, + left: usize = 0, + ink: bool = false, + color: u8 = 0, + + fn dot(row: *Row, styles: []const u8) ?u8 { + if (row.left == 0) { + if (row.at == row.text.len) return null; + const end = modal.nextGrapheme(row.text, row.at); + const grapheme = row.text[row.at..end]; + row.left = File.graphemeDisplayWidth(grapheme); + const n = std.unicode.utf8ByteSequenceLength(grapheme[0]) catch unreachable; + const cp = std.unicode.utf8Decode(grapheme[0..n]) catch unreachable; + const blank = switch (cp) { + '\t'...'\r', ' ', 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true, + else => false, + }; + row.ink = !blank or grapheme.len != n; + row.color = if (styles.len == 0) 0 else styles[row.base + row.at]; + row.at = end; + } + row.left -= 1; + return if (row.ink) row.color else null; + } +}; + +fn render(output: ?Result, source: []const u8, styles: []const u8) !usize { + if (source.len == 0) return 0; + const end = source.len - @intFromBool(source[source.len - 1] == '\n'); + var lines = std.mem.splitScalar(u8, source[0..end], '\n'); + var offset: usize = 0; + while (lines.peek() != null) { + var rows: [4]Row = @splat(.{}); + for (&rows) |*row| { + const line = lines.next() orelse break; + row.text = std.mem.trimEnd(u8, line, "\r"); + row.base = @intFromPtr(line.ptr) - @intFromPtr(source.ptr); + } + var spaces: usize = 0; + while (true) { + var more = false; + for (rows) |row| more = more or row.at < row.text.len or row.left > 0; + if (!more) break; + const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; + var mask: u8 = 0; + var counts: [5]u8 = @splat(0); + for (&rows, 0..) |*row, y| { + for (0..2) |x| { + if (row.dot(styles)) |color| { + mask |= @as(u8, 1) << bits[y][x]; + counts[color] += 1; + } + } + } + if (mask == 0) { + spaces += 1; + continue; + } + if (spaces + 3 > max_output_bytes - offset) return error.MiniTooLarge; + var color: u8 = 0; + var most: u8 = 0; + for (counts[1..], 1..) |count, i| { + if (count > most) { + color = @intCast(i); + most = count; + } + } + if (output) |out| { + @memset(out.content[offset..][0..spaces], ' '); + @memset(out.colors[offset..][0..spaces], 0); + _ = std.unicode.utf8Encode(@as(u21, 0x2800) + mask, out.content[offset + spaces ..][0..3]) catch unreachable; + @memset(out.colors[offset + spaces ..][0..3], color); + } + offset += spaces + 3; + spaces = 0; + } + if (offset == max_output_bytes) return error.MiniTooLarge; + if (output) |out| { + out.content[offset] = '\n'; + out.colors[offset] = 0; + } + offset += 1; + } + return offset; +} + +pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) !Result { + if (source.len > max_input_bytes) return error.MiniTooLarge; + if (!std.unicode.utf8ValidateSlice(source)) return error.InvalidUtf8; + if (styles.len != 0 and styles.len != source.len) return error.InvalidMiniColors; + for (styles) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMiniColors; + const len = try render(null, source, styles); + const content = try gpa.alloc(u8, len); + errdefer gpa.free(content); + const colors = try gpa.alloc(u8, len); + errdefer gpa.free(colors); + const result: Result = .{ .content = content, .colors = colors }; + const written = try render(result, source, styles); + std.debug.assert(written == len); + return result; +} + +pub fn open(p: *Pardes, id: usize, argument: []const u8) !void { + const caller = p.panes[id] orelse return error.MissingPane; + const word = std.mem.trim(u8, argument, " \t\r\n"); + if (word.len == 0) return error.MissingPath; + var path_buf: [4096]u8 = undefined; + const target = filesystem.resolve(p, word, Pardes.paneDir(caller), &path_buf) orelse return error.FileNotFound; + if (target.dir) return error.NotAFile; + const source = try p.gpa.dupe(u8, target.path); + errdefer p.gpa.free(source); + const input = try filesystem.readLimit(p, source, max_input_bytes); + defer p.gpa.free(input); + const styles = try syntax.highlightFileRange(p.tree_sitter_gpa, source, input, 0, input.len); + defer p.tree_sitter_gpa.free(styles); + const result = try generate(p.gpa, input, styles); + errdefer result.deinit(p.gpa); + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const file = if (pane.file) |*f| f else continue; + const old = file.mini orelse continue; + if (!std.mem.eql(u8, old.source, source)) continue; + if (std.mem.eql(u8, file.content, result.content) and std.mem.eql(u8, old.colors, result.colors)) { + p.gpa.free(source); + result.deinit(p.gpa); + } else { + File.setContent(p, file, result.content); + file.mini = .{ .source = source, .colors = result.colors }; + file.syntax_dirty = false; + Output.resetBody(p, pane); + } + p.active = i; + return; + } + const free = p.freeSlot() orelse return error.NoPaneSlots; + const dir = std.fs.path.dirname(source) orelse "/"; + const path = try std.fmt.allocPrint(p.gpa, "{s}/Mini {s}", .{ std.mem.trimEnd(u8, dir, "/"), std.fs.path.basename(source) }); + errdefer p.gpa.free(path); + const history = try File.History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(free); + pane.file = .{ + .path = path, + .content = result.content, + .output = .{ .from = .{ .cmd = .Mini } }, + .mini = .{ .source = source, .colors = result.colors }, + .history = history, + .syntax_dirty = false, + }; + pane.cur_pinned = true; + p.placeDoc(id, free, pane); + p.active = free; +} + +test "Mini maps every braille dot and partial line group" { + const gpa = std.testing.allocator; + const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; + for (0..256) |mask| { + var source: [12]u8 = undefined; + for (0..4) |row| { + for (0..2) |col| source[row * 3 + col] = if (mask & (@as(usize, 1) << bits[row][col]) != 0) 'x' else ' '; + source[row * 3 + 2] = '\n'; + } + const result = try generate(gpa, &source, ""); + defer result.deinit(gpa); + var expected: [4]u8 = undefined; + const len: usize = if (mask == 0) 0 else try std.unicode.utf8Encode(@as(u21, 0x2800) + @as(u21, @intCast(mask)), &expected); + expected[len] = '\n'; + try std.testing.expectEqualStrings(expected[0 .. len + 1], result.content); + try std.testing.expectEqual(result.content.len, result.colors.len); + for (result.colors) |color| try std.testing.expectEqual(@as(u8, 0), color); + } + for ([_]struct { source: []const u8, expected: []const u8 }{ + .{ .source = "", .expected = "" }, + .{ .source = "x", .expected = "⠁\n" }, + .{ .source = "xx\n", .expected = "⠉\n" }, + .{ .source = "x \n", .expected = "⠁\n" }, + .{ .source = "\n\n\n\nx", .expected = "\n⠁\n" }, + .{ .source = "x\r\nx\r\n", .expected = "⠃\n" }, + }) |case| { + const result = try generate(gpa, case.source, ""); + defer result.deinit(gpa); + try std.testing.expectEqualStrings(case.expected, result.content); + } +} + +test "Mini uses display cells for tabs combining text and wide characters" { + const gpa = std.testing.allocator; + for ([_]struct { source: []const u8, expected: []const u8 }{ + .{ .source = "e\u{301}界\n", .expected = "⠉⠁\n" }, + .{ .source = " x\n", .expected = " ⠁\n" }, + .{ .source = "\u{a0}x\n", .expected = "⠈\n" }, + }) |case| { + const result = try generate(gpa, case.source, ""); + defer result.deinit(gpa); + try std.testing.expectEqualStrings(case.expected, result.content); + } + const tabs = try generate(gpa, "\tx\n", ""); + defer tabs.deinit(gpa); + const spaces = config.tab_width / 2; + for (tabs.content[0..spaces]) |byte| try std.testing.expectEqual(@as(u8, ' '), byte); + try std.testing.expectEqualStrings(if (config.tab_width % 2 == 0) "⠁\n" else "⠈\n", tabs.content[spaces..]); +} + +test "Mini chooses highlighted dots over plain ink with stable color ties" { + const gpa = std.testing.allocator; + const source = "xx\nxx\nxx\nxx\n"; + var styles: [source.len]u8 = @splat(0); + styles[0] = @intFromEnum(syntax.Syn.keyword); + const rare = try generate(gpa, source, &styles); + defer rare.deinit(gpa); + try std.testing.expectEqualStrings("⣿\n", rare.content); + try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1, 0 }, rare.colors); + styles[0] = @intFromEnum(syntax.Syn.string); + styles[1] = @intFromEnum(syntax.Syn.number); + const tied = try generate(gpa, source, &styles); + defer tied.deinit(gpa); + try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2, 0 }, tied.colors); + styles[3] = @intFromEnum(syntax.Syn.number); + const majority = try generate(gpa, source, &styles); + defer majority.deinit(gpa); + try std.testing.expectEqualSlices(u8, &.{ 3, 3, 3, 0 }, majority.colors); +} + +test "Mini generation bounds and allocation failures leave no partial result" { + const Case = struct { + fn run(gpa: std.mem.Allocator) !void { + const result = try generate(gpa, "alpha\nbeta\ngamma\ndelta\nepsilon\n", ""); + defer result.deinit(gpa); + } + }; + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{}); + try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "x", &.{5})); + try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "xx", &.{0})); + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); + const source = try std.testing.allocator.alloc(u8, max_input_bytes + 1); + defer std.testing.allocator.free(source); + try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source, "")); + for (source[0..max_input_bytes], 0..) |*byte, i| byte.* = if (i % 2 == 0) 'x' else ' '; + try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source[0..max_input_bytes], "")); + try std.testing.expect(!allocator.has_induced_failure); +} + +test "Mini publishes only complete snapshots and content replacement drops metadata" { + const Case = struct { + fn run(gpa: std.mem.Allocator, path: []const u8) !void { + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const source = try p.setTestFile("untouched\n"); + const free = p.freeSlot(); + open(p, 0, path) catch |err| { + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(free, p.freeSlot()); + try std.testing.expectEqual(source, p.panes[0].?); + try std.testing.expectEqualStrings("untouched\n", source.file.?.content); + return err; + }; + const file = &p.panes[p.active].?.file.?; + try std.testing.expectEqualStrings("⠉\n", file.content); + try std.testing.expectEqualStrings(path, file.mini.?.source); + const replacement = try gpa.dupe(u8, "plain\n"); + File.setContent(p, file, replacement); + try std.testing.expect(file.mini == null); + try std.testing.expectEqualStrings("plain\n", file.content); + } + }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mini.txt", .data = "xx\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path_buf: [4096]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); +} diff --git a/src/fs.zig b/src/fs.zig index 4f395b1c..4fbfe9f9 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -36,6 +36,7 @@ else const source_files = [_]Source{ .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, + .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, .{ .path = "src/look.zig", .contents = @embedFile("look.zig") }, diff --git a/src/panes.zig b/src/panes.zig index 0fb49636..d494cfe4 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -3126,7 +3126,7 @@ pub const Output = struct { return openRead(p, id, .errors, "", content); } - fn resetBody(p: *Pardes, pane: *Pane) void { + pub fn resetBody(p: *Pardes, pane: *Pane) void { pane.file.?.scroll = 0; pane.cur_row = 0; pane.cur_col = 0; @@ -3174,310 +3174,7 @@ pub const Output = struct { } }; -pub const Mini = struct { - pub const max_input_bytes = 4 * 1024 * 1024; - pub const max_output_bytes = 4 * 1024 * 1024; - - pub const State = struct { - source: []u8, - colors: []u8, - - pub fn deinit(state: *State, gpa: std.mem.Allocator) void { - gpa.free(state.source); - gpa.free(state.colors); - state.* = undefined; - } - }; - - pub const Result = struct { - content: []u8, - colors: []u8, - - pub fn deinit(result: Result, gpa: std.mem.Allocator) void { - gpa.free(result.content); - gpa.free(result.colors); - } - }; - - const Row = struct { - text: []const u8 = "", - base: usize = 0, - at: usize = 0, - left: usize = 0, - ink: bool = false, - color: u8 = 0, - - fn dot(row: *Row, styles: []const u8) ?u8 { - if (row.left == 0) { - if (row.at == row.text.len) return null; - const end = modal.nextGrapheme(row.text, row.at); - const grapheme = row.text[row.at..end]; - row.left = File.graphemeDisplayWidth(grapheme); - const n = std.unicode.utf8ByteSequenceLength(grapheme[0]) catch unreachable; - const cp = std.unicode.utf8Decode(grapheme[0..n]) catch unreachable; - const blank = switch (cp) { - '\t'...'\r', ' ', 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true, - else => false, - }; - row.ink = !blank or grapheme.len != n; - row.color = if (styles.len == 0) 0 else styles[row.base + row.at]; - row.at = end; - } - row.left -= 1; - return if (row.ink) row.color else null; - } - }; - - fn render(output: ?Result, source: []const u8, styles: []const u8) !usize { - if (source.len == 0) return 0; - const end = source.len - @intFromBool(source[source.len - 1] == '\n'); - var lines = std.mem.splitScalar(u8, source[0..end], '\n'); - var offset: usize = 0; - while (lines.peek() != null) { - var rows: [4]Row = @splat(.{}); - for (&rows) |*row| { - const line = lines.next() orelse break; - row.text = std.mem.trimEnd(u8, line, "\r"); - row.base = @intFromPtr(line.ptr) - @intFromPtr(source.ptr); - } - var spaces: usize = 0; - while (true) { - var more = false; - for (rows) |row| more = more or row.at < row.text.len or row.left > 0; - if (!more) break; - const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; - var mask: u8 = 0; - var counts: [5]u8 = @splat(0); - for (&rows, 0..) |*row, y| { - for (0..2) |x| { - if (row.dot(styles)) |color| { - mask |= @as(u8, 1) << bits[y][x]; - counts[color] += 1; - } - } - } - if (mask == 0) { - spaces += 1; - continue; - } - if (spaces + 3 > max_output_bytes - offset) return error.MiniTooLarge; - var color: u8 = 0; - var most: u8 = 0; - for (counts[1..], 1..) |count, i| { - if (count > most) { - color = @intCast(i); - most = count; - } - } - if (output) |out| { - @memset(out.content[offset..][0..spaces], ' '); - @memset(out.colors[offset..][0..spaces], 0); - _ = std.unicode.utf8Encode(@as(u21, 0x2800) + mask, out.content[offset + spaces ..][0..3]) catch unreachable; - @memset(out.colors[offset + spaces ..][0..3], color); - } - offset += spaces + 3; - spaces = 0; - } - if (offset == max_output_bytes) return error.MiniTooLarge; - if (output) |out| { - out.content[offset] = '\n'; - out.colors[offset] = 0; - } - offset += 1; - } - return offset; - } - - pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) !Result { - if (source.len > max_input_bytes) return error.MiniTooLarge; - if (!std.unicode.utf8ValidateSlice(source)) return error.InvalidUtf8; - if (styles.len != 0 and styles.len != source.len) return error.InvalidMiniColors; - for (styles) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMiniColors; - const len = try render(null, source, styles); - const content = try gpa.alloc(u8, len); - errdefer gpa.free(content); - const colors = try gpa.alloc(u8, len); - errdefer gpa.free(colors); - const result: Result = .{ .content = content, .colors = colors }; - const written = try render(result, source, styles); - std.debug.assert(written == len); - return result; - } - - pub fn open(p: *Pardes, id: usize, argument: []const u8) !void { - const caller = p.panes[id] orelse return error.MissingPane; - const word = std.mem.trim(u8, argument, " \t\r\n"); - if (word.len == 0) return error.MissingPath; - var path_buf: [4096]u8 = undefined; - const target = filesystem.resolve(p, word, Pardes.paneDir(caller), &path_buf) orelse return error.FileNotFound; - if (target.dir) return error.NotAFile; - const source = try p.gpa.dupe(u8, target.path); - errdefer p.gpa.free(source); - const input = try filesystem.readLimit(p, source, max_input_bytes); - defer p.gpa.free(input); - const styles = try syntax.highlightFileRange(p.tree_sitter_gpa, source, input, 0, input.len); - defer p.tree_sitter_gpa.free(styles); - const result = try generate(p.gpa, input, styles); - errdefer result.deinit(p.gpa); - for (p.panes, 0..) |slot, i| { - const pane = slot orelse continue; - const file = if (pane.file) |*f| f else continue; - const old = file.mini orelse continue; - if (!std.mem.eql(u8, old.source, source)) continue; - if (std.mem.eql(u8, file.content, result.content) and std.mem.eql(u8, old.colors, result.colors)) { - p.gpa.free(source); - result.deinit(p.gpa); - } else { - File.setContent(p, file, result.content); - file.mini = .{ .source = source, .colors = result.colors }; - file.syntax_dirty = false; - Output.resetBody(p, pane); - } - p.active = i; - return; - } - const free = p.freeSlot() orelse return error.NoPaneSlots; - const dir = std.fs.path.dirname(source) orelse "/"; - const path = try std.fmt.allocPrint(p.gpa, "{s}/Mini {s}", .{ std.mem.trimEnd(u8, dir, "/"), std.fs.path.basename(source) }); - errdefer p.gpa.free(path); - const history = try File.History.create(p.gpa); - errdefer p.gpa.destroy(history); - const pane = try p.newDocPane(free); - pane.file = .{ - .path = path, - .content = result.content, - .output = .{ .from = .{ .cmd = .Mini } }, - .mini = .{ .source = source, .colors = result.colors }, - .history = history, - .syntax_dirty = false, - }; - pane.cur_pinned = true; - p.placeDoc(id, free, pane); - p.active = free; - } - - test "Mini maps every braille dot and partial line group" { - const gpa = std.testing.allocator; - const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; - for (0..256) |mask| { - var source: [12]u8 = undefined; - for (0..4) |row| { - for (0..2) |col| source[row * 3 + col] = if (mask & (@as(usize, 1) << bits[row][col]) != 0) 'x' else ' '; - source[row * 3 + 2] = '\n'; - } - const result = try generate(gpa, &source, ""); - defer result.deinit(gpa); - var expected: [4]u8 = undefined; - const len: usize = if (mask == 0) 0 else try std.unicode.utf8Encode(@as(u21, 0x2800) + @as(u21, @intCast(mask)), &expected); - expected[len] = '\n'; - try std.testing.expectEqualStrings(expected[0 .. len + 1], result.content); - try std.testing.expectEqual(result.content.len, result.colors.len); - for (result.colors) |color| try std.testing.expectEqual(@as(u8, 0), color); - } - for ([_]struct { source: []const u8, expected: []const u8 }{ - .{ .source = "", .expected = "" }, - .{ .source = "x", .expected = "⠁\n" }, - .{ .source = "xx\n", .expected = "⠉\n" }, - .{ .source = "x \n", .expected = "⠁\n" }, - .{ .source = "\n\n\n\nx", .expected = "\n⠁\n" }, - .{ .source = "x\r\nx\r\n", .expected = "⠃\n" }, - }) |case| { - const result = try generate(gpa, case.source, ""); - defer result.deinit(gpa); - try std.testing.expectEqualStrings(case.expected, result.content); - } - } - - test "Mini uses display cells for tabs combining text and wide characters" { - const gpa = std.testing.allocator; - for ([_]struct { source: []const u8, expected: []const u8 }{ - .{ .source = "e\u{301}界\n", .expected = "⠉⠁\n" }, - .{ .source = " x\n", .expected = " ⠁\n" }, - .{ .source = "\u{a0}x\n", .expected = "⠈\n" }, - }) |case| { - const result = try generate(gpa, case.source, ""); - defer result.deinit(gpa); - try std.testing.expectEqualStrings(case.expected, result.content); - } - const tabs = try generate(gpa, "\tx\n", ""); - defer tabs.deinit(gpa); - const spaces = config.tab_width / 2; - for (tabs.content[0..spaces]) |byte| try std.testing.expectEqual(@as(u8, ' '), byte); - try std.testing.expectEqualStrings(if (config.tab_width % 2 == 0) "⠁\n" else "⠈\n", tabs.content[spaces..]); - } - - test "Mini chooses highlighted dots over plain ink with stable color ties" { - const gpa = std.testing.allocator; - const source = "xx\nxx\nxx\nxx\n"; - var styles: [source.len]u8 = @splat(0); - styles[0] = @intFromEnum(syntax.Syn.keyword); - const rare = try generate(gpa, source, &styles); - defer rare.deinit(gpa); - try std.testing.expectEqualStrings("⣿\n", rare.content); - try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1, 0 }, rare.colors); - styles[0] = @intFromEnum(syntax.Syn.string); - styles[1] = @intFromEnum(syntax.Syn.number); - const tied = try generate(gpa, source, &styles); - defer tied.deinit(gpa); - try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2, 0 }, tied.colors); - styles[3] = @intFromEnum(syntax.Syn.number); - const majority = try generate(gpa, source, &styles); - defer majority.deinit(gpa); - try std.testing.expectEqualSlices(u8, &.{ 3, 3, 3, 0 }, majority.colors); - } - - test "Mini generation bounds and allocation failures leave no partial result" { - const Case = struct { - fn run(gpa: std.mem.Allocator) !void { - const result = try generate(gpa, "alpha\nbeta\ngamma\ndelta\nepsilon\n", ""); - defer result.deinit(gpa); - } - }; - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{}); - try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "x", &.{5})); - try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "xx", &.{0})); - var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); - const source = try std.testing.allocator.alloc(u8, max_input_bytes + 1); - defer std.testing.allocator.free(source); - try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source, "")); - for (source[0..max_input_bytes], 0..) |*byte, i| byte.* = if (i % 2 == 0) 'x' else ' '; - try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source[0..max_input_bytes], "")); - try std.testing.expect(!allocator.has_induced_failure); - } - - test "Mini publishes only complete snapshots and content replacement drops metadata" { - const Case = struct { - fn run(gpa: std.mem.Allocator, path: []const u8) !void { - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const source = try p.setTestFile("untouched\n"); - const free = p.freeSlot(); - open(p, 0, path) catch |err| { - try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(free, p.freeSlot()); - try std.testing.expectEqual(source, p.panes[0].?); - try std.testing.expectEqualStrings("untouched\n", source.file.?.content); - return err; - }; - const file = &p.panes[p.active].?.file.?; - try std.testing.expectEqualStrings("⠉\n", file.content); - try std.testing.expectEqualStrings(path, file.mini.?.source); - const replacement = try gpa.dupe(u8, "plain\n"); - File.setContent(p, file, replacement); - try std.testing.expect(file.mini == null); - try std.testing.expectEqualStrings("plain\n", file.content); - } - }; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mini.txt", .data = "xx\n" }); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - var path_buf: [4096]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); - } -}; +pub const Mini = @import("Mini.zig"); pub const Image = struct { const GridKey = struct { -- cgit v1.3 From 2352f0079404f31d458745e687d195d8f9c5b39f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:18:46 -0300 Subject: Move the Image pane namespace out of panes.zig into image.zig Pure move: the body of `pub const Image = struct { ... }` now sits at the end of image.zig, dedented, under a "the image pane" banner, so the image thing (decoding, glyph art, and the pane that shows it) is one file. Its nine `image.X` self-references lose the prefix; image.zig gains the four imports the pane code uses. panes.zig keeps `pub const Image = @import("image.zig");`, so `panes.Image.x` callers are unchanged. image.zig joins the embedded source list, since the pane code left panes.zig which was on it. Co-Authored-By: Claude Opus 5.5 --- src/fs.zig | 1 + src/image.zig | 235 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/panes.zig | 231 +-------------------------------------------------------- 3 files changed, 237 insertions(+), 230 deletions(-) (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index 4fbfe9f9..8fd4d711 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -37,6 +37,7 @@ const source_files = [_]Source{ .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, + .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, .{ .path = "src/look.zig", .contents = @embedFile("look.zig") }, diff --git a/src/image.zig b/src/image.zig index 592230c8..09f049ca 100644 --- a/src/image.zig +++ b/src/image.zig @@ -7,6 +7,10 @@ const zstbi = @import("zstbi"); const terminal_panes = @import("pardes.zig").terminal_panes; const ghostty_vt = if (terminal_panes) @import("ghostty-vt") else struct {}; const pdf_enabled = @import("pardes_config").mupdf; +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const filesystem = @import("fs.zig"); +const dump = @import("dump.zig"); // Glyph matching adapted from caioluders/petsciinator. pub const GlyphArt = struct { pub const commodore = [16][3]u8{ @@ -751,3 +755,234 @@ pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?struct { rgba: []u8, w const rgba = gpa.dupe(u8, src.data) catch return null; return .{ .rgba = rgba, .w = src.width, .h = src.height }; } + +// ---- the image pane ---- + +const GridKey = struct { + cols: u16 = 0, + rows: u16 = 0, + palette: PaletteMode = .commodore, + ascii: bool = true, +}; + +pub const State = struct { + path: []u8, + glyph_art: bool = false, + pmode: PaletteMode = .commodore, + ascii: bool = true, + tried: bool = false, + rgba: []u8 = &.{}, + iw: usize = 0, + ih: usize = 0, + /// Dump-loaded bytes, decoded lazily by the same path as a disk image. + raw: []u8 = &.{}, + grid: GlyphArt.Grid = .{ .cells = &.{}, .cols = 0, .rows = 0 }, + grid_key: GridKey = .{}, + + pub fn deinit(state: *State, gpa: std.mem.Allocator) void { + gpa.free(state.path); + if (state.rgba.len > 0) gpa.free(state.rgba); + if (state.raw.len > 0) gpa.free(state.raw); + if (state.grid.cells.len > 0) gpa.free(state.grid.cells); + state.* = undefined; + } +}; + +/// Construct an image pane from a path and optionally transferred dump bytes. +/// `raw` must be image_gpa-owned and ownership transfers only on success. +/// Without them the file is read here, not at the first draw: a draw +/// must not go out into the host (`pardes.turn`), and the path may be a +/// mount this editor serves. A file that cannot be read draws blank. +pub fn create(p: *pardes.Pardes, id: usize, path: []const u8, raw: []u8) !*pardes.Pane { + var bytes = raw; + var read_here = false; + if (bytes.len == 0) { + // The slot stays ours across the read: another request may + // make a pane meanwhile. + p.reserved_slots[id] = true; + defer p.reserved_slots[id] = false; + if (filesystem.read(p, path)) |from_disk| { + defer p.gpa.free(from_disk); + bytes = try p.image_gpa.dupe(u8, from_disk); + read_here = true; + } else |_| {} + } + errdefer if (read_here) p.image_gpa.free(bytes); + const path_copy = try p.image_gpa.dupe(u8, path); + errdefer p.image_gpa.free(path_copy); + const pane = try p.newDocPane(id); + pane.image = .{ .path = path_copy, .raw = bytes }; + return pane; +} + +/// Serialize the binary image record used by images and, for dump-schema +/// compatibility, PDFs. Common pane metadata is supplied by the core. +pub fn dumpPane( + p: *pardes.Pardes, + arena: std.mem.Allocator, + pane: *const pardes.Pane, + tag: []const u8, + body: []const u8, + scroll: usize, + path: []const u8, + raw: []const u8, +) !dump.Pane { + const bytes = if (raw.len > 0) raw else filesystem.read(p, path) catch &.{}; + defer if (raw.len == 0) p.gpa.free(bytes); + return .{ + .kind = .image, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .image = .{ + .path = path, + .bytes_b64 = if (bytes.len > 0) try dump.encodeBytes(arena, bytes) else "", + .petscii = if (pane.image) |state| state.glyph_art else false, + .palette = if (pane.image) |state| switch (state.pmode) { + .commodore => .commodore, + .terminal => .terminal, + } else .commodore, + .ascii = if (pane.image) |state| state.ascii else true, + }, + }; +} + +pub fn restore(p: *pardes.Pardes, id: usize, src: dump.Pane) !*pardes.Pane { + const saved = src.image.?; + var raw: []u8 = if (saved.bytes_b64.len > 0) + try dump.decodeBytes(p.image_gpa, saved.bytes_b64) + else + &.{}; + errdefer if (raw.len > 0) p.image_gpa.free(raw); + const pane = try create(p, id, saved.path, raw); + raw = &.{}; + pane.image.?.glyph_art = saved.petscii; + pane.image.?.pmode = switch (saved.palette) { + .commodore => .commodore, + .terminal => .terminal, + }; + pane.image.?.ascii = saved.ascii; + pane.cols = @max(1, src.cols); + pane.rows = @max(1, src.rows); + return pane; +} + +pub fn toggleGlyphArt(state: *State) void { + state.glyph_art = !state.glyph_art; +} + +pub fn togglePalette(state: *State) void { + state.pmode = if (state.pmode == .commodore) .terminal else .commodore; +} + +pub fn toggleAscii(state: *State) void { + state.ascii = !state.ascii; +} + +/// Image renderer choices are pane-local, not global Config values. Keep them +/// queryable where they apply: the live tag beside the image's path. +pub fn tagPrefix(arena: std.mem.Allocator, state: *const State) ![]u8 { + return std.fmt.allocPrint( + arena, + "{s} petscii:{s} palette:{s} ascii:{s} {s}", + .{ + config.tag_image, + if (state.glyph_art) "on" else "off", + @tagName(state.pmode), + if (state.ascii) "on" else "off", + state.path, + }, + ); +} + +pub fn legacySavedPrefix(state: *const State, saved_tag: []const u8) ?[]const u8 { + const lead = config.tag_image ++ " "; + if (!std.mem.startsWith(u8, saved_tag, lead)) return null; + const path_at = lead.len; + if (!std.mem.startsWith(u8, saved_tag[path_at..], state.path)) return null; + return saved_tag[0 .. path_at + state.path.len]; +} + +fn ensureDecoded(p: *pardes.Pardes, state: *State) void { + if (state.tried) return; + state.tried = true; + if (state.raw.len == 0) return; // nothing was readable at open + if (decode(p.image_gpa, state.raw)) |decoded| { + state.rgba = decoded.rgba; + state.iw = decoded.w; + state.ih = decoded.h; + } +} + +fn ensureGrid(p: *pardes.Pardes, state: *State, cols: u16, rows: u16) void { + const wanted = GridKey{ .cols = cols, .rows = rows, .palette = state.pmode, .ascii = state.ascii }; + if (state.grid.cells.len > 0 and std.meta.eql(state.grid_key, wanted)) return; + if (state.grid.cells.len > 0) p.image_gpa.free(state.grid.cells); + const palette = switch (state.pmode) { + .commodore => GlyphArt.commodore, + .terminal => terminal_palette, + }; + state.grid = GlyphArt.render( + p.image_gpa, + state.rgba, + state.iw, + state.ih, + cols, + rows, + palette, + state.ascii, + ) catch .{ .cells = &.{}, .cols = 0, .rows = 0 }; + state.grid_key = wanted; +} + +pub fn draw( + p: *pardes.Pardes, + state: *State, + pane_id: u8, + serial: u32, + x: u16, + y: u16, + cols: u16, + rows: u16, +) void { + ensureDecoded(p, state); + if (state.rgba.len == 0 or cols == 0 or rows == 0) return; + if (!state.glyph_art and p.native_images) { + _ = p.appendImagePlace(.{ + .pane = pane_id, + .serial = serial, + .x = x, + .y = y, + .w = cols, + .h = rows, + .rgba = state.rgba, + .iw = state.iw, + .ih = state.ih, + }); + return; + } + + ensureGrid(p, state, cols, rows); + if (state.grid.cells.len == 0) return; + const offx = if (cols > state.grid.cols) (@as(usize, cols) - state.grid.cols) / 2 else 0; + const offy = if (rows > state.grid.rows) (@as(usize, rows) - state.grid.rows) / 2 else 0; + for (0..state.grid.rows) |cy| for (0..state.grid.cols) |cx| { + const cell = &state.grid.cells[cy * state.grid.cols + cx]; + const fg: pardes.Color = switch (state.pmode) { + .commodore => .{ .rgb = GlyphArt.commodore[cell.fg] }, + .terminal => .{ .index = cell.fg }, + }; + const bg: pardes.Color = switch (state.pmode) { + .commodore => .{ .rgb = GlyphArt.commodore[cell.bg] }, + .terminal => .{ .index = cell.bg }, + }; + const sx = x + @as(u16, @intCast(offx + cx)); + const sy = y + @as(u16, @intCast(offy + cy)); + if (sx < p.surface.cols and sy < p.surface.rows) + p.surface.set(sx, sy, cell.glyph[0..cell.glyph_len], .{ .fg = fg, .bg = bg }); + }; +} diff --git a/src/panes.zig b/src/panes.zig index d494cfe4..bc579a92 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -3176,236 +3176,7 @@ pub const Output = struct { pub const Mini = @import("Mini.zig"); -pub const Image = struct { - const GridKey = struct { - cols: u16 = 0, - rows: u16 = 0, - palette: image.PaletteMode = .commodore, - ascii: bool = true, - }; - - pub const State = struct { - path: []u8, - glyph_art: bool = false, - pmode: image.PaletteMode = .commodore, - ascii: bool = true, - tried: bool = false, - rgba: []u8 = &.{}, - iw: usize = 0, - ih: usize = 0, - /// Dump-loaded bytes, decoded lazily by the same path as a disk image. - raw: []u8 = &.{}, - grid: image.GlyphArt.Grid = .{ .cells = &.{}, .cols = 0, .rows = 0 }, - grid_key: GridKey = .{}, - - pub fn deinit(state: *State, gpa: std.mem.Allocator) void { - gpa.free(state.path); - if (state.rgba.len > 0) gpa.free(state.rgba); - if (state.raw.len > 0) gpa.free(state.raw); - if (state.grid.cells.len > 0) gpa.free(state.grid.cells); - state.* = undefined; - } - }; - - /// Construct an image pane from a path and optionally transferred dump bytes. - /// `raw` must be image_gpa-owned and ownership transfers only on success. - /// Without them the file is read here, not at the first draw: a draw - /// must not go out into the host (`pardes.turn`), and the path may be a - /// mount this editor serves. A file that cannot be read draws blank. - pub fn create(p: *pardes.Pardes, id: usize, path: []const u8, raw: []u8) !*pardes.Pane { - var bytes = raw; - var read_here = false; - if (bytes.len == 0) { - // The slot stays ours across the read: another request may - // make a pane meanwhile. - p.reserved_slots[id] = true; - defer p.reserved_slots[id] = false; - if (filesystem.read(p, path)) |from_disk| { - defer p.gpa.free(from_disk); - bytes = try p.image_gpa.dupe(u8, from_disk); - read_here = true; - } else |_| {} - } - errdefer if (read_here) p.image_gpa.free(bytes); - const path_copy = try p.image_gpa.dupe(u8, path); - errdefer p.image_gpa.free(path_copy); - const pane = try p.newDocPane(id); - pane.image = .{ .path = path_copy, .raw = bytes }; - return pane; - } - - /// Serialize the binary image record used by images and, for dump-schema - /// compatibility, PDFs. Common pane metadata is supplied by the core. - pub fn dumpPane( - p: *pardes.Pardes, - arena: std.mem.Allocator, - pane: *const pardes.Pane, - tag: []const u8, - body: []const u8, - scroll: usize, - path: []const u8, - raw: []const u8, - ) !dump.Pane { - const bytes = if (raw.len > 0) raw else filesystem.read(p, path) catch &.{}; - defer if (raw.len == 0) p.gpa.free(bytes); - return .{ - .kind = .image, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .image = .{ - .path = path, - .bytes_b64 = if (bytes.len > 0) try dump.encodeBytes(arena, bytes) else "", - .petscii = if (pane.image) |state| state.glyph_art else false, - .palette = if (pane.image) |state| switch (state.pmode) { - .commodore => .commodore, - .terminal => .terminal, - } else .commodore, - .ascii = if (pane.image) |state| state.ascii else true, - }, - }; - } - - pub fn restore(p: *pardes.Pardes, id: usize, src: dump.Pane) !*pardes.Pane { - const saved = src.image.?; - var raw: []u8 = if (saved.bytes_b64.len > 0) - try dump.decodeBytes(p.image_gpa, saved.bytes_b64) - else - &.{}; - errdefer if (raw.len > 0) p.image_gpa.free(raw); - const pane = try create(p, id, saved.path, raw); - raw = &.{}; - pane.image.?.glyph_art = saved.petscii; - pane.image.?.pmode = switch (saved.palette) { - .commodore => .commodore, - .terminal => .terminal, - }; - pane.image.?.ascii = saved.ascii; - pane.cols = @max(1, src.cols); - pane.rows = @max(1, src.rows); - return pane; - } - - pub fn toggleGlyphArt(state: *State) void { - state.glyph_art = !state.glyph_art; - } - - pub fn togglePalette(state: *State) void { - state.pmode = if (state.pmode == .commodore) .terminal else .commodore; - } - - pub fn toggleAscii(state: *State) void { - state.ascii = !state.ascii; - } - - /// Image renderer choices are pane-local, not global Config values. Keep them - /// queryable where they apply: the live tag beside the image's path. - pub fn tagPrefix(arena: std.mem.Allocator, state: *const State) ![]u8 { - return std.fmt.allocPrint( - arena, - "{s} petscii:{s} palette:{s} ascii:{s} {s}", - .{ - config.tag_image, - if (state.glyph_art) "on" else "off", - @tagName(state.pmode), - if (state.ascii) "on" else "off", - state.path, - }, - ); - } - - pub fn legacySavedPrefix(state: *const State, saved_tag: []const u8) ?[]const u8 { - const lead = config.tag_image ++ " "; - if (!std.mem.startsWith(u8, saved_tag, lead)) return null; - const path_at = lead.len; - if (!std.mem.startsWith(u8, saved_tag[path_at..], state.path)) return null; - return saved_tag[0 .. path_at + state.path.len]; - } - - fn ensureDecoded(p: *pardes.Pardes, state: *State) void { - if (state.tried) return; - state.tried = true; - if (state.raw.len == 0) return; // nothing was readable at open - if (image.decode(p.image_gpa, state.raw)) |decoded| { - state.rgba = decoded.rgba; - state.iw = decoded.w; - state.ih = decoded.h; - } - } - - fn ensureGrid(p: *pardes.Pardes, state: *State, cols: u16, rows: u16) void { - const wanted = GridKey{ .cols = cols, .rows = rows, .palette = state.pmode, .ascii = state.ascii }; - if (state.grid.cells.len > 0 and std.meta.eql(state.grid_key, wanted)) return; - if (state.grid.cells.len > 0) p.image_gpa.free(state.grid.cells); - const palette = switch (state.pmode) { - .commodore => image.GlyphArt.commodore, - .terminal => image.terminal_palette, - }; - state.grid = image.GlyphArt.render( - p.image_gpa, - state.rgba, - state.iw, - state.ih, - cols, - rows, - palette, - state.ascii, - ) catch .{ .cells = &.{}, .cols = 0, .rows = 0 }; - state.grid_key = wanted; - } - - pub fn draw( - p: *pardes.Pardes, - state: *State, - pane_id: u8, - serial: u32, - x: u16, - y: u16, - cols: u16, - rows: u16, - ) void { - ensureDecoded(p, state); - if (state.rgba.len == 0 or cols == 0 or rows == 0) return; - if (!state.glyph_art and p.native_images) { - _ = p.appendImagePlace(.{ - .pane = pane_id, - .serial = serial, - .x = x, - .y = y, - .w = cols, - .h = rows, - .rgba = state.rgba, - .iw = state.iw, - .ih = state.ih, - }); - return; - } - - ensureGrid(p, state, cols, rows); - if (state.grid.cells.len == 0) return; - const offx = if (cols > state.grid.cols) (@as(usize, cols) - state.grid.cols) / 2 else 0; - const offy = if (rows > state.grid.rows) (@as(usize, rows) - state.grid.rows) / 2 else 0; - for (0..state.grid.rows) |cy| for (0..state.grid.cols) |cx| { - const cell = &state.grid.cells[cy * state.grid.cols + cx]; - const fg: pardes.Color = switch (state.pmode) { - .commodore => .{ .rgb = image.GlyphArt.commodore[cell.fg] }, - .terminal => .{ .index = cell.fg }, - }; - const bg: pardes.Color = switch (state.pmode) { - .commodore => .{ .rgb = image.GlyphArt.commodore[cell.bg] }, - .terminal => .{ .index = cell.bg }, - }; - const sx = x + @as(u16, @intCast(offx + cx)); - const sy = y + @as(u16, @intCast(offy + cy)); - if (sx < p.surface.cols and sy < p.surface.rows) - p.surface.set(sx, sy, cell.glyph[0..cell.glyph_len], .{ .fg = fg, .bg = bg }); - }; - } -}; +pub const Image = @import("image.zig"); pub const Pdf = struct { pub const enabled = @import("pardes_config").mupdf; -- cgit v1.3 From 2f3f8776613ebb357ff6458267c3d79c79944968 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:19:08 -0300 Subject: Move the Output namespace out of panes.zig into Output.zig Pure move: the body of `pub const Output = struct { ... }` is now the file Output.zig, dedented, with the imports it uses; panes.zig keeps `pub const Output = @import("Output.zig");`, so `panes.Output.x` callers are unchanged. decorateRow and RowDecoration.styleAt become pub because File calls them from another file now. Output.zig joins the embedded source list. Co-Authored-By: Claude Opus 5.5 --- src/Output.zig | 782 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/fs.zig | 1 + src/panes.zig | 766 +------------------------------------------------------ 3 files changed, 784 insertions(+), 765 deletions(-) create mode 100644 src/Output.zig (limited to 'src/fs.zig') diff --git a/src/Output.zig b/src/Output.zig new file mode 100644 index 00000000..00122b16 --- /dev/null +++ b/src/Output.zig @@ -0,0 +1,782 @@ +//! Output buffers (+Errors, search and jump results, help, messages, the +//! changelog): their rows, traits and look targets. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const modal = @import("modal.zig"); +const dump = @import("dump.zig"); +const limits = @import("memory.zig").limits; +const builtins = @import("builtins.zig"); +const effect_sources = @import("effect_sources.zig"); +const build_options = @import("pardes_config"); +const lsp = @import("lsp/lsp.zig"); +const look = @import("look.zig"); +const locations = @import("locations.zig"); +const Pane = panes.Pane; +const File = panes.File; + +const Builtin = builtins.registry.Builtin(); +const gui_shader_source_mode = effect_sources.guiShaderSourceMode(); + +const fonts = if (builtins.capabilities.font_picker) @import("fonts.zig") else struct {}; + +pub const Origin = union(enum) { + cmd: Builtin, + query: lsp.Kind, + search, + errors, + pdf_links, +}; + +pub const max_arg = dump.max_origin_arg; + +pub const State = struct { + from: Origin, + arg_buf: [max_arg]u8 = undefined, + arg_len: u16 = 0, + + pub fn arg(o: *const State) []const u8 { + return o.arg_buf[0..o.arg_len]; + } +}; + +const RowDecoration = struct { + location_end: usize = 0, + prefix_end: usize = 0, + declaration: bool = false, + mark_start: usize = 0, + mark_end: usize = 0, + severity: enum { none, err, warning, info, hint } = .none, + + pub fn styleAt(row: RowDecoration, p: *const Pardes, byte: usize) ?pardes.CellStyle { + // Body paper changes immediately, so its ink must change with it + // even while the surrounding tags are still fading. + const chrome = pardes.ChromeTheme.fromTheme(p.theme()); + if (row.declaration or byte < @max(row.location_end, row.prefix_end)) + return .{ .fg = .{ .rgb = chrome.lineno } }; + if (byte < row.mark_start or byte >= row.mark_end) return null; + if (row.severity == .none) return .{ + .fg = .{ .rgb = chrome.search_fg }, + .bg = .{ .rgb = chrome.search_bg }, + }; + return .{ .fg = .{ .rgb = switch (row.severity) { + .err => chrome.diagnostic_error, + .warning => chrome.diagnostic_warning, + .info => chrome.diagnostic_info, + .hint => chrome.diagnostic_hint, + .none => unreachable, + } }, .bold = true }; + } +}; + +fn rowDecoration(output: ?State, line: []const u8) RowDecoration { + return decorateRow(output, line, null); +} + +pub fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) RowDecoration { + const origin = (output orelse return .{}).from; + if (!traits(origin).locations) return .{}; + const target = locations.parse(line); + const spot = if (metadata) |m| m.at else target.at; + if (spot.line == 0) return .{}; + var row: RowDecoration = .{ + .location_end = if (metadata) |m| m.location_end else target.end, + .prefix_end = if (metadata) |m| m.code_start else target.end, + .declaration = if (metadata) |m| m.declaration else false, + }; + const source_start = if (metadata) |m| m.code_start else target.code_start; + if (source_start >= line.len) return row; + if (metadata) |m| if (m.kind == .context) return row; + const mark_occurrence = switch (origin) { + .search => true, + .cmd => |cmd| cmd == .Grep, + .query => |kind| switch (kind) { + .definition, .declaration, .type_definition, .implementation, .references => true, + else => false, + }, + else => false, + }; + if (mark_occurrence and spot.col > 0 and spot.end_line == spot.line and + spot.end_col >= spot.col) + { + row.mark_start = source_start +| (spot.col - 1); + row.mark_end = @min(line.len, source_start +| spot.end_col); + } + const is_diagnostic = switch (origin) { + .query => |kind| kind == .diagnostics or kind == .workspace_diagnostics, + else => false, + }; + if (is_diagnostic) { + const text = line[source_start..]; + inline for (.{ .{ "error:", .err }, .{ "warning:", .warning }, .{ "info:", .info }, .{ "hint:", .hint } }) |label| { + if (std.mem.startsWith(u8, text, label[0])) { + row.mark_start = source_start; + row.mark_end = source_start + label[0].len; + row.severity = label[1]; + } + } + } + return row; +} + +test "result decoration follows source byte ranges and diagnostic provenance" { + const row = rowDecoration(.{ .from = .search }, "src/a.rs:3:5-7 let abc = 1;"); + try std.testing.expectEqualStrings("abc", "src/a.rs:3:5-7 let abc = 1;"[row.mark_start..row.mark_end]); + const prose = rowDecoration(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose"); + try std.testing.expectEqual(@as(usize, 0), prose.mark_end); + const diagnostic = rowDecoration(.{ .from = .{ .query = .diagnostics } }, "src/a.rs:3:5-7 warning: unused"); + 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 = rowDecoration(.{ .from = .search }, "src/a.rs:3:99999999999999999999-99999999999999999999 text"); + 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 = rowDecoration(.{ .from = .{ .query = kind } }, snippet); + 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 = rowDecoration(.{ .from = .{ .query = kind } }, snippet); + 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 "plain output does not opt into location decoration" { + const report = rowDecoration(.{ .from = .{ .cmd = .LocationsConfig } }, "LocationsConfig context:5 tscontext:on"); + try std.testing.expectEqualDeep(RowDecoration{}, report); + const prose = rowDecoration(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose"); + try std.testing.expectEqualDeep(RowDecoration{}, prose); + const errors = rowDecoration(.{ .from = .errors }, "src/a.rs:3:5-7 error: prose"); + try std.testing.expectEqualDeep(RowDecoration{}, errors); + try std.testing.expect(!traits(.{ .cmd = .Find }).locations); + try std.testing.expect(traits(.{ .cmd = .Grep }).locations); + 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); + @memcpy(o.arg_buf[0..o.arg_len], text); +} + +pub const Traits = builtins.OutputTraits; + +const file_row: Traits = .{ .name = "", .doc = true, .saves = true }; + +pub fn traits(o: Origin) Traits { + return switch (o) { + // rows are `location text`, so n/N walk them + .search => .{ .name = config.search_buffer, .steps = true, .locations = true }, + .errors => .{ .name = config.errors_buffer, .doc = true }, + .pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true }, + .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, + .query => |k| switch (k) { + .hover => .{ .name = config.hover_buffer }, + // prose: an action list, a diff, a report about the backend + .code_action, .format, .status, .explain => .{ .name = config.lsp_buffer }, + .rename => .{ .name = config.search_buffer, .steps = true, .locations = true }, + .definition, .declaration, .type_definition, .implementation, .references => .{ + .name = config.search_buffer, + .steps = true, + .locations = true, + .jumps = true, + }, + // The hierarchy kinds behave like references: a list of places, + // and a lone answer (one caller, one subtype) is a jump. + .incoming_calls, .outgoing_calls, .supertypes, .subtypes => .{ + .name = config.search_buffer, + .steps = true, + .locations = true, + .jumps = true, + }, + .document_symbols, .workspace_symbols, .diagnostics, .workspace_diagnostics, .select_refs, .completion => .{ + .name = config.search_buffer, + .steps = true, + .locations = true, + }, + }, + }; +} + +pub fn usesLocationsConfig(from: Origin) bool { + const tr = traits(from); + return tr.steps and !tr.commands and from != .pdf_links and + !std.meta.eql(from, Origin{ .cmd = .Find }) and + !std.meta.eql(from, Origin{ .query = .completion }); +} + +pub fn fileTraits(out: ?State) Traits { + return traits((out orelse return file_row).from); +} + +pub const Grain = enum { + word, + line, + whole, +}; + +pub fn grain(out: ?State) Grain { + const tr = fileTraits(out); + if (tr.commands) return .whole; + return if (tr.steps) .line else .word; +} + +pub fn word(o: Origin) []const u8 { + return switch (o) { + .cmd => |b| @tagName(b), + .query => |k| @tagName(k), + .search => "/", + .errors => config.errors_buffer, + .pdf_links => config.pdf_links_buffer, + }; +} + +pub fn fromWord(w: []const u8) ?Origin { + if (w.len == 0) return null; + if (std.mem.eql(u8, w, "/")) return .search; + if (std.mem.eql(u8, w, config.errors_buffer)) return .errors; + if (std.mem.eql(u8, w, config.pdf_links_buffer)) return .pdf_links; + if (std.meta.stringToEnum(Builtin, w)) |b| + if (builtins.registry.outputTraits(b) != null) return .{ .cmd = b }; + if (std.meta.stringToEnum(lsp.Kind, w)) |k| return .{ .query = k }; + return null; +} + +pub fn resultsFrom(p: *Pardes, pane: *Pane, from: Origin) bool { + const rp = p.panes[pane.search_pane orelse return false] orelse return false; + const f = rp.file orelse return false; + const o = f.output orelse return false; + return std.meta.eql(o.from, from); +} + +pub const Location = struct { + path: []const u8, + at: look.Spot, + end: usize, + + fn order(a: Location, b: Location) std.math.Order { + const path = std.mem.order(u8, a.path, b.path); + if (path != .eq) return path; + if (a.at.line != b.at.line) return std.math.order(a.at.line, b.at.line); + return std.math.order(a.at.col, b.at.col); + } +}; + +pub fn location(line: []const u8) Location { + const target = locations.parse(std.mem.trimEnd(u8, line, " \t\r\n")); + return .{ .path = target.path, .at = target.at, .end = target.end }; +} + +pub fn isResultRow(file: *const File.State, row: usize) bool { + if (row < file.location_rows.len) return file.location_rows[row].kind == .match; + return !locations.isContextLine(modal.lineSlice(file.content, row)); +} + +fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?usize) !?usize { + switch (from) { + .search => {}, + .cmd => |cmd| switch (cmd) { + .Find, .Grep => {}, + else => return anchor, + }, + .query => |kind| switch (kind) { + .definition, + .declaration, + .type_definition, + .implementation, + .references, + .incoming_calls, + .outgoing_calls, + .supertypes, + .subtypes, + .document_symbols, + .workspace_symbols, + .diagnostics, + .workspace_diagnostics, + .select_refs, + .rename, + => {}, + else => return anchor, + }, + .errors, .pdf_links => return anchor, + } + if (content.len == 0) return anchor; + const path_only = std.meta.eql(from, Origin{ .cmd = .Find }); + const trailing_newline = content[content.len - 1] == '\n'; + const body = content[0 .. content.len - @intFromBool(trailing_newline)]; + var lines = std.mem.splitScalar(u8, body, '\n'); + var previous: ?Location = null; + var sorted = true; + var count: usize = 0; + while (lines.next()) |line| { + const current: Location = if (path_only) .{ .path = line, .at = .{}, .end = line.len } else location(line); + if (!path_only and current.at.line == 0) return anchor; + if (previous) |last| if (last.order(current) == .gt) { + sorted = false; + }; + previous = current; + count += 1; + } + if (sorted) return anchor; + + const Row = struct { + text: []const u8, + target: Location, + original: usize, + + fn lessThan(_: void, a: @This(), b: @This()) bool { + return switch (a.target.order(b.target)) { + .lt => true, + .eq => a.original < b.original, + .gt => false, + }; + } + }; + const rows = try arena.alloc(Row, count); + const copy = try arena.dupe(u8, body); + lines = std.mem.splitScalar(u8, copy, '\n'); + for (rows, 0..) |*row, original| { + const text = lines.next().?; + const target: Location = if (path_only) .{ .path = text, .at = .{}, .end = text.len } else location(text); + row.* = .{ + .text = text, + .target = target, + .original = original, + }; + } + std.mem.sort(Row, rows, {}, Row.lessThan); + var mapped = anchor; + var offset: usize = 0; + for (rows, 0..) |row, i| { + if (anchor == row.original) mapped = i; + @memcpy(content[offset..][0..row.text.len], row.text); + offset += row.text.len; + if (i + 1 < rows.len or trailing_newline) { + content[offset] = '\n'; + offset += 1; + } + } + std.debug.assert(offset == content.len); + return mapped; +} + +pub fn nextResult(content: []const u8, rows: []const locations.Row, path: []const u8, at: look.Spot) usize { + const current: Location = .{ .path = path, .at = at, .end = 0 }; + var lines = std.mem.splitScalar(u8, content, '\n'); + var first: ?usize = null; + var row: usize = 0; + while (lines.next()) |line| : (row += 1) { + if (row < rows.len) { + if (rows[row].kind != .match) continue; + } else if (locations.isContextLine(line)) continue; + const target = location(line); + if (target.at.line == 0) continue; + if (first == null) first = row; + if (target.order(current) == .gt) return row; + } + return first orelse 0; +} + +pub fn open(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8) !*Pane { + const path = try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ + std.mem.trimEnd(u8, dir, "/"), traits(from).name, + }); + errdefer p.gpa.free(path); + var out: State = .{ .from = from }; + try setArg(&out, arg); + const history = try File.History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(id); + pane.file = .{ .path = path, .content = content, .output = out, .history = history }; + pane.cur_pinned = true; + return pane; +} + +pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8, initial_anchor: ?usize) !void { + var result_content = content; + errdefer p.gpa.free(result_content); + var result_rows: []locations.Row = &.{}; + errdefer locations.freeRows(p.gpa, result_rows); + const pane = p.panes[id] orelse return error.MissingPane; + if (arg.len > max_arg) return error.ArgumentTooLong; + var anchor = try sortResults(p.scratch.allocator(), from, content, initial_anchor); + const by_arg = std.meta.activeTag(from) != .query; + if (p.locations_config.context == 0 and !p.locations_config.tscontext) { + for (p.panes, 0..) |slot, i| { + if (i == id) continue; + const rp = slot orelse continue; + const rf = if (rp.file) |*f| f else continue; + const output = if (rf.output) |*o| o else continue; + if (!std.meta.eql(output.from, from)) continue; + if (by_arg and !std.mem.eql(u8, output.arg(), arg)) continue; + if (!std.mem.eql(u8, std.fs.path.dirname(rf.path) orelse "", dir)) continue; + if (!locations.sameInput(content, rf.content, rf.location_rows, p.locations_config.layout)) continue; + try setArg(output, arg); + p.gpa.free(content); + p.active = id; + if (traits(from).steps) { + pane.search_pane = i; + pane.search_row = anchor; + p.armLookWalk(i); + } + return; + } + } + if (usesLocationsConfig(from)) { + const formatted = try locations.format(p, dir, content, anchor, true); + p.gpa.free(result_content); + result_content = formatted.content; + result_rows = formatted.rows; + anchor = formatted.anchor; + } + for (p.panes, 0..) |slot, i| { + if (i == id) continue; + const rp = slot orelse continue; + const rf = if (rp.file) |*f| f else continue; + const o = if (rf.output) |*x| x else continue; + if (!std.meta.eql(o.from, from)) continue; + if (by_arg and !std.mem.eql(u8, o.arg(), arg)) continue; + if (!std.mem.eql(u8, std.fs.path.dirname(rf.path) orelse "", dir)) continue; + try setArg(o, arg); + if (std.mem.eql(u8, rf.content, result_content)) { + p.gpa.free(result_content); + } else { + File.setContent(p, rf, result_content); + resetBody(p, rp); + } + if (locations.equalRows(rf.location_rows, result_rows)) { + locations.freeRows(p.gpa, result_rows); + } else { + locations.freeRows(p.gpa, rf.location_rows); + rf.location_rows = result_rows; + if (rf.highlights.len > 0) p.tree_sitter_gpa.free(rf.highlights); + rf.highlights = &.{}; + rf.highlight_start = 0; + rf.syntax_dirty = true; + } + p.active = id; + if (traits(from).steps) { + pane.search_pane = i; + pane.search_row = anchor; + p.armLookWalk(i); + } + return; + } + const free = p.freeSlot() orelse return error.NoPaneSlots; + const np = try open(p, free, dir, from, arg, result_content); + np.file.?.location_rows = result_rows; + p.placeDoc(id, free, np); + p.active = id; + if (traits(from).steps) { + pane.search_pane = free; + pane.search_row = anchor; + p.armLookWalk(free); + } +} + +pub fn openJumps(p: *Pardes, id: usize) !void { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + for (p.jumps[0..p.njumps]) |j| { + const jp = p.panes[j.pane] orelse continue; + var idbuf: [16]u8 = undefined; + const pdf_path: ?[]const u8 = if (comptime pardes.pdf_enabled) jp.pdfPath() else null; + const has_path = if (jp.file) |f| f.output == null else pdf_path != null; + const loc: []const u8 = if (has_path) + (if (jp.file) |f| f.path else pdf_path.?) + else + std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{j.pane}) catch unreachable; + const what: []const u8 = if (jp.file) |f| + std.mem.trim(u8, modal.lineSlice(f.content, j.line -| 1), " \t\r") + else if (jp.image) |iv| + iv.path + else if (pdf_path) |path| + path + else + jp.cwdSlice(); + var cut = @min(what.len, 120); + while (cut > 0 and cut < what.len and what[cut] & 0xc0 == 0x80) cut -= 1; + if (j.line == 0) + try out.writer.print("{s} {s}\n", .{ loc, what[0..cut] }) + else + try out.writer.print("{s}:{d}:{d} {s}\n", .{ loc, j.line, j.col, what[0..cut] }); + } + const content = try out.toOwnedSlice(); + try openStepped(p, id, .{ .cmd = .Jumplist }, content); +} + +pub fn openThemes(p: *Pardes, id: usize) !void { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + try out.writer.writeAll("# Pardes themes\n"); + for (pardes.themes, 0..) |t, i| { + if (i == pardes.native_theme_count) + try out.writer.writeAll("\n# Legacy and imported themes\n"); + try out.writer.print(comptime config.Runtime.findAction(.theme).?.word ++ " {s}\n", .{t.name}); + } + const content = try out.toOwnedSlice(); + try openStepped(p, id, .{ .cmd = .ThemeSel }, content); +} + +pub fn isWalkRow(file: *const File.State, row: usize, line: []const u8) bool { + const state = file.output orelse return true; + if (usesLocationsConfig(state.from)) return isResultRow(file, row); + if (!std.meta.eql(state.from, Origin{ .cmd = .ThemeSel })) return true; + // Section labels are for reading, not stops in the command walk. + return std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), comptime config.Runtime.findAction(.theme).?.word ++ " "); +} + +pub fn openFonts(p: *Pardes, id: usize) !void { + if (builtins.capabilities.font_picker) { + const arena = p.scratch.allocator(); + const font_list = fonts.list(arena, null); + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + for (font_list) |f| + try out.writer.print(comptime config.Runtime.findAction(.font).?.word ++ " {s}\n", .{f.name}); + const content = try out.toOwnedSlice(); + try openStepped(p, id, .{ .cmd = .FontSel }, content); + } +} + +fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void { + errdefer p.gpa.free(content); + const pane = p.panes[id] orelse return error.MissingPane; + const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); + const free = p.freeSlot() orelse return error.NoPaneSlots; + const np = try open(p, free, dir, from, "", content); + p.placeDoc(id, free, np); + p.active = id; + pane.search_pane = free; + pane.search_row = null; + p.armLookWalk(free); +} + +fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { + const full_header = "pardes builtins, and how to run each:\nSPC and its keys, a chord, a button, the\ntopbar - or the name, executed anywhere.\n\n"; + const group_header = "pardes builtins under SPC"; + const language_footer = + "\nlanguage keys (motions, not words):\n" ++ + "gd gD gy gi gr goto: definition,\n" ++ + " declaration, type-def,\n" ++ + " implementation, refs\n" ++ + "]d [d ]D [D diagnostics: next,\n" ++ + " prev, last, first\n" ++ + "= format (applies, one\n" ++ + " undo step)\n" ++ + "Tab after a . completion, in insert\n" ++ + "C-left-click definition, by mouse\n" ++ + "SPC l ... hover, rename, symbols,\n" ++ + " calls, types: above\n"; + var len: usize = if (prefix.len == 0) + full_header.len + language_footer.len + else + group_header.len + prefix.len * 2 + 2; + for (pardes.builtin_rows) |row| { + // a path-less builtin filters as the empty path: in the full listing + // (which starts with nothing) and out of every group + if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; + len += row.line.len + 1; + } + const content = try gpa.alloc(u8, len); + var at: usize = 0; + if (prefix.len == 0) { + @memcpy(content[0..full_header.len], full_header); + at = full_header.len; + } else { + @memcpy(content[0..group_header.len], group_header); + at = group_header.len; + for (prefix) |c| { + content[at] = ' '; + content[at + 1] = c; + at += 2; + } + content[at] = '\n'; + content[at + 1] = '\n'; + at += 2; + } + for (pardes.builtin_rows) |row| { + if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; + @memcpy(content[at..][0..row.line.len], row.line); + at += row.line.len; + content[at] = '\n'; + at += 1; + } + if (prefix.len == 0) { + @memcpy(content[at..][0..language_footer.len], language_footer); + at += language_footer.len; + } + std.debug.assert(at == content.len); + return content; +} + +pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { + const content = try helpContent(p.gpa, prefix); + // content is handed off unfreed on purpose: openRead adopts it or frees + // it, and nothing between the alloc above and this line can fail. + return openRead(p, id, .{ .cmd = .Help }, prefix, content); +} + +test "full Help renders every builtin row, then the language keys" { + const content = try helpContent(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| + try std.testing.expectEqualStrings(row.line, lines.next() orelse + return error.MissingBuiltinHelpRow); + // ...and after the last row, the language-keys section: the one part of + // the keymap no builtin row can carry, closing 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 group view stays a pure filter: no footer under a prefix + const group = try helpContent(std.testing.allocator, "l"); + defer std.testing.allocator.free(group); + try std.testing.expect(std.mem.indexOf(u8, group, "language keys") == null); +} + +pub fn openConfig(p: *Pardes, id: usize) !void { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + var dir_buf: [1024]u8 = undefined; + const host_fs = comptime (pardes.platform != .web and pardes.platform != .esp32p4); + try config.Runtime.writeReport(&out.writer, .{ + .default_dump_dir = if (host_fs) (pardes.dump.defaultDirectory(&dir_buf) orelse "") else "", + .startup_config_path = p.opts.startup_config_path, + .platform = @tagName(pardes.platform), + .theme_name = p.theme().name, + .compiled_default_shell = config.default_shell, + .gui_shader_source_mode = if (gui_shader_source_mode) |mode| + mode.label() + else + null, + .hover_delay_frames = config.look_preview_delay_frames, + .native_images = p.native_images, + .capabilities = builtins.capabilities, + .state = &p.settings, + }); + const content = try out.toOwnedSlice(); + return openRead(p, id, .{ .cmd = .Config }, "", content); +} + +/// The message-row log, oldest first — the lines that were said in passing and +/// then cleared by the next keystroke. +pub fn openMessages(p: *Pardes, id: usize) !void { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + var i: usize = 0; + while (p.messageLog(i)) |m| : (i += 1) { + if (m.serial != 0) try out.writer.print("{d}: ", .{m.serial}); + try out.writer.writeAll(m.slice()); + if (m.repeats > 1) try out.writer.print(" (x{d})", .{m.repeats}); + try out.writer.writeByte('\n'); + } + if (i == 0) try out.writer.writeAll("nothing has been said yet\n"); + const content = try out.toOwnedSlice(); + return openRead(p, id, .{ .cmd = .Messages }, "", content); +} + +/// The version banner plus the embedded CHANGELOG, so an installed binary can +/// say what it is and what changed without a repository beside it. +pub fn openChangelog(p: *Pardes, id: usize) !void { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + try out.writer.print("pardes {s}\n\n", .{build_options.version}); + try out.writer.writeAll(@embedFile("CHANGELOG.md")); + const content = try out.toOwnedSlice(); + return openRead(p, id, .{ .cmd = .Changelog }, "", content); +} + +pub fn openEffectCode(p: *Pardes, id: usize, argument: []const u8) !void { + const name = std.mem.trim(u8, argument, " \t\r\n"); + const setting = config.Runtime.find(name) orelse return error.UnknownEffect; + switch (setting.action) { + .transition, .scene => {}, + else => return error.NotAnEffect, + } + if (!setting.enabled(builtins.capabilities)) return error.EffectUnavailable; + // Without -Dembed-sources the paths would name nothing this build can open. + if (!limits.embedded_sources) return error.EffectUnavailable; + const paths = effect_sources.forSetting(setting) orelse + return error.EffectUnavailable; + + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + try out.writer.print("EffectCode {s} ({s})\n", .{ setting.word, @tagName(effect_sources.backend) }); + if (gui_shader_source_mode) |mode| + try out.writer.print("GUI shader source: {s}\n", .{mode.label()}); + try out.writer.writeByte('\n'); + for (paths) |path| try out.writer.print("/virtual/{s}\n", .{path}); + const content = try out.toOwnedSlice(); + return openRead(p, id, .{ .cmd = .EffectCode }, setting.word, content); +} + +pub fn openErrors(p: *Pardes, id: usize, content: []u8) !void { + return openRead(p, id, .errors, "", content); +} + +pub fn resetBody(p: *Pardes, pane: *Pane) void { + pane.file.?.scroll = 0; + pane.cur_row = 0; + pane.cur_col = 0; + pane.cur_pinned = true; + pane.hscroll = 0; + pane.wrap_n = 0; + pane.msel = .{}; + pane.vsel = .{}; + pane.nsel = 0; + pane.nsel_snap = 0; + pane.select = false; + pane.sel = @splat(.{}); + pane.sticky_col = -1; + pane.append_at = null; + pane.normal.clear(); + pane.look_at = null; + if (p.look_hover_wait) |wait| if (wait.serial == pane.serial) { + p.look_hover_wait = null; + }; + if (p.look_hover_preview) |preview| if (preview.serial == pane.serial) { + p.look_hover_preview = null; + }; + if (p.drag == .select and p.panes[p.drag.select.id] == pane) p.drag = .none; +} + +fn openRead(p: *Pardes, id: usize, from: Origin, arg: []const u8, content: []u8) !void { + errdefer p.gpa.free(content); + const pane = p.panes[id] orelse return error.MissingPane; + for (p.panes, 0..) |slot, i| { + const hp = slot orelse continue; + const hf = if (hp.file) |*f| f else continue; + const ho = if (hf.output) |*o| o else continue; + if (!std.meta.eql(ho.from, from)) continue; + try setArg(ho, arg); + File.setContent(p, hf, content); + resetBody(p, hp); + p.active = i; + return; + } + const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); + const free = p.freeSlot() orelse return error.NoPaneSlots; + const np = try open(p, free, dir, from, arg, content); + p.placeDoc(id, free, np); + p.active = free; +} diff --git a/src/fs.zig b/src/fs.zig index 8fd4d711..e6ebddf2 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -36,6 +36,7 @@ else const source_files = [_]Source{ .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, + .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, diff --git a/src/panes.zig b/src/panes.zig index bc579a92..6ee7d70b 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -2408,771 +2408,7 @@ pub const File = struct { } }; -pub const Output = struct { - const Builtin = builtins.registry.Builtin(); - const gui_shader_source_mode = effect_sources.guiShaderSourceMode(); - - const fonts = if (builtins.capabilities.font_picker) @import("fonts.zig") else struct {}; - - pub const Origin = union(enum) { - cmd: Builtin, - query: lsp.Kind, - search, - errors, - pdf_links, - }; - - pub const max_arg = dump.max_origin_arg; - - pub const State = struct { - from: Origin, - arg_buf: [max_arg]u8 = undefined, - arg_len: u16 = 0, - - pub fn arg(o: *const State) []const u8 { - return o.arg_buf[0..o.arg_len]; - } - }; - - const RowDecoration = struct { - location_end: usize = 0, - prefix_end: usize = 0, - declaration: bool = false, - mark_start: usize = 0, - mark_end: usize = 0, - severity: enum { none, err, warning, info, hint } = .none, - - fn styleAt(row: RowDecoration, p: *const Pardes, byte: usize) ?pardes.CellStyle { - // Body paper changes immediately, so its ink must change with it - // even while the surrounding tags are still fading. - const chrome = pardes.ChromeTheme.fromTheme(p.theme()); - if (row.declaration or byte < @max(row.location_end, row.prefix_end)) - return .{ .fg = .{ .rgb = chrome.lineno } }; - if (byte < row.mark_start or byte >= row.mark_end) return null; - if (row.severity == .none) return .{ - .fg = .{ .rgb = chrome.search_fg }, - .bg = .{ .rgb = chrome.search_bg }, - }; - return .{ .fg = .{ .rgb = switch (row.severity) { - .err => chrome.diagnostic_error, - .warning => chrome.diagnostic_warning, - .info => chrome.diagnostic_info, - .hint => chrome.diagnostic_hint, - .none => unreachable, - } }, .bold = true }; - } - }; - - fn rowDecoration(output: ?State, line: []const u8) RowDecoration { - return decorateRow(output, line, null); - } - - fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) RowDecoration { - const origin = (output orelse return .{}).from; - if (!traits(origin).locations) return .{}; - const target = locations.parse(line); - const spot = if (metadata) |m| m.at else target.at; - if (spot.line == 0) return .{}; - var row: RowDecoration = .{ - .location_end = if (metadata) |m| m.location_end else target.end, - .prefix_end = if (metadata) |m| m.code_start else target.end, - .declaration = if (metadata) |m| m.declaration else false, - }; - const source_start = if (metadata) |m| m.code_start else target.code_start; - if (source_start >= line.len) return row; - if (metadata) |m| if (m.kind == .context) return row; - const mark_occurrence = switch (origin) { - .search => true, - .cmd => |cmd| cmd == .Grep, - .query => |kind| switch (kind) { - .definition, .declaration, .type_definition, .implementation, .references => true, - else => false, - }, - else => false, - }; - if (mark_occurrence and spot.col > 0 and spot.end_line == spot.line and - spot.end_col >= spot.col) - { - row.mark_start = source_start +| (spot.col - 1); - row.mark_end = @min(line.len, source_start +| spot.end_col); - } - const is_diagnostic = switch (origin) { - .query => |kind| kind == .diagnostics or kind == .workspace_diagnostics, - else => false, - }; - if (is_diagnostic) { - const text = line[source_start..]; - inline for (.{ .{ "error:", .err }, .{ "warning:", .warning }, .{ "info:", .info }, .{ "hint:", .hint } }) |label| { - if (std.mem.startsWith(u8, text, label[0])) { - row.mark_start = source_start; - row.mark_end = source_start + label[0].len; - row.severity = label[1]; - } - } - } - return row; - } - - test "result decoration follows source byte ranges and diagnostic provenance" { - const row = rowDecoration(.{ .from = .search }, "src/a.rs:3:5-7 let abc = 1;"); - try std.testing.expectEqualStrings("abc", "src/a.rs:3:5-7 let abc = 1;"[row.mark_start..row.mark_end]); - const prose = rowDecoration(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose"); - try std.testing.expectEqual(@as(usize, 0), prose.mark_end); - const diagnostic = rowDecoration(.{ .from = .{ .query = .diagnostics } }, "src/a.rs:3:5-7 warning: unused"); - 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 = rowDecoration(.{ .from = .search }, "src/a.rs:3:99999999999999999999-99999999999999999999 text"); - 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 = rowDecoration(.{ .from = .{ .query = kind } }, snippet); - 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 = rowDecoration(.{ .from = .{ .query = kind } }, snippet); - 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 "plain output does not opt into location decoration" { - const report = rowDecoration(.{ .from = .{ .cmd = .LocationsConfig } }, "LocationsConfig context:5 tscontext:on"); - try std.testing.expectEqualDeep(RowDecoration{}, report); - const prose = rowDecoration(.{ .from = .{ .query = .hover } }, "src/a.rs:3:5-7 error: prose"); - try std.testing.expectEqualDeep(RowDecoration{}, prose); - const errors = rowDecoration(.{ .from = .errors }, "src/a.rs:3:5-7 error: prose"); - try std.testing.expectEqualDeep(RowDecoration{}, errors); - try std.testing.expect(!traits(.{ .cmd = .Find }).locations); - try std.testing.expect(traits(.{ .cmd = .Grep }).locations); - 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); - @memcpy(o.arg_buf[0..o.arg_len], text); - } - - pub const Traits = builtins.OutputTraits; - - const file_row: Traits = .{ .name = "", .doc = true, .saves = true }; - - pub fn traits(o: Origin) Traits { - return switch (o) { - // rows are `location text`, so n/N walk them - .search => .{ .name = config.search_buffer, .steps = true, .locations = true }, - .errors => .{ .name = config.errors_buffer, .doc = true }, - .pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true }, - .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, - .query => |k| switch (k) { - .hover => .{ .name = config.hover_buffer }, - // prose: an action list, a diff, a report about the backend - .code_action, .format, .status, .explain => .{ .name = config.lsp_buffer }, - .rename => .{ .name = config.search_buffer, .steps = true, .locations = true }, - .definition, .declaration, .type_definition, .implementation, .references => .{ - .name = config.search_buffer, - .steps = true, - .locations = true, - .jumps = true, - }, - // The hierarchy kinds behave like references: a list of places, - // and a lone answer (one caller, one subtype) is a jump. - .incoming_calls, .outgoing_calls, .supertypes, .subtypes => .{ - .name = config.search_buffer, - .steps = true, - .locations = true, - .jumps = true, - }, - .document_symbols, .workspace_symbols, .diagnostics, .workspace_diagnostics, .select_refs, .completion => .{ - .name = config.search_buffer, - .steps = true, - .locations = true, - }, - }, - }; - } - - pub fn usesLocationsConfig(from: Origin) bool { - const tr = traits(from); - return tr.steps and !tr.commands and from != .pdf_links and - !std.meta.eql(from, Origin{ .cmd = .Find }) and - !std.meta.eql(from, Origin{ .query = .completion }); - } - - pub fn fileTraits(out: ?State) Traits { - return traits((out orelse return file_row).from); - } - - pub const Grain = enum { - word, - line, - whole, - }; - - pub fn grain(out: ?State) Grain { - const tr = fileTraits(out); - if (tr.commands) return .whole; - return if (tr.steps) .line else .word; - } - - pub fn word(o: Origin) []const u8 { - return switch (o) { - .cmd => |b| @tagName(b), - .query => |k| @tagName(k), - .search => "/", - .errors => config.errors_buffer, - .pdf_links => config.pdf_links_buffer, - }; - } - - pub fn fromWord(w: []const u8) ?Origin { - if (w.len == 0) return null; - if (std.mem.eql(u8, w, "/")) return .search; - if (std.mem.eql(u8, w, config.errors_buffer)) return .errors; - if (std.mem.eql(u8, w, config.pdf_links_buffer)) return .pdf_links; - if (std.meta.stringToEnum(Builtin, w)) |b| - if (builtins.registry.outputTraits(b) != null) return .{ .cmd = b }; - if (std.meta.stringToEnum(lsp.Kind, w)) |k| return .{ .query = k }; - return null; - } - - pub fn resultsFrom(p: *Pardes, pane: *Pane, from: Origin) bool { - const rp = p.panes[pane.search_pane orelse return false] orelse return false; - const f = rp.file orelse return false; - const o = f.output orelse return false; - return std.meta.eql(o.from, from); - } - - pub const Location = struct { - path: []const u8, - at: look.Spot, - end: usize, - - fn order(a: Location, b: Location) std.math.Order { - const path = std.mem.order(u8, a.path, b.path); - if (path != .eq) return path; - if (a.at.line != b.at.line) return std.math.order(a.at.line, b.at.line); - return std.math.order(a.at.col, b.at.col); - } - }; - - pub fn location(line: []const u8) Location { - const target = locations.parse(std.mem.trimEnd(u8, line, " \t\r\n")); - return .{ .path = target.path, .at = target.at, .end = target.end }; - } - - pub fn isResultRow(file: *const File.State, row: usize) bool { - if (row < file.location_rows.len) return file.location_rows[row].kind == .match; - return !locations.isContextLine(modal.lineSlice(file.content, row)); - } - - fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?usize) !?usize { - switch (from) { - .search => {}, - .cmd => |cmd| switch (cmd) { - .Find, .Grep => {}, - else => return anchor, - }, - .query => |kind| switch (kind) { - .definition, - .declaration, - .type_definition, - .implementation, - .references, - .incoming_calls, - .outgoing_calls, - .supertypes, - .subtypes, - .document_symbols, - .workspace_symbols, - .diagnostics, - .workspace_diagnostics, - .select_refs, - .rename, - => {}, - else => return anchor, - }, - .errors, .pdf_links => return anchor, - } - if (content.len == 0) return anchor; - const path_only = std.meta.eql(from, Origin{ .cmd = .Find }); - const trailing_newline = content[content.len - 1] == '\n'; - const body = content[0 .. content.len - @intFromBool(trailing_newline)]; - var lines = std.mem.splitScalar(u8, body, '\n'); - var previous: ?Location = null; - var sorted = true; - var count: usize = 0; - while (lines.next()) |line| { - const current: Location = if (path_only) .{ .path = line, .at = .{}, .end = line.len } else location(line); - if (!path_only and current.at.line == 0) return anchor; - if (previous) |last| if (last.order(current) == .gt) { - sorted = false; - }; - previous = current; - count += 1; - } - if (sorted) return anchor; - - const Row = struct { - text: []const u8, - target: Location, - original: usize, - - fn lessThan(_: void, a: @This(), b: @This()) bool { - return switch (a.target.order(b.target)) { - .lt => true, - .eq => a.original < b.original, - .gt => false, - }; - } - }; - const rows = try arena.alloc(Row, count); - const copy = try arena.dupe(u8, body); - lines = std.mem.splitScalar(u8, copy, '\n'); - for (rows, 0..) |*row, original| { - const text = lines.next().?; - const target: Location = if (path_only) .{ .path = text, .at = .{}, .end = text.len } else location(text); - row.* = .{ - .text = text, - .target = target, - .original = original, - }; - } - std.mem.sort(Row, rows, {}, Row.lessThan); - var mapped = anchor; - var offset: usize = 0; - for (rows, 0..) |row, i| { - if (anchor == row.original) mapped = i; - @memcpy(content[offset..][0..row.text.len], row.text); - offset += row.text.len; - if (i + 1 < rows.len or trailing_newline) { - content[offset] = '\n'; - offset += 1; - } - } - std.debug.assert(offset == content.len); - return mapped; - } - - pub fn nextResult(content: []const u8, rows: []const locations.Row, path: []const u8, at: look.Spot) usize { - const current: Location = .{ .path = path, .at = at, .end = 0 }; - var lines = std.mem.splitScalar(u8, content, '\n'); - var first: ?usize = null; - var row: usize = 0; - while (lines.next()) |line| : (row += 1) { - if (row < rows.len) { - if (rows[row].kind != .match) continue; - } else if (locations.isContextLine(line)) continue; - const target = location(line); - if (target.at.line == 0) continue; - if (first == null) first = row; - if (target.order(current) == .gt) return row; - } - return first orelse 0; - } - - pub fn open(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8) !*Pane { - const path = try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ - std.mem.trimEnd(u8, dir, "/"), traits(from).name, - }); - errdefer p.gpa.free(path); - var out: State = .{ .from = from }; - try setArg(&out, arg); - const history = try File.History.create(p.gpa); - errdefer p.gpa.destroy(history); - const pane = try p.newDocPane(id); - pane.file = .{ .path = path, .content = content, .output = out, .history = history }; - pane.cur_pinned = true; - return pane; - } - - pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8, initial_anchor: ?usize) !void { - var result_content = content; - errdefer p.gpa.free(result_content); - var result_rows: []locations.Row = &.{}; - errdefer locations.freeRows(p.gpa, result_rows); - const pane = p.panes[id] orelse return error.MissingPane; - if (arg.len > max_arg) return error.ArgumentTooLong; - var anchor = try sortResults(p.scratch.allocator(), from, content, initial_anchor); - const by_arg = std.meta.activeTag(from) != .query; - if (p.locations_config.context == 0 and !p.locations_config.tscontext) { - for (p.panes, 0..) |slot, i| { - if (i == id) continue; - const rp = slot orelse continue; - const rf = if (rp.file) |*f| f else continue; - const output = if (rf.output) |*o| o else continue; - if (!std.meta.eql(output.from, from)) continue; - if (by_arg and !std.mem.eql(u8, output.arg(), arg)) continue; - if (!std.mem.eql(u8, std.fs.path.dirname(rf.path) orelse "", dir)) continue; - if (!locations.sameInput(content, rf.content, rf.location_rows, p.locations_config.layout)) continue; - try setArg(output, arg); - p.gpa.free(content); - p.active = id; - if (traits(from).steps) { - pane.search_pane = i; - pane.search_row = anchor; - p.armLookWalk(i); - } - return; - } - } - if (usesLocationsConfig(from)) { - const formatted = try locations.format(p, dir, content, anchor, true); - p.gpa.free(result_content); - result_content = formatted.content; - result_rows = formatted.rows; - anchor = formatted.anchor; - } - for (p.panes, 0..) |slot, i| { - if (i == id) continue; - const rp = slot orelse continue; - const rf = if (rp.file) |*f| f else continue; - const o = if (rf.output) |*x| x else continue; - if (!std.meta.eql(o.from, from)) continue; - if (by_arg and !std.mem.eql(u8, o.arg(), arg)) continue; - if (!std.mem.eql(u8, std.fs.path.dirname(rf.path) orelse "", dir)) continue; - try setArg(o, arg); - if (std.mem.eql(u8, rf.content, result_content)) { - p.gpa.free(result_content); - } else { - File.setContent(p, rf, result_content); - resetBody(p, rp); - } - if (locations.equalRows(rf.location_rows, result_rows)) { - locations.freeRows(p.gpa, result_rows); - } else { - locations.freeRows(p.gpa, rf.location_rows); - rf.location_rows = result_rows; - if (rf.highlights.len > 0) p.tree_sitter_gpa.free(rf.highlights); - rf.highlights = &.{}; - rf.highlight_start = 0; - rf.syntax_dirty = true; - } - p.active = id; - if (traits(from).steps) { - pane.search_pane = i; - pane.search_row = anchor; - p.armLookWalk(i); - } - return; - } - const free = p.freeSlot() orelse return error.NoPaneSlots; - const np = try open(p, free, dir, from, arg, result_content); - np.file.?.location_rows = result_rows; - p.placeDoc(id, free, np); - p.active = id; - if (traits(from).steps) { - pane.search_pane = free; - pane.search_row = anchor; - p.armLookWalk(free); - } - } - - pub fn openJumps(p: *Pardes, id: usize) !void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - for (p.jumps[0..p.njumps]) |j| { - const jp = p.panes[j.pane] orelse continue; - var idbuf: [16]u8 = undefined; - const pdf_path: ?[]const u8 = if (comptime pardes.pdf_enabled) jp.pdfPath() else null; - const has_path = if (jp.file) |f| f.output == null else pdf_path != null; - const loc: []const u8 = if (has_path) - (if (jp.file) |f| f.path else pdf_path.?) - else - std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{j.pane}) catch unreachable; - const what: []const u8 = if (jp.file) |f| - std.mem.trim(u8, modal.lineSlice(f.content, j.line -| 1), " \t\r") - else if (jp.image) |iv| - iv.path - else if (pdf_path) |path| - path - else - jp.cwdSlice(); - var cut = @min(what.len, 120); - while (cut > 0 and cut < what.len and what[cut] & 0xc0 == 0x80) cut -= 1; - if (j.line == 0) - try out.writer.print("{s} {s}\n", .{ loc, what[0..cut] }) - else - try out.writer.print("{s}:{d}:{d} {s}\n", .{ loc, j.line, j.col, what[0..cut] }); - } - const content = try out.toOwnedSlice(); - try openStepped(p, id, .{ .cmd = .Jumplist }, content); - } - - pub fn openThemes(p: *Pardes, id: usize) !void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try out.writer.writeAll("# Pardes themes\n"); - for (pardes.themes, 0..) |t, i| { - if (i == pardes.native_theme_count) - try out.writer.writeAll("\n# Legacy and imported themes\n"); - try out.writer.print(comptime config.Runtime.findAction(.theme).?.word ++ " {s}\n", .{t.name}); - } - const content = try out.toOwnedSlice(); - try openStepped(p, id, .{ .cmd = .ThemeSel }, content); - } - - pub fn isWalkRow(file: *const File.State, row: usize, line: []const u8) bool { - const state = file.output orelse return true; - if (usesLocationsConfig(state.from)) return isResultRow(file, row); - if (!std.meta.eql(state.from, Origin{ .cmd = .ThemeSel })) return true; - // Section labels are for reading, not stops in the command walk. - return std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), comptime config.Runtime.findAction(.theme).?.word ++ " "); - } - - pub fn openFonts(p: *Pardes, id: usize) !void { - if (builtins.capabilities.font_picker) { - const arena = p.scratch.allocator(); - const font_list = fonts.list(arena, null); - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - for (font_list) |f| - try out.writer.print(comptime config.Runtime.findAction(.font).?.word ++ " {s}\n", .{f.name}); - const content = try out.toOwnedSlice(); - try openStepped(p, id, .{ .cmd = .FontSel }, content); - } - } - - fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void { - errdefer p.gpa.free(content); - const pane = p.panes[id] orelse return error.MissingPane; - const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); - const free = p.freeSlot() orelse return error.NoPaneSlots; - const np = try open(p, free, dir, from, "", content); - p.placeDoc(id, free, np); - p.active = id; - pane.search_pane = free; - pane.search_row = null; - p.armLookWalk(free); - } - - fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { - const full_header = "pardes builtins, and how to run each:\nSPC and its keys, a chord, a button, the\ntopbar - or the name, executed anywhere.\n\n"; - const group_header = "pardes builtins under SPC"; - const language_footer = - "\nlanguage keys (motions, not words):\n" ++ - "gd gD gy gi gr goto: definition,\n" ++ - " declaration, type-def,\n" ++ - " implementation, refs\n" ++ - "]d [d ]D [D diagnostics: next,\n" ++ - " prev, last, first\n" ++ - "= format (applies, one\n" ++ - " undo step)\n" ++ - "Tab after a . completion, in insert\n" ++ - "C-left-click definition, by mouse\n" ++ - "SPC l ... hover, rename, symbols,\n" ++ - " calls, types: above\n"; - var len: usize = if (prefix.len == 0) - full_header.len + language_footer.len - else - group_header.len + prefix.len * 2 + 2; - for (pardes.builtin_rows) |row| { - // a path-less builtin filters as the empty path: in the full listing - // (which starts with nothing) and out of every group - if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - len += row.line.len + 1; - } - const content = try gpa.alloc(u8, len); - var at: usize = 0; - if (prefix.len == 0) { - @memcpy(content[0..full_header.len], full_header); - at = full_header.len; - } else { - @memcpy(content[0..group_header.len], group_header); - at = group_header.len; - for (prefix) |c| { - content[at] = ' '; - content[at + 1] = c; - at += 2; - } - content[at] = '\n'; - content[at + 1] = '\n'; - at += 2; - } - for (pardes.builtin_rows) |row| { - if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - @memcpy(content[at..][0..row.line.len], row.line); - at += row.line.len; - content[at] = '\n'; - at += 1; - } - if (prefix.len == 0) { - @memcpy(content[at..][0..language_footer.len], language_footer); - at += language_footer.len; - } - std.debug.assert(at == content.len); - return content; - } - - pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { - const content = try helpContent(p.gpa, prefix); - // content is handed off unfreed on purpose: openRead adopts it or frees - // it, and nothing between the alloc above and this line can fail. - return openRead(p, id, .{ .cmd = .Help }, prefix, content); - } - - test "full Help renders every builtin row, then the language keys" { - const content = try helpContent(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| - try std.testing.expectEqualStrings(row.line, lines.next() orelse - return error.MissingBuiltinHelpRow); - // ...and after the last row, the language-keys section: the one part of - // the keymap no builtin row can carry, closing 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 group view stays a pure filter: no footer under a prefix - const group = try helpContent(std.testing.allocator, "l"); - defer std.testing.allocator.free(group); - try std.testing.expect(std.mem.indexOf(u8, group, "language keys") == null); - } - - pub fn openConfig(p: *Pardes, id: usize) !void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - var dir_buf: [1024]u8 = undefined; - const host_fs = comptime (pardes.platform != .web and pardes.platform != .esp32p4); - try config.Runtime.writeReport(&out.writer, .{ - .default_dump_dir = if (host_fs) (pardes.dump.defaultDirectory(&dir_buf) orelse "") else "", - .startup_config_path = p.opts.startup_config_path, - .platform = @tagName(pardes.platform), - .theme_name = p.theme().name, - .compiled_default_shell = config.default_shell, - .gui_shader_source_mode = if (gui_shader_source_mode) |mode| - mode.label() - else - null, - .hover_delay_frames = config.look_preview_delay_frames, - .native_images = p.native_images, - .capabilities = builtins.capabilities, - .state = &p.settings, - }); - const content = try out.toOwnedSlice(); - return openRead(p, id, .{ .cmd = .Config }, "", content); - } - - /// The message-row log, oldest first — the lines that were said in passing and - /// then cleared by the next keystroke. - pub fn openMessages(p: *Pardes, id: usize) !void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - var i: usize = 0; - while (p.messageLog(i)) |m| : (i += 1) { - if (m.serial != 0) try out.writer.print("{d}: ", .{m.serial}); - try out.writer.writeAll(m.slice()); - if (m.repeats > 1) try out.writer.print(" (x{d})", .{m.repeats}); - try out.writer.writeByte('\n'); - } - if (i == 0) try out.writer.writeAll("nothing has been said yet\n"); - const content = try out.toOwnedSlice(); - return openRead(p, id, .{ .cmd = .Messages }, "", content); - } - - /// The version banner plus the embedded CHANGELOG, so an installed binary can - /// say what it is and what changed without a repository beside it. - pub fn openChangelog(p: *Pardes, id: usize) !void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try out.writer.print("pardes {s}\n\n", .{build_options.version}); - try out.writer.writeAll(@embedFile("CHANGELOG.md")); - const content = try out.toOwnedSlice(); - return openRead(p, id, .{ .cmd = .Changelog }, "", content); - } - - pub fn openEffectCode(p: *Pardes, id: usize, argument: []const u8) !void { - const name = std.mem.trim(u8, argument, " \t\r\n"); - const setting = config.Runtime.find(name) orelse return error.UnknownEffect; - switch (setting.action) { - .transition, .scene => {}, - else => return error.NotAnEffect, - } - if (!setting.enabled(builtins.capabilities)) return error.EffectUnavailable; - // Without -Dembed-sources the paths would name nothing this build can open. - if (!limits.embedded_sources) return error.EffectUnavailable; - const paths = effect_sources.forSetting(setting) orelse - return error.EffectUnavailable; - - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try out.writer.print("EffectCode {s} ({s})\n", .{ setting.word, @tagName(effect_sources.backend) }); - if (gui_shader_source_mode) |mode| - try out.writer.print("GUI shader source: {s}\n", .{mode.label()}); - try out.writer.writeByte('\n'); - for (paths) |path| try out.writer.print("/virtual/{s}\n", .{path}); - const content = try out.toOwnedSlice(); - return openRead(p, id, .{ .cmd = .EffectCode }, setting.word, content); - } - - pub fn openErrors(p: *Pardes, id: usize, content: []u8) !void { - return openRead(p, id, .errors, "", content); - } - - pub fn resetBody(p: *Pardes, pane: *Pane) void { - pane.file.?.scroll = 0; - pane.cur_row = 0; - pane.cur_col = 0; - pane.cur_pinned = true; - pane.hscroll = 0; - pane.wrap_n = 0; - pane.msel = .{}; - pane.vsel = .{}; - pane.nsel = 0; - pane.nsel_snap = 0; - pane.select = false; - pane.sel = @splat(.{}); - pane.sticky_col = -1; - pane.append_at = null; - pane.normal.clear(); - pane.look_at = null; - if (p.look_hover_wait) |wait| if (wait.serial == pane.serial) { - p.look_hover_wait = null; - }; - if (p.look_hover_preview) |preview| if (preview.serial == pane.serial) { - p.look_hover_preview = null; - }; - if (p.drag == .select and p.panes[p.drag.select.id] == pane) p.drag = .none; - } - - fn openRead(p: *Pardes, id: usize, from: Origin, arg: []const u8, content: []u8) !void { - errdefer p.gpa.free(content); - const pane = p.panes[id] orelse return error.MissingPane; - for (p.panes, 0..) |slot, i| { - const hp = slot orelse continue; - const hf = if (hp.file) |*f| f else continue; - const ho = if (hf.output) |*o| o else continue; - if (!std.meta.eql(ho.from, from)) continue; - try setArg(ho, arg); - File.setContent(p, hf, content); - resetBody(p, hp); - p.active = i; - return; - } - const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); - const free = p.freeSlot() orelse return error.NoPaneSlots; - const np = try open(p, free, dir, from, arg, content); - p.placeDoc(id, free, np); - p.active = free; - } -}; +pub const Output = @import("Output.zig"); pub const Mini = @import("Mini.zig"); -- cgit v1.3 From 7d78a880201d25b8e7b9de1f7bd22199f92a2705 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:24:58 -0300 Subject: Move the File namespace out of panes.zig into File.zig Pure move: the body of `pub const File = struct { ... }` is now the file File.zig, dedented, with the imports it uses; panes.zig keeps `pub const File = @import("File.zig");`, so `panes.File.x` callers and the `File.State` field of Pane are unchanged. File.zig joins the embedded source list. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 1305 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/fs.zig | 1 + src/panes.zig | 1288 +------------------------------------------------------- 3 files changed, 1307 insertions(+), 1287 deletions(-) create mode 100644 src/File.zig (limited to 'src/fs.zig') diff --git a/src/File.zig b/src/File.zig new file mode 100644 index 00000000..eb1c6a7c --- /dev/null +++ b/src/File.zig @@ -0,0 +1,1305 @@ +//! A file pane's text: its content and undo history, display columns, line +//! index, syntax highlights and the body it fills. +const panes = @import("panes.zig"); +const std = @import("std"); +const vaxis = @import("vaxis"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const modal = @import("modal.zig"); +const filesystem = @import("fs.zig"); +const syntax = @import("syntax.zig"); +const tracy = @import("tracy.zig"); +const dump = @import("dump.zig"); +const limits = @import("memory.zig").limits; +const locations = @import("locations.zig"); +const Pane = panes.Pane; +const Output = panes.Output; +const Mini = panes.Mini; +const Terminal = panes.Terminal; + +const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; + +/// Content and primary selection at one file edit boundary. Keeping only the +/// primary avoids putting Pane.max_selections ranges in every history entry. +pub const Snapshot = struct { + content: []u8, + cur_row: i32, + cur_col: i32, + vsel: Pane.CharSel, +}; + +pub const History = struct { + undo: [limits.undo_max]Snapshot = undefined, + undo_len: usize = 0, + redo: [limits.undo_max]Snapshot = undefined, + redo_len: usize = 0, + + pub fn create(gpa: std.mem.Allocator) !*History { + const history = try gpa.create(History); + history.undo_len = 0; + history.redo_len = 0; + return history; + } +}; + +/// A file pane's backing: owned content, its derived caches, and undo history. +pub const State = struct { + path: []u8, + content: []u8, + revision: u32 = 0, + /// Revision last known to match disk, after Save or an external reload. + /// Equal means the screen matches disk. + saved_revision: u32 = 0, + watch_after_save: bool = false, + /// Seconds of the last content change, for the filesystem's stat; zero until edited. + mtime: u32 = 0, + /// Non-null for a generated output buffer rather than an on-disk file. + output: ?Output.State = null, + mini: ?Mini.State = null, + scroll: usize = 0, + /// `line_starts[i]` is line i's byte offset. Empty means not built yet. + line_starts: []usize = &.{}, + /// One tree_sitter_gpa-owned syntax.Syn byte per highlighted source byte. + highlights: []u8 = &.{}, + location_rows: []locations.Row = &.{}, + highlight_start: usize = 0, + syntax_dirty: bool = true, + tree_context: bool = false, + context_declarations: []syntax.ContextDeclaration = &.{}, + context_revision: ?u32 = null, + history: *History, +}; + +pub fn dumpPane( + arena: std.mem.Allocator, + pane: *const Pane, + file: *const State, + tag: []const u8, + body: []const u8, + scroll: usize, + origin: []const u8, + origin_arg: []const u8, +) !dump.Pane { + return .{ + .kind = .file, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .file = .{ + .tree_context = file.tree_context, + .location_rows = try dumpLocationRows(arena, file.location_rows), + .path = file.path, + .content = file.content, + .content_b64 = try dump.encodeBytes(arena, file.content), + .dirty = file.revision != file.saved_revision, + .origin = origin, + .origin_arg = origin_arg, + .mini_source = if (file.mini) |mini| mini.source else "", + .mini_colors_b64 = if (file.mini) |mini| try dump.encodeBytes(arena, mini.colors) else "", + }, + }; +} + +fn dumpLocationRows(arena: std.mem.Allocator, rows: []const locations.Row) ![]const dump.LocationRow { + const saved = try arena.alloc(dump.LocationRow, rows.len); + for (rows, saved) |row, *out| out.* = .{ + .kind = @enumFromInt(@intFromEnum(row.kind)), + .declaration = row.declaration, + .path = row.path, + .line = row.at.line, + .col = row.at.col, + .end_line = row.at.end_line, + .end_col = row.at.end_col, + .location_end = row.location_end, + .code_start = row.code_start, + .colors_b64 = try dump.encodeBytes(arena, row.colors), + }; + return saved; +} + +fn sameSavedLocation(a: dump.LocationRow, b: dump.LocationRow) bool { + return std.mem.eql(u8, a.path, b.path) and a.line == b.line and a.col == b.col and + a.end_line == b.end_line and a.end_col == b.end_col; +} + +fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow) ![]locations.Row { + if (saved.len == 0) return &.{}; + if (saved.len > std.mem.count(u8, content, "\n") + 1) return error.InvalidLocationRows; + const rows = try gpa.alloc(locations.Row, saved.len); + var initialized: usize = 0; + errdefer { + for (rows[0..initialized]) |row| { + gpa.free(row.path); + gpa.free(row.colors); + } + gpa.free(rows); + } + var lines = std.mem.splitScalar(u8, content, '\n'); + var previous_line: []const u8 = ""; + for (saved, rows, 0..) |row, *out, index| { + const line = lines.next() orelse return error.InvalidLocationRows; + if (row.path.len == 0 or row.path.len >= 4096 or + row.location_end > row.code_start or row.code_start > line.len or + (row.kind == .match and row.location_end == 0) or + (row.declaration and row.kind != .context) or + row.line > std.math.maxInt(i32) or row.col > std.math.maxInt(i32) or + row.end_line > std.math.maxInt(i32) or row.end_col > std.math.maxInt(i32)) + return error.InvalidLocationRows; + const inline_row = row.code_start > row.location_end and row.code_start > 0 and line[row.code_start - 1] == '\t'; + const address_row = !inline_row and row.location_end > 0 and row.code_start == line.len; + const source_row = row.location_end == 0 and row.code_start == 0; + if (!inline_row and !address_row and !source_row) return error.InvalidLocationRows; + if (row.kind == .preview) { + if (!source_row or index == 0) return error.InvalidLocationRows; + const previous = saved[index - 1]; + if (previous.kind != .match or previous.location_end == 0 or previous.code_start != previous_line.len or previous_line[previous_line.len - 1] == '\t' or + !sameSavedLocation(previous, row)) return error.InvalidLocationRows; + } + if (address_row) { + if (index + 1 >= saved.len) return error.InvalidLocationRows; + const following = saved[index + 1]; + const expected: @TypeOf(row.kind) = if (row.kind == .match) .preview else .context; + if (following.kind != expected or following.code_start != 0 or following.location_end != 0 or + following.declaration != row.declaration or !sameSavedLocation(row, following)) return error.InvalidLocationRows; + } + const code_len = line.len - row.code_start; + if (row.colors_b64.len > std.base64.standard.Encoder.calcSize(code_len)) return error.InvalidLocationRows; + const colors = try dump.decodeBytes(gpa, row.colors_b64); + errdefer gpa.free(colors); + if (colors.len != 0 and colors.len != code_len) return error.InvalidLocationRows; + for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidLocationRows; + const path = try gpa.dupe(u8, row.path); + out.* = .{ + .kind = @enumFromInt(@intFromEnum(row.kind)), + .declaration = row.declaration, + .path = path, + .at = .{ .line = row.line, .col = row.col, .end_line = row.end_line, .end_col = row.end_col }, + .location_end = row.location_end, + .code_start = row.code_start, + .colors = colors, + }; + initialized += 1; + previous_line = line; + } + if (lines.next()) |remaining| if (remaining.len != 0 or lines.next() != null) return error.InvalidLocationRows; + return rows; +} + +test "location metadata restore rejects offsets and invalid syntax bytes" { + const gpa = std.testing.allocator; + var row: dump.LocationRow = .{ + .kind = .context, + .path = "x.zig", + .line = 1, + .location_end = 0, + .code_start = 3, + }; + const rows = try restoreLocationRows(gpa, "| \tx\n", &.{row}); + defer locations.freeRows(gpa, rows); + try std.testing.expectEqualStrings("x.zig", rows[0].path); + row.code_start = 8; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); + row.code_start = 3; + row.colors_b64 = "/w=="; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); + row.colors_b64 = ""; + row.kind = .match; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); +} + +test "stacked location metadata requires matching adjacent preview ownership" { + const gpa = std.testing.allocator; + const header = "x.c:2:1-3"; + const content = header ++ "\nfoo\n"; + const match: dump.LocationRow = .{ .kind = .match, .path = "x.c", .line = 2, .col = 1, .end_line = 2, .end_col = 3, .location_end = header.len, .code_start = header.len }; + const preview: dump.LocationRow = .{ .kind = .preview, .path = "x.c", .line = 2, .col = 1, .end_line = 2, .end_col = 3, .location_end = 0, .code_start = 0 }; + const restored = try restoreLocationRows(gpa, content, &.{ match, preview }); + defer locations.freeRows(gpa, restored); + try std.testing.expectEqual(.preview, restored[1].kind); + try std.testing.expectEqual(restored[0].at, restored[1].at); + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "foo\n", &.{preview})); + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, header ++ "\n", &.{match})); + var inline_match = match; + inline_match.code_start += 1; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, header ++ "\t\nfoo\n", &.{ inline_match, preview })); + var wrong = preview; + wrong.path = "other.c"; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); + wrong = preview; + wrong.line = 3; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); + wrong = preview; + wrong.code_start = 1; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); +} + +pub fn graphemeDisplayWidth(grapheme: []const u8) usize { + if (std.mem.eql(u8, grapheme, "\t")) return config.tab_width; + if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1; + return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); +} + +pub fn byteDisplayWidth(byte: u8) usize { + return if (byte == '\t') config.tab_width else 1; +} + +pub fn displayWidth(text: []const u8) usize { + var width: usize = 0; + var at: usize = 0; + while (at < text.len) { + const end = modal.nextGrapheme(text, at); + width +|= graphemeDisplayWidth(text[at..end]); + at = end; + } + return width; +} + +/// Source byte at a zero-based display column. Every cell occupied by a tab +/// maps back to that one tab byte. +pub fn byteAtDisplay(text: []const u8, display_col: usize) usize { + var col: usize = 0; + var at: usize = 0; + while (at < text.len) { + const end = modal.nextGrapheme(text, at); + const next = col +| graphemeDisplayWidth(text[at..end]); + if (display_col < next) return at; + col = next; + at = end; + } + return text.len; +} + +/// File cursor columns may live past EOL. Tabs expand before that boundary; +/// every virtual column after it remains one screen cell. +pub fn rawDisplayCol(line_text: []const u8, raw_col: usize) usize { + const bounded = modal.graphemeStart(line_text, @min(raw_col, line_text.len)); + return displayWidth(line_text[0..bounded]) +| (raw_col -| line_text.len); +} + +pub fn rawAtDisplay(line_text: []const u8, display_col: usize) usize { + const width = displayWidth(line_text); + if (display_col > width) return line_text.len +| (display_col - width); + return byteAtDisplay(line_text, display_col); +} + +pub fn byteAtDisplayFrom(line_text: []const u8, from_raw: usize, display_col: usize) usize { + if (from_raw >= line_text.len) return from_raw +| display_col; + const from = modal.graphemeStart(line_text, from_raw); + return from +| rawAtDisplay(line_text[from..], display_col); +} + +pub fn lineDisplayOffset(line_text: []const u8, from_raw: usize, to_raw: usize) i32 { + const from_display = rawDisplayCol(line_text, from_raw); + const to_display = rawDisplayCol(line_text, to_raw); + if (to_display >= from_display) return @intCast(to_display - from_display); + return -@as(i32, @intCast(from_display - to_display)); +} + +pub fn lineDisplayEndOffset(line_text: []const u8, from_raw: usize, at_raw: usize) i32 { + const start = lineDisplayOffset(line_text, from_raw, at_raw); + if (at_raw >= line_text.len) return start; + const at = modal.graphemeStart(line_text, at_raw); + const end = modal.nextGrapheme(line_text, at); + return start + @as(i32, @intCast(graphemeDisplayWidth(line_text[at..end]))) - 1; +} + +pub fn sourceLine(pane: *const Pane, row: i32) []const u8 { + const f = if (pane.file) |*file| file else return ""; + if (row < 0) return ""; + const line: usize = @intCast(row); + if (f.line_starts.len == 0) return modal.lineSlice(f.content, line); + if (line >= f.line_starts.len) return ""; + const start = f.line_starts[line]; + const end = if (line + 1 < f.line_starts.len) f.line_starts[line + 1] - 1 else f.content.len; + 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; + defer p.gpa.free(carried); + 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); + } + } +} + +pub fn displayOffset(pane: *const Pane, row: i32, from_raw: i32, to_raw: i32) i32 { + const line_text = sourceLine(pane, row); + const from: usize = @intCast(@max(0, from_raw)); + const to: usize = @intCast(@max(0, to_raw)); + return lineDisplayOffset(line_text, from, to); +} + +pub fn displayEndOffset(pane: *const Pane, row: i32, from_raw: i32, at_raw: i32) i32 { + const line_text = sourceLine(pane, row); + return lineDisplayEndOffset(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, at_raw))); +} + +pub fn byteAtRowDisplay(pane: *const Pane, row: i32, from_raw: i32, display_col: i32) i32 { + const line_text = sourceLine(pane, row); + return @intCast(byteAtDisplayFrom(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col)))); +} + +pub fn gutterWidth(pane: *const Pane) u16 { + if (pane.file == null) return 0; + const file = &pane.file.?; + var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); + var digits: u16 = 1; + while (lines >= 10) : (lines /= 10) digits += 1; + return @max(config.PREFIX_W, digits + 1); +} + +/// Convert between rendered cells and UTF-8 byte columns. Tag rows always +/// need grapheme conversion; file body rows additionally skip the gutter. +pub fn renderedLineByteCol(pane: *const Pane, row: i32, line_text: []const u8, display_col: usize) usize { + if (row < pardes.BOX_H) return rawAtDisplay(line_text, display_col); + if (pane.file == null) return rawAtDisplay(line_text, display_col); + const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len); + if (display_col <= prefix) return display_col; + return prefix +| rawAtDisplay(line_text[prefix..], display_col - prefix); +} + +pub fn renderedLineDisplayCol(pane: *const Pane, row: i32, line_text: []const u8, byte_col: usize) usize { + if (row < pardes.BOX_H) return rawDisplayCol(line_text, byte_col); + if (pane.file == null) return rawDisplayCol(line_text, byte_col); + const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len); + if (byte_col <= prefix) return byte_col; + 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_width; + 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", "\xe4\xb8", + }) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g)); +} + +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; + while (used < width and end < text.len) { + const b = text[end]; + if (b < 0x20 or b >= 0x7f) break; + if (end + 1 < text.len and text[end + 1] >= 0x80) break; + used += 1; + end += 1; + } + 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; +} + +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 fn lineCount(content: []const u8) usize { + return std.mem.count(u8, content, "\n") + 1; +} + +// Content changes invalidate this lazily rebuilt byte-offset index. +pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { + if (f.line_starts.len > 0) return f.line_starts; + // Exact allocation: deinitPane frees `line_starts` itself, so the stored + // slice must span the complete allocation rather than spare capacity. + const starts = try gpa.alloc(usize, lineCount(f.content)); + starts[0] = 0; + var i: usize = 1; + var off: usize = 0; + while (std.mem.indexOfScalarPos(u8, f.content, off, '\n')) |nl| { + off = nl + 1; + starts[i] = off; + i += 1; + } + f.line_starts = starts; + return starts; +} + +/// The line index of `new` from `old`'s: an edit replaces one span, so +/// line starts before it stand, starts after it shift, and only the span +/// is scanned. Rebuilding scanned the whole file on every keystroke. +fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8) ![]usize { + const n = @min(old.len, new.len); + var head: usize = 0; + while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; + while (head < n and old[head] == new[head]) head += 1; + var tail: usize = 0; + while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; + while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; + // A start s follows the newline at s-1: kept while that newline is in + // the common head, shifted while it is in the common tail. + const kept = std.sort.upperBound(usize, starts, head, struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order); + const old_tail_at = old.len - tail; + const moved = starts.len - std.sort.upperBound(usize, starts, old_tail_at, struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order); + const middle = new[head .. new.len - tail]; + const out = try gpa.alloc(usize, kept + std.mem.count(u8, middle, "\n") + moved); + @memcpy(out[0..kept], starts[0..kept]); + var i = kept; + var off: usize = 0; + while (std.mem.indexOfScalarPos(u8, middle, off, '\n')) |nl| { + off = nl + 1; + out[i] = head + off; + i += 1; + } + for (starts[starts.len - moved ..]) |start| { + out[i] = start + new.len - old.len; + i += 1; + } + return out; +} + +test "edited line index equals a rebuilt one" { + const gpa = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(7); + 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)]); + for (0..2000) |_| { + var old_state: State = undefined; + old_state.content = text.items; + old_state.line_starts = &.{}; + const starts = try lineIndex(gpa, &old_state); + defer gpa.free(starts); + // one random replace, like any edit through setContent + const at = r.uintAtMost(usize, text.items.len); + const del = r.uintAtMost(usize, @min(8, text.items.len - at)); + var ins: [8]u8 = undefined; + const ins_len = r.uintAtMost(usize, 8); + for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)]; + const old = try gpa.dupe(u8, text.items); + defer gpa.free(old); + try text.replaceRange(gpa, at, del, ins[0..ins_len]); + const edited = try editedLineStarts(gpa, starts, old, text.items); + defer gpa.free(edited); + var fresh_state: State = undefined; + fresh_state.content = text.items; + fresh_state.line_starts = &.{}; + const fresh = try lineIndex(gpa, &fresh_state); + defer gpa.free(fresh); + try std.testing.expectEqualSlices(usize, fresh, edited); + } +} + +/// 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); + return idx.len; +} + +/// byte offset of line `row`, or content.len past the end — modal +/// .lineStartOffset's contract exactly, without its walk +pub fn lineStart(gpa: std.mem.Allocator, f: *State, row: usize) usize { + const idx = lineIndex(gpa, f) catch return modal.lineStartOffset(f.content, row); + return if (row >= idx.len) f.content.len else idx[row]; +} + +pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const []const u8 { + const index = try lineIndex(pane.gpa, f); + const lines = try arena.alloc([]const u8, index.len); + for (index, 0..) |start, i| { + const end = if (i + 1 < index.len) index[i + 1] - 1 else f.content.len; + lines[i] = f.content[start..end]; + } + return lines; +} + +/// Use the file's line index only when `text` is its complete live content. +/// Edit-buffer fragments and other temporary text retain modal's scan path. +fn contentIndex(pane: *Pane, text: []const u8) ?[]const usize { + const f = if (pane.file) |*file| file else return null; + if (text.ptr != f.content.ptr or text.len != f.content.len) return null; + return lineIndex(pane.gpa, f) catch null; +} + +pub fn textOffset(pane: *Pane, text: []const u8, cursor: modal.Cursor) usize { + const index = contentIndex(pane, text) orelse return modal.offsetAt(text, cursor); + const row = @min(cursor.row, index.len - 1); + const start = index[row]; + const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; + return start + modal.graphemeStart(text[start..end], @min(cursor.col, end - start)); +} + +pub fn textLineStart(pane: *Pane, text: []const u8, row: usize) usize { + const index = contentIndex(pane, text) orelse return modal.lineStartOffset(text, row); + return if (row >= index.len) text.len else index[row]; +} + +pub fn textLine(pane: *Pane, text: []const u8, row: usize) []const u8 { + const index = contentIndex(pane, text) orelse return modal.lineSlice(text, row); + if (row >= index.len) return ""; + const start = index[row]; + const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; + 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, 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, fragment, row), + ); + } + try std.testing.expectEqual(allocations, allocator.allocations); +} + +pub fn textLineCount(pane: *Pane, text: []const u8) usize { + const index = contentIndex(pane, text) orelse return modal.cursorLineCount(text); + return index.len; +} + +pub fn textPosition(pane: *Pane, text: []const u8, offset: usize) modal.Cursor { + const index = contentIndex(pane, text) orelse return modal.positionAt(text, offset); + const bounded = @min(offset, text.len); + const row = std.sort.upperBound(usize, index, bounded, struct { + fn cmp(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.cmp) - 1; + const start = index[row]; + const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; + return .{ .row = row, .col = modal.graphemeStart(text[start..end], @min(bounded - start, end - start)) }; +} + +pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { + std.debug.assert(p.panes[id] == null and !p.reserved_slots[id]); + const path_copy = try p.gpa.dupe(u8, path); + errdefer p.gpa.free(path_copy); + const pane = try Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + errdefer p.gpa.destroy(pane); + const history = try History.create(p.gpa); + errdefer p.gpa.destroy(history); + p.reserved_slots[id] = true; + defer p.reserved_slots[id] = false; + const content = try filesystem.read(p, path); + errdefer p.gpa.free(content); + const total = lineCount(content); + const scroll: usize = if (line > 0 and line <= total) line - 1 else 0; + pane.file = .{ .path = path_copy, .content = content, .scroll = scroll, .history = history }; + pane.cur_pinned = true; + pane.cur_row = @intCast(scroll); + p.installPane(id, pane); + if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + return pane; +} + +pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { + const saved = src.file.?; + if (saved.mini_source.len > 0) { + const encoded_limit = std.base64.standard.Encoder.calcSize(Mini.max_output_bytes); + if (saved.mini_source.len >= 4096 or saved.content.len > Mini.max_output_bytes or + saved.content_b64.len > encoded_limit or saved.mini_colors_b64.len > encoded_limit) + return error.InvalidMini; + } + const content: []u8 = if (saved.content_b64.len > 0) + try dump.decodeBytes(p.gpa, saved.content_b64) + else + try p.gpa.dupe(u8, saved.content); + errdefer p.gpa.free(content); + const path = try p.gpa.dupe(u8, saved.path); + errdefer p.gpa.free(path); + + const output: ?Output.State = if (Output.fromWord(saved.origin)) |origin| blk: { + var value: Output.State = .{ .from = origin }; + try Output.setArg(&value, saved.origin_arg); + break :blk value; + } else null; + + if (saved.location_rows.len != 0 and output == null) return error.InvalidLocationRows; + const location_rows = try restoreLocationRows(p.gpa, content, saved.location_rows); + errdefer locations.freeRows(p.gpa, location_rows); + + var mini: ?Mini.State = null; + errdefer if (mini) |*state| state.deinit(p.gpa); + if (saved.mini_source.len > 0) { + if (output == null or !std.meta.eql(output.?.from, Output.Origin{ .cmd = .Mini })) return error.InvalidMini; + const source = try p.gpa.dupe(u8, saved.mini_source); + errdefer p.gpa.free(source); + const colors = try dump.decodeBytes(p.gpa, saved.mini_colors_b64); + errdefer p.gpa.free(colors); + if (colors.len != content.len or colors.len > Mini.max_output_bytes) return error.InvalidMini; + for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMini; + mini = .{ .source = source, .colors = colors }; + } else if (saved.mini_colors_b64.len > 0) return error.InvalidMini; + + const history = try History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(id); + pane.file = .{ + .path = path, + .content = content, + .output = output, + .mini = mini, + .location_rows = location_rows, + .scroll = src.scroll, + .revision = @intFromBool(saved.dirty), + .history = history, + }; + pane.file.?.tree_context = saved.tree_context and supportsContext(pane); + pane.cur_pinned = true; + pane.cur_row = @intCast(src.scroll); + pane.cols = @max(1, src.cols); + pane.rows = @max(1, src.rows); + if (output == null and filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true, .mode = .baseline_disk } }); + return pane; +} + +pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { + if (file.output == null) for (p.panes, 0..) |slot, id| { + if (slot == pane) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); + }; + p.gpa.free(file.path); + p.gpa.free(file.content); + if (file.mini) |*mini| mini.deinit(p.gpa); + if (file.line_starts.len > 0) p.gpa.free(file.line_starts); + if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); + locations.freeRows(p.gpa, file.location_rows); + if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); + for (file.history.undo[0..file.history.undo_len]) |snap| p.gpa.free(snap.content); + for (file.history.redo[0..file.history.redo_len]) |snap| p.gpa.free(snap.content); + p.gpa.destroy(file.history); +} + +fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { + if (p.fs.listeners == 0) return; + const id = for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + if (pane.file) |*state| if (state == f) break i; + } else return; + pardes.ctlfs.events.noteReplace(p, id, false, f.content, new); +} + +pub fn setContent(p: *Pardes, f: *State, new: []u8) void { + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = &.{}; + for (p.panes) |slot| if (slot) |pane| { + if (pane.file) |*file| if (file == f) { + for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + } + }; + }; + reportEdit(p, f, new); + if (f.mini) |*mini| mini.deinit(p.gpa); + f.mini = null; + const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new) catch &.{} else &.{}; + p.gpa.free(f.content); + f.content = new; + f.revision +%= 1; + f.mtime = pardes.ctlfs.events.now(); + if (f.line_starts.len > 0) p.gpa.free(f.line_starts); + f.line_starts = starts; + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = true; +} + +pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { + const n = nlines(pane.gpa, f); + const row: usize = @min(@as(usize, @intCast(@max(0, snap.cur_row))), n - 1); + const llen = modal.lineSlice(f.content, row).len; + pane.cur_row = @intCast(row); + pane.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, snap.cur_col))), llen)); + pane.vsel = snap.vsel; + pane.msel.active = false; + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); +} + +fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, snap: Snapshot) void { + if (len.* == slots.len) { + gpa.free(slots[0].content); + std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); + len.* -= 1; + } + slots[len.*] = snap; + len.* += 1; +} + +pub fn pushUndo(p: *Pardes, pane: *Pane) void { + const f = if (pane.file) |*file| file else return; + const history = f.history; + if (history.undo_len > 0 and std.mem.eql(u8, history.undo[history.undo_len - 1].content, f.content)) return; + const snap: Snapshot = .{ + .content = p.gpa.dupe(u8, f.content) catch return, + .cur_row = pane.cur_row, + .cur_col = pane.cur_col, + .vsel = pane.vsel, + }; + pushHistory(p.gpa, &history.undo, &history.undo_len, snap); + for (history.redo[0..history.redo_len]) |item| p.gpa.free(item.content); + history.redo_len = 0; +} + +pub fn undo(p: *Pardes, pane: *Pane) void { + const f = if (pane.file) |*file| file else return; + const history = f.history; + if (history.undo_len == 0) return; + const current: Snapshot = .{ + .content = p.gpa.dupe(u8, f.content) catch return, + .cur_row = pane.cur_row, + .cur_col = pane.cur_col, + .vsel = pane.vsel, + }; + pushHistory(p.gpa, &history.redo, &history.redo_len, current); + history.undo_len -= 1; + const previous = history.undo[history.undo_len]; + setContent(p, f, previous.content); + restoreSnap(pane, f, previous); +} + +pub fn redo(p: *Pardes, pane: *Pane) void { + const f = if (pane.file) |*file| file else return; + const history = f.history; + if (history.redo_len == 0) return; + const current: Snapshot = .{ + .content = p.gpa.dupe(u8, f.content) catch return, + .cur_row = pane.cur_row, + .cur_col = pane.cur_col, + .vsel = pane.vsel, + }; + pushHistory(p.gpa, &history.undo, &history.undo_len, current); + history.redo_len -= 1; + const next = history.redo[history.redo_len]; + setContent(p, f, next.content); + restoreSnap(pane, f, next); +} + +/// Commit an externally rewritten file onto the same undo history as typed +/// edits. Unsaved work remains one `u` away; there is no third merge state. +pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { + const pane = p.panes[id] orelse return; + const f = if (pane.file) |*file| file else return; + if (std.mem.eql(u8, f.content, bytes)) return; + const new = p.gpa.dupe(u8, bytes) catch return; + pushUndo(p, pane); + setContent(p, f, new); + f.saved_revision = f.revision; + // restoreSnap only consumes cursor/selection from this synthetic snapshot. + restoreSnap(pane, f, .{ + .content = undefined, + .cur_row = pane.cur_row, + .cur_col = pane.cur_col, + .vsel = pane.vsel, + }); +} + +/// re-highlight the visible window of any file whose syntax went stale +/// (edit, scroll, load) — visible-range-first so big files stay snappy +pub fn refreshHighlights(p: *Pardes) void { + const tz = tracy.zone(@src(), "refreshHighlights"); + defer tz.end(); + for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.file == null) continue; + const f = &pane.file.?; + if (f.tree_context and supportsContext(pane) and f.context_revision != f.revision) { + const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, f.content) catch continue; + if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations); + f.context_declarations = declarations; + f.context_revision = f.revision; + } + if (f.mini != null) { + f.syntax_dirty = false; + continue; + } + if (!f.syntax_dirty) continue; + if (!p.settings.colors) { + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = false; + continue; + } + const need_start = lineStart(p.gpa, f, f.scroll); + const need_end = @max(need_start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS)); + if ((!f.tree_context or (f.highlight_start == 0 and f.highlights.len == f.content.len)) and + f.highlights.len > 0 and need_start >= f.highlight_start and + need_end <= f.highlight_start + f.highlights.len) + { + f.syntax_dirty = false; + continue; + } + const slack: usize = if (f.highlights.len == 0) 0 else pane.rows; + const whole = pane.colorAlgo() == .locations or f.tree_context; + const start = if (whole) 0 else lineStart(p.gpa, f, f.scroll -| slack); + const end = if (whole) + f.content.len + else + @max(start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS + slack)); + const new_highlights = (switch (pane.colorAlgo()) { + .none => @as([]u8, &.{}), + .diff => syntax.highlightDiff(p.tree_sitter_gpa, f.content, start, end), + .locations => if (f.location_rows.len > 0) + syntax.highlightLocationRows(p.tree_sitter_gpa, f.content, f.location_rows) + else + syntax.highlightLocations(p.tree_sitter_gpa, f.content, start, end), + else => syntax.highlightFileRange(p.tree_sitter_gpa, f.path, f.content, start, end), + }) catch { + f.syntax_dirty = false; + continue; + }; + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = new_highlights; + f.highlight_start = if (f.highlights.len > 0) start else 0; + f.syntax_dirty = false; + } +} + +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); +} + +fn prepareContextRows(pane: *Pane, file: *State) void { + pane.context_rows = 0; + if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return; + const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row + for (file.context_declarations) |declaration| { + if (declaration.start_line >= file.scroll) break; + if (declaration.end_line < file.scroll) continue; + var row = declaration.start_line; + while (row <= declaration.header_end_line and row < file.scroll) : (row += 1) { + if (pane.context_rows >= capacity) return; + if (pane.context_rows > 0 and row <= pane.wrap_line[pane.context_rows - 1]) continue; + pane.wrap_line[pane.context_rows] = @intCast(row); + pane.context_rows += 1; + } + } +} + +pub fn wrapWidth(pane: *const Pane, wrap: bool) usize { + if (!wrap or pane.rows > pane.wrap_line.len) return 0; + return @max(1, @as(usize, pane.cols -| gutterWidth(pane)) -| 1); +} + +pub const VisualRow = struct { start: usize, end: usize }; + +pub fn visualRow(line: []const u8, col: usize, width: usize) VisualRow { + if (width == 0) return .{ .start = 0, .end = line.len }; + var start: usize = 0; + while (true) { + const end = fitEnd(line, start, width); + if (col < end or end >= line.len) return .{ .start = start, .end = end }; + start = end; + } +} + +pub fn bodyText(arena: std.mem.Allocator, pane: *Pane, f: *State, wrap: bool) ![]const u8 { + const width = wrapWidth(pane, wrap); + pane.body_wrapped = width > 0; + prepareContextRows(pane, f); + pane.wrap_n = 0; + + const len = fillBody(null, pane, f, width, false); + const out = try arena.alloc(u8, len); + const filled = fillBody(out, pane, f, width, true); + std.debug.assert(filled == out.len); + return out; +} + +/// Run the file-body row walk. With no destination it is the exact sizing +/// pass; with one it fills that allocation and records the wrapping map. +fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) usize { + if (record_wrap) pane.wrap_n = 0; + const prefix_width = gutterWidth(pane); + const total = nlines(pane.gpa, f); + var body_line: usize = f.scroll; + var body_at: usize = 0; + var written: usize = 0; + for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| { + if (i > 0) { + if (dst) |out| out[written] = '\n'; + written += 1; + } + const context = i < pane.context_rows; + const row = if (context) @as(usize, @intCast(pane.wrap_line[i])) else body_line; + const at = if (context) 0 else body_at; + const text = if (row < total) sourceLine(pane, @intCast(row)) else ""; + // Headers use one screen row per source row, preserving signatures + // without allowing a long ancestor to consume the whole viewport. + const end = if (width == 0 or context) text.len else fitEnd(text, at, width); + const cut = if (pane.hscroll > 0 and width == 0) + modal.graphemeStart(text, @min(@as(usize, @intCast(pane.hscroll)), text.len)) + else + at; + if ((width > 0 or pane.context_rows > 0) and record_wrap) { + pane.wrap_line[i] = @intCast(row); + pane.wrap_col[i] = @intCast(cut); + pane.wrap_n = @intCast(i + 1); + } + if (row < total) { + var lbuf: [@max(config.PREFIX_W, 32)]u8 = undefined; + const prefix = lbuf[0..prefix_width]; + @memset(prefix, ' '); + if (at == 0) { + var lineno = row + 1; + var digit: usize = prefix.len - 1; + while (true) { + digit -= 1; + prefix[digit] = '0' + @as(u8, @intCast(lineno % 10)); + lineno /= 10; + if (lineno == 0) break; + } + } + if (dst) |out| @memcpy(out[written..][0..prefix.len], prefix); + written += prefix.len; + const shown = text[cut..end]; + if (dst) |out| @memcpy(out[written..][0..shown.len], shown); + written += shown.len; + } + if (!context) { + if (width > 0 and end < text.len) { + body_at = end; + } else { + body_line += 1; + body_at = 0; + } + } + } + return written; +} + +pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { + const s = &p.surface; + const prefix_width = gutterWidth(pane); + const goff = pane.scroll(); + const gcur = Terminal.gridCursor(pane); + const gcrow = if (pane.cur_pinned) pane.cur_row else @as(i32, gcur.y) + goff; + const cur_line: i32 = if (active and !pane.tag_edit) gcrow else std.math.minInt(i32); + // the body's first row, the way renderPane derives it (Tagbottom) + const body_y = p.bodyTop(r); + const context_bg = p.theme().tag_bg; + for (0..@min(pane.context_rows, body_h)) |context_row| { + for (0..tw) |col| { + const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(context_row))); + cell.default = false; + cell.style.bg = .{ .rgb = context_bg }; + if (p.settings.tree_context_tag_style) cell.style.font_role = .tagline; + } + } + var vr: u16 = 0; + while (vr < body_h) : (vr += 1) { + const row_line: i32 = if (pane.wrap_n == 0) + goff + @as(i32, vr) + else if (vr < pane.wrap_n) pane.wrap_line[vr] else std.math.maxInt(i32); + const on_cursor = row_line == cur_line; + var c: u16 = 0; + while (c < prefix_width and c < tw) : (c += 1) { + const cell = s.at(tx + c, body_y + vr); + cell.default = false; // paints blank gutter rows too + cell.style.fg = .{ .rgb = if (on_cursor) + p.theme().lineno_active orelse p.theme().lineno + else + p.theme().lineno }; + cell.style.bold = on_cursor; + } + } +} + +const SynStyle = struct { fg: [3]u8, bold: bool }; + +fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { + return switch (sy) { + .none => null, + .keyword => .{ .fg = p.theme().kw, .bold = p.settings.syntax_bold }, + .string => .{ .fg = p.theme().str, .bold = false }, + .number => .{ .fg = p.theme().num, .bold = false }, + .comment => .{ .fg = p.theme().comment, .bold = false }, + }; +} + +/// syntax colors: recolor each content cell from its tree-sitter style byte; +/// content starts after the lineno gutter +pub fn recolorSyntax(p: *Pardes, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { + const highlights = if (f.mini) |mini| mini.colors else f.highlights; + const highlight_start = if (f.mini != null) 0 else f.highlight_start; + if (highlights.len == 0 and f.output == null) return; + const s = &p.surface; + const prefix_width = gutterWidth(pane); + const tz_recolor = tracy.zone(@src(), "synRecolor"); + defer tz_recolor.end(); + // indexed start, same as bodyText — an empty tail simply paints nothing + var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); + const total = nlines(p.gpa, f); + const body_y = p.bodyTop(r); + var vr: u16 = 0; + while (vr < body_h) : (vr += 1) { + var base: usize = undefined; + var line: []const u8 = undefined; + var hs: usize = @intCast(@max(0, pane.hscroll)); + var limit: usize = undefined; + if (pane.wrap_n == 0) { + line = flines.next() orelse break; + base = @intFromPtr(line.ptr) - @intFromPtr(f.content.ptr); + limit = line.len; + } else { + if (vr >= pane.wrap_n) break; + const lrow: usize = @intCast(@max(0, pane.wrap_line[vr])); + if (lrow >= total) break; + base = lineStart(p.gpa, f, lrow); + const lend = if (lrow + 1 < total) lineStart(p.gpa, f, lrow + 1) -| 1 else f.content.len; + line = f.content[base..lend]; + hs = @intCast(pane.wrap_col[vr]); + limit = if (vr + 1 < pane.wrap_n and pane.wrap_line[vr + 1] == pane.wrap_line[vr]) + @min(line.len, @as(usize, @intCast(pane.wrap_col[vr + 1]))) + else + line.len; + } + hs = modal.graphemeStart(line, @min(hs, line.len)); + const row_index: usize = @intCast(@max(0, pane.wrapAt(vr).line)); + const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null; + const decoration = Output.decorateRow(f.output, line, metadata); + var c: usize = 0; + var screen_c: usize = 0; + while (hs + c < limit and prefix_width + screen_c < tw) { + const grapheme_end = @min(limit, modal.nextGrapheme(line, hs + c)); + const cells = graphemeDisplayWidth(line[hs + c .. grapheme_end]); + const idx = base + hs + c; + if (idx >= highlight_start) { + const hidx = idx - highlight_start; + if (hidx < highlights.len) { + if (synStyle(p, @enumFromInt(highlights[hidx]))) |ss| { + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); + if (cell.default) continue; + cell.style.fg = .{ .rgb = ss.fg }; + cell.style.bold = ss.bold; + } + } + } + } + // Results keep their exact live text. Only the location, + // matched source range and diagnostic label gain emphasis. + if (decoration.styleAt(p, hs + c)) |style| { + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); + if (cell.default) continue; + cell.style.fg = style.fg; + cell.style.bold = style.bold; + if (style.bg != .default) cell.style.bg = style.bg; + } + } + screen_c += cells; + c = grapheme_end - hs; + } + } +} + +pub fn drawWrapMarkers( + p: *Pardes, + pane: *const Pane, + r: pardes.Rect, + tx: u16, + tw: u16, + body_h: u16, + pane_bg: pardes.Color, +) void { + if (tw <= gutterWidth(pane) + 1) return; + const body_y = p.bodyTop(r); + const marker_fg = p.chromeTheme().lineno; + var row: u16 = 0; + while (row + 1 < pane.wrap_n and row + 1 < body_h) : (row += 1) { + if (pane.wrap_line[row + 1] != pane.wrap_line[row]) continue; + p.surface.set(tx + tw - 1, body_y + row, config.wrap_marker, .{ + .fg = .{ .rgb = marker_fg }, + .bg = pane_bg, + }); + } +} + +pub fn paintWordSelection( + p: *Pardes, + pane: *Pane, + r: pardes.Rect, + row: i32, + word_lo: i32, + word_hi: i32, + bg: [3]u8, +) void { + const tx = r.x + config.GUTTER; + const tw = r.w - config.GUTTER; + const prefix_width = gutterWidth(pane); + const body_y = p.bodyTop(r); + var vr: i32 = 0; + while (vr + @as(i32, pardes.BOX_H) < @as(i32, r.h)) : (vr += 1) { + const here = pane.wrapAt(vr); + if (here.line != row) continue; + var hi = word_hi; + const next = pane.wrapAt(vr + 1); + if (next.line == row) hi = @min(hi, next.at); + const lo = @max(word_lo, here.at); + if (hi <= lo) continue; + const c0 = @as(i32, prefix_width) + displayOffset(pane, row, here.at, lo); + const c1 = @as(i32, prefix_width) + displayEndOffset(pane, row, here.at, hi - 1); + var col = @max(@as(i32, prefix_width), c0); + while (col <= c1 and col < @as(i32, tw)) : (col += 1) { + const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); + cell.default = false; + cell.style.bg = .{ .rgb = bg }; + } + } +} diff --git a/src/fs.zig b/src/fs.zig index e6ebddf2..8ed6fc77 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -36,6 +36,7 @@ else const source_files = [_]Source{ .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, + .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, diff --git a/src/panes.zig b/src/panes.zig index 6ee7d70b..051470b1 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -1120,1293 +1120,7 @@ pub const Pane = struct { } }; -pub const File = struct { - const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; - - /// Content and primary selection at one file edit boundary. Keeping only the - /// primary avoids putting Pane.max_selections ranges in every history entry. - pub const Snapshot = struct { - content: []u8, - cur_row: i32, - cur_col: i32, - vsel: Pane.CharSel, - }; - - pub const History = struct { - undo: [limits.undo_max]Snapshot = undefined, - undo_len: usize = 0, - redo: [limits.undo_max]Snapshot = undefined, - redo_len: usize = 0, - - pub fn create(gpa: std.mem.Allocator) !*History { - const history = try gpa.create(History); - history.undo_len = 0; - history.redo_len = 0; - return history; - } - }; - - /// A file pane's backing: owned content, its derived caches, and undo history. - pub const State = struct { - path: []u8, - content: []u8, - revision: u32 = 0, - /// Revision last known to match disk, after Save or an external reload. - /// Equal means the screen matches disk. - saved_revision: u32 = 0, - watch_after_save: bool = false, - /// Seconds of the last content change, for the filesystem's stat; zero until edited. - mtime: u32 = 0, - /// Non-null for a generated output buffer rather than an on-disk file. - output: ?Output.State = null, - mini: ?Mini.State = null, - scroll: usize = 0, - /// `line_starts[i]` is line i's byte offset. Empty means not built yet. - line_starts: []usize = &.{}, - /// One tree_sitter_gpa-owned syntax.Syn byte per highlighted source byte. - highlights: []u8 = &.{}, - location_rows: []locations.Row = &.{}, - highlight_start: usize = 0, - syntax_dirty: bool = true, - tree_context: bool = false, - context_declarations: []syntax.ContextDeclaration = &.{}, - context_revision: ?u32 = null, - history: *History, - }; - - pub fn dumpPane( - arena: std.mem.Allocator, - pane: *const Pane, - file: *const State, - tag: []const u8, - body: []const u8, - scroll: usize, - origin: []const u8, - origin_arg: []const u8, - ) !dump.Pane { - return .{ - .kind = .file, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .file = .{ - .tree_context = file.tree_context, - .location_rows = try dumpLocationRows(arena, file.location_rows), - .path = file.path, - .content = file.content, - .content_b64 = try dump.encodeBytes(arena, file.content), - .dirty = file.revision != file.saved_revision, - .origin = origin, - .origin_arg = origin_arg, - .mini_source = if (file.mini) |mini| mini.source else "", - .mini_colors_b64 = if (file.mini) |mini| try dump.encodeBytes(arena, mini.colors) else "", - }, - }; - } - - fn dumpLocationRows(arena: std.mem.Allocator, rows: []const locations.Row) ![]const dump.LocationRow { - const saved = try arena.alloc(dump.LocationRow, rows.len); - for (rows, saved) |row, *out| out.* = .{ - .kind = @enumFromInt(@intFromEnum(row.kind)), - .declaration = row.declaration, - .path = row.path, - .line = row.at.line, - .col = row.at.col, - .end_line = row.at.end_line, - .end_col = row.at.end_col, - .location_end = row.location_end, - .code_start = row.code_start, - .colors_b64 = try dump.encodeBytes(arena, row.colors), - }; - return saved; - } - - fn sameSavedLocation(a: dump.LocationRow, b: dump.LocationRow) bool { - return std.mem.eql(u8, a.path, b.path) and a.line == b.line and a.col == b.col and - a.end_line == b.end_line and a.end_col == b.end_col; - } - - fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow) ![]locations.Row { - if (saved.len == 0) return &.{}; - if (saved.len > std.mem.count(u8, content, "\n") + 1) return error.InvalidLocationRows; - const rows = try gpa.alloc(locations.Row, saved.len); - var initialized: usize = 0; - errdefer { - for (rows[0..initialized]) |row| { - gpa.free(row.path); - gpa.free(row.colors); - } - gpa.free(rows); - } - var lines = std.mem.splitScalar(u8, content, '\n'); - var previous_line: []const u8 = ""; - for (saved, rows, 0..) |row, *out, index| { - const line = lines.next() orelse return error.InvalidLocationRows; - if (row.path.len == 0 or row.path.len >= 4096 or - row.location_end > row.code_start or row.code_start > line.len or - (row.kind == .match and row.location_end == 0) or - (row.declaration and row.kind != .context) or - row.line > std.math.maxInt(i32) or row.col > std.math.maxInt(i32) or - row.end_line > std.math.maxInt(i32) or row.end_col > std.math.maxInt(i32)) - return error.InvalidLocationRows; - const inline_row = row.code_start > row.location_end and row.code_start > 0 and line[row.code_start - 1] == '\t'; - const address_row = !inline_row and row.location_end > 0 and row.code_start == line.len; - const source_row = row.location_end == 0 and row.code_start == 0; - if (!inline_row and !address_row and !source_row) return error.InvalidLocationRows; - if (row.kind == .preview) { - if (!source_row or index == 0) return error.InvalidLocationRows; - const previous = saved[index - 1]; - if (previous.kind != .match or previous.location_end == 0 or previous.code_start != previous_line.len or previous_line[previous_line.len - 1] == '\t' or - !sameSavedLocation(previous, row)) return error.InvalidLocationRows; - } - if (address_row) { - if (index + 1 >= saved.len) return error.InvalidLocationRows; - const following = saved[index + 1]; - const expected: @TypeOf(row.kind) = if (row.kind == .match) .preview else .context; - if (following.kind != expected or following.code_start != 0 or following.location_end != 0 or - following.declaration != row.declaration or !sameSavedLocation(row, following)) return error.InvalidLocationRows; - } - const code_len = line.len - row.code_start; - if (row.colors_b64.len > std.base64.standard.Encoder.calcSize(code_len)) return error.InvalidLocationRows; - const colors = try dump.decodeBytes(gpa, row.colors_b64); - errdefer gpa.free(colors); - if (colors.len != 0 and colors.len != code_len) return error.InvalidLocationRows; - for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidLocationRows; - const path = try gpa.dupe(u8, row.path); - out.* = .{ - .kind = @enumFromInt(@intFromEnum(row.kind)), - .declaration = row.declaration, - .path = path, - .at = .{ .line = row.line, .col = row.col, .end_line = row.end_line, .end_col = row.end_col }, - .location_end = row.location_end, - .code_start = row.code_start, - .colors = colors, - }; - initialized += 1; - previous_line = line; - } - if (lines.next()) |remaining| if (remaining.len != 0 or lines.next() != null) return error.InvalidLocationRows; - return rows; - } - - test "location metadata restore rejects offsets and invalid syntax bytes" { - const gpa = std.testing.allocator; - var row: dump.LocationRow = .{ - .kind = .context, - .path = "x.zig", - .line = 1, - .location_end = 0, - .code_start = 3, - }; - const rows = try restoreLocationRows(gpa, "| \tx\n", &.{row}); - defer locations.freeRows(gpa, rows); - try std.testing.expectEqualStrings("x.zig", rows[0].path); - row.code_start = 8; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); - row.code_start = 3; - row.colors_b64 = "/w=="; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); - row.colors_b64 = ""; - row.kind = .match; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); - } - - test "stacked location metadata requires matching adjacent preview ownership" { - const gpa = std.testing.allocator; - const header = "x.c:2:1-3"; - const content = header ++ "\nfoo\n"; - const match: dump.LocationRow = .{ .kind = .match, .path = "x.c", .line = 2, .col = 1, .end_line = 2, .end_col = 3, .location_end = header.len, .code_start = header.len }; - const preview: dump.LocationRow = .{ .kind = .preview, .path = "x.c", .line = 2, .col = 1, .end_line = 2, .end_col = 3, .location_end = 0, .code_start = 0 }; - const restored = try restoreLocationRows(gpa, content, &.{ match, preview }); - defer locations.freeRows(gpa, restored); - try std.testing.expectEqual(.preview, restored[1].kind); - try std.testing.expectEqual(restored[0].at, restored[1].at); - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "foo\n", &.{preview})); - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, header ++ "\n", &.{match})); - var inline_match = match; - inline_match.code_start += 1; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, header ++ "\t\nfoo\n", &.{ inline_match, preview })); - var wrong = preview; - wrong.path = "other.c"; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); - wrong = preview; - wrong.line = 3; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); - wrong = preview; - wrong.code_start = 1; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); - } - - pub fn graphemeDisplayWidth(grapheme: []const u8) usize { - if (std.mem.eql(u8, grapheme, "\t")) return config.tab_width; - if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1; - return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); - } - - pub fn byteDisplayWidth(byte: u8) usize { - return if (byte == '\t') config.tab_width else 1; - } - - pub fn displayWidth(text: []const u8) usize { - var width: usize = 0; - var at: usize = 0; - while (at < text.len) { - const end = modal.nextGrapheme(text, at); - width +|= graphemeDisplayWidth(text[at..end]); - at = end; - } - return width; - } - - /// Source byte at a zero-based display column. Every cell occupied by a tab - /// maps back to that one tab byte. - pub fn byteAtDisplay(text: []const u8, display_col: usize) usize { - var col: usize = 0; - var at: usize = 0; - while (at < text.len) { - const end = modal.nextGrapheme(text, at); - const next = col +| graphemeDisplayWidth(text[at..end]); - if (display_col < next) return at; - col = next; - at = end; - } - return text.len; - } - - /// File cursor columns may live past EOL. Tabs expand before that boundary; - /// every virtual column after it remains one screen cell. - pub fn rawDisplayCol(line_text: []const u8, raw_col: usize) usize { - const bounded = modal.graphemeStart(line_text, @min(raw_col, line_text.len)); - return displayWidth(line_text[0..bounded]) +| (raw_col -| line_text.len); - } - - pub fn rawAtDisplay(line_text: []const u8, display_col: usize) usize { - const width = displayWidth(line_text); - if (display_col > width) return line_text.len +| (display_col - width); - return byteAtDisplay(line_text, display_col); - } - - pub fn byteAtDisplayFrom(line_text: []const u8, from_raw: usize, display_col: usize) usize { - if (from_raw >= line_text.len) return from_raw +| display_col; - const from = modal.graphemeStart(line_text, from_raw); - return from +| rawAtDisplay(line_text[from..], display_col); - } - - pub fn lineDisplayOffset(line_text: []const u8, from_raw: usize, to_raw: usize) i32 { - const from_display = rawDisplayCol(line_text, from_raw); - const to_display = rawDisplayCol(line_text, to_raw); - if (to_display >= from_display) return @intCast(to_display - from_display); - return -@as(i32, @intCast(from_display - to_display)); - } - - pub fn lineDisplayEndOffset(line_text: []const u8, from_raw: usize, at_raw: usize) i32 { - const start = lineDisplayOffset(line_text, from_raw, at_raw); - if (at_raw >= line_text.len) return start; - const at = modal.graphemeStart(line_text, at_raw); - const end = modal.nextGrapheme(line_text, at); - return start + @as(i32, @intCast(graphemeDisplayWidth(line_text[at..end]))) - 1; - } - - pub fn sourceLine(pane: *const Pane, row: i32) []const u8 { - const f = if (pane.file) |*file| file else return ""; - if (row < 0) return ""; - const line: usize = @intCast(row); - if (f.line_starts.len == 0) return modal.lineSlice(f.content, line); - if (line >= f.line_starts.len) return ""; - const start = f.line_starts[line]; - const end = if (line + 1 < f.line_starts.len) f.line_starts[line + 1] - 1 else f.content.len; - 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; - defer p.gpa.free(carried); - 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); - } - } - } - - pub fn displayOffset(pane: *const Pane, row: i32, from_raw: i32, to_raw: i32) i32 { - const line_text = sourceLine(pane, row); - const from: usize = @intCast(@max(0, from_raw)); - const to: usize = @intCast(@max(0, to_raw)); - return lineDisplayOffset(line_text, from, to); - } - - pub fn displayEndOffset(pane: *const Pane, row: i32, from_raw: i32, at_raw: i32) i32 { - const line_text = sourceLine(pane, row); - return lineDisplayEndOffset(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, at_raw))); - } - - pub fn byteAtRowDisplay(pane: *const Pane, row: i32, from_raw: i32, display_col: i32) i32 { - const line_text = sourceLine(pane, row); - return @intCast(byteAtDisplayFrom(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col)))); - } - - pub fn gutterWidth(pane: *const Pane) u16 { - if (pane.file == null) return 0; - const file = &pane.file.?; - var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); - var digits: u16 = 1; - while (lines >= 10) : (lines /= 10) digits += 1; - return @max(config.PREFIX_W, digits + 1); - } - - /// Convert between rendered cells and UTF-8 byte columns. Tag rows always - /// need grapheme conversion; file body rows additionally skip the gutter. - pub fn renderedLineByteCol(pane: *const Pane, row: i32, line_text: []const u8, display_col: usize) usize { - if (row < pardes.BOX_H) return rawAtDisplay(line_text, display_col); - if (pane.file == null) return rawAtDisplay(line_text, display_col); - const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len); - if (display_col <= prefix) return display_col; - return prefix +| rawAtDisplay(line_text[prefix..], display_col - prefix); - } - - pub fn renderedLineDisplayCol(pane: *const Pane, row: i32, line_text: []const u8, byte_col: usize) usize { - if (row < pardes.BOX_H) return rawDisplayCol(line_text, byte_col); - if (pane.file == null) return rawDisplayCol(line_text, byte_col); - const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len); - if (byte_col <= prefix) return byte_col; - 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_width; - 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", "\xe4\xb8", - }) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g)); - } - - 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; - while (used < width and end < text.len) { - const b = text[end]; - if (b < 0x20 or b >= 0x7f) break; - if (end + 1 < text.len and text[end + 1] >= 0x80) break; - used += 1; - end += 1; - } - 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; - } - - 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 fn lineCount(content: []const u8) usize { - return std.mem.count(u8, content, "\n") + 1; - } - - // Content changes invalidate this lazily rebuilt byte-offset index. - pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { - if (f.line_starts.len > 0) return f.line_starts; - // Exact allocation: deinitPane frees `line_starts` itself, so the stored - // slice must span the complete allocation rather than spare capacity. - const starts = try gpa.alloc(usize, lineCount(f.content)); - starts[0] = 0; - var i: usize = 1; - var off: usize = 0; - while (std.mem.indexOfScalarPos(u8, f.content, off, '\n')) |nl| { - off = nl + 1; - starts[i] = off; - i += 1; - } - f.line_starts = starts; - return starts; - } - - /// The line index of `new` from `old`'s: an edit replaces one span, so - /// line starts before it stand, starts after it shift, and only the span - /// is scanned. Rebuilding scanned the whole file on every keystroke. - fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8) ![]usize { - const n = @min(old.len, new.len); - var head: usize = 0; - while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; - while (head < n and old[head] == new[head]) head += 1; - var tail: usize = 0; - while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; - while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; - // A start s follows the newline at s-1: kept while that newline is in - // the common head, shifted while it is in the common tail. - const kept = std.sort.upperBound(usize, starts, head, struct { - fn order(key: usize, item: usize) std.math.Order { - return std.math.order(key, item); - } - }.order); - const old_tail_at = old.len - tail; - const moved = starts.len - std.sort.upperBound(usize, starts, old_tail_at, struct { - fn order(key: usize, item: usize) std.math.Order { - return std.math.order(key, item); - } - }.order); - const middle = new[head .. new.len - tail]; - const out = try gpa.alloc(usize, kept + std.mem.count(u8, middle, "\n") + moved); - @memcpy(out[0..kept], starts[0..kept]); - var i = kept; - var off: usize = 0; - while (std.mem.indexOfScalarPos(u8, middle, off, '\n')) |nl| { - off = nl + 1; - out[i] = head + off; - i += 1; - } - for (starts[starts.len - moved ..]) |start| { - out[i] = start + new.len - old.len; - i += 1; - } - return out; - } - - test "edited line index equals a rebuilt one" { - const gpa = std.testing.allocator; - var prng = std.Random.DefaultPrng.init(7); - 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)]); - for (0..2000) |_| { - var old_state: State = undefined; - old_state.content = text.items; - old_state.line_starts = &.{}; - const starts = try lineIndex(gpa, &old_state); - defer gpa.free(starts); - // one random replace, like any edit through setContent - const at = r.uintAtMost(usize, text.items.len); - const del = r.uintAtMost(usize, @min(8, text.items.len - at)); - var ins: [8]u8 = undefined; - const ins_len = r.uintAtMost(usize, 8); - for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)]; - const old = try gpa.dupe(u8, text.items); - defer gpa.free(old); - try text.replaceRange(gpa, at, del, ins[0..ins_len]); - const edited = try editedLineStarts(gpa, starts, old, text.items); - defer gpa.free(edited); - var fresh_state: State = undefined; - fresh_state.content = text.items; - fresh_state.line_starts = &.{}; - const fresh = try lineIndex(gpa, &fresh_state); - defer gpa.free(fresh); - try std.testing.expectEqualSlices(usize, fresh, edited); - } - } - - /// 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); - return idx.len; - } - - /// byte offset of line `row`, or content.len past the end — modal - /// .lineStartOffset's contract exactly, without its walk - pub fn lineStart(gpa: std.mem.Allocator, f: *State, row: usize) usize { - const idx = lineIndex(gpa, f) catch return modal.lineStartOffset(f.content, row); - return if (row >= idx.len) f.content.len else idx[row]; - } - - pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const []const u8 { - const index = try lineIndex(pane.gpa, f); - const lines = try arena.alloc([]const u8, index.len); - for (index, 0..) |start, i| { - const end = if (i + 1 < index.len) index[i + 1] - 1 else f.content.len; - lines[i] = f.content[start..end]; - } - return lines; - } - - /// Use the file's line index only when `text` is its complete live content. - /// Edit-buffer fragments and other temporary text retain modal's scan path. - fn contentIndex(pane: *Pane, text: []const u8) ?[]const usize { - const f = if (pane.file) |*file| file else return null; - if (text.ptr != f.content.ptr or text.len != f.content.len) return null; - return lineIndex(pane.gpa, f) catch null; - } - - pub fn textOffset(pane: *Pane, text: []const u8, cursor: modal.Cursor) usize { - const index = contentIndex(pane, text) orelse return modal.offsetAt(text, cursor); - const row = @min(cursor.row, index.len - 1); - const start = index[row]; - const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; - return start + modal.graphemeStart(text[start..end], @min(cursor.col, end - start)); - } - - pub fn textLineStart(pane: *Pane, text: []const u8, row: usize) usize { - const index = contentIndex(pane, text) orelse return modal.lineStartOffset(text, row); - return if (row >= index.len) text.len else index[row]; - } - - pub fn textLine(pane: *Pane, text: []const u8, row: usize) []const u8 { - const index = contentIndex(pane, text) orelse return modal.lineSlice(text, row); - if (row >= index.len) return ""; - const start = index[row]; - const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; - 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, 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, fragment, row), - ); - } - try std.testing.expectEqual(allocations, allocator.allocations); - } - - pub fn textLineCount(pane: *Pane, text: []const u8) usize { - const index = contentIndex(pane, text) orelse return modal.cursorLineCount(text); - return index.len; - } - - pub fn textPosition(pane: *Pane, text: []const u8, offset: usize) modal.Cursor { - const index = contentIndex(pane, text) orelse return modal.positionAt(text, offset); - const bounded = @min(offset, text.len); - const row = std.sort.upperBound(usize, index, bounded, struct { - fn cmp(key: usize, item: usize) std.math.Order { - return std.math.order(key, item); - } - }.cmp) - 1; - const start = index[row]; - const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; - return .{ .row = row, .col = modal.graphemeStart(text[start..end], @min(bounded - start, end - start)) }; - } - - pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { - std.debug.assert(p.panes[id] == null and !p.reserved_slots[id]); - const path_copy = try p.gpa.dupe(u8, path); - errdefer p.gpa.free(path_copy); - const pane = try Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); - errdefer p.gpa.destroy(pane); - const history = try History.create(p.gpa); - errdefer p.gpa.destroy(history); - p.reserved_slots[id] = true; - defer p.reserved_slots[id] = false; - const content = try filesystem.read(p, path); - errdefer p.gpa.free(content); - const total = lineCount(content); - const scroll: usize = if (line > 0 and line <= total) line - 1 else 0; - pane.file = .{ .path = path_copy, .content = content, .scroll = scroll, .history = history }; - pane.cur_pinned = true; - pane.cur_row = @intCast(scroll); - p.installPane(id, pane); - if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); - return pane; - } - - pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { - const saved = src.file.?; - if (saved.mini_source.len > 0) { - const encoded_limit = std.base64.standard.Encoder.calcSize(Mini.max_output_bytes); - if (saved.mini_source.len >= 4096 or saved.content.len > Mini.max_output_bytes or - saved.content_b64.len > encoded_limit or saved.mini_colors_b64.len > encoded_limit) - return error.InvalidMini; - } - const content: []u8 = if (saved.content_b64.len > 0) - try dump.decodeBytes(p.gpa, saved.content_b64) - else - try p.gpa.dupe(u8, saved.content); - errdefer p.gpa.free(content); - const path = try p.gpa.dupe(u8, saved.path); - errdefer p.gpa.free(path); - - const output: ?Output.State = if (Output.fromWord(saved.origin)) |origin| blk: { - var value: Output.State = .{ .from = origin }; - try Output.setArg(&value, saved.origin_arg); - break :blk value; - } else null; - - if (saved.location_rows.len != 0 and output == null) return error.InvalidLocationRows; - const location_rows = try restoreLocationRows(p.gpa, content, saved.location_rows); - errdefer locations.freeRows(p.gpa, location_rows); - - var mini: ?Mini.State = null; - errdefer if (mini) |*state| state.deinit(p.gpa); - if (saved.mini_source.len > 0) { - if (output == null or !std.meta.eql(output.?.from, Output.Origin{ .cmd = .Mini })) return error.InvalidMini; - const source = try p.gpa.dupe(u8, saved.mini_source); - errdefer p.gpa.free(source); - const colors = try dump.decodeBytes(p.gpa, saved.mini_colors_b64); - errdefer p.gpa.free(colors); - if (colors.len != content.len or colors.len > Mini.max_output_bytes) return error.InvalidMini; - for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMini; - mini = .{ .source = source, .colors = colors }; - } else if (saved.mini_colors_b64.len > 0) return error.InvalidMini; - - const history = try History.create(p.gpa); - errdefer p.gpa.destroy(history); - const pane = try p.newDocPane(id); - pane.file = .{ - .path = path, - .content = content, - .output = output, - .mini = mini, - .location_rows = location_rows, - .scroll = src.scroll, - .revision = @intFromBool(saved.dirty), - .history = history, - }; - pane.file.?.tree_context = saved.tree_context and supportsContext(pane); - pane.cur_pinned = true; - pane.cur_row = @intCast(src.scroll); - pane.cols = @max(1, src.cols); - pane.rows = @max(1, src.rows); - if (output == null and filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true, .mode = .baseline_disk } }); - return pane; - } - - pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { - if (file.output == null) for (p.panes, 0..) |slot, id| { - if (slot == pane) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); - }; - p.gpa.free(file.path); - p.gpa.free(file.content); - if (file.mini) |*mini| mini.deinit(p.gpa); - if (file.line_starts.len > 0) p.gpa.free(file.line_starts); - if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); - locations.freeRows(p.gpa, file.location_rows); - if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); - for (file.history.undo[0..file.history.undo_len]) |snap| p.gpa.free(snap.content); - for (file.history.redo[0..file.history.redo_len]) |snap| p.gpa.free(snap.content); - p.gpa.destroy(file.history); - } - - fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { - if (p.fs.listeners == 0) return; - const id = for (p.panes, 0..) |slot, i| { - const pane = slot orelse continue; - if (pane.file) |*state| if (state == f) break i; - } else return; - pardes.ctlfs.events.noteReplace(p, id, false, f.content, new); - } - - pub fn setContent(p: *Pardes, f: *State, new: []u8) void { - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = &.{}; - for (p.panes) |slot| if (slot) |pane| { - if (pane.file) |*file| if (file == f) { - for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - } - }; - }; - reportEdit(p, f, new); - if (f.mini) |*mini| mini.deinit(p.gpa); - f.mini = null; - const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new) catch &.{} else &.{}; - p.gpa.free(f.content); - f.content = new; - f.revision +%= 1; - f.mtime = pardes.ctlfs.events.now(); - if (f.line_starts.len > 0) p.gpa.free(f.line_starts); - f.line_starts = starts; - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = &.{}; - f.highlight_start = 0; - f.syntax_dirty = true; - } - - pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { - const n = nlines(pane.gpa, f); - const row: usize = @min(@as(usize, @intCast(@max(0, snap.cur_row))), n - 1); - const llen = modal.lineSlice(f.content, row).len; - pane.cur_row = @intCast(row); - pane.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, snap.cur_col))), llen)); - pane.vsel = snap.vsel; - pane.msel.active = false; - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); - } - - fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, snap: Snapshot) void { - if (len.* == slots.len) { - gpa.free(slots[0].content); - std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); - len.* -= 1; - } - slots[len.*] = snap; - len.* += 1; - } - - pub fn pushUndo(p: *Pardes, pane: *Pane) void { - const f = if (pane.file) |*file| file else return; - const history = f.history; - if (history.undo_len > 0 and std.mem.eql(u8, history.undo[history.undo_len - 1].content, f.content)) return; - const snap: Snapshot = .{ - .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.cur_row, - .cur_col = pane.cur_col, - .vsel = pane.vsel, - }; - pushHistory(p.gpa, &history.undo, &history.undo_len, snap); - for (history.redo[0..history.redo_len]) |item| p.gpa.free(item.content); - history.redo_len = 0; - } - - pub fn undo(p: *Pardes, pane: *Pane) void { - const f = if (pane.file) |*file| file else return; - const history = f.history; - if (history.undo_len == 0) return; - const current: Snapshot = .{ - .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.cur_row, - .cur_col = pane.cur_col, - .vsel = pane.vsel, - }; - pushHistory(p.gpa, &history.redo, &history.redo_len, current); - history.undo_len -= 1; - const previous = history.undo[history.undo_len]; - setContent(p, f, previous.content); - restoreSnap(pane, f, previous); - } - - pub fn redo(p: *Pardes, pane: *Pane) void { - const f = if (pane.file) |*file| file else return; - const history = f.history; - if (history.redo_len == 0) return; - const current: Snapshot = .{ - .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.cur_row, - .cur_col = pane.cur_col, - .vsel = pane.vsel, - }; - pushHistory(p.gpa, &history.undo, &history.undo_len, current); - history.redo_len -= 1; - const next = history.redo[history.redo_len]; - setContent(p, f, next.content); - restoreSnap(pane, f, next); - } - - /// Commit an externally rewritten file onto the same undo history as typed - /// edits. Unsaved work remains one `u` away; there is no third merge state. - pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { - const pane = p.panes[id] orelse return; - const f = if (pane.file) |*file| file else return; - if (std.mem.eql(u8, f.content, bytes)) return; - const new = p.gpa.dupe(u8, bytes) catch return; - pushUndo(p, pane); - setContent(p, f, new); - f.saved_revision = f.revision; - // restoreSnap only consumes cursor/selection from this synthetic snapshot. - restoreSnap(pane, f, .{ - .content = undefined, - .cur_row = pane.cur_row, - .cur_col = pane.cur_col, - .vsel = pane.vsel, - }); - } - - /// re-highlight the visible window of any file whose syntax went stale - /// (edit, scroll, load) — visible-range-first so big files stay snappy - pub fn refreshHighlights(p: *Pardes) void { - const tz = tracy.zone(@src(), "refreshHighlights"); - defer tz.end(); - for (p.panes) |slot| { - const pane = slot orelse continue; - if (pane.file == null) continue; - const f = &pane.file.?; - if (f.tree_context and supportsContext(pane) and f.context_revision != f.revision) { - const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, f.content) catch continue; - if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations); - f.context_declarations = declarations; - f.context_revision = f.revision; - } - if (f.mini != null) { - f.syntax_dirty = false; - continue; - } - if (!f.syntax_dirty) continue; - if (!p.settings.colors) { - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = &.{}; - f.highlight_start = 0; - f.syntax_dirty = false; - continue; - } - const need_start = lineStart(p.gpa, f, f.scroll); - const need_end = @max(need_start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS)); - if ((!f.tree_context or (f.highlight_start == 0 and f.highlights.len == f.content.len)) and - f.highlights.len > 0 and need_start >= f.highlight_start and - need_end <= f.highlight_start + f.highlights.len) - { - f.syntax_dirty = false; - continue; - } - const slack: usize = if (f.highlights.len == 0) 0 else pane.rows; - const whole = pane.colorAlgo() == .locations or f.tree_context; - const start = if (whole) 0 else lineStart(p.gpa, f, f.scroll -| slack); - const end = if (whole) - f.content.len - else - @max(start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS + slack)); - const new_highlights = (switch (pane.colorAlgo()) { - .none => @as([]u8, &.{}), - .diff => syntax.highlightDiff(p.tree_sitter_gpa, f.content, start, end), - .locations => if (f.location_rows.len > 0) - syntax.highlightLocationRows(p.tree_sitter_gpa, f.content, f.location_rows) - else - syntax.highlightLocations(p.tree_sitter_gpa, f.content, start, end), - else => syntax.highlightFileRange(p.tree_sitter_gpa, f.path, f.content, start, end), - }) catch { - f.syntax_dirty = false; - continue; - }; - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = new_highlights; - f.highlight_start = if (f.highlights.len > 0) start else 0; - f.syntax_dirty = false; - } - } - - 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); - } - - fn prepareContextRows(pane: *Pane, file: *State) void { - pane.context_rows = 0; - if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return; - const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row - for (file.context_declarations) |declaration| { - if (declaration.start_line >= file.scroll) break; - if (declaration.end_line < file.scroll) continue; - var row = declaration.start_line; - while (row <= declaration.header_end_line and row < file.scroll) : (row += 1) { - if (pane.context_rows >= capacity) return; - if (pane.context_rows > 0 and row <= pane.wrap_line[pane.context_rows - 1]) continue; - pane.wrap_line[pane.context_rows] = @intCast(row); - pane.context_rows += 1; - } - } - } - - pub fn wrapWidth(pane: *const Pane, wrap: bool) usize { - if (!wrap or pane.rows > pane.wrap_line.len) return 0; - return @max(1, @as(usize, pane.cols -| gutterWidth(pane)) -| 1); - } - - pub const VisualRow = struct { start: usize, end: usize }; - - pub fn visualRow(line: []const u8, col: usize, width: usize) VisualRow { - if (width == 0) return .{ .start = 0, .end = line.len }; - var start: usize = 0; - while (true) { - const end = fitEnd(line, start, width); - if (col < end or end >= line.len) return .{ .start = start, .end = end }; - start = end; - } - } - - pub fn bodyText(arena: std.mem.Allocator, pane: *Pane, f: *State, wrap: bool) ![]const u8 { - const width = wrapWidth(pane, wrap); - pane.body_wrapped = width > 0; - prepareContextRows(pane, f); - pane.wrap_n = 0; - - const len = fillBody(null, pane, f, width, false); - const out = try arena.alloc(u8, len); - const filled = fillBody(out, pane, f, width, true); - std.debug.assert(filled == out.len); - return out; - } - - /// Run the file-body row walk. With no destination it is the exact sizing - /// pass; with one it fills that allocation and records the wrapping map. - fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) usize { - if (record_wrap) pane.wrap_n = 0; - const prefix_width = gutterWidth(pane); - const total = nlines(pane.gpa, f); - var body_line: usize = f.scroll; - var body_at: usize = 0; - var written: usize = 0; - for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| { - if (i > 0) { - if (dst) |out| out[written] = '\n'; - written += 1; - } - const context = i < pane.context_rows; - const row = if (context) @as(usize, @intCast(pane.wrap_line[i])) else body_line; - const at = if (context) 0 else body_at; - const text = if (row < total) sourceLine(pane, @intCast(row)) else ""; - // Headers use one screen row per source row, preserving signatures - // without allowing a long ancestor to consume the whole viewport. - const end = if (width == 0 or context) text.len else fitEnd(text, at, width); - const cut = if (pane.hscroll > 0 and width == 0) - modal.graphemeStart(text, @min(@as(usize, @intCast(pane.hscroll)), text.len)) - else - at; - if ((width > 0 or pane.context_rows > 0) and record_wrap) { - pane.wrap_line[i] = @intCast(row); - pane.wrap_col[i] = @intCast(cut); - pane.wrap_n = @intCast(i + 1); - } - if (row < total) { - var lbuf: [@max(config.PREFIX_W, 32)]u8 = undefined; - const prefix = lbuf[0..prefix_width]; - @memset(prefix, ' '); - if (at == 0) { - var lineno = row + 1; - var digit: usize = prefix.len - 1; - while (true) { - digit -= 1; - prefix[digit] = '0' + @as(u8, @intCast(lineno % 10)); - lineno /= 10; - if (lineno == 0) break; - } - } - if (dst) |out| @memcpy(out[written..][0..prefix.len], prefix); - written += prefix.len; - const shown = text[cut..end]; - if (dst) |out| @memcpy(out[written..][0..shown.len], shown); - written += shown.len; - } - if (!context) { - if (width > 0 and end < text.len) { - body_at = end; - } else { - body_line += 1; - body_at = 0; - } - } - } - return written; - } - - pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { - const s = &p.surface; - const prefix_width = gutterWidth(pane); - const goff = pane.scroll(); - const gcur = Terminal.gridCursor(pane); - const gcrow = if (pane.cur_pinned) pane.cur_row else @as(i32, gcur.y) + goff; - const cur_line: i32 = if (active and !pane.tag_edit) gcrow else std.math.minInt(i32); - // the body's first row, the way renderPane derives it (Tagbottom) - const body_y = p.bodyTop(r); - const context_bg = p.theme().tag_bg; - for (0..@min(pane.context_rows, body_h)) |context_row| { - for (0..tw) |col| { - const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(context_row))); - cell.default = false; - cell.style.bg = .{ .rgb = context_bg }; - if (p.settings.tree_context_tag_style) cell.style.font_role = .tagline; - } - } - var vr: u16 = 0; - while (vr < body_h) : (vr += 1) { - const row_line: i32 = if (pane.wrap_n == 0) - goff + @as(i32, vr) - else if (vr < pane.wrap_n) pane.wrap_line[vr] else std.math.maxInt(i32); - const on_cursor = row_line == cur_line; - var c: u16 = 0; - while (c < prefix_width and c < tw) : (c += 1) { - const cell = s.at(tx + c, body_y + vr); - cell.default = false; // paints blank gutter rows too - cell.style.fg = .{ .rgb = if (on_cursor) - p.theme().lineno_active orelse p.theme().lineno - else - p.theme().lineno }; - cell.style.bold = on_cursor; - } - } - } - - const SynStyle = struct { fg: [3]u8, bold: bool }; - - fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { - return switch (sy) { - .none => null, - .keyword => .{ .fg = p.theme().kw, .bold = p.settings.syntax_bold }, - .string => .{ .fg = p.theme().str, .bold = false }, - .number => .{ .fg = p.theme().num, .bold = false }, - .comment => .{ .fg = p.theme().comment, .bold = false }, - }; - } - - /// syntax colors: recolor each content cell from its tree-sitter style byte; - /// content starts after the lineno gutter - pub fn recolorSyntax(p: *Pardes, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { - const highlights = if (f.mini) |mini| mini.colors else f.highlights; - const highlight_start = if (f.mini != null) 0 else f.highlight_start; - if (highlights.len == 0 and f.output == null) return; - const s = &p.surface; - const prefix_width = gutterWidth(pane); - const tz_recolor = tracy.zone(@src(), "synRecolor"); - defer tz_recolor.end(); - // indexed start, same as bodyText — an empty tail simply paints nothing - var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); - const total = nlines(p.gpa, f); - const body_y = p.bodyTop(r); - var vr: u16 = 0; - while (vr < body_h) : (vr += 1) { - var base: usize = undefined; - var line: []const u8 = undefined; - var hs: usize = @intCast(@max(0, pane.hscroll)); - var limit: usize = undefined; - if (pane.wrap_n == 0) { - line = flines.next() orelse break; - base = @intFromPtr(line.ptr) - @intFromPtr(f.content.ptr); - limit = line.len; - } else { - if (vr >= pane.wrap_n) break; - const lrow: usize = @intCast(@max(0, pane.wrap_line[vr])); - if (lrow >= total) break; - base = lineStart(p.gpa, f, lrow); - const lend = if (lrow + 1 < total) lineStart(p.gpa, f, lrow + 1) -| 1 else f.content.len; - line = f.content[base..lend]; - hs = @intCast(pane.wrap_col[vr]); - limit = if (vr + 1 < pane.wrap_n and pane.wrap_line[vr + 1] == pane.wrap_line[vr]) - @min(line.len, @as(usize, @intCast(pane.wrap_col[vr + 1]))) - else - line.len; - } - hs = modal.graphemeStart(line, @min(hs, line.len)); - const row_index: usize = @intCast(@max(0, pane.wrapAt(vr).line)); - const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null; - const decoration = Output.decorateRow(f.output, line, metadata); - var c: usize = 0; - var screen_c: usize = 0; - while (hs + c < limit and prefix_width + screen_c < tw) { - const grapheme_end = @min(limit, modal.nextGrapheme(line, hs + c)); - const cells = graphemeDisplayWidth(line[hs + c .. grapheme_end]); - const idx = base + hs + c; - if (idx >= highlight_start) { - const hidx = idx - highlight_start; - if (hidx < highlights.len) { - if (synStyle(p, @enumFromInt(highlights[hidx]))) |ss| { - var fill: usize = 0; - while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { - const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); - if (cell.default) continue; - cell.style.fg = .{ .rgb = ss.fg }; - cell.style.bold = ss.bold; - } - } - } - } - // Results keep their exact live text. Only the location, - // matched source range and diagnostic label gain emphasis. - if (decoration.styleAt(p, hs + c)) |style| { - var fill: usize = 0; - while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { - const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); - if (cell.default) continue; - cell.style.fg = style.fg; - cell.style.bold = style.bold; - if (style.bg != .default) cell.style.bg = style.bg; - } - } - screen_c += cells; - c = grapheme_end - hs; - } - } - } - - pub fn drawWrapMarkers( - p: *Pardes, - pane: *const Pane, - r: pardes.Rect, - tx: u16, - tw: u16, - body_h: u16, - pane_bg: pardes.Color, - ) void { - if (tw <= gutterWidth(pane) + 1) return; - const body_y = p.bodyTop(r); - const marker_fg = p.chromeTheme().lineno; - var row: u16 = 0; - while (row + 1 < pane.wrap_n and row + 1 < body_h) : (row += 1) { - if (pane.wrap_line[row + 1] != pane.wrap_line[row]) continue; - p.surface.set(tx + tw - 1, body_y + row, config.wrap_marker, .{ - .fg = .{ .rgb = marker_fg }, - .bg = pane_bg, - }); - } - } - - pub fn paintWordSelection( - p: *Pardes, - pane: *Pane, - r: pardes.Rect, - row: i32, - word_lo: i32, - word_hi: i32, - bg: [3]u8, - ) void { - const tx = r.x + config.GUTTER; - const tw = r.w - config.GUTTER; - const prefix_width = gutterWidth(pane); - const body_y = p.bodyTop(r); - var vr: i32 = 0; - while (vr + @as(i32, pardes.BOX_H) < @as(i32, r.h)) : (vr += 1) { - const here = pane.wrapAt(vr); - if (here.line != row) continue; - var hi = word_hi; - const next = pane.wrapAt(vr + 1); - if (next.line == row) hi = @min(hi, next.at); - const lo = @max(word_lo, here.at); - if (hi <= lo) continue; - const c0 = @as(i32, prefix_width) + displayOffset(pane, row, here.at, lo); - const c1 = @as(i32, prefix_width) + displayEndOffset(pane, row, here.at, hi - 1); - var col = @max(@as(i32, prefix_width), c0); - while (col <= c1 and col < @as(i32, tw)) : (col += 1) { - const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - } - } - } -}; +pub const File = @import("File.zig"); pub const Output = @import("Output.zig"); -- cgit v1.3 From af74ce84f8230adb45857f2a6364d96a6205e4c0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:27:42 -0300 Subject: Move the Terminal namespace out of panes.zig into Terminal.zig Pure move: the body of `pub const Terminal = struct { ... }` is now the file Terminal.zig, dedented, with the imports it uses; panes.zig keeps `pub const Terminal = @import("Terminal.zig");`, so `panes.Terminal.x` callers and Pane's `Terminal.State` field are unchanged. Terminal.zig joins the embedded source list. Co-Authored-By: Claude Opus 5.5 --- src/Terminal.zig | 2539 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/fs.zig | 1 + src/panes.zig | 2527 +---------------------------------------------------- 3 files changed, 2541 insertions(+), 2526 deletions(-) create mode 100644 src/Terminal.zig (limited to 'src/fs.zig') diff --git a/src/Terminal.zig b/src/Terminal.zig new file mode 100644 index 00000000..a8588952 --- /dev/null +++ b/src/Terminal.zig @@ -0,0 +1,2539 @@ +//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay +//! typed over shell rows, and the Filter that recolours output to the theme. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const modal = @import("modal.zig"); +const tracy = @import("tracy.zig"); +const dump = @import("dump.zig"); +const Key = pardes.Key; +const Pane = panes.Pane; +const EditText = panes.EditText; +const File = panes.File; + +pub const enabled = pardes.terminal_panes; +const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; + +pub const history_max = if (enabled) 64 else 8; + +pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; +pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; + +/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). +pub const prompt_aid = "pardes"; + +/// ghostty's handler, plus where the shell is in its command cycle as +/// its OSC 133 marks tell it: ghostty parses D's exit status and drops +/// it, and /pane//pty/run waits on exactly that. Only marks carrying +/// pardes's own `aid` move it, so fish's native marks, a nested shell's +/// and a stray `133;D` in some file being printed all pass it by. +pub const MarkedHandler = if (enabled) struct { + inner: ghostty_vt.TerminalStream.Handler, + phase: enum { none, prompt, input, running } = .none, + /// Counts commands started (C at the input phase). + started: u32 = 0, + /// Counts prompts drawn (B), so a line the shell refused without + /// running (a fish syntax error: no C, no D, a new prompt) shows. + prompts: u32 = 0, + /// D marks outside a running command: the shell handled a line + /// without starting it (bash on a syntax error prints no C). + declined: u32 = 0, + /// The newest prompt continues an unfinished line (bash's PS2, marked + /// `k=c`): the shell still holds the start of the command. + continuation: bool = false, + /// Where the newest command's output began (its C) and ended (its + /// D) on the primary screen, pinned so scrolling keeps them. + out_start: ?*ghostty_vt.Pin = null, + out_end: ?*ghostty_vt.Pin = null, + /// The running command's output was erased under it -- a clear, ED 3, + /// a reset -- so the pins no longer span what it printed: ED 3 moves + /// a pin to the next page without flagging it `garbage` + /// (PageList.erasePage). + lost: bool = false, + + /// The newest command to end: which one, and its status if given. + finished: ?struct { seq: u32, status: ?i32 } = null, + + const Action = ghostty_vt.TerminalStream.Action; + + /// Move one of the output pins to the cursor. Only the primary screen + /// is pinned: a command's own full-screen display is not its output. + fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { + const screen = self.inner.terminal.screens.get(.primary) orelse return; + if (slot.*) |old| screen.pages.untrackPin(old); + slot.* = null; + if (!now or self.inner.terminal.screens.active_key != .primary) return; + slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; + } + + pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { + if (comptime action == .semantic_prompt) mark: { + const aid = value.readOption(.aid) orelse break :mark; + if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; + switch (value.action) { + .fresh_line_new_prompt => { + self.phase = .prompt; + self.continuation = value.readOption(.prompt_kind) == .continuation; + }, + .end_prompt_start_input => { + self.phase = .input; + self.prompts +%= 1; + }, + // bash's DEBUG trap also fires on its own PROMPT_COMMAND, + // outside the input phase; only a C that ends input counts + .end_input_start_output => if (self.phase == .input) { + self.phase = .running; + self.started +%= 1; + self.lost = false; + self.pinCursor(&self.out_start, true); + self.pinCursor(&self.out_end, false); + }, + .end_command => if (self.phase == .running) { + self.phase = .none; + self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; + self.pinCursor(&self.out_end, true); + } else { + self.declined +%= 1; + }, + else => {}, + } + } + if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .full_reset) { + if (self.phase == .running) self.lost = true; + } + self.inner.vt(action, value); + } + + pub fn deinit(self: *@This()) void { + self.inner.deinit(); + } +} else void; + +pub const Replay = struct { + bytes: [1024 * 1024]u8 = undefined, + head: usize = 0, + len: usize = 0, +}; + +pub const State = struct { + vt: VtSlot, + stream: StreamSlot, + replay: Replay, + reply: [256]u8 = undefined, + reply_len: u16 = 0, +}; + +const GColor = ghostty_vt.color; + +const FilterPaletteKey = struct { + bg: GColor.RGB, + fg: GColor.RGB, + base: [16]GColor.RGB, +}; + +pub const FilterPalette = if (enabled) LivePalette else struct {}; + +const LivePalette = struct { + key: ?FilterPaletteKey = null, + colors: GColor.Palette = GColor.default, + + fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { + const bg = asGhostRgb(theme.bg orelse theme.tag_bg); + const fg = asGhostRgb(theme.fg orelse theme.tag_fg); + var base: [16]GColor.RGB = undefined; + if (theme.palette) |palette| { + for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); + } else { + const synthesized = [16][3]u8{ + theme.bg orelse theme.tag_bg, + theme.kw, + theme.str, + theme.num, + theme.box, + theme.sel_bg, + theme.comment, + theme.fg orelse theme.tag_fg, + theme.lineno, + theme.kw, + theme.str, + theme.num, + theme.scroll_thumb, + theme.sel_fg, + theme.tag_fg, + theme.fg orelse theme.tag_fg, + }; + for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); + } + + const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; + if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; + + var seed = GColor.default; + for (base, 0..) |rgb, i| seed[i] = rgb; + self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); + self.key = key; + return &self.colors; + } +}; + +fn asGhostRgb(rgb: [3]u8) GColor.RGB { + return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; +} + +fn asPardesColor(rgb: GColor.RGB) pardes.Color { + return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; +} + +/// The owned text standing in for `rows` live terminal rows, beginning at +/// absolute surface row `row`. The emulator grid remains untouched underneath. +pub const EditBuffer = struct { + row: i32 = 0, + rows: i32 = 1, + text: []u8 = &.{}, +}; + +/// One whole-state terminal edit boundary. Null means the pane has not yet +/// materialized an edit buffer; non-null snapshots own their text. +pub const Snapshot = struct { + ovl: ?EditBuffer, + cur_row: i32, + cur_col: i32, + vsel: Pane.CharSel, +}; + +pub const PendingCommand = struct { + bytes: []u8 = &.{}, + wait: enum { none, spawn, input } = .none, +}; + +pub fn armShellSpawn(pane: *Pane) void { + if (comptime !enabled) return; + std.debug.assert(pane.pending_command.bytes.len == 0); + pane.pending_command.wait = .spawn; +} + +pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { + if (pane.pending_command.wait == .none) return false; + const old_len = pane.pending_command.bytes.len; + const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); + const bytes = if (old_len == 0) + try pane.gpa.alloc(u8, new_len) + else + try pane.gpa.realloc(pane.pending_command.bytes, new_len); + @memcpy(bytes[old_len..][0..command.len], command); + bytes[new_len - 1] = '\r'; + pane.pending_command.bytes = bytes; + pane.greet = false; + return true; +} + +pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { + const pane = p.panes[id] orelse return; + if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; + if (prompt_marks) { + pane.pending_command.wait = .input; + releasePendingCommand(p, id, pane, false); + } else { + pane.greet = false; + releasePendingCommand(p, id, pane, true); + } +} + +pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { + if (pane.pending_command.wait == .input) + releasePendingCommand(p, id, pane, promptInputReady(pane)); +} + +fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { + if (!ready) return; + const bytes = pane.pending_command.bytes; + pane.pending_command = .{}; + if (bytes.len > 0) { + p.emitWrite(id, bytes); + pane.gpa.free(bytes); + } +} + +pub fn deinitPendingCommand(pane: *Pane) void { + if (pane.pending_command.bytes.len > 0) + pane.gpa.free(pane.pending_command.bytes); + pane.pending_command = .{}; +} + +pub fn terminalIo() std.Io { + return if (comptime !pardes.hosted) + std.Io.failing + else + std.Io.Threaded.global_single_threaded.io(); +} + +/// The three numbers ghostty's scrollbar reports; all zero without an emulator. +pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; + +pub fn scrollbar(pane: *const Pane) Scrollbar { + if (comptime !enabled) return .{}; + const state = pane.terminal orelse return .{}; + const sb = state.vt.screens.active.pages.scrollbar(); + return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; +} + +/// The emulator's viewport offset, in SHELL rows: the top of what it shows. +pub fn gridOffset(pane: *const Pane) i32 { + return @intCast(scrollbar(pane).offset); +} + +/// Where the emulator itself puts the cursor, in active-area cells — the origin +/// without one, which is where an empty pane's cursor belongs anyway. +pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; + +pub fn gridCursor(pane: *const Pane) GridCursor { + if (comptime !enabled) return .{}; + const state = pane.terminal orelse return .{}; + const cur = state.vt.screens.active.cursor; + return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; +} + +pub fn visibleCursor(pane: *const Pane) ?GridCursor { + if (comptime !enabled) return null; + const state = pane.terminal orelse return null; + if (!state.vt.modes.get(.cursor_visible)) return null; + const cur = state.vt.screens.active.cursor; + const sb = scrollbar(pane); + const row = sb.total - sb.len + cur.y; + if (row < sb.offset or row - sb.offset >= sb.len) return null; + return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; +} + +/// Move the emulator's viewport by `delta` shell rows (negative scrolls back). +pub fn scrollGrid(pane: *Pane, delta: i32) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.vt.screens.active.scroll(.{ .delta_row = delta }); +} + +/// Is the viewport already showing the last row of output? +pub fn atBottom(pane: *const Pane) bool { + if (comptime !enabled) return true; + const sb = scrollbar(pane); + return sb.offset + sb.len >= sb.total; +} + +/// Snap the viewport back onto live output. +pub fn followOutput(pane: *Pane) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.vt.screens.active.scroll(.active); +} + +/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping +/// a scrollback; the next resize retries with the same numbers. +pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + if (cols != pane.cols) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; +} + +/// DECSET 2004: the program wants its pastes bracketed. +pub fn bracketedPaste(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.modes.get(.bracketed_paste); +} + +/// The program tracks the mouse itself, so a click in its body is its event. +pub fn reportsMouse(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + const m = &state.vt.modes; + return m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any); +} + +/// ...and wants them in SGR (1006) rather than the legacy X10 bytes. +pub fn mouseFormatSgr(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.modes.get(.mouse_format_sgr); +} + +/// The whole scrollback as plain text, `gpa`-owned: what `Save` writes out. +pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { + if (comptime !enabled) return &.{}; + const state = pane.terminal orelse return &.{}; + return state.vt.screens.active.dumpStringAlloc(gpa, .{ .screen = .{} }); +} + +/// Release the emulator's heap. The Pane allocation itself is the core's. +pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.stream.deinit(); + state.vt.deinit(gpa); + gpa.destroy(state); + pane.terminal = null; +} + +/// Allocate the live emulator half of a terminal pane. Slot ownership, serial +/// assignment, and spawn effects remain core lifecycle invariants. +pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try createDoc(gpa, cols, rows); + errdefer gpa.destroy(pane); + if (comptime !enabled) return pane; + const state = try gpa.create(State); + errdefer gpa.destroy(state); + state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ + .cols = cols, + .rows = rows, + .max_scrollback = 16 * 1024 * 1024, + }); + state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); + state.replay.head = 0; + state.replay.len = 0; + state.reply_len = 0; + state.stream.handler.inner.effects.write_pty = ptyReport; + state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; + pane.terminal = state; + pane.tty_filter = true; + return pane; +} + +pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try gpa.create(Pane); + pane.* = .{ + .gpa = gpa, + .cols = cols, + .rows = rows, + }; + return pane; +} + +/// Where a restored terminal's history ends and its new shell begins. +pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; + +/// Rebuild a dump's terminal emulator from its recorded output. `live`: a +/// shell will be spawned into it, so the history is marked off from what +/// that shell prints and the pane waits for it like any new terminal. +/// Registration and tag/cwd policy stay with the core; raw VT replay and +/// viewport restoration belong here. +pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { + const terminal = src.terminal.?; + if (comptime !enabled) { + const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); + errdefer p.gpa.destroy(pane); + if (terminal.stream.len > 0) + pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; + return pane; + } + // An older dump's raw output tail cannot come back live: cut off mid + // redraw, or written at sizes the pane no longer has, it replays as + // garbage. Its rendered text can. + const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; + const bytes = if (legacy_text) + try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") + else if (terminal.stream_b64.len > 0) + try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) + else + &.{}; + const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); + if (live) { + if (bytes.len > 0) { + ingest(pane, bytes); + ingest(pane, restored_banner); + } + followOutput(pane); + // A view left scrolled back stays on what it was showing: the + // banner's line breaks scrolled a full screen by that many more. + if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); + armShellSpawn(pane); + } else if (bytes.len > 0) { + ingest(pane, bytes); + followOutput(pane); + if (src.scroll > 0) + scrollGrid(pane, -@as(i32, @intCast(src.scroll))); + } + return pane; +} + +/// Feed the emulator and retain the bounded suffix a dump can replay. Live +/// output and restoration share this byte path, then apply different views. +fn ingest(pane: *Pane, bytes: []const u8) void { + const state = pane.terminal.?; + const replay = &state.replay; + if (bytes.len >= replay.bytes.len) { + const kept = bytes[bytes.len - replay.bytes.len ..]; + @memcpy(&replay.bytes, kept); + replay.head = 0; + replay.len = replay.bytes.len; + } else { + const overflow = bytes.len -| (replay.bytes.len - replay.len); + replay.head = (replay.head + overflow) % replay.bytes.len; + replay.len -= overflow; + const tail = (replay.head + replay.len) % replay.bytes.len; + const first = @min(bytes.len, replay.bytes.len - tail); + @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); + @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); + replay.len += bytes.len; + } + state.stream.nextSlice(bytes); +} + +/// Return the replay ring in chronological order. Wrapped records are copied +/// into `allocator`; contiguous records remain a borrowed slice of the pane. +fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { + const state = pane.terminal orelse return &.{}; + const replay = &state.replay; + if (replay.len == 0) return &.{}; + if (replay.head + replay.len <= replay.bytes.len) + return replay.bytes[replay.head..][0..replay.len]; + const out = try allocator.alloc(u8, replay.len); + const first = replay.bytes.len - replay.head; + @memcpy(out[0..first], replay.bytes[replay.head..]); + @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); + 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 and enabled, 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 "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(!mouseFormatSgr(pane)); + try std.testing.expect(!promptInputReady(pane)); + scrollGrid(pane, 100); + followOutput(pane); + resizeGrid(pane, allocator, 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.expectEqualStrings("", try replayBytes(pane, allocator)); + try std.testing.expect(!failing.has_induced_failure); +} + +test "terminal state keeps parser fragments and sends emulator replies through its owner" { + if (comptime !enabled) return error.SkipZigTest; + 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); + try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); +} + +test "replay keeps a bounded chronological suffix across large writes and wrapping" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const pane = try create(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); + ingest(pane, "hello"); + const small = try replayBytes(pane, gpa); + try std.testing.expectEqualStrings("hello", small); + try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); + + const capacity = pane.terminal.?.replay.bytes.len; + const input = try gpa.alloc(u8, capacity + 7); + defer gpa.free(input); + @memset(input, 0); + const ending = "\x1b[31mred\x1b[0m\r\n"; + @memcpy(input[input.len - ending.len ..], ending); + ingest(pane, input); + try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); + ingest(pane, "next\r\n"); + const wrapped = try replayBytes(pane, gpa); + defer gpa.free(wrapped); + try std.testing.expectEqual(capacity, wrapped.len); + try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); + try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); +} + +test "replay restores terminal cells from the retained stream" { + if (comptime !enabled) 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, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); + const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); + defer gpa.free(encoded); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = pane.cols, + .rows = pane.rows, + .terminal = .{ .stream_b64 = encoded }, + }, false); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + const before = try screenTextAlloc(pane, gpa); + defer gpa.free(before); + const after = try screenTextAlloc(restored, gpa); + defer gpa.free(after); + try std.testing.expectEqualStrings(before, after); + try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); +} + +test "a restored terminal keeps its history above a marker and gets a shell where it was" { + if (comptime !enabled or 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"); + try p.dumpState(); + const restored = try Pardes.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.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 "an older dump comes back live from its rendered text, not its raw output tail" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + // A tail cut mid-redraw: relative moves from a cursor it never set. + const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); + defer gpa.free(tail); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = 40, + .rows = 12, + .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, + }, true); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + defer deinitPendingCommand(restored); + const text = try screenTextAlloc(restored, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); +} + +/// Record and parse one live pty read, invalidate its motion surface, and +/// follow it only when the body (possibly parked under a tag edit) is raw. +pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { + // There are no pty reads at all without an emulator to parse them into. + if (comptime !enabled) return; + if (pane.terminal == null) return; + const has_positions = pane.ovl != null or pane.cur_pinned or pane.vsel.active or + pane.msel.active or pane.nsel > 0 or pane.append_at != null or pane.look_at != null or + pane.ed_undo_len > 0 or pane.ed_redo_len > 0 or pointerRowCount(pane) > 0; + // Sticky bottom, as every other terminal does it: output drags the + // viewport down only when the viewport was already on the last row, so + // a reader scrolled back into the scrollback stays where they scrolled. + const at_bottom = atBottom(pane); + if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); + p.shell_rows.markStale(pane); + const body_mode = if (pane.tag_edit) pane.tag_mode else pane.mode; + if (body_mode == .tty and at_bottom) followOutput(pane); +} + +const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; +const PositionPin = struct { + target: *i32, + row: RowPin, + overlay: ?*EditBuffer, + edit_row: ?i32 = null, +}; + +fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { + if (row < 0) return .{ .offset = row }; + const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); + var left = pages.total_rows - 1 - bounded; + var node = pages.pages.last.?; + while (left >= node.rows()) { + left -= node.rows(); + node = node.prev.?; + } + const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { + failed.* = true; + return .{}; + }; + return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; +} + +fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { + const pin = row.pin orelse return row.offset; + const alive = pages orelse return 0; + if (pin.garbage) return 0; + var after: usize = 0; + var node = alive.pages.last; + while (node) |item| : (node = item.prev) { + if (item == pin.node) + return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; + after += item.rows(); + } + return 0; +} + +fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { + var grid = target.*; + if (overlay) |edit| { + const lines: i32 = @intCast(modal.lineCount(edit.text)); + if (grid >= edit.row and grid < edit.row +| lines) + return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; + if (grid > edit.row) grid = grid -| lines +| edit.rows; + } + return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; +} + +fn pointerRowCount(pane: *const Pane) usize { + var count: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + count += rows.len; + }; + return count; +} + +fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { + const screens = &pane.terminal.?.vt.screens; + const key = screens.active_key; + const generation = screens.generation(key); + const pages = &screens.active.pages; + const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *Pane.CharSel }; + var groups: [history_max * 2 + 1]Group = undefined; + groups[0] = .{ + .overlay = if (pane.ovl) |*overlay| overlay else null, + .cursor = &pane.cur_row, + .selection = &pane.vsel, + }; + var ngroups: usize = 1; + for ([_][]Snapshot{ pane.ed_undo[0..pane.ed_undo_len], pane.ed_redo[0..pane.ed_redo_len] }) |history| { + for (history) |*snapshot| { + groups[ngroups] = .{ + .overlay = if (snapshot.ovl) |*overlay| overlay else null, + .cursor = &snapshot.cur_row, + .selection = &snapshot.vsel, + }; + ngroups += 1; + } + } + const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; + var spans: [groups.len]Span = undefined; + var nspans: usize = 0; + var positions: [groups.len * 2 + Pane.max_selections * 2 + 4]PositionPin = undefined; + var npositions: usize = 0; + var failed = false; + for (groups[0..ngroups]) |group| { + if (group.overlay) |overlay| { + spans[nspans] = .{ + .overlay = overlay, + .start = trackRow(pages, overlay.row, &failed), + .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), + }; + nspans += 1; + } + positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); + npositions += 1; + if (group.selection.active) { + positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); + npositions += 1; + } + } + const overlay = groups[0].overlay; + var extra: [Pane.max_selections * 2 + 4]*i32 = undefined; + var nextra: usize = 0; + if (pane.msel.active) { + extra[nextra] = &pane.msel.r0; + extra[nextra + 1] = &pane.msel.r1; + nextra += 2; + } + for (pane.sels[0..pane.nsel]) |*selection| { + extra[nextra] = &selection.row; + extra[nextra + 1] = &selection.arow; + nextra += 2; + } + if (pane.append_at) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + if (pane.look_at) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + for (extra[0..nextra]) |target| { + positions[npositions] = trackPosition(pages, target, overlay, &failed); + npositions += 1; + } + const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; + defer if (pointer_positions) |pins| pane.gpa.free(pins); + if (pointer_positions) |pins| { + var index: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + for (rows) |*row| { + pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); + index += 1; + } + }; + } else failed = true; + ingest(pane, bytes); + // RIS can destroy the alternate screen and every pin it owned. + const alive = if (screens.generation(key) == generation) pages else null; + var moved = false; + var pointer_rows_lost = alive == null or pointer_positions == null; + if (pointer_positions) |pins| for (pins) |position| { + if (alive != null) if (position.row.pin) |pin| { + if (pin.garbage) pointer_rows_lost = true; + }; + }; + for (spans[0..nspans]) |span| { + const start = pinnedRow(alive, span.start); + const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); + moved = moved or start != span.overlay.row or rows != span.overlay.rows; + span.overlay.row = start; + span.overlay.rows = rows; + if (alive) |owner| { + if (span.start.pin) |pin| owner.untrackPin(pin); + if (span.end.pin) |pin| owner.untrackPin(pin); + } + } + for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { + var row = pinnedRow(alive, position.row); + if (position.overlay) |edit| { + if (position.edit_row) |relative| { + row = edit.row +| relative; + } else if (row > edit.row) { + row = if (row < edit.row +| edit.rows) + edit.row + else + row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); + } + } + moved = moved or row != position.target.*; + position.target.* = row; + if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); + }; + if (pointer_rows_lost) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. + if (failed) { + const message = "terminal edit position reset: out of memory"; + @memcpy(pane.msg[0..message.len], message); + pane.msg_len = message.len; + } +} + +test "raw terminal output needs no position tracking allocations" { + if (comptime !enabled) return error.SkipZigTest; + 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.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()); +} + +pub fn promptInputReady(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active_key != .alternate and + state.vt.screens.active.cursor.semantic_content == .input; +} + +pub const CommandOutput = struct { + /// Owned by the caller. + text: [:0]const u8, + /// Whether `text` starts where the command did. It does not when that + /// start is not there to read: cut off by `max_rows`, scrolled out of + /// the history (ghostty moved the pin to the oldest row it kept and + /// flagged it `garbage`), erased under it (`MarkedHandler.lost`), or + /// never pinned (a C or D that came on the alternate screen). + whole: bool, +}; + +/// What the newest finished command printed: the screen text between its +/// C and D marks, read from at most `max_rows` rows above its end, so a +/// command that printed the whole history costs no more than its tail. +pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { + // Unless there is text to read, whether the nothing it printed is the + // whole of it. + const whole = if (comptime enabled) printed: { + const state = pane.terminal orelse break :printed true; + const marks = &state.stream.handler; + const start = marks.out_start orelse break :printed false; + const end = marks.out_end orelse break :printed false; + const screen = state.vt.screens.get(.primary) orelse break :printed false; + if (end.garbage) break :printed false; + var whole = !marks.lost and !start.garbage; + // D is where the next prompt begins: the output ends a cell before. + const last = end.leftWrap(1) orelse break :printed whole; + if (start.eql(end.*) or last.before(start.*)) break :printed whole; + var from = start.*; + if (last.up(max_rows)) |floor| if (from.before(floor)) { + from = floor; + from.x = 0; + whole = false; + }; + return .{ + .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), + .whole = whole, + }; + } else true; + return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; +} + +/// At a prompt with nothing typed on its line: no input left of the +/// cursor and none under it (text typed and then Ctrl-A'd starts at the +/// cursor). Nothing further right counts: that is where fish draws a +/// right prompt, and fish suggests nothing on an empty line. +pub fn promptInputEmpty(pane: *const Pane) bool { + if (comptime !enabled) return false; + if (!promptInputReady(pane)) return false; + const cursor = &pane.terminal.?.vt.screens.active.cursor; + const row = cursor.page_pin.cells(.all); + for (row[0..@min(cursor.x + 1, row.len)]) |cell| + if (cell.semantic_content == .input and !cell.isEmpty()) return false; + return true; +} + +/// Encode one key for the program that owns a raw terminal and queue its pty +/// write, respecting the application's keyboard protocol and terminal modes. +pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { + if (comptime enabled) { + const pane = p.panes[id] orelse return; + const state = pane.terminal orelse return; + const input = ghostty_vt.input; + const physical: input.Key = switch (key.cp) { + Key.enter => .enter, + Key.backspace => .backspace, + Key.tab => .tab, + Key.escape => .escape, + Key.up => .arrow_up, + Key.down => .arrow_down, + Key.left => .arrow_left, + Key.right => .arrow_right, + Key.home => .home, + Key.end => .end, + Key.page_up => .page_up, + Key.page_down => .page_down, + Key.delete => .delete, + else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, + }; + var utf8: [4]u8 = undefined; + const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; + const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace) + utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] + else + ""; + var buffer: [256]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + input.encodeKey(&writer, .{ + .key = physical, + .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, + .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, + .utf8 = text, + .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, + }, options: { + var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); + // fromTerminal cannot know this one and says so, defaulting to + // "option is not alt" — right for an app that lets macOS do the + // unicode translation and hands the encoder the composed text. + // Every pardes shell resolves the modifier itself and hands the + // core the BASE key with the alt bit and no text at all (see + // PardesView.keyDown, and app.mjs doing the same with the same + // two bits), so by the time this runs alt already means alt. + // Left at the default, a macOS build drops the ESC prefix on + // the floor and forwards Alt-n to the child as a bare `n`. + opts.macos_option_as_alt = .true; + break :options opts; + }) catch return; + if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); + return; + } + var control: [1]u8 = undefined; + const bytes: ?[]const u8 = blk: { + if (key.ctrl) { + if (key.cp >= 'a' and key.cp <= 'z') { + control[0] = @intCast(key.cp - 0x60); + break :blk control[0..1]; + } + // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. + if (key.cp >= '@' and key.cp <= '_') { + control[0] = @intCast(key.cp - 0x40); + break :blk control[0..1]; + } + } + if (key.text.len > 0) break :blk key.text; + break :blk switch (key.cp) { + Key.enter => "\r", + Key.backspace => "\x7f", + Key.tab => "\t", + Key.escape => "\x1b", + Key.up => "\x1b[A", + Key.down => "\x1b[B", + Key.right => "\x1b[C", + Key.left => "\x1b[D", + Key.delete => "\x1b[3~", + else => null, + }; + }; + if (bytes) |encoded| + p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); +} + +pub fn enterTty(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; + if (comptime enabled) if (!selected and pane.terminal != null and pane.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { + const screen = pane.terminal.?.vt.screens.active; + const goff: i32 = @intCast(screen.pages.scrollbar().offset); + const vp_row = pane.gridRow(pane.cur_row) - goff; + if (vp_row < 0) break :handoff; + + var grid_col: i32 = @max(0, pane.cur_col); + if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { + if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { + .cut => |cols| grid_col += @intCast(cols), + .keep, .blank => {}, + }; + } + const click_pin = screen.pages.pin(.{ + .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, + }) orelse break :handoff; + const cursor_pin = screen.cursor.page_pin.*; + var prompts = cursor_pin.promptIterator(.left_up, null); + const prompt_pin = prompts.next() orelse break :handoff; + if (click_pin.before(prompt_pin)) break :handoff; + const moves = screen.promptClickMove(click_pin); + for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); + for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); + }; + + pane.mode = .tty; + followOutput(pane); // entering raw mode is a request for the live shell + pane.msel.active = false; + pane.vsel.active = false; + pane.nsel = 0; + // The raw renderer follows the live cursor. A captured mouse selection + // keeps its modal endpoint for the next return to editor mode. + pane.cur_pinned = selected; + pane.select = false; + pane.append_at = null; + pane.sticky_col = -1; + pane.normal.clear(); +} + +// Returned slices remain valid until the next cache rebuild or reset. +pub const RowsCache = struct { + /// whose grid this describes; null = the slot is free + pane: ?*const Pane = null, + /// the rows joined by '\n' — `flatSurface` hands this back verbatim + /// instead of rebuilding the join on every keystroke + text: []const u8 = &.{}, + /// slices INTO `text`, absolute grid rows from 0 + rows: [][]const u8 = &.{}, + /// `text` is a prefix of this: blanking a prompt row shortens the join, + /// and the slack is not worth a second allocation to reclaim + text_alloc: []u8 = &.{}, + stale: bool = false, + + pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.text_alloc.len > 0) gpa.free(c.text_alloc); + if (c.rows.len > 0) gpa.free(c.rows); + c.* = .{}; + } + + /// Free a stale entry. Called at the top of `update`, and nowhere else. + pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.stale) c.reset(gpa); + } + + /// `pane`'s grid moved: the entry no longer describes it. + pub fn markStale(c: *RowsCache, pane: *const Pane) void { + if (c.pane == pane) c.stale = true; + } + + pub fn dropPane(c: *RowsCache, pane: *const Pane) void { + if (c.pane != pane) return; + c.pane = null; + c.stale = true; + } +}; + +const Rows = struct { + text_alloc: []u8, + text: []const u8, + rows: [][]const u8, +}; + +const empty_grid = [1][]const u8{""}; + +/// What LEAVING raw tty mode does to one prompt row, decided from its cells +/// alone. See config.tty_blank for why any of this happens. +const PromptCut = union(enum) { + /// show the row exactly as ghostty dumped it + keep, + /// show nothing at all + blank, + /// drop this many leading COLUMNS — the prompt — and keep the rest, which + /// is what was typed at it + cut: usize, +}; + +fn promptCut(pin: ghostty_vt.Pin) PromptCut { + if (config.tty_blank == .prompt_and_input) return .blank; + const cells = pin.cells(.all); + var cols: usize = 0; + while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; + // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or + // a repaint that has moved on. Nothing here is the prompt, so hide nothing. + if (cols == 0) return .keep; + // ...and all prompt, nothing typed yet: the row is chrome end to end. + if (cols >= cells.len) return .blank; + return .{ .cut = cols }; +} + +pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { + if (comptime !enabled) return 0; + if (row < 0) return 0; + const state = pane.terminal orelse return 0; + const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; + if (pin.rowAndCell().row.semantic_prompt == .none) return 0; + return switch (promptCut(pin)) { + .keep => 0, + .blank => raw.len, + .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), + }; +} + +fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { + const cols = switch (promptCut(pin)) { + .keep => return raw, + .blank => return "", + .cut => |n| n, + }; + const cells = pin.cells(.all); + var at: usize = 0; + var col: usize = 0; + while (col < cols and at < raw.len) { + const cell = &cells[col]; + at = @min(raw.len, at + dumpedBytes(pin, cell)); + // the tail cell of a wide glyph spells nothing of its own + col += if (cell.wide == .wide) @as(usize, 2) else 1; + } + return std.mem.trimEnd(u8, raw[at..], " \t"); +} + +fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { + switch (cell.wide) { + .spacer_head, .spacer_tail => return 0, + .narrow, .wide => {}, + } + var n: usize = switch (cell.content_tag) { + .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( + cell.codepoint(), + ) catch 1, + // A cell carrying only a colour still spells one blank in the dump. + else => 1, + }; + if (cell.content_tag == .codepoint_grapheme) { + if (pin.grapheme(cell)) |extra| for (extra) |cp| { + n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; + }; + } + return n; +} + +pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { + if (comptime !enabled) return &empty_grid; + if (pane.terminal == null) return &empty_grid; + const c = &p.shell_rows; + if (!c.stale and c.pane == pane) return c.rows; + if (c.pane != null) { + c.stale = true; + return (try buildRows(p.scratch.allocator(), p, pane)).rows; + } + const built = try buildRows(p.gpa, p, pane); + c.* = .{ + .pane = pane, + .text = built.text, + .rows = built.rows, + .text_alloc = built.text_alloc, + }; + return c.rows; +} + +/// 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 { + const rows = try shellRows(p, pane); + if (pane.ovl == null) return rows; + var last = rows.len; + if (pane.ovl) |overlay| + last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); + var count = last; + if (pane.ovl) |overlay| { + if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) + count = count - @min( + @as(usize, @intCast(overlay.rows)), + last - @as(usize, @intCast(overlay.row)), + ) + @max(1, modal.lineCount(overlay.text)); + } + const lines = try p.scratch.allocator().alloc([]const u8, count); + var n: usize = 0; + var grid_row: usize = 0; + while (grid_row < last) : (grid_row += 1) { + if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { + var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); + while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; + grid_row += @intCast(overlay.rows - 1); + continue; + }; + lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; + n += 1; + } + return lines[0..n]; +} + +/// Flatten `cursorLines` without rebuilding the common cached/no-overlay +/// case. Scratch-owned when a join is required. +pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { + const cache = &p.shell_rows; + if (!cache.stale and cache.pane == pane and + lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; + var total: usize = if (lines.len > 0) lines.len - 1 else 0; + for (lines) |line| total += line.len; + const text = try p.scratch.allocator().alloc(u8, total); + var at: usize = 0; + for (lines, 0..) |line, i| { + if (i > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..line.len], line); + at += line.len; + } + return text; +} + +/// Materialize or extend the terminal edit overlay with one exact allocation. +/// Row slices are scratch-owned/borrowed; only the joined text is installed. +pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { + const want_lo = @max(0, @min(lo, hi)); + const want_hi = @max(want_lo, @max(lo, hi)); + const fresh = pane.ovl == null; + const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; + const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); + const up = old.row - want_lo; + const down = want_hi - (old.row + lines - 1); + const extending = fresh or up > 0 or down > 0; + var row0 = old.row; + var covered = old.rows; + var text = old.text; + var owned = false; + if (extending) { + const rows = shellRows(p, pane) catch return null; + row0 = old.row - @max(0, up); + covered = old.rows + @max(0, up) + @max(0, down); + const up_len: usize = @intCast(@max(0, up)); + const down_len: usize = @intCast(@max(0, down)); + const parts = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; + for (parts[0..up_len], 0..) |*part, i| { + const src = @as(usize, @intCast(row0)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + const middle: usize = @intCast(old.row); + parts[up_len] = if (fresh) + (if (middle < rows.len) rows[middle] else "") + else + old.text; + for (parts[up_len + 1 ..], 0..) |*part, i| { + const src = @as(usize, @intCast(old.row + old.rows)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + text = std.mem.join(p.gpa, "\n", parts) catch return null; + owned = true; + } + + const row: usize = @intCast(@max(0, want_lo - row0)); + const line_len: i32 = @intCast(modal.lineSlice(text, row).len); + if (col > line_len) { + const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { + if (owned) p.gpa.free(text); + return null; + }; + @memset(spaces, ' '); + const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { + if (owned) p.gpa.free(text); + return null; + }; + if (owned) p.gpa.free(text); + text = padded; + owned = true; + } + if (owned) { + if (pane.ovl) |overlay| p.gpa.free(overlay.text); + pane.ovl = .{ .row = row0, .rows = covered, .text = text }; + } + return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; +} + +/// Consume a rewritten overlay, freeing the terminal edit text it replaces. +pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { + const overlay = if (pane.ovl) |*value| value else return p.gpa.free(new); + for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + } + p.gpa.free(overlay.text); + overlay.text = new; +} + +/// The shell's screen and scrollback (the primary screen, even under a +/// full-screen program) as VT that replays to what was shown: styled +/// text, soft-wrapped lines rejoined so they reflow at another width. +fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { + const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; + var out: std.Io.Writer.Allocating = .init(arena); + try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); + return out.written(); +} + +/// Serialize terminal-only state; the core supplies shared pane metadata. +pub fn dumpPane( + pane: *Pane, + arena: std.mem.Allocator, + tag: []const u8, + body: []const u8, + scroll: usize, +) !dump.Pane { + if (!enabled or pane.terminal == null) { + const text = if (pane.ovl) |overlay| overlay.text else ""; + return .{ + .kind = .terminal, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .terminal = .{ + .cwd = try arena.dupe(u8, pane.cwdSlice()), + .stream = try arena.dupe(u8, text), + .stream_b64 = &.{}, + .cursor = .{ .col = 0, .row = 0 }, + }, + }; + } + const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); + const extra = if (pane.ovl) |overlay| overlay.text.len else 0; + const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); + var len: usize = 0; + var lines = std.mem.splitAny(u8, full, "\n"); + var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); + var row: i32 = 0; + var skip: i32 = 0; + while (lines.next()) |raw| : (row += 1) { + // Hidden overlay rows still consume prompt pins to keep them aligned. + const prompt = if (pane.mode != .tty) prompts.next() else null; + if (skip > 0) { + skip -= 1; + continue; + } + if (row > 0) { + stream[len] = '\n'; + len += 1; + } + if (pane.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { + @memcpy(stream[len..][0..overlay.text.len], overlay.text); + len += overlay.text.len; + skip = overlay.rows - 1; + continue; + }; + const shown = if (prompt) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + @memcpy(stream[len..][0..shown.len], shown); + len += shown.len; + } + return .{ + .kind = .terminal, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .terminal = .{ + .cwd = try arena.dupe(u8, pane.cwdSlice()), + .stream = stream[0..len], + .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), + .stream_is_screen = true, + .cursor = .{ + .col = pane.terminal.?.vt.screens.active.cursor.x, + .row = pane.terminal.?.vt.screens.active.cursor.y, + }, + }, + }; +} + +fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { + const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); + var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); + // split yields one more item than delimiters; the extra final slot is the + // cursor row retained below. + const n_rows = std.mem.count(u8, full, "\n") + 2; + const rows = try alloc.alloc([]const u8, n_rows); + errdefer alloc.free(rows); + // Blanking a prompt row only ever SHORTENS it and the retained cursor row + // adds one separator, so the dump's length plus one bounds the join. + const text = try alloc.alloc(u8, full.len + 1); + errdefer alloc.free(text); + var at: usize = 0; + var n: usize = 0; + var it = std.mem.splitScalar(u8, full, '\n'); + while (it.next()) |raw| { + const shown = if (pit.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + if (n > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..shown.len], shown); + rows[n] = text[at..][0..shown.len]; + at += shown.len; + n += 1; + } + text[at] = '\n'; + at += 1; + rows[n] = text[at..][0..0]; + n += 1; + std.debug.assert(n == n_rows); + return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; +} + +pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { + const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { + const state = pane.terminal orelse break :vp &.{}; + const screen = state.vt.screens.active; + var tl = screen.pages.getTopLeft(.viewport); + tl.x = 0; + const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; + var rows_out: std.Io.Writer.Allocating = .init(arena); + try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); + const raw = try rows_out.toOwnedSlice(); + var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); + const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); + var lines = std.mem.splitScalar(u8, raw, '\n'); + var n: usize = 0; + while (lines.next()) |ln| { + vp[n] = if (pane.mode != .tty) + if (prompts.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln + else + ln + else + ln; + n += 1; + } + std.debug.assert(n == vp.len); + break :vp vp; + }; + + const len = fillBody(null, pane, vp); + const out = try arena.alloc(u8, len); + const filled = fillBody(out, pane, vp); + std.debug.assert(filled == out.len); + return out; +} + +pub const BodyRow = union(enum) { + grid: i32, + edit: struct { line: []const u8, idx: usize }, +}; + +const BodyWalk = struct { + pane: *Pane, + goff: i32, + g: i32, + /// the buffer can start above the viewport: drop the lines scrolled past + skip: usize, + n: usize = 0, + lines: ?std.mem.SplitIterator(u8, .scalar) = null, + covered: i32 = 0, + line_idx: usize = 0, + + fn init(pane: *Pane) BodyWalk { + const off = pane.scroll(); + const goff = gridOffset(pane); + return .{ + .pane = pane, + .goff = goff, + .g = if (pane.mode == .tty) goff else pane.gridRow(off), + .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, + }; + } + + fn next(w: *BodyWalk) ?BodyRow { + while (w.n < w.pane.rows) { + if (w.lines) |*it| { + if (it.next()) |line| { + const idx = w.line_idx; + w.line_idx += 1; + // Lines scrolled off the top still count: the index names a + // line of the BUFFER, not of the visible body. + if (w.skip > 0) { + w.skip -= 1; + continue; + } + w.n += 1; + return .{ .edit = .{ .line = line, .idx = idx } }; + } + // The buffer stands in for `rows` shell rows however many lines + // it actually spelled, which is the whole slide. + w.g += w.covered; + w.skip = 0; + w.lines = null; + continue; + } + if (w.pane.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { + w.lines = std.mem.splitScalar(u8, o.text, '\n'); + w.covered = o.rows; + w.line_idx = 0; + continue; + }; + const vi = w.g - w.goff; + w.g += 1; + w.n += 1; + return .{ .grid = vi }; + } + return null; + } +}; + +/// Run the terminal body row walk. A null destination counts bytes; a slice +/// fills the exact allocation made from that count. +fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { + var walk: BodyWalk = .init(pane); + var written: usize = 0; + var first = true; + while (walk.next()) |row| { + if (!first) { + if (dst) |out| out[written] = '\n'; + written += 1; + } + first = false; + const bytes = switch (row) { + .edit => |e| e.line, + .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) + viewport[@intCast(vi)] + else + "", + }; + if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); + written += bytes.len; + } + return written; +} + +// Match surviving edit-buffer rows to their original terminal styles. +const EditAnchors = struct { + /// the buffer's own text, walked in order: a line the VIEWPORT skipped still + /// consumes the row it came from, so the lines below it stay aligned + text: []const u8 = &.{}, + at: usize = 0, + shell: []const []const u8 = &.{}, + /// the covered span, absolute grid rows, as `[first, end)` + first: usize = 0, + end: usize = 0, + lines: usize = 0, + /// the line `at` names, and the first row still unclaimed + idx: usize = 0, + cursor: usize = 0, + budget: usize = 0, + active: bool = false, + + fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { + if (o.rows <= 0 or o.row < 0) return .{}; + const first: usize = @intCast(o.row); + const screen = pane.terminal.?.vt.screens.active; + const total = screen.pages.scrollbar().total; + if (first >= total) return .{}; + const covered: usize = @intCast(o.rows); + const count = @min(covered, total - first); + const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; + const br = screen.pages.pin(.{ .screen = .{ + .x = screen.pages.cols - 1, + .y = @intCast(first + count - 1), + } }) orelse return .{}; + const arena = p.scratch.allocator(); + var output: std.Io.Writer.Allocating = .init(arena); + screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; + const shell = arena.alloc([]const u8, count) catch return .{}; + var raw = std.mem.splitScalar(u8, output.written(), '\n'); + var pins = tl.rowIterator(.right_down, br); + for (shell) |*row| { + const text = raw.next() orelse ""; + row.* = if (pins.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text + else + text; + } + const lines = std.mem.count(u8, o.text, "\n") + 1; + return .{ + .text = o.text, + .shell = shell, + .first = first, + .end = first + count, + .lines = lines, + .cursor = first, + .budget = covered + 4 * lines, + .active = true, + }; + } + + fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { + if (!a.active or idx >= a.lines) return null; + var found: ?Anchor = null; + while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); + return found; + } + + fn nextLine(a: *EditAnchors) ?[]const u8 { + if (a.at > a.text.len) return null; + const rest = a.text[a.at..]; + if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { + a.at += n + 1; + return rest[0..n]; + } + // The last line has no terminator; one past the end ends the walk. + a.at = a.text.len + 1; + return rest; + } + + /// Where this line still stands over the grid, if anywhere. + fn claim(a: *EditAnchors, line: []const u8) ?Anchor { + const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; + var k = a.cursor; + while (k < end) : (k += 1) { + if (a.budget == 0) return null; + a.budget -= 1; + if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; + a.cursor = k + 1; + return .{ .row = @intCast(k) }; + } + if (a.cursor >= a.end) return null; + const shell = a.shell[a.cursor - a.first]; + var p: usize = 0; + while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; + var s: usize = 0; + const room = @min(line.len, shell.len) - p; + while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; + if (p + s == 0) return null; + if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; + const row = a.cursor; + if (s > 0 or p >= shell.len) a.cursor += 1; + return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; + } +}; + +const Anchor = struct { + /// the row, absolute while it comes from `EditAnchors`, viewport once + /// `recolorAnsi` has subtracted the walk's offset + row: i32, + prefix: usize = std.math.maxInt(usize), + suffix: usize = 0, + /// the row's own dumped length — what the suffix is measured from on the + /// GRID side, where the edit may have changed the byte count + shell_len: usize = 0, + + fn whole(an: Anchor) bool { + return an.prefix == std.math.maxInt(usize); + } +}; + +pub fn recolorAnsi(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { + // No emulator, no ANSI cells: the whole pass — and the 256-colour theme + // projection behind it — is compiled out. + if (comptime !enabled) return; + const s = &p.surface; + if (pane.terminal == null) return; + const body_y = p.bodyTop(r); + var filtered_storage: FilteredColors = undefined; + const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { + const tz_filter = tracy.zone(@src(), "filterInit"); + defer tz_filter.end(); + filtered_storage = FilteredColors.init(p, pane); + break :blk &filtered_storage; + } else null; + // DECSCNM, read once: the filtered palette folds it in itself, the raw + // path needs it per cell. + const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); + const pages = &pane.terminal.?.vt.screens.active.pages; + const vp_rows: i32 = @intCast(scrollbar(pane).len); + // Which buffer lines the user has not actually changed, so a row swallowed + // by a growing buffer keeps the colour it still stands over. + var anchors: ?EditAnchors = null; + var walk: BodyWalk = .init(pane); + var lines = std.mem.splitScalar(u8, body, '\n'); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + // Before any early exit below, or the lines fall out of step with rows. + const text = lines.next() orelse ""; + const anchor: Anchor = switch (row) { + .edit => |e| blk: { + if (anchors == null) anchors = .init(p, pane, pane.ovl.?); + var an = anchors.?.shellRow(e.idx) orelse continue; + an.row -= walk.goff; + break :blk an; + }, + .grid => |v| .{ .row = v }, + }; + const vi = anchor.row; + if (vi < 0 or vi >= vp_rows) continue; + const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const cut: u16 = if (pane.mode == .tty) 0 else cut: { + if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; + break :cut switch (promptCut(row_pin)) { + .keep => 0, + // Blanked end to end: the row shows nothing of the grid, so + // projecting the prompt's own colours onto it would be a lie. + .blank => continue, + .cut => |n| std.math.cast(u16, n) orelse continue, + }; + }; + if (cut > 0 and text.len == 0) continue; + var at: usize = 0; + var sc: u16 = 0; + var gc: u16 = cut; + var sb: usize = 0; + const mine_from = @min(anchor.prefix, text.len); + const mine_to = text.len - @min(anchor.suffix, text.len); + var crossed = false; + while (at < text.len and sc < tw) { + const stop = modal.nextGrapheme(text, at); + if (stop <= at) break; + const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; + if (at >= mine_from and at < mine_to) { + sc += span; + at = stop; + continue; + } + if (at >= mine_to and !crossed) { + crossed = true; + const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); + while (sb < upto) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + sb += dumpedBytes(row_pin, ci.cell); + gc = std.math.add(u16, gc, 1) catch break; + } + } + const want = stop - at; + // Consume every cell that contributed to this grapheme. A cluster + // ghostty split across several cells is still ONE printed glyph. + var covered: usize = 0; + var style: ?pardes.CellStyle = null; + while (covered < want) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) + style = cellStyle(p, ci, filtered, scnm); + covered += dumpedBytes(row_pin, ci.cell); + gc = std.math.add(u16, gc, 1) catch break; + // A spacer contributes no bytes; without this the loop would + // spin on a row that ends in one. + if (covered == 0 and gc >= pane.cols) break; + } + while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| { + if (t.cell.wide != .spacer_tail) break; + gc = std.math.add(u16, gc, 1) catch break; + } + if (style) |st| for (0..span) |k| { + const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = st; + }; + sb += covered; + sc += span; + at = stop; + } + var tail: ?pardes.CellStyle = null; + if (anchor.whole() or anchor.suffix > 0) { + while (sc < tw) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + gc = std.math.add(u16, gc, 1) catch break; + if (ci.cell.wide == .spacer_tail) continue; + const cell = s.at(tx + sc, body_y + vr); + sc += 1; + const style = cellStyle(p, ci, filtered, scnm); + tail = style; + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = style; + } + if (tail) |style| while (sc < tw) : (sc += 1) { + const cell = s.at(tx + sc, body_y + vr); + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = style; + }; + } + } +} + +fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { + const style = ci.style(); + var cs: pardes.CellStyle = .{ + .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), + .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), + .bold = style.flags.bold, + .dim = style.flags.faint, + .italic = style.flags.italic, + .blink = style.flags.blink, + .reverse = style.flags.inverse, + .invisible = style.flags.invisible, + .strikethrough = style.flags.strikethrough, + .ul = switch (style.flags.underline) { + .none => .off, + .single => .single, + .double => .double, + .curly => .curly, + .dotted => .dotted, + .dashed => .dashed, + }, + }; + if (filtered == null) switch (ci.cell.content_tag) { + .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), + .bg_color_rgb => { + const rgb = ci.cell.content.color_rgb; + cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; + }, + else => {}, + }; + return cs; +} + +const FilteredColors = struct { + source: GColor.Palette, + target: *const GColor.Palette, + theme_bg: GColor.RGB, + theme_fg: GColor.RGB, + dynamic_bg: ?GColor.RGB, + dynamic_fg: ?GColor.RGB, + default_bg: GColor.RGB, + /// What a foreground too near `default_bg` becomes instead. + fallback_fg: GColor.RGB, + default_bg_luminance: f64, + fg_for_palette: [256]pardes.Color = undefined, + bg_for_palette: [256]pardes.Color = undefined, + /// The two answers for a cell that names no colour of its own. + fg_default: pardes.Color = undefined, + bg_default: pardes.Color = undefined, + cache_rgb: [256]GColor.RGB = undefined, + cache_key: [256]u8 = undefined, + cache_valid: [256]bool = @splat(false), + + fn init(p: *Pardes, pane: *const Pane) FilteredColors { + var source = GColor.default; + for (&source, 0..) |*rgb, i| + rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + const theme = p.theme(); + var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); + var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); + var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); + var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); + if (pane.terminal.?.vt.modes.get(.reverse_colors)) { + std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); + std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); + } + var self: FilteredColors = .{ + .source = source, + .target = p.tty_filter_palette.get(theme), + .theme_bg = theme_bg, + .theme_fg = theme_fg, + .dynamic_bg = dynamic_bg, + .dynamic_fg = dynamic_fg, + .default_bg = theme_bg, + .fallback_fg = theme_fg, + .default_bg_luminance = luminanceOf(theme_bg), + }; + if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); + self.default_bg_luminance = luminanceOf(self.default_bg); + if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) + self.fallback_fg = self.theme_bg; + + self.fg_default = asPardesColor(self.legible( + if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, + )); + self.bg_default = asPardesColor(self.default_bg); + for (&self.source, 0..) |current, i| { + const idx: u8 = @intCast(i); + const mapped = self.paletteRgb(idx, current); + self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); + self.bg_for_palette[idx] = asPardesColor(mapped); + } + return self; + } + + fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { + return switch (style.fg_color) { + .none => self.fg_default, + .palette => |idx| self.fg_for_palette[idx], + .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ + .default = self.dynamic_fg orelse self.theme_fg, + .palette = &self.source, + .bold = null, + })))), + }; + } + + fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { + switch (cell.content_tag) { + .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], + .bg_color_rgb => {}, + else => switch (style.bg_color) { + .none => return self.bg_default, + .palette => |idx| return self.bg_for_palette[idx], + .rgb => {}, + }, + } + // Truecolour, from either the cell or its style. + return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); + } + + fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { + if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= + config.tty_filter_min_contrast) return rgb; + return self.fallback_fg; + } + + fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { + if (current.eql(GColor.default[idx])) return self.target[idx]; + return self.keyedRgb(current); + } + + fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { + return self.target[self.nearestKey(rgb)]; + } + + fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { + const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; + const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); + if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) + return self.cache_key[slot]; + + var best: u8 = 0; + var best_distance: u32 = std.math.maxInt(u32); + for (GColor.default, 0..) |candidate, i| { + const distance = colorDistance(rgb, candidate); + // Strict comparison makes duplicate-colour ties stable at the + // lowest canonical xterm key. + if (distance < best_distance) { + best_distance = distance; + best = @intCast(i); + } + } + self.cache_rgb[slot] = rgb; + self.cache_key[slot] = best; + self.cache_valid[slot] = true; + return best; + } +}; + +const channel_luminance: [256]f64 = blk: { + @setEvalBranchQuota(20000); + var table: [256]f64 = undefined; + for (&table, 0..) |*slot, c| { + const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; + slot.* = if (normalized <= 0.03928) + normalized / 12.92 + else + std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); + } + break :blk table; +}; + +fn luminanceOf(rgb: GColor.RGB) f64 { + return 0.2126 * channel_luminance[rgb.r] + + 0.7152 * channel_luminance[rgb.g] + + 0.0722 * channel_luminance[rgb.b]; +} + +/// ghostty's `RGB.contrast` with both luminances already in hand. +fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { + const lighter = @max(a_luminance, b_luminance); + const darker = @min(a_luminance, b_luminance); + return (lighter + 0.05) / (darker + 0.05); +} + +fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { + const dr = @as(i32, a.r) - @as(i32, b.r); + const dg = @as(i32, a.g) - @as(i32, b.g); + const db = @as(i32, a.b) - @as(i32, b.b); + 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)), + ); + } + } +} + +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].?; + try testing.expect(pane.tty_filter); + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ + "\x1b[38;5;196mB" ++ + "\x1b[38;2;255;0;0mC" ++ + "\x1b[0;48;5;25mD" ++ + "\x1b[0;48;2;0;95;175mE" ++ + "\x1b[0;1;2;3;4;5;7;8;9mF" ++ + "\x1b[0;48;5;25m\x1b[K" ++ + "\r\n\x1b[0;38;5;2m界" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + + const raw = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); + + pane.tty_filter = true; + _ = frame.reset(.retain_capacity); + const filtered = try p.render(frame.allocator()); + var expected_cache: FilterPalette = .{}; + const expected = expected_cache.get(p.theme()); + try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); + try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); + try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); + try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); + try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); + + const attrs = filtered.at(tx + 5, body_y).style; + try testing.expect(attrs.bold); + try testing.expect(attrs.dim); + try testing.expect(attrs.italic); + try testing.expect(attrs.blink); + try testing.expect(attrs.reverse); + try testing.expect(attrs.invisible); + try testing.expect(attrs.strikethrough); + try testing.expectEqual(.single, attrs.ul); + + const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; + try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); + try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); + try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); + try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); + // A filtered terminal never delegates either colour to a backend palette, + // including cells which were empty/default before the pass. + for (0..r.w - config.GUTTER) |col| { + const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); + try testing.expect(!cell.default); + switch (cell.style.fg) { + .rgb => {}, + else => return error.FilteredForegroundWasNotRgb, + } + switch (cell.style.bg) { + .rgb => {}, + else => return error.FilteredBackgroundWasNotRgb, + } + } + + // Colors remains the global master gate. The pane remembers Filter while + // ANSI projection is dormant, and resumes it without replaying VT bytes. + p.settings.colors = false; + _ = frame.reset(.retain_capacity); + const plain = try p.render(frame.allocator()); + try testing.expect(pane.tty_filter); + try testing.expectEqual(asPardesColor(asGhostRgb(p.theme().fg.?)), plain.at(tx, body_y).style.fg); + p.settings.colors = true; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); + const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; + try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); + pane.tty_filter = false; + pane.tty_filter = true; + try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); + _ = frame.reset(.retain_capacity); + const osc_palette = try p.render(frame.allocator()); + try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); + + // Dynamic default foreground/background colours key every default cell, + // including the otherwise blank end of the row. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ + "\x1b]11;#5f5f5f\x1b\\" } }); + const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; + const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; + try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); + try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); + _ = frame.reset(.retain_capacity); + const dynamic = try p.render(frame.allocator()); + const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), blank.fg); + try testing.expectEqual(asPardesColor(expected[59]), blank.bg); + + const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; + try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); + try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); + const reversed_explicit = reversed.at(tx, body_y).style; + try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); + try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); + try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); + _ = frame.reset(.retain_capacity); + const unreversed = try p.render(frame.allocator()); + const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); + try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); + + // The cache is keyed by values, not a theme name. Replacing a custom + // theme in place immediately recolours already-rendered indexed cells. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); + var custom = p.theme().*; + custom.name = try p.gpa.dupe(u8, "same-name"); + custom.palette = null; + custom.kw = .{ 1, 2, 3 }; + p.custom_theme = custom; + _ = frame.reset(.retain_capacity); + const custom_first = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); + if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; + _ = frame.reset(.retain_capacity); + const custom_second = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); +} + +test "terminal Filter keeps extended keys dark-to-light on a light theme" { + const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); + defer p.deinit(); + try std.testing.expectEqualStrings("acme", p.theme().name); + var cache: FilterPalette = .{}; + const palette = cache.get(p.theme()); + try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); + try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); +} + +test "terminal Filter preserves exact palette-null light theme default roles" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + var light = p.theme().*; + light.name = try p.gpa.dupe(u8, "filter-light-defaults"); + light.bg = .{ 0xf8, 0xf8, 0xf8 }; + light.fg = .{ 0x38, 0x38, 0x38 }; + light.palette = null; + p.custom_theme = light; + + const pane = p.panes[0].?; + try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); + try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); + pane.tty_filter = true; + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const ordinary = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); +} + +test "terminal Filter maps the default roles before it maps anything else" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + // Native dark/light palettes plus legacy helix/dark/acme, including + // the null-page fallback that only the legacy dark theme exercises. + for (0..9) |t| { + p.settings.theme = @intCast(t); + const stage_one = FilteredColors.init(p, pane); + // `dark` declares no background of its own, which is exactly why the + // resolver reads the tag colours as the fallback rather than `.?`. + const theme = p.theme(); + try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); + try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); + // With no OSC 11 in play the mapped page IS that anchor, and the + // fallback is the other one: a background never contrasts with itself. + try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); + try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); + } + + p.settings.theme = 0; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); + var moved = FilteredColors.init(p, pane); + try testing.expect(!moved.default_bg.eql(moved.theme_bg)); + try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); +} + +test "terminal Filter refuses a foreground that would collapse onto the page" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ + "\x1b[0;30mB" ++ + "\x1b[0;31mR" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + + for (0..9) |t| { + p.settings.theme = @intCast(t); + var fc = FilteredColors.init(p, pane); + const page = asPardesColor(fc.default_bg); + const rescued = asPardesColor(fc.fallback_fg); + _ = frame.reset(.retain_capacity); + const g = try p.render(frame.allocator()); + + // The colour each of the three would have been given with no floor. + const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); + const raw_black = fc.paletteRgb(0, GColor.default[0]); + const raw_red = fc.paletteRgb(1, GColor.default[1]); + + for ([_]struct { at: u16, raw: GColor.RGB }{ + .{ .at = 0, .raw = raw_white }, + .{ .at = 1, .raw = raw_black }, + .{ .at = 2, .raw = raw_red }, + }) |case| { + const cell = g.at(tx + case.at, body_y).style; + try testing.expectEqual(page, cell.bg); + if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { + // Refused: the projection's answer is not painted, the anchor is. + try testing.expectEqual(rescued, cell.fg); + try testing.expect(!std.meta.eql(cell.fg, cell.bg)); + } else { + // Cleared the floor, so stage two leaves it exactly alone. + try testing.expectEqual(asPardesColor(case.raw), cell.fg); + } + // Either way a filtered cell delegates neither colour to a backend. + switch (cell.fg) { + .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= + config.tty_filter_min_contrast), + else => return error.FilteredForegroundWasNotRgb, + } + } + + // At least one of the three has to have been a real collapse, or this + // theme proved nothing: white on the light theme, black on the dark. + try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or + raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); + // A saturated red is never the page on any curated theme. + try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); + } +} + +test "terminal Filter holds every projected foreground off the page" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + + for (0..9) |t| { + p.settings.theme = @intCast(t); + var fc = FilteredColors.init(p, pane); + var refused: usize = 0; + for (fc.target, 0..) |projected, key| { + const ink = fc.legible(projected); + try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); + if (!ink.eql(projected)) { + refused += 1; + try testing.expect(ink.eql(fc.fallback_fg)); + // Only ever refused for being too near the page. + try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); + } + // The key a background asks for is handed back untouched, including + // the one whose value is the page itself. + try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); + } + // Every curated theme owns at least one collapsing key — that is why + // the floor exists — and the floor must not be flattening the palette. + try testing.expect(refused > 0); + try testing.expect(refused < fc.target.len / 8); + } +} + +test "tty ansi colors follow the prompt hug into normal mode" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; + const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; + + // tty mode projects the emulator's ansi colours cell for cell. + pane.mode = .tty; + p.shell_rows.stale = true; + const tty = try p.render(frame.allocator()); + try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); + try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); + + pane.mode = .normal; + p.shell_rows.stale = true; + _ = frame.reset(.retain_capacity); + const norm = try p.render(frame.allocator()); + try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); + try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); + try testing.expectEqual(red, norm.at(tx, body_y).style.fg); + try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); +} + +test "a prompt row hidden end to end paints nothing at all" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tty_filter = false; + pane.mode = .normal; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + p.shell_rows.stale = true; + const s = try p.render(frame.allocator()); + + try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); + 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 }; +} + +pub 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. + if (comptime !enabled) return; + 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"); +} + +/// the snapshot takes ownership of a COPY of the edit buffer's text +pub fn snap(p: *Pardes, pane: *Pane) ?Snapshot { + var ovl: ?EditBuffer = null; + if (pane.ovl) |o| ovl = .{ .row = o.row, .rows = o.rows, .text = p.gpa.dupe(u8, o.text) catch return null }; + return .{ .ovl = ovl, .cur_row = pane.cur_row, .cur_col = pane.cur_col, .vsel = pane.vsel }; +} + +/// undo/redo restores the selection recorded with the snapshot (helix +/// keeps selections in its history transactions) +pub fn restoreSnap(p: *Pardes, pane: *Pane, s: Snapshot) void { + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = s.ovl; + pane.cur_row = s.cur_row; + pane.cur_col = s.cur_col; + pane.cur_pinned = true; + pane.vsel = s.vsel; + pane.msel.active = false; + pane.ensureCursorVisible(); +} + +fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, value: Snapshot) void { + if (len.* == slots.len) { + if (slots[0].ovl) |overlay| gpa.free(overlay.text); + std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); + len.* -= 1; + } + slots[len.*] = value; + len.* += 1; +} + +pub fn pushUndo(p: *Pardes, pane: *Pane) void { + const current = pane.ovl orelse EditBuffer{ .rows = 0 }; + if (pane.ed_undo_len > 0) { + const top = pane.ed_undo[pane.ed_undo_len - 1]; + const same = if (top.ovl) |overlay| pane.ovl != null and overlay.row == current.row and + overlay.rows == current.rows and std.mem.eql(u8, overlay.text, current.text) else pane.ovl == null; + if (same) return; + } + const value = snap(p, pane) orelse return; + pushHistory(p.gpa, &pane.ed_undo, &pane.ed_undo_len, value); + for (pane.ed_redo[0..pane.ed_redo_len]) |item| if (item.ovl) |overlay| p.gpa.free(overlay.text); + pane.ed_redo_len = 0; +} + +pub fn undo(p: *Pardes, pane: *Pane) void { + if (pane.ed_undo_len == 0) return; + const current = snap(p, pane) orelse return; + pushHistory(p.gpa, &pane.ed_redo, &pane.ed_redo_len, current); + pane.ed_undo_len -= 1; + restoreSnap(p, pane, pane.ed_undo[pane.ed_undo_len]); +} + +pub fn redo(p: *Pardes, pane: *Pane) void { + if (pane.ed_redo_len == 0) return; + const current = snap(p, pane) orelse return; + pushHistory(p.gpa, &pane.ed_undo, &pane.ed_undo_len, current); + pane.ed_redo_len -= 1; + restoreSnap(p, pane, pane.ed_redo[pane.ed_redo_len]); +} + +pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { + const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); + const room = state.reply.len - state.reply_len; + const n = @min(room, data.len); + @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); + state.reply_len += @intCast(n); +} + +const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( + @FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"), +).optional.child).pointer.child).@"fn".return_type.?; +pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs { + return .{}; +} diff --git a/src/fs.zig b/src/fs.zig index 8ed6fc77..fed15344 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -40,6 +40,7 @@ const source_files = [_]Source{ .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, + .{ .path = "src/Terminal.zig", .contents = @embedFile("Terminal.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, .{ .path = "src/look.zig", .contents = @embedFile("look.zig") }, diff --git a/src/panes.zig b/src/panes.zig index 051470b1..0f203e6f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -3918,2532 +3918,7 @@ pub const Pdf = struct { } else struct {}; }; -pub const Terminal = struct { - pub const enabled = pardes.terminal_panes; - const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; - - pub const history_max = if (enabled) 64 else 8; - - pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; - pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; - - /// The `aid` pardes's injected bash and fish marks carry (host_io.zig). - pub const prompt_aid = "pardes"; - - /// ghostty's handler, plus where the shell is in its command cycle as - /// its OSC 133 marks tell it: ghostty parses D's exit status and drops - /// it, and /pane//pty/run waits on exactly that. Only marks carrying - /// pardes's own `aid` move it, so fish's native marks, a nested shell's - /// and a stray `133;D` in some file being printed all pass it by. - pub const MarkedHandler = if (enabled) struct { - inner: ghostty_vt.TerminalStream.Handler, - phase: enum { none, prompt, input, running } = .none, - /// Counts commands started (C at the input phase). - started: u32 = 0, - /// Counts prompts drawn (B), so a line the shell refused without - /// running (a fish syntax error: no C, no D, a new prompt) shows. - prompts: u32 = 0, - /// D marks outside a running command: the shell handled a line - /// without starting it (bash on a syntax error prints no C). - declined: u32 = 0, - /// The newest prompt continues an unfinished line (bash's PS2, marked - /// `k=c`): the shell still holds the start of the command. - continuation: bool = false, - /// Where the newest command's output began (its C) and ended (its - /// D) on the primary screen, pinned so scrolling keeps them. - out_start: ?*ghostty_vt.Pin = null, - out_end: ?*ghostty_vt.Pin = null, - /// The running command's output was erased under it -- a clear, ED 3, - /// a reset -- so the pins no longer span what it printed: ED 3 moves - /// a pin to the next page without flagging it `garbage` - /// (PageList.erasePage). - lost: bool = false, - - /// The newest command to end: which one, and its status if given. - finished: ?struct { seq: u32, status: ?i32 } = null, - - const Action = ghostty_vt.TerminalStream.Action; - - /// Move one of the output pins to the cursor. Only the primary screen - /// is pinned: a command's own full-screen display is not its output. - fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { - const screen = self.inner.terminal.screens.get(.primary) orelse return; - if (slot.*) |old| screen.pages.untrackPin(old); - slot.* = null; - if (!now or self.inner.terminal.screens.active_key != .primary) return; - slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; - } - - pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { - if (comptime action == .semantic_prompt) mark: { - const aid = value.readOption(.aid) orelse break :mark; - if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; - switch (value.action) { - .fresh_line_new_prompt => { - self.phase = .prompt; - self.continuation = value.readOption(.prompt_kind) == .continuation; - }, - .end_prompt_start_input => { - self.phase = .input; - self.prompts +%= 1; - }, - // bash's DEBUG trap also fires on its own PROMPT_COMMAND, - // outside the input phase; only a C that ends input counts - .end_input_start_output => if (self.phase == .input) { - self.phase = .running; - self.started +%= 1; - self.lost = false; - self.pinCursor(&self.out_start, true); - self.pinCursor(&self.out_end, false); - }, - .end_command => if (self.phase == .running) { - self.phase = .none; - self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; - self.pinCursor(&self.out_end, true); - } else { - self.declined +%= 1; - }, - else => {}, - } - } - if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .full_reset) { - if (self.phase == .running) self.lost = true; - } - self.inner.vt(action, value); - } - - pub fn deinit(self: *@This()) void { - self.inner.deinit(); - } - } else void; - - pub const Replay = struct { - bytes: [1024 * 1024]u8 = undefined, - head: usize = 0, - len: usize = 0, - }; - - pub const State = struct { - vt: VtSlot, - stream: StreamSlot, - replay: Replay, - reply: [256]u8 = undefined, - reply_len: u16 = 0, - }; - - const GColor = ghostty_vt.color; - - const FilterPaletteKey = struct { - bg: GColor.RGB, - fg: GColor.RGB, - base: [16]GColor.RGB, - }; - - pub const FilterPalette = if (enabled) LivePalette else struct {}; - - const LivePalette = struct { - key: ?FilterPaletteKey = null, - colors: GColor.Palette = GColor.default, - - fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { - const bg = asGhostRgb(theme.bg orelse theme.tag_bg); - const fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var base: [16]GColor.RGB = undefined; - if (theme.palette) |palette| { - for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); - } else { - const synthesized = [16][3]u8{ - theme.bg orelse theme.tag_bg, - theme.kw, - theme.str, - theme.num, - theme.box, - theme.sel_bg, - theme.comment, - theme.fg orelse theme.tag_fg, - theme.lineno, - theme.kw, - theme.str, - theme.num, - theme.scroll_thumb, - theme.sel_fg, - theme.tag_fg, - theme.fg orelse theme.tag_fg, - }; - for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); - } - - const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; - if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; - - var seed = GColor.default; - for (base, 0..) |rgb, i| seed[i] = rgb; - self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); - self.key = key; - return &self.colors; - } - }; - - fn asGhostRgb(rgb: [3]u8) GColor.RGB { - return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; - } - - fn asPardesColor(rgb: GColor.RGB) pardes.Color { - return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; - } - - /// The owned text standing in for `rows` live terminal rows, beginning at - /// absolute surface row `row`. The emulator grid remains untouched underneath. - pub const EditBuffer = struct { - row: i32 = 0, - rows: i32 = 1, - text: []u8 = &.{}, - }; - - /// One whole-state terminal edit boundary. Null means the pane has not yet - /// materialized an edit buffer; non-null snapshots own their text. - pub const Snapshot = struct { - ovl: ?EditBuffer, - cur_row: i32, - cur_col: i32, - vsel: Pane.CharSel, - }; - - pub const PendingCommand = struct { - bytes: []u8 = &.{}, - wait: enum { none, spawn, input } = .none, - }; - - pub fn armShellSpawn(pane: *Pane) void { - if (comptime !enabled) return; - std.debug.assert(pane.pending_command.bytes.len == 0); - pane.pending_command.wait = .spawn; - } - - pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { - if (pane.pending_command.wait == .none) return false; - const old_len = pane.pending_command.bytes.len; - const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); - const bytes = if (old_len == 0) - try pane.gpa.alloc(u8, new_len) - else - try pane.gpa.realloc(pane.pending_command.bytes, new_len); - @memcpy(bytes[old_len..][0..command.len], command); - bytes[new_len - 1] = '\r'; - pane.pending_command.bytes = bytes; - pane.greet = false; - return true; - } - - pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { - const pane = p.panes[id] orelse return; - if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; - if (prompt_marks) { - pane.pending_command.wait = .input; - releasePendingCommand(p, id, pane, false); - } else { - pane.greet = false; - releasePendingCommand(p, id, pane, true); - } - } - - pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { - if (pane.pending_command.wait == .input) - releasePendingCommand(p, id, pane, promptInputReady(pane)); - } - - fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { - if (!ready) return; - const bytes = pane.pending_command.bytes; - pane.pending_command = .{}; - if (bytes.len > 0) { - p.emitWrite(id, bytes); - pane.gpa.free(bytes); - } - } - - pub fn deinitPendingCommand(pane: *Pane) void { - if (pane.pending_command.bytes.len > 0) - pane.gpa.free(pane.pending_command.bytes); - pane.pending_command = .{}; - } - - pub fn terminalIo() std.Io { - return if (comptime !pardes.hosted) - std.Io.failing - else - std.Io.Threaded.global_single_threaded.io(); - } - - /// The three numbers ghostty's scrollbar reports; all zero without an emulator. - pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; - - pub fn scrollbar(pane: *const Pane) Scrollbar { - if (comptime !enabled) return .{}; - const state = pane.terminal orelse return .{}; - const sb = state.vt.screens.active.pages.scrollbar(); - return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; - } - - /// The emulator's viewport offset, in SHELL rows: the top of what it shows. - pub fn gridOffset(pane: *const Pane) i32 { - return @intCast(scrollbar(pane).offset); - } - - /// Where the emulator itself puts the cursor, in active-area cells — the origin - /// without one, which is where an empty pane's cursor belongs anyway. - pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; - - pub fn gridCursor(pane: *const Pane) GridCursor { - if (comptime !enabled) return .{}; - const state = pane.terminal orelse return .{}; - const cur = state.vt.screens.active.cursor; - return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; - } - - pub fn visibleCursor(pane: *const Pane) ?GridCursor { - if (comptime !enabled) return null; - const state = pane.terminal orelse return null; - if (!state.vt.modes.get(.cursor_visible)) return null; - const cur = state.vt.screens.active.cursor; - const sb = scrollbar(pane); - const row = sb.total - sb.len + cur.y; - if (row < sb.offset or row - sb.offset >= sb.len) return null; - return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; - } - - /// Move the emulator's viewport by `delta` shell rows (negative scrolls back). - pub fn scrollGrid(pane: *Pane, delta: i32) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.vt.screens.active.scroll(.{ .delta_row = delta }); - } - - /// Is the viewport already showing the last row of output? - pub fn atBottom(pane: *const Pane) bool { - if (comptime !enabled) return true; - const sb = scrollbar(pane); - return sb.offset + sb.len >= sb.total; - } - - /// Snap the viewport back onto live output. - pub fn followOutput(pane: *Pane) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.vt.screens.active.scroll(.active); - } - - /// Reflow the grid. A failed reflow keeps the grid it had rather than dropping - /// a scrollback; the next resize retries with the same numbers. - pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - if (cols != pane.cols) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; - } - - /// DECSET 2004: the program wants its pastes bracketed. - pub fn bracketedPaste(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.modes.get(.bracketed_paste); - } - - /// The program tracks the mouse itself, so a click in its body is its event. - pub fn reportsMouse(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - const m = &state.vt.modes; - return m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any); - } - - /// ...and wants them in SGR (1006) rather than the legacy X10 bytes. - pub fn mouseFormatSgr(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.modes.get(.mouse_format_sgr); - } - - /// The whole scrollback as plain text, `gpa`-owned: what `Save` writes out. - pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { - if (comptime !enabled) return &.{}; - const state = pane.terminal orelse return &.{}; - return state.vt.screens.active.dumpStringAlloc(gpa, .{ .screen = .{} }); - } - - /// Release the emulator's heap. The Pane allocation itself is the core's. - pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.stream.deinit(); - state.vt.deinit(gpa); - gpa.destroy(state); - pane.terminal = null; - } - - /// Allocate the live emulator half of a terminal pane. Slot ownership, serial - /// assignment, and spawn effects remain core lifecycle invariants. - pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try createDoc(gpa, cols, rows); - errdefer gpa.destroy(pane); - if (comptime !enabled) return pane; - const state = try gpa.create(State); - errdefer gpa.destroy(state); - state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ - .cols = cols, - .rows = rows, - .max_scrollback = 16 * 1024 * 1024, - }); - state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); - state.replay.head = 0; - state.replay.len = 0; - state.reply_len = 0; - state.stream.handler.inner.effects.write_pty = ptyReport; - state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; - pane.terminal = state; - pane.tty_filter = true; - return pane; - } - - pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try gpa.create(Pane); - pane.* = .{ - .gpa = gpa, - .cols = cols, - .rows = rows, - }; - return pane; - } - - /// Where a restored terminal's history ends and its new shell begins. - pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; - - /// Rebuild a dump's terminal emulator from its recorded output. `live`: a - /// shell will be spawned into it, so the history is marked off from what - /// that shell prints and the pane waits for it like any new terminal. - /// Registration and tag/cwd policy stay with the core; raw VT replay and - /// viewport restoration belong here. - pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { - const terminal = src.terminal.?; - if (comptime !enabled) { - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - errdefer p.gpa.destroy(pane); - if (terminal.stream.len > 0) - pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; - return pane; - } - // An older dump's raw output tail cannot come back live: cut off mid - // redraw, or written at sizes the pane no longer has, it replays as - // garbage. Its rendered text can. - const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; - const bytes = if (legacy_text) - try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") - else if (terminal.stream_b64.len > 0) - try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) - else - &.{}; - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - if (live) { - if (bytes.len > 0) { - ingest(pane, bytes); - ingest(pane, restored_banner); - } - followOutput(pane); - // A view left scrolled back stays on what it was showing: the - // banner's line breaks scrolled a full screen by that many more. - if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); - armShellSpawn(pane); - } else if (bytes.len > 0) { - ingest(pane, bytes); - followOutput(pane); - if (src.scroll > 0) - scrollGrid(pane, -@as(i32, @intCast(src.scroll))); - } - return pane; - } - - /// Feed the emulator and retain the bounded suffix a dump can replay. Live - /// output and restoration share this byte path, then apply different views. - fn ingest(pane: *Pane, bytes: []const u8) void { - const state = pane.terminal.?; - const replay = &state.replay; - if (bytes.len >= replay.bytes.len) { - const kept = bytes[bytes.len - replay.bytes.len ..]; - @memcpy(&replay.bytes, kept); - replay.head = 0; - replay.len = replay.bytes.len; - } else { - const overflow = bytes.len -| (replay.bytes.len - replay.len); - replay.head = (replay.head + overflow) % replay.bytes.len; - replay.len -= overflow; - const tail = (replay.head + replay.len) % replay.bytes.len; - const first = @min(bytes.len, replay.bytes.len - tail); - @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); - @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); - replay.len += bytes.len; - } - state.stream.nextSlice(bytes); - } - - /// Return the replay ring in chronological order. Wrapped records are copied - /// into `allocator`; contiguous records remain a borrowed slice of the pane. - fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { - const state = pane.terminal orelse return &.{}; - const replay = &state.replay; - if (replay.len == 0) return &.{}; - if (replay.head + replay.len <= replay.bytes.len) - return replay.bytes[replay.head..][0..replay.len]; - const out = try allocator.alloc(u8, replay.len); - const first = replay.bytes.len - replay.head; - @memcpy(out[0..first], replay.bytes[replay.head..]); - @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); - 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 and enabled, 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 "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(!mouseFormatSgr(pane)); - try std.testing.expect(!promptInputReady(pane)); - scrollGrid(pane, 100); - followOutput(pane); - resizeGrid(pane, allocator, 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.expectEqualStrings("", try replayBytes(pane, allocator)); - try std.testing.expect(!failing.has_induced_failure); - } - - test "terminal state keeps parser fragments and sends emulator replies through its owner" { - if (comptime !enabled) return error.SkipZigTest; - 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); - try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); - } - - test "replay keeps a bounded chronological suffix across large writes and wrapping" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); - ingest(pane, "hello"); - const small = try replayBytes(pane, gpa); - try std.testing.expectEqualStrings("hello", small); - try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); - - const capacity = pane.terminal.?.replay.bytes.len; - const input = try gpa.alloc(u8, capacity + 7); - defer gpa.free(input); - @memset(input, 0); - const ending = "\x1b[31mred\x1b[0m\r\n"; - @memcpy(input[input.len - ending.len ..], ending); - ingest(pane, input); - try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); - ingest(pane, "next\r\n"); - const wrapped = try replayBytes(pane, gpa); - defer gpa.free(wrapped); - try std.testing.expectEqual(capacity, wrapped.len); - try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); - try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); - } - - test "replay restores terminal cells from the retained stream" { - if (comptime !enabled) 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, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); - defer gpa.free(encoded); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = pane.cols, - .rows = pane.rows, - .terminal = .{ .stream_b64 = encoded }, - }, false); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - const before = try screenTextAlloc(pane, gpa); - defer gpa.free(before); - const after = try screenTextAlloc(restored, gpa); - defer gpa.free(after); - try std.testing.expectEqualStrings(before, after); - try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); - } - - test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime !enabled or 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"); - try p.dumpState(); - const restored = try Pardes.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.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 "an older dump comes back live from its rendered text, not its raw output tail" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - // A tail cut mid-redraw: relative moves from a cursor it never set. - const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); - defer gpa.free(tail); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = 40, - .rows = 12, - .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, - }, true); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - defer deinitPendingCommand(restored); - const text = try screenTextAlloc(restored, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); - } - - /// Record and parse one live pty read, invalidate its motion surface, and - /// follow it only when the body (possibly parked under a tag edit) is raw. - pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { - // There are no pty reads at all without an emulator to parse them into. - if (comptime !enabled) return; - if (pane.terminal == null) return; - const has_positions = pane.ovl != null or pane.cur_pinned or pane.vsel.active or - pane.msel.active or pane.nsel > 0 or pane.append_at != null or pane.look_at != null or - pane.ed_undo_len > 0 or pane.ed_redo_len > 0 or pointerRowCount(pane) > 0; - // Sticky bottom, as every other terminal does it: output drags the - // viewport down only when the viewport was already on the last row, so - // a reader scrolled back into the scrollback stays where they scrolled. - const at_bottom = atBottom(pane); - if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); - p.shell_rows.markStale(pane); - const body_mode = if (pane.tag_edit) pane.tag_mode else pane.mode; - if (body_mode == .tty and at_bottom) followOutput(pane); - } - - const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; - const PositionPin = struct { - target: *i32, - row: RowPin, - overlay: ?*EditBuffer, - edit_row: ?i32 = null, - }; - - fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { - if (row < 0) return .{ .offset = row }; - const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); - var left = pages.total_rows - 1 - bounded; - var node = pages.pages.last.?; - while (left >= node.rows()) { - left -= node.rows(); - node = node.prev.?; - } - const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { - failed.* = true; - return .{}; - }; - return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; - } - - fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { - const pin = row.pin orelse return row.offset; - const alive = pages orelse return 0; - if (pin.garbage) return 0; - var after: usize = 0; - var node = alive.pages.last; - while (node) |item| : (node = item.prev) { - if (item == pin.node) - return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; - after += item.rows(); - } - return 0; - } - - fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { - var grid = target.*; - if (overlay) |edit| { - const lines: i32 = @intCast(modal.lineCount(edit.text)); - if (grid >= edit.row and grid < edit.row +| lines) - return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; - if (grid > edit.row) grid = grid -| lines +| edit.rows; - } - return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; - } - - fn pointerRowCount(pane: *const Pane) usize { - var count: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - count += rows.len; - }; - return count; - } - - fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { - const screens = &pane.terminal.?.vt.screens; - const key = screens.active_key; - const generation = screens.generation(key); - const pages = &screens.active.pages; - const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *Pane.CharSel }; - var groups: [history_max * 2 + 1]Group = undefined; - groups[0] = .{ - .overlay = if (pane.ovl) |*overlay| overlay else null, - .cursor = &pane.cur_row, - .selection = &pane.vsel, - }; - var ngroups: usize = 1; - for ([_][]Snapshot{ pane.ed_undo[0..pane.ed_undo_len], pane.ed_redo[0..pane.ed_redo_len] }) |history| { - for (history) |*snapshot| { - groups[ngroups] = .{ - .overlay = if (snapshot.ovl) |*overlay| overlay else null, - .cursor = &snapshot.cur_row, - .selection = &snapshot.vsel, - }; - ngroups += 1; - } - } - const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; - var spans: [groups.len]Span = undefined; - var nspans: usize = 0; - var positions: [groups.len * 2 + Pane.max_selections * 2 + 4]PositionPin = undefined; - var npositions: usize = 0; - var failed = false; - for (groups[0..ngroups]) |group| { - if (group.overlay) |overlay| { - spans[nspans] = .{ - .overlay = overlay, - .start = trackRow(pages, overlay.row, &failed), - .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), - }; - nspans += 1; - } - positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); - npositions += 1; - if (group.selection.active) { - positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); - npositions += 1; - } - } - const overlay = groups[0].overlay; - var extra: [Pane.max_selections * 2 + 4]*i32 = undefined; - var nextra: usize = 0; - if (pane.msel.active) { - extra[nextra] = &pane.msel.r0; - extra[nextra + 1] = &pane.msel.r1; - nextra += 2; - } - for (pane.sels[0..pane.nsel]) |*selection| { - extra[nextra] = &selection.row; - extra[nextra + 1] = &selection.arow; - nextra += 2; - } - if (pane.append_at) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - if (pane.look_at) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - for (extra[0..nextra]) |target| { - positions[npositions] = trackPosition(pages, target, overlay, &failed); - npositions += 1; - } - const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; - defer if (pointer_positions) |pins| pane.gpa.free(pins); - if (pointer_positions) |pins| { - var index: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - for (rows) |*row| { - pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); - index += 1; - } - }; - } else failed = true; - ingest(pane, bytes); - // RIS can destroy the alternate screen and every pin it owned. - const alive = if (screens.generation(key) == generation) pages else null; - var moved = false; - var pointer_rows_lost = alive == null or pointer_positions == null; - if (pointer_positions) |pins| for (pins) |position| { - if (alive != null) if (position.row.pin) |pin| { - if (pin.garbage) pointer_rows_lost = true; - }; - }; - for (spans[0..nspans]) |span| { - const start = pinnedRow(alive, span.start); - const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); - moved = moved or start != span.overlay.row or rows != span.overlay.rows; - span.overlay.row = start; - span.overlay.rows = rows; - if (alive) |owner| { - if (span.start.pin) |pin| owner.untrackPin(pin); - if (span.end.pin) |pin| owner.untrackPin(pin); - } - } - for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { - var row = pinnedRow(alive, position.row); - if (position.overlay) |edit| { - if (position.edit_row) |relative| { - row = edit.row +| relative; - } else if (row > edit.row) { - row = if (row < edit.row +| edit.rows) - edit.row - else - row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); - } - } - moved = moved or row != position.target.*; - position.target.* = row; - if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); - }; - if (pointer_rows_lost) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. - if (failed) { - const message = "terminal edit position reset: out of memory"; - @memcpy(pane.msg[0..message.len], message); - pane.msg_len = message.len; - } - } - - test "raw terminal output needs no position tracking allocations" { - if (comptime !enabled) return error.SkipZigTest; - 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.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()); - } - - pub fn promptInputReady(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active_key != .alternate and - state.vt.screens.active.cursor.semantic_content == .input; - } - - pub const CommandOutput = struct { - /// Owned by the caller. - text: [:0]const u8, - /// Whether `text` starts where the command did. It does not when that - /// start is not there to read: cut off by `max_rows`, scrolled out of - /// the history (ghostty moved the pin to the oldest row it kept and - /// flagged it `garbage`), erased under it (`MarkedHandler.lost`), or - /// never pinned (a C or D that came on the alternate screen). - whole: bool, - }; - - /// What the newest finished command printed: the screen text between its - /// C and D marks, read from at most `max_rows` rows above its end, so a - /// command that printed the whole history costs no more than its tail. - pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { - // Unless there is text to read, whether the nothing it printed is the - // whole of it. - const whole = if (comptime enabled) printed: { - const state = pane.terminal orelse break :printed true; - const marks = &state.stream.handler; - const start = marks.out_start orelse break :printed false; - const end = marks.out_end orelse break :printed false; - const screen = state.vt.screens.get(.primary) orelse break :printed false; - if (end.garbage) break :printed false; - var whole = !marks.lost and !start.garbage; - // D is where the next prompt begins: the output ends a cell before. - const last = end.leftWrap(1) orelse break :printed whole; - if (start.eql(end.*) or last.before(start.*)) break :printed whole; - var from = start.*; - if (last.up(max_rows)) |floor| if (from.before(floor)) { - from = floor; - from.x = 0; - whole = false; - }; - return .{ - .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), - .whole = whole, - }; - } else true; - return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; - } - - /// At a prompt with nothing typed on its line: no input left of the - /// cursor and none under it (text typed and then Ctrl-A'd starts at the - /// cursor). Nothing further right counts: that is where fish draws a - /// right prompt, and fish suggests nothing on an empty line. - pub fn promptInputEmpty(pane: *const Pane) bool { - if (comptime !enabled) return false; - if (!promptInputReady(pane)) return false; - const cursor = &pane.terminal.?.vt.screens.active.cursor; - const row = cursor.page_pin.cells(.all); - for (row[0..@min(cursor.x + 1, row.len)]) |cell| - if (cell.semantic_content == .input and !cell.isEmpty()) return false; - return true; - } - - /// Encode one key for the program that owns a raw terminal and queue its pty - /// write, respecting the application's keyboard protocol and terminal modes. - pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { - if (comptime enabled) { - const pane = p.panes[id] orelse return; - const state = pane.terminal orelse return; - const input = ghostty_vt.input; - const physical: input.Key = switch (key.cp) { - Key.enter => .enter, - Key.backspace => .backspace, - Key.tab => .tab, - Key.escape => .escape, - Key.up => .arrow_up, - Key.down => .arrow_down, - Key.left => .arrow_left, - Key.right => .arrow_right, - Key.home => .home, - Key.end => .end, - Key.page_up => .page_up, - Key.page_down => .page_down, - Key.delete => .delete, - else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, - }; - var utf8: [4]u8 = undefined; - const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; - const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace) - utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] - else - ""; - var buffer: [256]u8 = undefined; - var writer = std.Io.Writer.fixed(&buffer); - input.encodeKey(&writer, .{ - .key = physical, - .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, - .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, - .utf8 = text, - .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, - }, options: { - var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); - // fromTerminal cannot know this one and says so, defaulting to - // "option is not alt" — right for an app that lets macOS do the - // unicode translation and hands the encoder the composed text. - // Every pardes shell resolves the modifier itself and hands the - // core the BASE key with the alt bit and no text at all (see - // PardesView.keyDown, and app.mjs doing the same with the same - // two bits), so by the time this runs alt already means alt. - // Left at the default, a macOS build drops the ESC prefix on - // the floor and forwards Alt-n to the child as a bare `n`. - opts.macos_option_as_alt = .true; - break :options opts; - }) catch return; - if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); - return; - } - var control: [1]u8 = undefined; - const bytes: ?[]const u8 = blk: { - if (key.ctrl) { - if (key.cp >= 'a' and key.cp <= 'z') { - control[0] = @intCast(key.cp - 0x60); - break :blk control[0..1]; - } - // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. - if (key.cp >= '@' and key.cp <= '_') { - control[0] = @intCast(key.cp - 0x40); - break :blk control[0..1]; - } - } - if (key.text.len > 0) break :blk key.text; - break :blk switch (key.cp) { - Key.enter => "\r", - Key.backspace => "\x7f", - Key.tab => "\t", - Key.escape => "\x1b", - Key.up => "\x1b[A", - Key.down => "\x1b[B", - Key.right => "\x1b[C", - Key.left => "\x1b[D", - Key.delete => "\x1b[3~", - else => null, - }; - }; - if (bytes) |encoded| - p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); - } - - pub fn enterTty(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; - if (comptime enabled) if (!selected and pane.terminal != null and pane.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { - const screen = pane.terminal.?.vt.screens.active; - const goff: i32 = @intCast(screen.pages.scrollbar().offset); - const vp_row = pane.gridRow(pane.cur_row) - goff; - if (vp_row < 0) break :handoff; - - var grid_col: i32 = @max(0, pane.cur_col); - if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { - if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { - .cut => |cols| grid_col += @intCast(cols), - .keep, .blank => {}, - }; - } - const click_pin = screen.pages.pin(.{ - .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, - }) orelse break :handoff; - const cursor_pin = screen.cursor.page_pin.*; - var prompts = cursor_pin.promptIterator(.left_up, null); - const prompt_pin = prompts.next() orelse break :handoff; - if (click_pin.before(prompt_pin)) break :handoff; - const moves = screen.promptClickMove(click_pin); - for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); - for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); - }; - - pane.mode = .tty; - followOutput(pane); // entering raw mode is a request for the live shell - pane.msel.active = false; - pane.vsel.active = false; - pane.nsel = 0; - // The raw renderer follows the live cursor. A captured mouse selection - // keeps its modal endpoint for the next return to editor mode. - pane.cur_pinned = selected; - pane.select = false; - pane.append_at = null; - pane.sticky_col = -1; - pane.normal.clear(); - } - - // Returned slices remain valid until the next cache rebuild or reset. - pub const RowsCache = struct { - /// whose grid this describes; null = the slot is free - pane: ?*const Pane = null, - /// the rows joined by '\n' — `flatSurface` hands this back verbatim - /// instead of rebuilding the join on every keystroke - text: []const u8 = &.{}, - /// slices INTO `text`, absolute grid rows from 0 - rows: [][]const u8 = &.{}, - /// `text` is a prefix of this: blanking a prompt row shortens the join, - /// and the slack is not worth a second allocation to reclaim - text_alloc: []u8 = &.{}, - stale: bool = false, - - pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.text_alloc.len > 0) gpa.free(c.text_alloc); - if (c.rows.len > 0) gpa.free(c.rows); - c.* = .{}; - } - - /// Free a stale entry. Called at the top of `update`, and nowhere else. - pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.stale) c.reset(gpa); - } - - /// `pane`'s grid moved: the entry no longer describes it. - pub fn markStale(c: *RowsCache, pane: *const Pane) void { - if (c.pane == pane) c.stale = true; - } - - pub fn dropPane(c: *RowsCache, pane: *const Pane) void { - if (c.pane != pane) return; - c.pane = null; - c.stale = true; - } - }; - - const Rows = struct { - text_alloc: []u8, - text: []const u8, - rows: [][]const u8, - }; - - const empty_grid = [1][]const u8{""}; - - /// What LEAVING raw tty mode does to one prompt row, decided from its cells - /// alone. See config.tty_blank for why any of this happens. - const PromptCut = union(enum) { - /// show the row exactly as ghostty dumped it - keep, - /// show nothing at all - blank, - /// drop this many leading COLUMNS — the prompt — and keep the rest, which - /// is what was typed at it - cut: usize, - }; - - fn promptCut(pin: ghostty_vt.Pin) PromptCut { - if (config.tty_blank == .prompt_and_input) return .blank; - const cells = pin.cells(.all); - var cols: usize = 0; - while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; - // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or - // a repaint that has moved on. Nothing here is the prompt, so hide nothing. - if (cols == 0) return .keep; - // ...and all prompt, nothing typed yet: the row is chrome end to end. - if (cols >= cells.len) return .blank; - return .{ .cut = cols }; - } - - pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { - if (comptime !enabled) return 0; - if (row < 0) return 0; - const state = pane.terminal orelse return 0; - const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; - if (pin.rowAndCell().row.semantic_prompt == .none) return 0; - return switch (promptCut(pin)) { - .keep => 0, - .blank => raw.len, - .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), - }; - } - - fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { - const cols = switch (promptCut(pin)) { - .keep => return raw, - .blank => return "", - .cut => |n| n, - }; - const cells = pin.cells(.all); - var at: usize = 0; - var col: usize = 0; - while (col < cols and at < raw.len) { - const cell = &cells[col]; - at = @min(raw.len, at + dumpedBytes(pin, cell)); - // the tail cell of a wide glyph spells nothing of its own - col += if (cell.wide == .wide) @as(usize, 2) else 1; - } - return std.mem.trimEnd(u8, raw[at..], " \t"); - } - - fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { - switch (cell.wide) { - .spacer_head, .spacer_tail => return 0, - .narrow, .wide => {}, - } - var n: usize = switch (cell.content_tag) { - .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( - cell.codepoint(), - ) catch 1, - // A cell carrying only a colour still spells one blank in the dump. - else => 1, - }; - if (cell.content_tag == .codepoint_grapheme) { - if (pin.grapheme(cell)) |extra| for (extra) |cp| { - n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; - }; - } - return n; - } - - pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { - if (comptime !enabled) return &empty_grid; - if (pane.terminal == null) return &empty_grid; - const c = &p.shell_rows; - if (!c.stale and c.pane == pane) return c.rows; - if (c.pane != null) { - c.stale = true; - return (try buildRows(p.scratch.allocator(), p, pane)).rows; - } - const built = try buildRows(p.gpa, p, pane); - c.* = .{ - .pane = pane, - .text = built.text, - .rows = built.rows, - .text_alloc = built.text_alloc, - }; - return c.rows; - } - - /// 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 { - const rows = try shellRows(p, pane); - if (pane.ovl == null) return rows; - var last = rows.len; - if (pane.ovl) |overlay| - last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); - var count = last; - if (pane.ovl) |overlay| { - if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) - count = count - @min( - @as(usize, @intCast(overlay.rows)), - last - @as(usize, @intCast(overlay.row)), - ) + @max(1, modal.lineCount(overlay.text)); - } - const lines = try p.scratch.allocator().alloc([]const u8, count); - var n: usize = 0; - var grid_row: usize = 0; - while (grid_row < last) : (grid_row += 1) { - if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { - var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); - while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; - grid_row += @intCast(overlay.rows - 1); - continue; - }; - lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; - n += 1; - } - return lines[0..n]; - } - - /// Flatten `cursorLines` without rebuilding the common cached/no-overlay - /// case. Scratch-owned when a join is required. - pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { - const cache = &p.shell_rows; - if (!cache.stale and cache.pane == pane and - lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; - var total: usize = if (lines.len > 0) lines.len - 1 else 0; - for (lines) |line| total += line.len; - const text = try p.scratch.allocator().alloc(u8, total); - var at: usize = 0; - for (lines, 0..) |line, i| { - if (i > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..line.len], line); - at += line.len; - } - return text; - } - - /// Materialize or extend the terminal edit overlay with one exact allocation. - /// Row slices are scratch-owned/borrowed; only the joined text is installed. - pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { - const want_lo = @max(0, @min(lo, hi)); - const want_hi = @max(want_lo, @max(lo, hi)); - const fresh = pane.ovl == null; - const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; - const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); - const up = old.row - want_lo; - const down = want_hi - (old.row + lines - 1); - const extending = fresh or up > 0 or down > 0; - var row0 = old.row; - var covered = old.rows; - var text = old.text; - var owned = false; - if (extending) { - const rows = shellRows(p, pane) catch return null; - row0 = old.row - @max(0, up); - covered = old.rows + @max(0, up) + @max(0, down); - const up_len: usize = @intCast(@max(0, up)); - const down_len: usize = @intCast(@max(0, down)); - const parts = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; - for (parts[0..up_len], 0..) |*part, i| { - const src = @as(usize, @intCast(row0)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - const middle: usize = @intCast(old.row); - parts[up_len] = if (fresh) - (if (middle < rows.len) rows[middle] else "") - else - old.text; - for (parts[up_len + 1 ..], 0..) |*part, i| { - const src = @as(usize, @intCast(old.row + old.rows)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - text = std.mem.join(p.gpa, "\n", parts) catch return null; - owned = true; - } - - const row: usize = @intCast(@max(0, want_lo - row0)); - const line_len: i32 = @intCast(modal.lineSlice(text, row).len); - if (col > line_len) { - const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { - if (owned) p.gpa.free(text); - return null; - }; - @memset(spaces, ' '); - const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { - if (owned) p.gpa.free(text); - return null; - }; - if (owned) p.gpa.free(text); - text = padded; - owned = true; - } - if (owned) { - if (pane.ovl) |overlay| p.gpa.free(overlay.text); - pane.ovl = .{ .row = row0, .rows = covered, .text = text }; - } - return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; - } - - /// Consume a rewritten overlay, freeing the terminal edit text it replaces. - pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { - const overlay = if (pane.ovl) |*value| value else return p.gpa.free(new); - for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - } - p.gpa.free(overlay.text); - overlay.text = new; - } - - /// The shell's screen and scrollback (the primary screen, even under a - /// full-screen program) as VT that replays to what was shown: styled - /// text, soft-wrapped lines rejoined so they reflow at another width. - fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { - const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; - var out: std.Io.Writer.Allocating = .init(arena); - try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); - return out.written(); - } - - /// Serialize terminal-only state; the core supplies shared pane metadata. - pub fn dumpPane( - pane: *Pane, - arena: std.mem.Allocator, - tag: []const u8, - body: []const u8, - scroll: usize, - ) !dump.Pane { - if (!enabled or pane.terminal == null) { - const text = if (pane.ovl) |overlay| overlay.text else ""; - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .stream = try arena.dupe(u8, text), - .stream_b64 = &.{}, - .cursor = .{ .col = 0, .row = 0 }, - }, - }; - } - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); - const extra = if (pane.ovl) |overlay| overlay.text.len else 0; - const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); - var len: usize = 0; - var lines = std.mem.splitAny(u8, full, "\n"); - var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - var row: i32 = 0; - var skip: i32 = 0; - while (lines.next()) |raw| : (row += 1) { - // Hidden overlay rows still consume prompt pins to keep them aligned. - const prompt = if (pane.mode != .tty) prompts.next() else null; - if (skip > 0) { - skip -= 1; - continue; - } - if (row > 0) { - stream[len] = '\n'; - len += 1; - } - if (pane.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { - @memcpy(stream[len..][0..overlay.text.len], overlay.text); - len += overlay.text.len; - skip = overlay.rows - 1; - continue; - }; - const shown = if (prompt) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - @memcpy(stream[len..][0..shown.len], shown); - len += shown.len; - } - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .stream = stream[0..len], - .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), - .stream_is_screen = true, - .cursor = .{ - .col = pane.terminal.?.vt.screens.active.cursor.x, - .row = pane.terminal.?.vt.screens.active.cursor.y, - }, - }, - }; - } - - fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); - var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - // split yields one more item than delimiters; the extra final slot is the - // cursor row retained below. - const n_rows = std.mem.count(u8, full, "\n") + 2; - const rows = try alloc.alloc([]const u8, n_rows); - errdefer alloc.free(rows); - // Blanking a prompt row only ever SHORTENS it and the retained cursor row - // adds one separator, so the dump's length plus one bounds the join. - const text = try alloc.alloc(u8, full.len + 1); - errdefer alloc.free(text); - var at: usize = 0; - var n: usize = 0; - var it = std.mem.splitScalar(u8, full, '\n'); - while (it.next()) |raw| { - const shown = if (pit.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - if (n > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..shown.len], shown); - rows[n] = text[at..][0..shown.len]; - at += shown.len; - n += 1; - } - text[at] = '\n'; - at += 1; - rows[n] = text[at..][0..0]; - n += 1; - std.debug.assert(n == n_rows); - return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; - } - - pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { - const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { - const state = pane.terminal orelse break :vp &.{}; - const screen = state.vt.screens.active; - var tl = screen.pages.getTopLeft(.viewport); - tl.x = 0; - const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; - var rows_out: std.Io.Writer.Allocating = .init(arena); - try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); - const raw = try rows_out.toOwnedSlice(); - var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); - const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); - var lines = std.mem.splitScalar(u8, raw, '\n'); - var n: usize = 0; - while (lines.next()) |ln| { - vp[n] = if (pane.mode != .tty) - if (prompts.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln - else - ln - else - ln; - n += 1; - } - std.debug.assert(n == vp.len); - break :vp vp; - }; - - const len = fillBody(null, pane, vp); - const out = try arena.alloc(u8, len); - const filled = fillBody(out, pane, vp); - std.debug.assert(filled == out.len); - return out; - } - - pub const BodyRow = union(enum) { - grid: i32, - edit: struct { line: []const u8, idx: usize }, - }; - - const BodyWalk = struct { - pane: *Pane, - goff: i32, - g: i32, - /// the buffer can start above the viewport: drop the lines scrolled past - skip: usize, - n: usize = 0, - lines: ?std.mem.SplitIterator(u8, .scalar) = null, - covered: i32 = 0, - line_idx: usize = 0, - - fn init(pane: *Pane) BodyWalk { - const off = pane.scroll(); - const goff = gridOffset(pane); - return .{ - .pane = pane, - .goff = goff, - .g = if (pane.mode == .tty) goff else pane.gridRow(off), - .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, - }; - } - - fn next(w: *BodyWalk) ?BodyRow { - while (w.n < w.pane.rows) { - if (w.lines) |*it| { - if (it.next()) |line| { - const idx = w.line_idx; - w.line_idx += 1; - // Lines scrolled off the top still count: the index names a - // line of the BUFFER, not of the visible body. - if (w.skip > 0) { - w.skip -= 1; - continue; - } - w.n += 1; - return .{ .edit = .{ .line = line, .idx = idx } }; - } - // The buffer stands in for `rows` shell rows however many lines - // it actually spelled, which is the whole slide. - w.g += w.covered; - w.skip = 0; - w.lines = null; - continue; - } - if (w.pane.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { - w.lines = std.mem.splitScalar(u8, o.text, '\n'); - w.covered = o.rows; - w.line_idx = 0; - continue; - }; - const vi = w.g - w.goff; - w.g += 1; - w.n += 1; - return .{ .grid = vi }; - } - return null; - } - }; - - /// Run the terminal body row walk. A null destination counts bytes; a slice - /// fills the exact allocation made from that count. - fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { - var walk: BodyWalk = .init(pane); - var written: usize = 0; - var first = true; - while (walk.next()) |row| { - if (!first) { - if (dst) |out| out[written] = '\n'; - written += 1; - } - first = false; - const bytes = switch (row) { - .edit => |e| e.line, - .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) - viewport[@intCast(vi)] - else - "", - }; - if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); - written += bytes.len; - } - return written; - } - - // Match surviving edit-buffer rows to their original terminal styles. - const EditAnchors = struct { - /// the buffer's own text, walked in order: a line the VIEWPORT skipped still - /// consumes the row it came from, so the lines below it stay aligned - text: []const u8 = &.{}, - at: usize = 0, - shell: []const []const u8 = &.{}, - /// the covered span, absolute grid rows, as `[first, end)` - first: usize = 0, - end: usize = 0, - lines: usize = 0, - /// the line `at` names, and the first row still unclaimed - idx: usize = 0, - cursor: usize = 0, - budget: usize = 0, - active: bool = false, - - fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { - if (o.rows <= 0 or o.row < 0) return .{}; - const first: usize = @intCast(o.row); - const screen = pane.terminal.?.vt.screens.active; - const total = screen.pages.scrollbar().total; - if (first >= total) return .{}; - const covered: usize = @intCast(o.rows); - const count = @min(covered, total - first); - const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; - const br = screen.pages.pin(.{ .screen = .{ - .x = screen.pages.cols - 1, - .y = @intCast(first + count - 1), - } }) orelse return .{}; - const arena = p.scratch.allocator(); - var output: std.Io.Writer.Allocating = .init(arena); - screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; - const shell = arena.alloc([]const u8, count) catch return .{}; - var raw = std.mem.splitScalar(u8, output.written(), '\n'); - var pins = tl.rowIterator(.right_down, br); - for (shell) |*row| { - const text = raw.next() orelse ""; - row.* = if (pins.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text - else - text; - } - const lines = std.mem.count(u8, o.text, "\n") + 1; - return .{ - .text = o.text, - .shell = shell, - .first = first, - .end = first + count, - .lines = lines, - .cursor = first, - .budget = covered + 4 * lines, - .active = true, - }; - } - - fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { - if (!a.active or idx >= a.lines) return null; - var found: ?Anchor = null; - while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); - return found; - } - - fn nextLine(a: *EditAnchors) ?[]const u8 { - if (a.at > a.text.len) return null; - const rest = a.text[a.at..]; - if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { - a.at += n + 1; - return rest[0..n]; - } - // The last line has no terminator; one past the end ends the walk. - a.at = a.text.len + 1; - return rest; - } - - /// Where this line still stands over the grid, if anywhere. - fn claim(a: *EditAnchors, line: []const u8) ?Anchor { - const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; - var k = a.cursor; - while (k < end) : (k += 1) { - if (a.budget == 0) return null; - a.budget -= 1; - if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; - a.cursor = k + 1; - return .{ .row = @intCast(k) }; - } - if (a.cursor >= a.end) return null; - const shell = a.shell[a.cursor - a.first]; - var p: usize = 0; - while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; - var s: usize = 0; - const room = @min(line.len, shell.len) - p; - while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; - if (p + s == 0) return null; - if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; - const row = a.cursor; - if (s > 0 or p >= shell.len) a.cursor += 1; - return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; - } - }; - - const Anchor = struct { - /// the row, absolute while it comes from `EditAnchors`, viewport once - /// `recolorAnsi` has subtracted the walk's offset - row: i32, - prefix: usize = std.math.maxInt(usize), - suffix: usize = 0, - /// the row's own dumped length — what the suffix is measured from on the - /// GRID side, where the edit may have changed the byte count - shell_len: usize = 0, - - fn whole(an: Anchor) bool { - return an.prefix == std.math.maxInt(usize); - } - }; - - pub fn recolorAnsi(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { - // No emulator, no ANSI cells: the whole pass — and the 256-colour theme - // projection behind it — is compiled out. - if (comptime !enabled) return; - const s = &p.surface; - if (pane.terminal == null) return; - const body_y = p.bodyTop(r); - var filtered_storage: FilteredColors = undefined; - const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { - const tz_filter = tracy.zone(@src(), "filterInit"); - defer tz_filter.end(); - filtered_storage = FilteredColors.init(p, pane); - break :blk &filtered_storage; - } else null; - // DECSCNM, read once: the filtered palette folds it in itself, the raw - // path needs it per cell. - const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); - const pages = &pane.terminal.?.vt.screens.active.pages; - const vp_rows: i32 = @intCast(scrollbar(pane).len); - // Which buffer lines the user has not actually changed, so a row swallowed - // by a growing buffer keeps the colour it still stands over. - var anchors: ?EditAnchors = null; - var walk: BodyWalk = .init(pane); - var lines = std.mem.splitScalar(u8, body, '\n'); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - // Before any early exit below, or the lines fall out of step with rows. - const text = lines.next() orelse ""; - const anchor: Anchor = switch (row) { - .edit => |e| blk: { - if (anchors == null) anchors = .init(p, pane, pane.ovl.?); - var an = anchors.?.shellRow(e.idx) orelse continue; - an.row -= walk.goff; - break :blk an; - }, - .grid => |v| .{ .row = v }, - }; - const vi = anchor.row; - if (vi < 0 or vi >= vp_rows) continue; - const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const cut: u16 = if (pane.mode == .tty) 0 else cut: { - if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; - break :cut switch (promptCut(row_pin)) { - .keep => 0, - // Blanked end to end: the row shows nothing of the grid, so - // projecting the prompt's own colours onto it would be a lie. - .blank => continue, - .cut => |n| std.math.cast(u16, n) orelse continue, - }; - }; - if (cut > 0 and text.len == 0) continue; - var at: usize = 0; - var sc: u16 = 0; - var gc: u16 = cut; - var sb: usize = 0; - const mine_from = @min(anchor.prefix, text.len); - const mine_to = text.len - @min(anchor.suffix, text.len); - var crossed = false; - while (at < text.len and sc < tw) { - const stop = modal.nextGrapheme(text, at); - if (stop <= at) break; - const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; - if (at >= mine_from and at < mine_to) { - sc += span; - at = stop; - continue; - } - if (at >= mine_to and !crossed) { - crossed = true; - const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); - while (sb < upto) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - sb += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - } - } - const want = stop - at; - // Consume every cell that contributed to this grapheme. A cluster - // ghostty split across several cells is still ONE printed glyph. - var covered: usize = 0; - var style: ?pardes.CellStyle = null; - while (covered < want) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) - style = cellStyle(p, ci, filtered, scnm); - covered += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - // A spacer contributes no bytes; without this the loop would - // spin on a row that ends in one. - if (covered == 0 and gc >= pane.cols) break; - } - while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| { - if (t.cell.wide != .spacer_tail) break; - gc = std.math.add(u16, gc, 1) catch break; - } - if (style) |st| for (0..span) |k| { - const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = st; - }; - sb += covered; - sc += span; - at = stop; - } - var tail: ?pardes.CellStyle = null; - if (anchor.whole() or anchor.suffix > 0) { - while (sc < tw) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - gc = std.math.add(u16, gc, 1) catch break; - if (ci.cell.wide == .spacer_tail) continue; - const cell = s.at(tx + sc, body_y + vr); - sc += 1; - const style = cellStyle(p, ci, filtered, scnm); - tail = style; - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - } - if (tail) |style| while (sc < tw) : (sc += 1) { - const cell = s.at(tx + sc, body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - }; - } - } - } - - fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { - const style = ci.style(); - var cs: pardes.CellStyle = .{ - .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), - .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), - .bold = style.flags.bold, - .dim = style.flags.faint, - .italic = style.flags.italic, - .blink = style.flags.blink, - .reverse = style.flags.inverse, - .invisible = style.flags.invisible, - .strikethrough = style.flags.strikethrough, - .ul = switch (style.flags.underline) { - .none => .off, - .single => .single, - .double => .double, - .curly => .curly, - .dotted => .dotted, - .dashed => .dashed, - }, - }; - if (filtered == null) switch (ci.cell.content_tag) { - .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), - .bg_color_rgb => { - const rgb = ci.cell.content.color_rgb; - cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; - }, - else => {}, - }; - return cs; - } - - const FilteredColors = struct { - source: GColor.Palette, - target: *const GColor.Palette, - theme_bg: GColor.RGB, - theme_fg: GColor.RGB, - dynamic_bg: ?GColor.RGB, - dynamic_fg: ?GColor.RGB, - default_bg: GColor.RGB, - /// What a foreground too near `default_bg` becomes instead. - fallback_fg: GColor.RGB, - default_bg_luminance: f64, - fg_for_palette: [256]pardes.Color = undefined, - bg_for_palette: [256]pardes.Color = undefined, - /// The two answers for a cell that names no colour of its own. - fg_default: pardes.Color = undefined, - bg_default: pardes.Color = undefined, - cache_rgb: [256]GColor.RGB = undefined, - cache_key: [256]u8 = undefined, - cache_valid: [256]bool = @splat(false), - - fn init(p: *Pardes, pane: *const Pane) FilteredColors { - var source = GColor.default; - for (&source, 0..) |*rgb, i| - rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; - const theme = p.theme(); - var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); - var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); - var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); - if (pane.terminal.?.vt.modes.get(.reverse_colors)) { - std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); - std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); - } - var self: FilteredColors = .{ - .source = source, - .target = p.tty_filter_palette.get(theme), - .theme_bg = theme_bg, - .theme_fg = theme_fg, - .dynamic_bg = dynamic_bg, - .dynamic_fg = dynamic_fg, - .default_bg = theme_bg, - .fallback_fg = theme_fg, - .default_bg_luminance = luminanceOf(theme_bg), - }; - if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); - self.default_bg_luminance = luminanceOf(self.default_bg); - if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) - self.fallback_fg = self.theme_bg; - - self.fg_default = asPardesColor(self.legible( - if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, - )); - self.bg_default = asPardesColor(self.default_bg); - for (&self.source, 0..) |current, i| { - const idx: u8 = @intCast(i); - const mapped = self.paletteRgb(idx, current); - self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); - self.bg_for_palette[idx] = asPardesColor(mapped); - } - return self; - } - - fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { - return switch (style.fg_color) { - .none => self.fg_default, - .palette => |idx| self.fg_for_palette[idx], - .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ - .default = self.dynamic_fg orelse self.theme_fg, - .palette = &self.source, - .bold = null, - })))), - }; - } - - fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { - switch (cell.content_tag) { - .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], - .bg_color_rgb => {}, - else => switch (style.bg_color) { - .none => return self.bg_default, - .palette => |idx| return self.bg_for_palette[idx], - .rgb => {}, - }, - } - // Truecolour, from either the cell or its style. - return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); - } - - fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { - if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= - config.tty_filter_min_contrast) return rgb; - return self.fallback_fg; - } - - fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { - if (current.eql(GColor.default[idx])) return self.target[idx]; - return self.keyedRgb(current); - } - - fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { - return self.target[self.nearestKey(rgb)]; - } - - fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { - const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; - const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); - if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) - return self.cache_key[slot]; - - var best: u8 = 0; - var best_distance: u32 = std.math.maxInt(u32); - for (GColor.default, 0..) |candidate, i| { - const distance = colorDistance(rgb, candidate); - // Strict comparison makes duplicate-colour ties stable at the - // lowest canonical xterm key. - if (distance < best_distance) { - best_distance = distance; - best = @intCast(i); - } - } - self.cache_rgb[slot] = rgb; - self.cache_key[slot] = best; - self.cache_valid[slot] = true; - return best; - } - }; - - const channel_luminance: [256]f64 = blk: { - @setEvalBranchQuota(20000); - var table: [256]f64 = undefined; - for (&table, 0..) |*slot, c| { - const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; - slot.* = if (normalized <= 0.03928) - normalized / 12.92 - else - std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); - } - break :blk table; - }; - - fn luminanceOf(rgb: GColor.RGB) f64 { - return 0.2126 * channel_luminance[rgb.r] + - 0.7152 * channel_luminance[rgb.g] + - 0.0722 * channel_luminance[rgb.b]; - } - - /// ghostty's `RGB.contrast` with both luminances already in hand. - fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { - const lighter = @max(a_luminance, b_luminance); - const darker = @min(a_luminance, b_luminance); - return (lighter + 0.05) / (darker + 0.05); - } - - fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { - const dr = @as(i32, a.r) - @as(i32, b.r); - const dg = @as(i32, a.g) - @as(i32, b.g); - const db = @as(i32, a.b) - @as(i32, b.b); - 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)), - ); - } - } - } - - 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].?; - try testing.expect(pane.tty_filter); - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ - "\x1b[38;5;196mB" ++ - "\x1b[38;2;255;0;0mC" ++ - "\x1b[0;48;5;25mD" ++ - "\x1b[0;48;2;0;95;175mE" ++ - "\x1b[0;1;2;3;4;5;7;8;9mF" ++ - "\x1b[0;48;5;25m\x1b[K" ++ - "\r\n\x1b[0;38;5;2m界" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; - - const raw = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); - - pane.tty_filter = true; - _ = frame.reset(.retain_capacity); - const filtered = try p.render(frame.allocator()); - var expected_cache: FilterPalette = .{}; - const expected = expected_cache.get(p.theme()); - try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); - try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); - try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); - - const attrs = filtered.at(tx + 5, body_y).style; - try testing.expect(attrs.bold); - try testing.expect(attrs.dim); - try testing.expect(attrs.italic); - try testing.expect(attrs.blink); - try testing.expect(attrs.reverse); - try testing.expect(attrs.invisible); - try testing.expect(attrs.strikethrough); - try testing.expectEqual(.single, attrs.ul); - - const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; - try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); - try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); - try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); - // A filtered terminal never delegates either colour to a backend palette, - // including cells which were empty/default before the pass. - for (0..r.w - config.GUTTER) |col| { - const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); - try testing.expect(!cell.default); - switch (cell.style.fg) { - .rgb => {}, - else => return error.FilteredForegroundWasNotRgb, - } - switch (cell.style.bg) { - .rgb => {}, - else => return error.FilteredBackgroundWasNotRgb, - } - } - - // Colors remains the global master gate. The pane remembers Filter while - // ANSI projection is dormant, and resumes it without replaying VT bytes. - p.settings.colors = false; - _ = frame.reset(.retain_capacity); - const plain = try p.render(frame.allocator()); - try testing.expect(pane.tty_filter); - try testing.expectEqual(asPardesColor(asGhostRgb(p.theme().fg.?)), plain.at(tx, body_y).style.fg); - p.settings.colors = true; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); - const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; - try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); - pane.tty_filter = false; - pane.tty_filter = true; - try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); - _ = frame.reset(.retain_capacity); - const osc_palette = try p.render(frame.allocator()); - try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); - - // Dynamic default foreground/background colours key every default cell, - // including the otherwise blank end of the row. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ - "\x1b]11;#5f5f5f\x1b\\" } }); - const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; - const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; - try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); - try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); - _ = frame.reset(.retain_capacity); - const dynamic = try p.render(frame.allocator()); - const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), blank.bg); - - const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; - try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); - const reversed_explicit = reversed.at(tx, body_y).style; - try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); - try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); - try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); - _ = frame.reset(.retain_capacity); - const unreversed = try p.render(frame.allocator()); - const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); - - // The cache is keyed by values, not a theme name. Replacing a custom - // theme in place immediately recolours already-rendered indexed cells. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); - var custom = p.theme().*; - custom.name = try p.gpa.dupe(u8, "same-name"); - custom.palette = null; - custom.kw = .{ 1, 2, 3 }; - p.custom_theme = custom; - _ = frame.reset(.retain_capacity); - const custom_first = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); - if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; - _ = frame.reset(.retain_capacity); - const custom_second = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); - } - - test "terminal Filter keeps extended keys dark-to-light on a light theme" { - const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); - defer p.deinit(); - try std.testing.expectEqualStrings("acme", p.theme().name); - var cache: FilterPalette = .{}; - const palette = cache.get(p.theme()); - try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); - try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); - } - - test "terminal Filter preserves exact palette-null light theme default roles" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - var light = p.theme().*; - light.name = try p.gpa.dupe(u8, "filter-light-defaults"); - light.bg = .{ 0xf8, 0xf8, 0xf8 }; - light.fg = .{ 0x38, 0x38, 0x38 }; - light.palette = null; - p.custom_theme = light; - - const pane = p.panes[0].?; - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); - pane.tty_filter = true; - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; - const ordinary = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); - } - - test "terminal Filter maps the default roles before it maps anything else" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - // Native dark/light palettes plus legacy helix/dark/acme, including - // the null-page fallback that only the legacy dark theme exercises. - for (0..9) |t| { - p.settings.theme = @intCast(t); - const stage_one = FilteredColors.init(p, pane); - // `dark` declares no background of its own, which is exactly why the - // resolver reads the tag colours as the fallback rather than `.?`. - const theme = p.theme(); - try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); - try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); - // With no OSC 11 in play the mapped page IS that anchor, and the - // fallback is the other one: a background never contrasts with itself. - try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); - try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); - } - - p.settings.theme = 0; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, pane); - try testing.expect(!moved.default_bg.eql(moved.theme_bg)); - try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); - } - - test "terminal Filter refuses a foreground that would collapse onto the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ - "\x1b[0;30mB" ++ - "\x1b[0;31mR" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); - const page = asPardesColor(fc.default_bg); - const rescued = asPardesColor(fc.fallback_fg); - _ = frame.reset(.retain_capacity); - const g = try p.render(frame.allocator()); - - // The colour each of the three would have been given with no floor. - const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); - const raw_black = fc.paletteRgb(0, GColor.default[0]); - const raw_red = fc.paletteRgb(1, GColor.default[1]); - - for ([_]struct { at: u16, raw: GColor.RGB }{ - .{ .at = 0, .raw = raw_white }, - .{ .at = 1, .raw = raw_black }, - .{ .at = 2, .raw = raw_red }, - }) |case| { - const cell = g.at(tx + case.at, body_y).style; - try testing.expectEqual(page, cell.bg); - if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { - // Refused: the projection's answer is not painted, the anchor is. - try testing.expectEqual(rescued, cell.fg); - try testing.expect(!std.meta.eql(cell.fg, cell.bg)); - } else { - // Cleared the floor, so stage two leaves it exactly alone. - try testing.expectEqual(asPardesColor(case.raw), cell.fg); - } - // Either way a filtered cell delegates neither colour to a backend. - switch (cell.fg) { - .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= - config.tty_filter_min_contrast), - else => return error.FilteredForegroundWasNotRgb, - } - } - - // At least one of the three has to have been a real collapse, or this - // theme proved nothing: white on the light theme, black on the dark. - try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or - raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); - // A saturated red is never the page on any curated theme. - try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - } - } - - test "terminal Filter holds every projected foreground off the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); - var refused: usize = 0; - for (fc.target, 0..) |projected, key| { - const ink = fc.legible(projected); - try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - if (!ink.eql(projected)) { - refused += 1; - try testing.expect(ink.eql(fc.fallback_fg)); - // Only ever refused for being too near the page. - try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); - } - // The key a background asks for is handed back untouched, including - // the one whose value is the page itself. - try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); - } - // Every curated theme owns at least one collapsing key — that is why - // the floor exists — and the floor must not be flattening the palette. - try testing.expect(refused > 0); - try testing.expect(refused < fc.target.len / 8); - } - } - - test "tty ansi colors follow the prompt hug into normal mode" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; - const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; - const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; - - // tty mode projects the emulator's ansi colours cell for cell. - pane.mode = .tty; - p.shell_rows.stale = true; - const tty = try p.render(frame.allocator()); - try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); - try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); - - pane.mode = .normal; - p.shell_rows.stale = true; - _ = frame.reset(.retain_capacity); - const norm = try p.render(frame.allocator()); - try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); - try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); - try testing.expectEqual(red, norm.at(tx, body_y).style.fg); - try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); - } - - test "a prompt row hidden end to end paints nothing at all" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tty_filter = false; - pane.mode = .normal; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; - p.shell_rows.stale = true; - const s = try p.render(frame.allocator()); - - try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); - 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 }; - } - - pub 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. - if (comptime !enabled) return; - 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"); - } - - /// the snapshot takes ownership of a COPY of the edit buffer's text - pub fn snap(p: *Pardes, pane: *Pane) ?Snapshot { - var ovl: ?EditBuffer = null; - if (pane.ovl) |o| ovl = .{ .row = o.row, .rows = o.rows, .text = p.gpa.dupe(u8, o.text) catch return null }; - return .{ .ovl = ovl, .cur_row = pane.cur_row, .cur_col = pane.cur_col, .vsel = pane.vsel }; - } - - /// undo/redo restores the selection recorded with the snapshot (helix - /// keeps selections in its history transactions) - pub fn restoreSnap(p: *Pardes, pane: *Pane, s: Snapshot) void { - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = s.ovl; - pane.cur_row = s.cur_row; - pane.cur_col = s.cur_col; - pane.cur_pinned = true; - pane.vsel = s.vsel; - pane.msel.active = false; - pane.ensureCursorVisible(); - } - - fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, value: Snapshot) void { - if (len.* == slots.len) { - if (slots[0].ovl) |overlay| gpa.free(overlay.text); - std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); - len.* -= 1; - } - slots[len.*] = value; - len.* += 1; - } - - pub fn pushUndo(p: *Pardes, pane: *Pane) void { - const current = pane.ovl orelse EditBuffer{ .rows = 0 }; - if (pane.ed_undo_len > 0) { - const top = pane.ed_undo[pane.ed_undo_len - 1]; - const same = if (top.ovl) |overlay| pane.ovl != null and overlay.row == current.row and - overlay.rows == current.rows and std.mem.eql(u8, overlay.text, current.text) else pane.ovl == null; - if (same) return; - } - const value = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.ed_undo, &pane.ed_undo_len, value); - for (pane.ed_redo[0..pane.ed_redo_len]) |item| if (item.ovl) |overlay| p.gpa.free(overlay.text); - pane.ed_redo_len = 0; - } - - pub fn undo(p: *Pardes, pane: *Pane) void { - if (pane.ed_undo_len == 0) return; - const current = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.ed_redo, &pane.ed_redo_len, current); - pane.ed_undo_len -= 1; - restoreSnap(p, pane, pane.ed_undo[pane.ed_undo_len]); - } - - pub fn redo(p: *Pardes, pane: *Pane) void { - if (pane.ed_redo_len == 0) return; - const current = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.ed_undo, &pane.ed_undo_len, current); - pane.ed_redo_len -= 1; - restoreSnap(p, pane, pane.ed_redo[pane.ed_redo_len]); - } - - pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { - const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); - const room = state.reply.len - state.reply_len; - const n = @min(room, data.len); - @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); - state.reply_len += @intCast(n); - } - - const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( - @FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"), - ).optional.child).pointer.child).@"fn".return_type.?; - pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs { - return .{}; - } -}; +pub const Terminal = @import("Terminal.zig"); test { _ = Pane; -- cgit v1.3 From 0ce8269c251eaba188883c38dd3e97be9fb362cc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:30:25 -0300 Subject: Move the Pdf namespace out of panes.zig into pdf_view.zig Pure move: the body of `pub const Pdf = struct { ... }` is now the file pdf_view.zig, dedented, with the imports it uses; panes.zig keeps `pub const Pdf = @import("pdf_view.zig");`, so `panes.Pdf.x` callers are unchanged. The file is not Pdf.zig because pdf.zig (the MuPDF module) sits beside it and the two names are one file on a case-insensitive disk. pdf_view.zig joins the embedded source list. Co-Authored-By: Claude Opus 5.5 --- src/fs.zig | 1 + src/panes.zig | 2790 +---------------------------------------------------- src/pdf_view.zig | 2802 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 2804 insertions(+), 2789 deletions(-) create mode 100644 src/pdf_view.zig (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index fed15344..3dccdf7f 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -41,6 +41,7 @@ const source_files = [_]Source{ .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, .{ .path = "src/Terminal.zig", .contents = @embedFile("Terminal.zig") }, + .{ .path = "src/pdf_view.zig", .contents = @embedFile("pdf_view.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, .{ .path = "src/look.zig", .contents = @embedFile("look.zig") }, diff --git a/src/panes.zig b/src/panes.zig index 0f203e6f..9bf2d92f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -1128,2795 +1128,7 @@ pub const Mini = @import("Mini.zig"); pub const Image = @import("image.zig"); -pub const Pdf = struct { - pub const enabled = @import("pardes_config").mupdf; - pub const pdf = if (enabled) @import("mupdf") else struct { - pub const PageSize = struct { width: f32, height: f32 }; - pub const Raster = struct { - width: usize = 0, - height: usize = 0, - stride: usize = 0, - len: usize = 0, - pub const Band = struct { y: usize = 0, height: usize = 0, len: usize = 0 }; - pub fn wholePage(_: @This()) Band { - return .{}; - } - pub fn band(_: @This(), _: usize, _: usize) Band { - return .{}; - } - }; - }; - pub const Point = if (enabled) pdf.Point else void; - pub const Quad = if (enabled) pdf.Quad else void; - pub const Document = if (enabled) pdf.Document else opaque {}; - pub const OutlineInternalDestination = if (enabled) pdf.OutlineInternalDestination else void; - const raster_max = 256; - const raster_spare = 4; - pub const page_gap_px: u32 = 8; - const band_grain: usize = 64; - - pub const FitMode = if (enabled) enum { width, height } else void; - pub const TintMode = if (enabled) pdf.TintMode else void; - pub const TintColors = if (enabled) pdf.TintColors else void; - pub const RenderRequest = if (enabled) pdf.RenderRequest else void; - - /// Dump records must remain recognizable as PDFs even in a build without - /// MuPDF, where Look deliberately treats them as ordinary files. - pub fn isPath(path: []const u8) bool { - return std.ascii.endsWithIgnoreCase(path, ".pdf"); - } - - pub const RasterPolicy = struct { - dpi: u16, - max_dimension: u16, - match_viewport: bool, - }; - - pub fn legacySavedPrefix(path: []const u8, saved_tag: []const u8) ?[]const u8 { - if (std.mem.startsWith(u8, saved_tag, path) and std.mem.startsWith(u8, saved_tag[path.len..], " [")) { - const start = path.len + 2; - const end = std.mem.indexOfScalarPos(u8, saved_tag, start, ']') orelse return null; - var parts = std.mem.splitScalar(u8, saved_tag[start..end], '/'); - _ = std.fmt.parseInt(usize, parts.next() orelse return null, 10) catch return null; - _ = std.fmt.parseInt(usize, parts.next() orelse return null, 10) catch return null; - if (parts.next() != null) return null; - return saved_tag[0 .. end + 1]; - } - if (!std.mem.startsWith(u8, saved_tag, "pdf ")) return null; - const marker = " PdfSections "; - const marker_at = std.mem.indexOf(u8, saved_tag, marker) orelse return null; - const path_at = marker_at + marker.len; - if (!std.mem.startsWith(u8, saved_tag[path_at..], path)) return null; - return saved_tag[0 .. path_at + path.len]; - } - - pub const TintKey = if (enabled) struct { - mode: TintMode, - colors: pdf.TintColors, - - pub fn eql(a: @This(), b: @This()) bool { - return a.mode == b.mode and - (a.mode == .disabled or std.meta.eql(a.colors, b.colors)); - } - } else void; - - pub const Highlight = if (enabled) pdf.Highlight else void; - pub const Highlights = if (enabled) struct { - const Page = struct { page: usize, items: []const Highlight }; - pages: [3]Page = undefined, - len: usize = 0, - /// Repaint whenever the set changes, not only when a page's raster was - /// invalidated (`HighlightInput.live`). - live: bool = false, - - pub fn forPage(highlights: @This(), page: usize) []const Highlight { - for (highlights.pages[0..highlights.len]) |group| - if (group.page == page) return group.items; - return &.{}; - } - } else void; - - pub const HighlightInput = if (enabled) struct { - hover_quads: []const Quad = &.{}, - hover_page: ?usize = null, - hover_color: [3]u8, - selection_color: [3]u8, - live: bool = false, - } else void; - - pub fn buildHighlights( - state: *const State, - arena: std.mem.Allocator, - input: HighlightInput, - ) !Highlights { - if (comptime !enabled) return; - const search_len = if (state.search_results) |results| results.quads.len else 0; - const selection_len = if (state.selection) |selection| selection.quads.len else 0; - const items = try arena.alloc(Highlight, input.hover_quads.len + search_len + selection_len); - var result: Highlights = .{ .live = input.live }; - var n: usize = 0; - // Hover, search and selection can belong to three different pages. - // Group them once so raster rendering can borrow a contiguous slice. - for ([_]?usize{ input.hover_page, state.page, state.selection_page }) |candidate| { - const page = candidate orelse continue; - var seen = false; - for (result.pages[0..result.len]) |group| { - if (group.page == page) seen = true; - } - if (seen) continue; - const start = n; - if (input.hover_page == page) for (input.hover_quads) |quad| { - items[n] = pdf.Highlight.init(quad, .{ - input.hover_color[0], input.hover_color[1], input.hover_color[2], 0x2c, - }, .custom); - n += 1; - }; - if (state.page == page) if (state.search_results) |results| { - for (results.quads) |item| { - items[n] = pdf.Highlight.init(item.quad, .{ 0xff, 0xd5, 0x4f, 0x70 }, .search); - n += 1; - } - }; - if (state.selection_page == page) if (state.selection) |selection| { - for (selection.quads) |quad| { - items[n] = pdf.Highlight.init(quad, .{ - input.selection_color[0], input.selection_color[1], input.selection_color[2], 0x78, - }, .selection); - n += 1; - } - }; - result.pages[result.len] = .{ .page = page, .items = items[start..n] }; - result.len += 1; - } - return result; - } - - test "PDF selections retain their owning page across page focus" { - if (comptime !enabled) return; - const gpa = std.testing.allocator; - var state = try State.open(gpa, "docs/design.pdf", 1); - defer state.deinit(gpa); - try std.testing.expect(state.page_count > 1); - var found = try state.document.search(gpa, 0, "Pardes"); - defer found.deinit(gpa); - const quad = found.quads[0].quad; - const point: Point = .{ - .x = (quad.ul.x + quad.ur.x + quad.ll.x + quad.lr.x) / 4, - .y = (quad.ul.y + quad.ur.y + quad.ll.y + quad.lr.y) / 4, - }; - try std.testing.expectEqual(.changed, state.setSelection(gpa, point, point, true)); - const selected = try gpa.dupe(u8, state.selection_text); - defer gpa.free(selected); - try std.testing.expect(selected.len > 0); - try std.testing.expect(state.focusLocation(gpa, 2, 0)); - try std.testing.expectEqual(@as(?usize, 0), state.selection_page); - try std.testing.expectEqualStrings(selected, state.selection_text); - var arena = std.heap.ArenaAllocator.init(gpa); - defer arena.deinit(); - const highlights = try buildHighlights(&state, arena.allocator(), .{ - .hover_quads = &.{quad}, - .hover_page = 1, - .hover_color = .{ 1, 2, 3 }, - .selection_color = .{ 4, 5, 6 }, - }); - try std.testing.expectEqual(state.selection.?.quads.len, highlights.forPage(0).len); - try std.testing.expectEqual(@as(usize, 1), highlights.forPage(1).len); - try std.testing.expectEqual(@as(usize, 0), highlights.forPage(2).len); - try std.testing.expect(state.focusLocation(gpa, 1, 0)); - try std.testing.expectEqualStrings(selected, state.selection_text); - try std.testing.expectEqual(.unchanged, state.setSelection(gpa, point, point, true)); - try std.testing.expect(state.focusLocation(gpa, 2, 0)); - state.rasters[0] = .{ .valid = true, .page = 0, .tried = true, .decorated = true }; - state.rasters_len = 1; - try std.testing.expectEqual(.changed, state.setSelection(gpa, point, point, false)); - try std.testing.expectEqual(@as(?usize, 1), state.selection_page); - try std.testing.expect(!state.rasters[0].tried); - state.clearSelection(gpa); - try std.testing.expect(state.selection_page == null); - try std.testing.expectEqual(@as(usize, 0), state.selection_text.len); - } - - pub const Raster = if (enabled) struct { - valid: bool = false, - page: usize = 0, - rgba: []u8 = &.{}, - /// Full page shape; rgba contains only the band below. - iw: usize = 0, - ih: usize = 0, - band_y: usize = 0, - band_h: usize = 0, - request: pdf.RenderRequest = .{}, - request_valid: bool = false, - tried: bool = false, - decorated: bool = false, - tint_key: ?TintKey = null, - revision: u32 = 0, - /// `rgba` before its highlights and tint, kept once the page has been - /// highlighted: a highlight change repaints rows from it instead of - /// rendering the page again. - clean: []u8 = &.{}, - /// The highlights baked into `rgba` (gpa-owned), so a change repaints - /// only the rows of the quads that differ. - baked: []Highlight = &.{}, - /// `baked` is a true record (false after a render could not copy it). - baked_valid: bool = false, - /// Page rows changed since revision `patch_from`, the one last handed - /// to a shell; 0 when the pixels were replaced wholesale since. - patch_from: u32 = 0, - patch_rows: pdf.Document.Rows = .{ .start = 0, .end = 0 }, - } else void; - - pub const SectionsOutput = if (enabled) struct { - pane: usize, - serial: u32, - revision: u32, - } else void; - - pub const SelectionUpdate = enum { failed, stationary, unchanged, changed }; - - pub const State = if (enabled) struct { - path: []u8, - document: Document, - page: usize = 0, - page_count: usize, - page_sizes: []pdf.PageSize, - page_starts: []u64, - page_heights: []u32, - document_height: u64 = 0, - layout_viewport_w: u32 = 0, - layout_viewport_h: u32 = 0, - layout_fit: FitMode = .width, - layout_valid: bool = false, - document_scroll_y: f64 = 0, - scroll_to_page_pending: bool = true, - rasters: [raster_max]Raster = undefined, - rasters_len: usize = 0, - spare: [raster_spare][]u8 = @splat(&.{}), - spare_len: usize = 0, - layout_anchor_pending: bool = false, - layout_anchor_page: usize = 0, - layout_anchor_fraction: f64 = 0, - next_raster_revision: u32 = 0, - scroll_travel: f64 = 0, - fit: FitMode = .width, - tint: TintMode = .filtered, - pan_x: u16 = 0, - pan_y: u16 = 0, - highlights_dirty: bool = false, - search_reveal_pending: bool = false, - search_results: ?pdf.SearchResults = null, - selection: ?pdf.Selection = null, - selection_page: ?usize = null, - selection_text: []u8 = &.{}, - selection_anchor: ?Point = null, - selection_head: ?Point = null, - drag_anchor: ?Point = null, - drag_head: ?Point = null, - text: []u8 = &.{}, - text_tried: bool = false, - text_scroll: usize = 0, - text_scroll_clamp_pending: bool = false, - search_query: []u8 = &.{}, - search_hit: usize = 0, - reveal_viewport_w: u32 = 0, - reveal_viewport_h: u32 = 0, - reveal_fit: FitMode = .width, - reveal_viewport_valid: bool = false, - outline: ?pdf.Outline = null, - outline_tried: bool = false, - sections_output: ?SectionsOutput = null, - outline_reveal_pending: ?pdf.OutlineInternalDestination = null, - - /// Read whole and opened from memory (the bridge copies), never from - /// the file itself: MuPDF reads a file lazily at every page, and the - /// path may be a mount this editor serves, which only a read that - /// gives the turn up can come back from (`filesystem.readFile`). - pub fn open(gpa: std.mem.Allocator, path: []const u8, page_one_based: usize) !@This() { - const local = filesystem.localPath(path) orelse return error.NonLocalPath; - const bytes = try filesystem.readFile(gpa, local); - defer gpa.free(bytes); - return initDocument(gpa, path, try Document.openBytes(bytes), page_one_based); - } - - pub fn openBytes(gpa: std.mem.Allocator, path: []const u8, bytes: []const u8, page_one_based: usize) !@This() { - return initDocument(gpa, path, try Document.openBytes(bytes), page_one_based); - } - - fn initDocument(gpa: std.mem.Allocator, path: []const u8, opened: Document, page_one_based: usize) !@This() { - var document = opened; - errdefer document.deinit(); - const page_sizes = try gpa.alloc(pdf.PageSize, document.pages); - errdefer gpa.free(page_sizes); - for (page_sizes, 0..) |*size, page| size.* = try document.pageSize(page); - const page_starts = try gpa.alloc(u64, document.pages); - errdefer gpa.free(page_starts); - const page_heights = try gpa.alloc(u32, document.pages); - errdefer gpa.free(page_heights); - const owned_path = try gpa.dupe(u8, path); - errdefer gpa.free(owned_path); - return .{ - .path = owned_path, - .document = document, - .page = if (page_one_based > 0) - @min(page_one_based - 1, document.pages - 1) - else - 0, - .page_count = document.pages, - .page_sizes = page_sizes, - .page_starts = page_starts, - .page_heights = page_heights, - }; - } - - pub fn reload(state: *@This(), gpa: std.mem.Allocator) !void { - const preserve_anchor = !state.scroll_to_page_pending and - (state.layout_anchor_pending or - (state.layout_valid and state.page_count > 0 and state.document_height > 0)); - var anchor_page: usize = state.layout_anchor_page; - var anchor_fraction: f64 = state.layout_anchor_fraction; - if (preserve_anchor and !state.layout_anchor_pending) { - anchor_page = pageAtOffset(state, state.document_scroll_y); - const start: f64 = @floatFromInt(state.page_starts[anchor_page]); - const height: f64 = @floatFromInt(@max(@as(u32, 1), state.page_heights[anchor_page])); - anchor_fraction = std.math.clamp( - (state.document_scroll_y - start) / height, - 0, - 1, - ); - } - - var fresh = try @This().open(gpa, state.path, state.page + 1); - errdefer fresh.deinit(gpa); - if (state.search_query.len > 0) - fresh.search_query = try gpa.dupe(u8, state.search_query); - - fresh.fit = state.fit; - fresh.tint = state.tint; - fresh.pan_x = state.pan_x; - fresh.pan_y = state.pan_y; - fresh.text_scroll = state.text_scroll; - fresh.text_scroll_clamp_pending = true; - fresh.search_hit = state.search_hit; - fresh.highlights_dirty = fresh.search_query.len > 0; - fresh.search_reveal_pending = state.search_reveal_pending; - fresh.reveal_viewport_w = state.reveal_viewport_w; - fresh.reveal_viewport_h = state.reveal_viewport_h; - fresh.reveal_fit = state.reveal_fit; - fresh.reveal_viewport_valid = state.reveal_viewport_valid; - // Revisions are part of the backend texture key. Resetting this counter - // while the pane serial stays live can alias a cached pre-reload page. - fresh.next_raster_revision = state.next_raster_revision; - fresh.sections_output = state.sections_output; - if (preserve_anchor) { - fresh.scroll_to_page_pending = false; - fresh.layout_anchor_pending = true; - fresh.layout_anchor_page = anchor_page; - fresh.layout_anchor_fraction = anchor_fraction; - } - - var old = state.*; - state.* = fresh; - old.deinit(gpa); - } - - pub fn invalidateRaster(state: *@This(), page: usize) void { - if (rasterForPage(state, page)) |raster| raster.tried = false; - } - - pub fn invalidateAllRasters(state: *@This()) void { - for (state.rasters[0..state.rasters_len]) |*raster| { - if (raster.valid) raster.tried = false; - } - } - - fn retireRgba(state: *@This(), gpa: std.mem.Allocator, rgba: []u8) void { - if (rgba.len == 0) return; - if (state.spare_len == state.spare.len) return gpa.free(rgba); - state.spare[state.spare_len] = rgba; - state.spare_len += 1; - } - - fn retireRaster(state: *@This(), gpa: std.mem.Allocator, raster: *Raster) void { - if (raster.clean.len > 0) gpa.free(raster.clean); - gpa.free(raster.baked); - state.retireRgba(gpa, raster.rgba); - raster.* = .{}; - } - - fn claimRgba(state: *@This(), gpa: std.mem.Allocator, bytes: usize) ?[]u8 { - for (state.spare[0..state.spare_len], 0..) |candidate, index| { - if (candidate.len != bytes) continue; - state.spare_len -= 1; - state.spare[index] = state.spare[state.spare_len]; - return candidate; - } - return gpa.alloc(u8, bytes) catch null; - } - - fn trimSpares(state: *@This(), gpa: std.mem.Allocator) void { - while (state.spare_len > 1) { - state.spare_len -= 1; - gpa.free(state.spare[state.spare_len]); - } - } - - fn dropSearchResults(state: *@This(), gpa: std.mem.Allocator) void { - if (state.search_results) |*results| results.deinit(gpa); - state.search_results = null; - } - - fn dropSelection(state: *@This(), gpa: std.mem.Allocator) void { - if (state.selection) |*selection| selection.deinit(gpa); - state.selection = null; - state.selection_page = null; - if (state.selection_text.len > 0) gpa.free(state.selection_text); - state.selection_text = &.{}; - state.selection_anchor = null; - state.selection_head = null; - } - - pub fn setSelection( - state: *@This(), - gpa: std.mem.Allocator, - start: Point, - end: Point, - invalidate_raster: bool, - ) SelectionUpdate { - if (state.selection != null and state.selection_page == state.page and - state.selection_anchor != null and state.selection_head != null and - state.selection_anchor.?.x == start.x and state.selection_anchor.?.y == start.y and - state.selection_head.?.x == end.x and state.selection_head.?.y == end.y) return .unchanged; - var selection = state.document.select(gpa, state.page, start, end) catch return .failed; - const text = state.document.copySelection( - gpa, - state.page, - selection.start, - selection.end, - ) catch { - selection.deinit(gpa); - return .failed; - }; - - const old_page = state.selection_page; - state.dropSelection(gpa); - state.selection = selection; - state.selection_page = state.page; - state.selection_text = text; - state.selection_anchor = start; - state.selection_head = end; - if (old_page) |page| if (page != state.page) state.invalidateRaster(page); - if (invalidate_raster) state.invalidateRaster(state.page); - return .changed; - } - - pub fn clearDrag(state: *@This()) void { - state.drag_anchor = null; - state.drag_head = null; - } - - pub fn clearSelection(state: *@This(), gpa: std.mem.Allocator) void { - const page = state.selection_page; - state.dropSelection(gpa); - if (page) |selected_page| state.invalidateRaster(selected_page); - } - - pub fn cancelChrome(state: *@This(), gpa: std.mem.Allocator) void { - state.clearDrag(); - state.clearSelection(gpa); - if (state.search_query.len == 0) return; - state.dropSearchQuery(gpa); - state.invalidateRaster(state.page); - } - - fn invalidatePage(state: *@This(), gpa: std.mem.Allocator) void { - state.dropSearchResults(gpa); - state.clearDrag(); - if (state.text.len > 0) gpa.free(state.text); - state.text = &.{}; - state.text_tried = false; - state.text_scroll = 0; - state.text_scroll_clamp_pending = false; - state.highlights_dirty = state.search_query.len > 0; - state.search_reveal_pending = state.search_query.len > 0; - state.search_hit = 0; - } - - fn dropSearchQuery(state: *@This(), gpa: std.mem.Allocator) void { - if (state.search_query.len > 0) gpa.free(state.search_query); - state.search_query = &.{}; - state.search_hit = 0; - state.dropSearchResults(gpa); - state.highlights_dirty = false; - state.search_reveal_pending = false; - } - - pub fn setSearchQuery(state: *@This(), gpa: std.mem.Allocator, query: []const u8) !void { - if (std.mem.eql(u8, state.search_query, query)) return; - const owned = try gpa.dupe(u8, query); - state.dropSearchQuery(gpa); - state.search_query = owned; - state.highlights_dirty = query.len > 0; - state.search_reveal_pending = query.len > 0; - state.invalidateRaster(state.page); - } - - pub fn ensureText(state: *@This(), gpa: std.mem.Allocator) []const u8 { - if (!state.text_tried) { - state.text_tried = true; - state.text = state.document.pageText(gpa, state.page) catch &.{}; - } - if (state.text_scroll_clamp_pending) { - const lines = std.mem.count(u8, state.text, "\n") + 1; - state.text_scroll = @min(state.text_scroll, lines - 1); - state.text_scroll_clamp_pending = false; - } - return state.text; - } - - pub fn resolveSearch(state: *@This(), gpa: std.mem.Allocator) void { - if (!state.highlights_dirty) return; - state.highlights_dirty = false; - state.dropSearchResults(gpa); - if (state.search_query.len == 0) return; - const results = state.document.search(gpa, state.page, state.search_query) catch return; - state.search_hit = if (results.hit_count == 0) - 0 - else - @min(state.search_hit, results.hit_count - 1); - state.search_results = results; - } - - pub fn ensureOutline(state: *@This(), gpa: std.mem.Allocator) ?*const pdf.Outline { - if (!state.outline_tried) { - state.outline_tried = true; - state.outline = state.document.outline(gpa) catch null; - } - return if (state.outline) |*outline| outline else null; - } - - pub fn renderSections( - state: *@This(), - pdf_gpa: std.mem.Allocator, - output_gpa: std.mem.Allocator, - ) ![]u8 { - const entries: []const pdf.OutlineEntry = if (state.ensureOutline(pdf_gpa)) |outline| - outline.entries - else - &.{}; - return SectionRows.render(output_gpa, state.path, entries); - } - - pub fn sectionDestination( - state: *@This(), - gpa: std.mem.Allocator, - ordinal: usize, - ) ?pdf.OutlineDestination { - const outline = state.ensureOutline(gpa) orelse return null; - return SectionRows.resolve(outline.entries, ordinal); - } - - /// Apply the one-based page/hit location encoded in a PDF search row. - /// Returns whether host pane cursor chrome must be reset. - pub fn focusLocation( - state: *@This(), - gpa: std.mem.Allocator, - line: usize, - column: usize, - ) bool { - const changed = line > 0 and state.activatePage(gpa, line - 1, true); - if (column > 0 and state.search_query.len > 0) { - state.search_hit = column - 1; - state.search_reveal_pending = true; - } - return changed; - } - - /// Change the document page while leaving pane cursor/selection chrome to - /// the UI adapter. Returns whether that pane-local chrome must be reset. - pub fn activatePage( - state: *@This(), - gpa: std.mem.Allocator, - page: usize, - reveal: bool, - ) bool { - state.outline_reveal_pending = null; - const next = @min(page, state.page_count -| 1); - const changed = next != state.page; - if (changed) { - state.invalidatePage(gpa); - state.page = next; - } - if (reveal) { - state.scroll_to_page_pending = true; - if (state.layout_valid) { - state.document_scroll_y = @floatFromInt(state.page_starts[next]); - state.scroll_to_page_pending = false; - } - } else { - state.search_reveal_pending = false; - } - return changed; - } - - pub fn toggleFit(state: *@This()) void { - state.fit = if (state.fit == .width) .height else .width; - state.pan_x = 0; - state.pan_y = 0; - state.layout_valid = false; - state.scroll_to_page_pending = true; - state.search_reveal_pending = state.search_query.len > 0; - } - - pub fn toggleTint(state: *@This()) void { - state.tint = state.tint.next(); - state.invalidateAllRasters(); - } - - pub fn queueOutlineReveal( - state: *@This(), - destination: pdf.OutlineInternalDestination, - ) void { - state.scroll_to_page_pending = false; - state.layout_anchor_pending = false; - state.outline_reveal_pending = destination; - } - - pub fn deinit(state: *@This(), gpa: std.mem.Allocator) void { - gpa.free(state.path); - for (state.rasters[0..state.rasters_len]) |raster| { - if (raster.rgba.len > 0) gpa.free(raster.rgba); - if (raster.clean.len > 0) gpa.free(raster.clean); - gpa.free(raster.baked); - } - for (state.spare[0..state.spare_len]) |rgba| gpa.free(rgba); - gpa.free(state.page_sizes); - gpa.free(state.page_starts); - gpa.free(state.page_heights); - if (state.text.len > 0) gpa.free(state.text); - if (state.search_query.len > 0) gpa.free(state.search_query); - if (state.search_results) |*results| results.deinit(gpa); - if (state.selection) |*selection| selection.deinit(gpa); - if (state.selection_text.len > 0) gpa.free(state.selection_text); - if (state.outline) |*outline| outline.deinit(gpa); - state.document.deinit(); - state.* = undefined; - } - } else void; - - pub const SearchOutput = struct { - bytes: usize = 0, - rows: usize = 0, - anchor: ?usize = null, - }; - - pub fn textLines( - state: *State, - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - ) ![]const []const u8 { - if (comptime !enabled) return &.{}; - const page_text = state.ensureText(gpa); - const lines = try arena.alloc([]const u8, std.mem.count(u8, page_text, "\n") + 1); - var it = std.mem.splitScalar(u8, page_text, '\n'); - var n: usize = 0; - while (it.next()) |line| : (n += 1) lines[n] = line; - return lines; - } - - pub fn visibleText( - state: *State, - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - max_rows: usize, - ) ![]const u8 { - if (comptime !enabled) return ""; - const page_text = state.ensureText(gpa); - var start: usize = 0; - for (0..state.text_scroll) |_| { - const newline = std.mem.indexOfScalarPos(u8, page_text, start, '\n') orelse - return arena.dupe(u8, ""); - start = newline + 1; - } - if (max_rows == 0) return arena.dupe(u8, ""); - - var end = start; - var row: usize = 0; - while (row < max_rows) : (row += 1) { - const newline = std.mem.indexOfScalarPos(u8, page_text, end, '\n') orelse { - end = page_text.len; - break; - }; - if (row + 1 == max_rows) { - end = newline; - break; - } - end = newline + 1; - } - return arena.dupe(u8, page_text[start..end]); - } - - /// Materialize exact MuPDF logical hits as `path:PAGE:HIT query` rows. The - /// same hit numbering drives persistent highlights and later reveal actions. - pub fn searchRows( - state: *State, - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - pattern: []const u8, - from_cursor: bool, - out: []u8, - ) !SearchOutput { - if (comptime !enabled) return .{}; - try state.setSearchQuery(gpa, pattern); - const shown = std.fs.path.basename(state.path); - var result: SearchOutput = .{}; - const max_hits = 512; - var snippet_len = @min(pattern.len, 200); - while (snippet_len > 0 and snippet_len < pattern.len and pattern[snippet_len] & 0xc0 == 0x80) - snippet_len -= 1; - const snippet = pattern[0..snippet_len]; - for (0..state.page_count) |page| { - if (result.rows >= max_hits) break; - var found = try state.document.search(gpa, page, pattern); - defer found.deinit(gpa); - - const cursor_hit: ?usize = if (from_cursor and page == state.page and state.selection_page == page) cursor: { - const selection = state.selection orelse break :cursor null; - for (found.quads) |item| { - const q = item.quad; - const center: Point = .{ - .x = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4, - .y = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4, - }; - if (selection.contains(center)) break :cursor item.hit; - } - break :cursor null; - } else null; - - for (0..found.hit_count) |hit_index| { - if (result.rows >= max_hits) break; - const line = try std.fmt.allocPrint(arena, "{s}:{d}:{d} {s}\n", .{ - shown, page + 1, hit_index + 1, snippet, - }); - if (line.len > out.len - result.bytes) return result; - if (from_cursor and - (page < state.page or - (page == state.page and cursor_hit != null and hit_index <= cursor_hit.?))) - result.anchor = result.rows; - @memcpy(out[result.bytes..][0..line.len], line); - result.bytes += line.len; - result.rows += 1; - } - } - return result; - } - - pub const Viewport = struct { pixel_w: u32, pixel_h: u32 }; - pub const VisiblePages = struct { first: usize = 0, len: usize = 0 }; - pub const PanAxis = enum { horizontal, vertical }; - pub const PanResult = enum { moved, edge, unavailable }; - pub const ScrollResult = struct { active_page: usize }; - pub const CellPixels = struct { w: u16, h: u16 }; - pub const NormalHost = enum { - none, - leader, - command_line, - search, - search_forward, - search_backward, - }; - pub const NormalResult = struct { - host: NormalHost = .none, - page_changed: bool = false, - }; - - const PlacedGeometry = struct { - geometry: image.NativeGeometry, - pixel_offset_y: f32, - }; - - pub const PlacedRaster = if (enabled) struct { - page: usize, - revision: u32, - fit: FitMode, - pan_x: u16, - geometry: image.NativeGeometry, - pixel_offset_y: f32, - rgba: []const u8, - width: usize, - band_height: usize, - } else void; - - const VisibleRows = struct { - base: image.NativeGeometry, - y0: u32, - y1: u32, - dst_y: u32, - dst_h: u32, - pixel_offset_y: f32, - }; - - pub fn renderRequest(viewport: Viewport, policy: RasterPolicy) RenderRequest { - if (comptime !enabled) return; - return .{ - .dpi = policy.dpi, - .minimum_width = if (policy.match_viewport) viewport.pixel_w else 0, - .minimum_height = if (policy.match_viewport) viewport.pixel_h else 0, - .max_dimension = policy.max_dimension, - }; - } - - fn pageHeight(size: pdf.PageSize, viewport: Viewport, fit: FitMode) u32 { - if (comptime !enabled) return 0; - if (fit == .height) return viewport.pixel_h; - const scaled = @as(f64, @floatFromInt(viewport.pixel_w)) * - @as(f64, size.height) / @as(f64, size.width); - return @max(1, @as(u32, @intFromFloat(@min( - @as(f64, @floatFromInt(std.math.maxInt(u32))), - @round(scaled), - )))); - } - - fn pageAtOffset(state: *const State, offset: f64) usize { - if (comptime !enabled) return 0; - const y: u64 = @intFromFloat(std.math.clamp( - @floor(offset), - 0, - @as(f64, @floatFromInt(state.document_height -| 1)), - )); - var lo: usize = 0; - var hi: usize = state.page_count; - while (lo + 1 < hi) { - const mid = lo + (hi - lo) / 2; - if (state.page_starts[mid] <= y) lo = mid else hi = mid; - } - const end = state.page_starts[lo] + state.page_heights[lo]; - return if (y >= end and lo + 1 < state.page_count) lo + 1 else lo; - } - - fn pageVisible(state: *const State, page: usize, viewport: Viewport) bool { - if (comptime !enabled) return false; - const top = @as(f64, @floatFromInt(state.page_starts[page])) - state.document_scroll_y; - const bottom = top + @as(f64, @floatFromInt(state.page_heights[page])); - return bottom > 0 and top < @as(f64, @floatFromInt(viewport.pixel_h)); - } - - pub fn visiblePages(state: *const State, viewport: Viewport) VisiblePages { - if (comptime !enabled) return .{}; - var out: VisiblePages = .{}; - var page = pageAtOffset(state, state.document_scroll_y); - if (page > 0 and pageVisible(state, page - 1, viewport)) page -= 1; - out.first = page; - while (page < state.page_count) : (page += 1) { - const top = @as(f64, @floatFromInt(state.page_starts[page])) - state.document_scroll_y; - if (top >= @as(f64, @floatFromInt(viewport.pixel_h))) break; - if (pageVisible(state, page, viewport)) out.len += 1; - } - return out; - } - - fn visibleContains(visible: VisiblePages, page: usize) bool { - return page >= visible.first and page - visible.first < visible.len; - } - - pub fn rasterForPage(state: *State, page: usize) ?*Raster { - if (comptime !enabled) return null; - for (state.rasters[0..state.rasters_len]) |*raster| - if (raster.valid and raster.page == page) return raster; - return null; - } - - fn rasterForPageConst(state: *const State, page: usize) ?*const Raster { - if (comptime !enabled) return null; - for (state.rasters[0..state.rasters_len]) |*raster| - if (raster.valid and raster.page == page) return raster; - return null; - } - - fn visibleRows( - state: *const State, - viewport: Viewport, - page: usize, - iw: usize, - ih: usize, - ) ?VisibleRows { - if (comptime !enabled) return null; - const page_h = state.page_heights[page]; - const base = image.nativeGeometry( - iw, - ih, - viewport.pixel_w, - page_h, - switch (state.fit) { - .width => .width, - .height => .height, - }, - state.pan_x, - 0, - ) orelse return null; - if (base.dst.h == 0 or base.src.h == 0) return null; - - const scroll_floor = @floor(state.document_scroll_y); - const fractional: f32 = @floatCast(state.document_scroll_y - scroll_floor); - const scroll_i: i64 = @intFromFloat(@min( - scroll_floor, - @as(f64, @floatFromInt(std.math.maxInt(i64))), - )); - const start_i: i64 = @intCast(@min( - state.page_starts[page], - @as(u64, std.math.maxInt(i64)), - )); - const full_y = start_i - scroll_i + @as(i64, base.dst.y); - const full_bottom = full_y + @as(i64, base.dst.h); - const visible_y = @max(@as(i64, 0), full_y); - const visible_bottom = @min(@as(i64, viewport.pixel_h), full_bottom); - if (visible_bottom <= visible_y) return null; - - const rel_y0: u64 = @intCast(visible_y - full_y); - const rel_y1: u64 = @intCast(visible_bottom - full_y); - const src_y0: u32 = base.src.y + @as(u32, @intCast( - rel_y0 * base.src.h / base.dst.h, - )); - const src_y1: u32 = base.src.y + @as(u32, @intCast(@min( - @as(u64, base.src.h), - (rel_y1 * base.src.h + base.dst.h - 1) / base.dst.h, - ))); - if (src_y1 <= src_y0) return null; - return .{ - .base = base, - .y0 = src_y0, - .y1 = src_y1, - .dst_y = @intCast(visible_y), - .dst_h = @intCast(visible_bottom - visible_y), - .pixel_offset_y = -fractional, - }; - } - - fn placedGeometry( - state: *const State, - raster: *const Raster, - viewport: Viewport, - page: usize, - ) ?PlacedGeometry { - if (comptime !enabled) return null; - const rows = visibleRows(state, viewport, page, raster.iw, raster.ih) orelse return null; - const band_y: u32 = @intCast(raster.band_y); - const band_end: u32 = @intCast(raster.band_y + raster.band_h); - if (rows.y0 < band_y or rows.y1 > band_end) return null; - return .{ - .geometry = .{ - .src = .{ - .x = rows.base.src.x, - .y = rows.y0 - band_y, - .w = rows.base.src.w, - .h = rows.y1 - rows.y0, - }, - .dst = .{ - .x = rows.base.dst.x, - .y = rows.dst_y, - .w = rows.base.dst.w, - .h = rows.dst_h, - }, - }, - .pixel_offset_y = rows.pixel_offset_y, - }; - } - - pub fn placedRaster(state: *const State, viewport: Viewport, page: usize) ?PlacedRaster { - if (comptime !enabled) return null; - const raster = rasterForPageConst(state, page) orelse return null; - if (raster.rgba.len == 0) return null; - const placed = placedGeometry(state, raster, viewport, page) orelse return null; - return .{ - .page = page, - .revision = raster.revision, - .fit = state.fit, - .pan_x = state.pan_x, - .geometry = placed.geometry, - .pixel_offset_y = placed.pixel_offset_y, - .rgba = raster.rgba, - .width = raster.iw, - .band_height = raster.band_h, - }; - } - - pub fn activeGeometry(state: *const State, viewport: Viewport) ?image.NativeGeometry { - if (comptime !enabled) return null; - const raster = rasterForPageConst(state, state.page) orelse return null; - const placed = placedGeometry(state, raster, viewport, state.page) orelse return null; - return placed.geometry; - } - - pub fn pageAtViewportY(state: *const State, local_y: f64) ?usize { - if (comptime !enabled) return null; - if (!state.layout_valid or !std.math.isFinite(local_y) or local_y < 0) return null; - const document_y = state.document_scroll_y + local_y; - const page = pageAtOffset(state, document_y); - const start: f64 = @floatFromInt(state.page_starts[page]); - if (document_y < start or - document_y >= start + @as(f64, @floatFromInt(state.page_heights[page]))) return null; - return page; - } - - pub fn pageReady(state: *const State, viewport: Viewport, page: usize) bool { - if (comptime !enabled) return false; - return placedRaster(state, viewport, page) != null; - } - - pub fn nativeReady(state: *const State, viewport: Viewport) bool { - if (comptime !enabled) return false; - for (state.rasters[0..state.rasters_len]) |*raster| { - if (raster.valid and raster.rgba.len > 0 and - placedGeometry(state, raster, viewport, raster.page) != null) return true; - } - return false; - } - - pub fn pointAtPage( - state: *const State, - viewport: Viewport, - page: usize, - px: i64, - py: i64, - clamp_to_page: bool, - ) ?Point { - if (comptime !enabled) return null; - const raster = rasterForPageConst(state, page) orelse return null; - if (raster.rgba.len == 0) return null; - const placed = placedGeometry(state, raster, viewport, page) orelse return null; - return pointAtGeometry( - placed.geometry, - placed.pixel_offset_y, - raster.iw, - raster.ih, - raster.band_y, - px, - py, - clamp_to_page, - ); - } - - fn slotShape(slot: *const Raster) pdf.Raster { - const stride = slot.iw * 4; - return .{ .width = slot.iw, .height = slot.ih, .stride = stride, .len = stride * slot.ih }; - } - - fn flinging(state: *const State, viewport: Viewport) bool { - if (comptime !enabled) return false; - return state.scroll_travel >= @as(f64, @floatFromInt(viewport.pixel_h)); - } - - fn wantedBand( - state: *const State, - viewport: Viewport, - page: usize, - shape: pdf.Raster, - is_flinging: bool, - ) pdf.Raster.Band { - if (!is_flinging) return shape.wholePage(); - const rows = visibleRows(state, viewport, page, shape.width, shape.height) orelse - return shape.wholePage(); - const first = (@as(usize, rows.y0) / band_grain) * band_grain; - const last = std.math.divCeil(usize, @as(usize, rows.y1), band_grain) catch - return shape.wholePage(); - return shape.band(first, last * band_grain - first); - } - - fn reconcile( - state: *State, - gpa: std.mem.Allocator, - request: RenderRequest, - tint_key: TintKey, - highlights: Highlights, - visible: VisiblePages, - viewport: Viewport, - ) void { - if (comptime !enabled) return; - const tz = tracy.zone(@src(), "pdf.reconcile"); - defer tz.end(); - - // Remove first so arriving pages can claim departing page buffers. Only - // the final visible set can be seen, so a fling skips crossed-over pages. - var index: usize = 0; - while (index < state.rasters_len) { - if (visibleContains(visible, state.rasters[index].page)) { - index += 1; - continue; - } - state.retireRaster(gpa, &state.rasters[index]); - state.rasters_len -= 1; - if (index != state.rasters_len) - state.rasters[index] = state.rasters[state.rasters_len]; - } - - const is_flinging = flinging(state, viewport); - var page = visible.first; - const end = visible.first + visible.len; - while (page < end) : (page += 1) { - var raster = rasterForPage(state, page); - if (raster == null) { - if (state.rasters_len == state.rasters.len) continue; - state.rasters[state.rasters_len] = .{ .valid = true, .page = page }; - state.rasters_len += 1; - raster = &state.rasters[state.rasters_len - 1]; - } - const slot = raster.?; - const page_highlights = highlights.forPage(page); - const decorated = page_highlights.len > 0; - const base_stale = !slot.request_valid or !slot.request.eql(request) or - slot.tint_key == null or !slot.tint_key.?.eql(tint_key) or - slot.rgba.len == 0 or slot.band_h == 0; - const uncovered = !base_stale and uncovered: { - const want = wantedBand(state, viewport, page, slotShape(slot), is_flinging); - break :uncovered slot.band_y > want.y or - slot.band_y + slot.band_h < want.y + want.height; - }; - if (!base_stale and !uncovered) { - if (slot.tried and slot.decorated == decorated and - !(highlights.live and !sameHighlights(slot.baked, page_highlights))) continue; - // Invalidated, but it already shows exactly these highlights - // (a preview withdrawn that was never drawn, on every pointer - // move over a page): nothing to render. - if (slot.baked_valid and sameHighlights(slot.baked, page_highlights)) { - slot.tried = true; - continue; - } - // Only the highlights moved: repaint their rows in place. - if (repaintHighlights(state, gpa, slot, request, tint_key, page_highlights)) continue; - } - - slot.tried = true; - slot.request = request; - slot.request_valid = true; - const shape_or_null = shape: { - const tz_measure = tracy.zone(@src(), "pdf.measure"); - defer tz_measure.end(); - break :shape state.document.measureRenderAt(page, request) catch null; - }; - const shape = shape_or_null orelse continue; - const want = wantedBand(state, viewport, page, shape, is_flinging); - const fresh = state.claimRgba(gpa, want.len) orelse continue; - const filled = filled: { - { - const tz_render = tracy.zone(@src(), "pdf.render_into"); - defer tz_render.end(); - // A highlighted page keeps its clean rows for repaints. - const keep_clean = pardes.platform != .macos and (decorated or slot.clean.len > 0); - state.document.renderIntoAtWithPaper( - page, - request, - shape, - want, - if (keep_clean) &.{} else page_highlights, - fresh, - pardes.platform == .macos, - ) catch break :filled false; - if (slot.clean.len != 0 and (!keep_clean or slot.clean.len != fresh.len)) { - gpa.free(slot.clean); - slot.clean = &.{}; - } - if (keep_clean) { - if (slot.clean.len == 0) slot.clean = gpa.alloc(u8, fresh.len) catch &.{}; - if (slot.clean.len == fresh.len) @memcpy(slot.clean, fresh); - state.document.paintHighlightsAt(page, request, shape, want, page_highlights, fresh) catch - break :filled false; - } - } - const tz_tint = tracy.zone(@src(), "pdf.tint"); - defer tz_tint.end(); - pdf.tintRgba(fresh, tint_key.mode, tint_key.colors) catch - break :filled false; - break :filled true; - }; - if (!filled) { - state.retireRgba(gpa, fresh); - // `clean` may already hold the band that failed. - if (slot.clean.len > 0) gpa.free(slot.clean); - slot.clean = &.{}; - continue; - } - - state.retireRgba(gpa, slot.rgba); - slot.rgba = fresh; - slot.iw = shape.width; - slot.ih = shape.height; - slot.band_y = want.y; - slot.band_h = want.height; - slot.decorated = decorated; - slot.tint_key = tint_key; - if (gpa.dupe(Highlight, page_highlights)) |copy| { - gpa.free(slot.baked); - slot.baked = copy; - slot.baked_valid = true; - } else |_| { - // Unrecorded highlights cannot be compared or diffed. - slot.baked_valid = false; - if (slot.clean.len > 0) gpa.free(slot.clean); - slot.clean = &.{}; - } - slot.patch_from = 0; - slot.patch_rows = .{ .start = 0, .end = 0 }; - state.next_raster_revision +%= 1; - if (state.next_raster_revision == 0) state.next_raster_revision = 1; - slot.revision = state.next_raster_revision; - } - state.trimSpares(gpa); - } - - /// Repaint only the rows where the old and new highlights differ: the - /// clean rows kept from the page's last render, MuPDF's highlight pass - /// (the whole new set) over them, the per-pixel tint — the operations a - /// full render performs, in its order, on fewer rows and without running - /// the page again. False leaves the slot for the full path. - fn repaintHighlights( - state: *State, - gpa: std.mem.Allocator, - slot: *Raster, - request: RenderRequest, - tint_key: TintKey, - page_highlights: []const Highlight, - ) bool { - const tz = tracy.zone(@src(), "pdf.repaint_highlights"); - defer tz.end(); - if (slot.clean.len != slot.rgba.len or !slot.baked_valid) return false; - if (sameHighlights(slot.baked, page_highlights)) { - slot.tried = true; - return true; - } - const baked = gpa.dupe(Highlight, page_highlights) catch return false; - const changed = changedHighlights(gpa, slot.baked, page_highlights) catch { - gpa.free(baked); - return false; - }; - defer gpa.free(changed); - var dirty = state.document.highlightRows(slot.page, request, changed) catch { - gpa.free(baked); - return false; - }; - slot.tried = true; - dirty.start = @max(dirty.start, slot.band_y); - dirty.end = @min(dirty.end, slot.band_y + slot.band_h); - if (dirty.start < dirty.end) { - const shape = slotShape(slot); - const band = shape.band(dirty.start, dirty.end - dirty.start); - const offset = (dirty.start - slot.band_y) * shape.stride; - const out = slot.rgba[offset..][0..band.len]; - @memcpy(out, slot.clean[offset..][0..band.len]); - // On failure the rows are half-made: let the full path redo them. - state.document.paintHighlightsAt(slot.page, request, shape, band, page_highlights, out) catch { - gpa.free(baked); - slot.tried = false; - return false; - }; - pdf.tintRgba(out, tint_key.mode, tint_key.colors) catch { - gpa.free(baked); - slot.tried = false; - return false; - }; - slot.patch_rows = unionRows(slot.patch_rows, dirty); - state.next_raster_revision +%= 1; - if (state.next_raster_revision == 0) state.next_raster_revision = 1; - slot.revision = state.next_raster_revision; - } - gpa.free(slot.baked); - slot.baked = baked; - slot.decorated = page_highlights.len > 0; - return true; - } - - fn sameHighlights(a: []const Highlight, b: []const Highlight) bool { - return std.mem.eql(u8, std.mem.sliceAsBytes(a), std.mem.sliceAsBytes(b)); - } - - /// The highlights in one set and not the other, as multisets (a quad - /// painted twice blends twice). When only the order changed, blending - /// order did, so everything counts. - // ponytail: quadratic match; past 64k comparisons every quad counts. - fn changedHighlights(gpa: std.mem.Allocator, old: []const Highlight, new: []const Highlight) ![]Highlight { - const out = try gpa.alloc(Highlight, old.len + new.len); - errdefer gpa.free(out); - var n: usize = 0; - if (old.len * new.len <= 1 << 16) { - const matched = try gpa.alloc(bool, new.len); - defer gpa.free(matched); - @memset(matched, false); - for (old) |h| { - for (new, matched) |candidate, *used| { - if (!used.* and std.mem.eql(u8, std.mem.asBytes(&h), std.mem.asBytes(&candidate))) { - used.* = true; - break; - } - } else { - out[n] = h; - n += 1; - } - } - for (new, matched) |h, used| if (!used) { - out[n] = h; - n += 1; - }; - } - if (n == 0) { - @memcpy(out[0..old.len], old); - @memcpy(out[old.len..], new); - return out; - } - // Freed by length: hand back exactly what the caller will free. - return gpa.realloc(out, n); - } - - fn unionRows(a: pdf.Document.Rows, b: pdf.Document.Rows) pdf.Document.Rows { - if (a.start >= a.end) return b; - if (b.start >= b.end) return a; - return .{ .start = @min(a.start, b.start), .end = @max(a.end, b.end) }; - } - - pub fn renderFrame( - state: *State, - gpa: std.mem.Allocator, - arena: std.mem.Allocator, - viewport: Viewport, - policy: RasterPolicy, - tint_key: TintKey, - highlight_input: HighlightInput, - ) VisiblePages { - if (comptime !enabled) return .{}; - ensureLayout(state, viewport); - state.resolveSearch(gpa); - const highlights = buildHighlights(state, arena, highlight_input) catch Highlights{}; - const request = renderRequest(viewport, policy); - var visible = visiblePages(state, viewport); - reconcile(state, gpa, request, tint_key, highlights, visible, viewport); - - rearmSearchReveal(state, viewport); - revealSearch(state, viewport, activeGeometry(state, viewport)); - visible = visiblePages(state, viewport); - reconcile(state, gpa, request, tint_key, highlights, visible, viewport); - return visible; - } - - pub fn normalizedPixel(value: f32, dimension: usize) u32 { - const scaled = std.math.clamp(value, 0, 1) * @as(f32, @floatFromInt(dimension)); - return @intCast(@min(dimension - 1, @as(usize, @intFromFloat(scaled)))); - } - - pub fn scaledStep(base: u32, count: u32) u32 { - return @intCast(@min( - @as(u64, std.math.maxInt(u32)), - @as(u64, base) * @max(@as(u64, 1), count), - )); - } - - pub fn scrollDocument(state: *State, viewport: Viewport, delta_pixels: f64) ?ScrollResult { - if (comptime !enabled) return null; - if (!std.math.isFinite(delta_pixels) or delta_pixels == 0) return null; - const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h)); - const next = std.math.clamp(state.document_scroll_y + delta_pixels, 0, max_scroll); - if (next == state.document_scroll_y) return null; - state.scroll_travel += @abs(next - state.document_scroll_y); - state.document_scroll_y = next; - return .{ .active_page = pageAtOffset(state, next) }; - } - - pub fn panPixels( - state: *State, - geometry: image.NativeGeometry, - axis: PanAxis, - direction: i8, - display_pixels: u32, - ) PanResult { - if (comptime !enabled) return .unavailable; - const raster = rasterForPage(state, state.page) orelse return .unavailable; - const source_full: u32 = @intCast(switch (axis) { - .horizontal => raster.iw, - .vertical => raster.ih, - }); - const crop = switch (axis) { - .horizontal => geometry.src.w, - .vertical => geometry.src.h, - }; - const source_at = switch (axis) { - .horizontal => geometry.src.x, - .vertical => geometry.src.y, - }; - const displayed = @max(@as(u32, 1), switch (axis) { - .horizontal => geometry.dst.w, - .vertical => geometry.dst.h, - }); - const overflow = source_full -| crop; - if (overflow == 0 or - (direction < 0 and source_at == 0) or - (direction > 0 and source_at >= overflow)) return .edge; - - const source_step = @max( - @as(u64, 1), - (@as(u64, display_pixels) * @as(u64, crop) + displayed - 1) / displayed, - ); - const normalized_step: u32 = @intCast(@min( - @as(u64, std.math.maxInt(u16)), - @max( - @as(u64, 1), - (source_step * std.math.maxInt(u16) + overflow - 1) / overflow, - ), - )); - const position = switch (axis) { - .horizontal => &state.pan_x, - .vertical => &state.pan_y, - }; - if (direction > 0) { - position.* = @intCast(@min( - @as(u32, std.math.maxInt(u16)), - @as(u32, position.*) + normalized_step, - )); - } else { - position.* -|= @intCast(normalized_step); - } - return .moved; - } - - fn setHorizontalEdge(state: *State, geometry: image.NativeGeometry, end: bool) void { - if (comptime !enabled) return; - const raster = rasterForPage(state, state.page) orelse return; - if (raster.iw <= geometry.src.w) return; - state.pan_x = if (end) std.math.maxInt(u16) else 0; - } - - fn rearmSearchReveal(state: *State, viewport: Viewport) void { - if (comptime !enabled) return; - if (state.search_query.len == 0) return; - if (!state.reveal_viewport_valid or - state.reveal_viewport_w != viewport.pixel_w or - state.reveal_viewport_h != viewport.pixel_h or - state.reveal_fit != state.fit) - state.search_reveal_pending = true; - } - - pub fn revealSearch( - state: *State, - viewport: Viewport, - geometry: ?image.NativeGeometry, - ) void { - if (comptime !enabled) return; - if (!state.search_reveal_pending) return; - state.reveal_viewport_w = viewport.pixel_w; - state.reveal_viewport_h = viewport.pixel_h; - state.reveal_fit = state.fit; - state.reveal_viewport_valid = true; - const results = state.search_results orelse { - state.search_reveal_pending = false; - return; - }; - if (results.hit_count == 0 or results.quads.len == 0) { - state.search_reveal_pending = false; - return; - } - state.search_hit = @min(state.search_hit, results.hit_count - 1); - const q = for (results.quads) |item| { - if (item.hit == state.search_hit) break item.quad; - } else { - state.search_reveal_pending = false; - return; - }; - state.search_reveal_pending = false; - const center_x = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4; - const center_y = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4; - if (state.fit == .width) { - ensureLayout(state, viewport); - const page_y = @as(f64, @floatFromInt(state.page_starts[state.page])) + - @as(f64, center_y) * @as(f64, @floatFromInt(state.page_heights[state.page])); - const wanted = page_y - @as(f64, @floatFromInt(viewport.pixel_h)) / 2; - const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h)); - state.document_scroll_y = std.math.clamp(wanted, 0, max_scroll); - return; - } - const placed = geometry orelse return; - const raster = rasterForPage(state, state.page) orelse return; - const full: u32 = @intCast(raster.iw); - const at = normalizedPixel(center_x, raster.iw); - if (at >= placed.src.x and at < placed.src.x + placed.src.w) return; - const overflow = full -| placed.src.w; - if (overflow == 0) return; - const wanted = @min(overflow, at -| placed.src.w / 2); - state.pan_x = @intCast( - (@as(u64, wanted) * std.math.maxInt(u16) + overflow / 2) / overflow, - ); - } - - pub fn stepPage(state: *State, gpa: std.mem.Allocator, delta: i64) bool { - const current: i64 = @intCast(state.page); - const last: i64 = @intCast(state.page_count -| 1); - return state.activatePage( - gpa, - @intCast(std.math.clamp(current + delta, 0, last)), - true, - ); - } - - fn scrollNormal( - state: *State, - gpa: std.mem.Allocator, - viewport: ?Viewport, - delta_pixels: f64, - ) bool { - const view = viewport orelse return false; - ensureLayout(state, view); - const result = scrollDocument(state, view, delta_pixels) orelse return false; - return result.active_page != state.page and - state.activatePage(gpa, result.active_page, false); - } - - fn moveRows( - state: *State, - gpa: std.mem.Allocator, - native_images: bool, - viewport: ?Viewport, - cell_pixels: CellPixels, - direction: i8, - count: u32, - ) bool { - if (!native_images) { - const pages: i64 = @intCast(@max(@as(u32, 1), count)); - return stepPage(state, gpa, if (direction > 0) pages else -pages); - } - return scrollNormal( - state, - gpa, - viewport, - @as(f64, @floatFromInt(scaledStep(cell_pixels.h, count))) * direction, - ); - } - - fn movePage( - state: *State, - gpa: std.mem.Allocator, - native_images: bool, - viewport: ?Viewport, - cell_pixels: CellPixels, - direction: i8, - kind: modal.Normal.Page, - count: u32, - ) bool { - if (!native_images) { - const pages: i64 = @intCast(@max(@as(u32, 1), count)); - return stepPage(state, gpa, if (direction > 0) pages else -pages); - } - const base: u32 = switch (kind) { - .half_down, .half_up => if (viewport) |view| - @max(@as(u32, 1), view.pixel_h / 2) - else - cell_pixels.h, - .down, .up => if (viewport) |view| view.pixel_h else cell_pixels.h, - }; - return scrollNormal( - state, - gpa, - viewport, - @as(f64, @floatFromInt(scaledStep(base, count))) * direction, - ); - } - - pub fn applyNormal( - state: *State, - gpa: std.mem.Allocator, - semantic: modal.Normal.Action, - native_images: bool, - cell_pixels: CellPixels, - viewport: ?Viewport, - geometry: ?image.NativeGeometry, - ) NormalResult { - if (comptime !enabled) return .{}; - var result: NormalResult = .{}; - switch (semantic) { - .escape => state.cancelChrome(gpa), - .move => |move| switch (move.motion) { - .down => result.page_changed = moveRows( - state, - gpa, - native_images, - viewport, - cell_pixels, - 1, - move.count, - ), - .up => result.page_changed = moveRows( - state, - gpa, - native_images, - viewport, - cell_pixels, - -1, - move.count, - ), - .left => if (native_images) if (geometry) |placed| { - _ = panPixels(state, placed, .horizontal, -1, scaledStep(cell_pixels.w, move.count)); - }, - .right => if (native_images) if (geometry) |placed| { - _ = panPixels(state, placed, .horizontal, 1, scaledStep(cell_pixels.w, move.count)); - }, - else => {}, - }, - .goto => |go| switch (go.target) { - .file_start => result.page_changed = state.activatePage( - gpa, - if (go.explicit_count) go.count -| 1 else 0, - true, - ), - .last_line => result.page_changed = state.activatePage(gpa, state.page_count -| 1, true), - .line_start, .first_nonws => if (native_images) if (geometry) |placed| - setHorizontalEdge(state, placed, false), - .line_end => if (native_images) if (geometry) |placed| - setHorizontalEdge(state, placed, true), - .line_down => result.page_changed = moveRows( - state, - gpa, - native_images, - viewport, - cell_pixels, - 1, - go.count, - ), - .line_up => result.page_changed = moveRows( - state, - gpa, - native_images, - viewport, - cell_pixels, - -1, - go.count, - ), - else => {}, - }, - .line => |line| switch (line) { - .start, .first_nonws => if (native_images) if (geometry) |placed| - setHorizontalEdge(state, placed, false), - .end => if (native_images) if (geometry) |placed| - setHorizontalEdge(state, placed, true), - }, - .goto_line => |go| { - if (go.explicit) - result.page_changed = state.activatePage(gpa, go.count -| 1, true); - }, - .page => |page| result.page_changed = switch (page.kind) { - .half_down, .down => movePage( - state, - gpa, - native_images, - viewport, - cell_pixels, - 1, - page.kind, - page.count, - ), - .half_up, .up => movePage( - state, - gpa, - native_images, - viewport, - cell_pixels, - -1, - page.kind, - page.count, - ), - }, - .view => |view| result.page_changed = switch (view) { - .scroll_down => moveRows(state, gpa, native_images, viewport, cell_pixels, 1, 1), - .scroll_up => moveRows(state, gpa, native_images, viewport, cell_pixels, -1, 1), - else => false, - }, - .leader => result.host = .leader, - .command_line => result.host = .command_line, - .search => result.host = .search, - .search_step => |direction| result.host = if (direction == .forward) - .search_forward - else - .search_backward, - else => {}, - } - return result; - } - - pub fn captureLayoutAnchor(state: *State) void { - if (comptime !enabled) return; - if (!state.layout_valid or state.page_count == 0 or state.document_height == 0) return; - const page = pageAtOffset(state, state.document_scroll_y); - const start: f64 = @floatFromInt(state.page_starts[page]); - const height: f64 = @floatFromInt(@max(@as(u32, 1), state.page_heights[page])); - state.layout_anchor_page = page; - state.layout_anchor_fraction = std.math.clamp((state.document_scroll_y - start) / height, 0, 1); - state.layout_anchor_pending = true; - } - - fn consumeOutlineReveal(state: *State, viewport: Viewport) void { - const destination = state.outline_reveal_pending orelse return; - state.outline_reveal_pending = null; - const page = @min(destination.page, state.page_count -| 1); - const size = state.page_sizes[page]; - const raw_y = destination.y orelse 0; - const y = if (std.math.isFinite(raw_y)) std.math.clamp(raw_y, 0, size.height) else 0; - state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[page])) + - @as(f64, y) / @as(f64, size.height) * @as(f64, @floatFromInt(state.page_heights[page])); - - if (destination.x) |raw_x| if (state.fit == .height and std.math.isFinite(raw_x)) { - const display_width = @as(f64, @floatFromInt(viewport.pixel_h)) * - @as(f64, size.width) / @as(f64, size.height); - const viewport_width: f64 = @floatFromInt(viewport.pixel_w); - if (display_width > viewport_width) { - const x = std.math.clamp(raw_x, 0, size.width); - const target = @as(f64, x) / @as(f64, size.width) * display_width; - const overflow = display_width - viewport_width; - const wanted = std.math.clamp(target - viewport_width / 2, 0, overflow); - state.pan_x = @intFromFloat(@round( - wanted / overflow * @as(f64, std.math.maxInt(u16)), - )); - } - }; - state.search_reveal_pending = false; - state.reveal_viewport_w = viewport.pixel_w; - state.reveal_viewport_h = viewport.pixel_h; - state.reveal_fit = state.fit; - state.reveal_viewport_valid = true; - } - - pub fn ensureLayout(state: *State, viewport: Viewport) void { - if (comptime !enabled) return; - const tz = tracy.zone(@src(), "pdf.ensure_layout"); - defer tz.end(); - if (state.layout_valid and !state.scroll_to_page_pending and - !state.layout_anchor_pending and - (state.layout_viewport_w != viewport.pixel_w or - state.layout_viewport_h != viewport.pixel_h)) captureLayoutAnchor(state); - if (!state.layout_valid or state.layout_viewport_w != viewport.pixel_w or - state.layout_viewport_h != viewport.pixel_h or state.layout_fit != state.fit) - { - var at: u64 = 0; - for (state.page_sizes, 0..) |size, page| { - state.page_starts[page] = at; - const height = pageHeight(size, viewport, state.fit); - state.page_heights[page] = height; - at = std.math.add(u64, at, height) catch std.math.maxInt(u64); - if (page + 1 < state.page_count) - at = std.math.add(u64, at, page_gap_px) catch std.math.maxInt(u64); - } - state.document_height = at; - state.layout_viewport_w = viewport.pixel_w; - state.layout_viewport_h = viewport.pixel_h; - state.layout_fit = state.fit; - state.layout_valid = true; - if (state.scroll_to_page_pending) { - state.document_scroll_y = @floatFromInt(state.page_starts[state.page]); - state.scroll_to_page_pending = false; - state.layout_anchor_pending = false; - } else if (state.layout_anchor_pending) { - const page = @min(state.layout_anchor_page, state.page_count -| 1); - state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[page])) + - state.layout_anchor_fraction * @as(f64, @floatFromInt(state.page_heights[page])); - state.layout_anchor_pending = false; - } - } - consumeOutlineReveal(state, viewport); - const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h)); - state.document_scroll_y = std.math.clamp(state.document_scroll_y, 0, max_scroll); - } - - pub const WordProbe = if (enabled) struct { - page: usize, - quads: []pdf.Quad, - text: []u8, - link: ?pdf.Link = null, - - pub fn deinit(probe: *@This(), gpa: std.mem.Allocator) void { - if (probe.link) |*link| link.deinit(gpa); - gpa.free(probe.quads); - gpa.free(probe.text); - probe.* = undefined; - } - } else void; - - pub const PointerDrag = if (enabled) struct { - native: bool = false, - /// Right-button Look probes this cell on release without borrowing or - /// replacing the pane's persistent MuPDF selection. - word_at: ?struct { col: u16, row: u16 } = null, - /// Drag updates keep selection geometry/text live, but their expensive - /// baked raster highlight is committed once on release. - selection_changed: bool = false, - } else struct {}; - - pub const PointerAction = enum { look, exec }; - - pub const PointerRelease = if (enabled) struct { - action: ?PointerAction = null, - text: []const u8 = &.{}, - probe: ?WordProbe = null, - - pub fn deinit(release: *@This(), gpa: std.mem.Allocator) void { - if (release.probe) |*probe| probe.deinit(gpa); - release.* = undefined; - } - } else struct { - pub fn deinit(_: *@This(), _: std.mem.Allocator) void {} - }; - - pub fn probeWord( - document: *Document, - gpa: std.mem.Allocator, - page: usize, - point: if (enabled) pdf.Point else void, - ) !?WordProbe { - if (comptime !enabled) return null; - var selection = try document.select(gpa, page, point, point); - errdefer selection.deinit(gpa); - const text = try document.copySelection(gpa, page, selection.start, selection.end); - errdefer gpa.free(text); - if (selection.quads.len == 0 or text.len == 0) { - selection.deinit(gpa); - gpa.free(text); - return null; - } - // Transfer the quad allocation out of Selection. There is intentionally - // no Selection.deinit on this success path: WordProbe is now its owner. - return .{ .page = page, .quads = selection.quads, .text = text }; - } - - pub fn pointAtGeometry( - geometry: image.NativeGeometry, - pixel_offset_y: f32, - full_width: usize, - full_height: usize, - band_y: usize, - pixel_x: i64, - pixel_y: i64, - clamp_to_page: bool, - ) ?Point { - if (comptime !enabled) return null; - if (full_width == 0 or full_height == 0 or - geometry.src.w == 0 or geometry.src.h == 0 or - geometry.dst.w == 0 or geometry.dst.h == 0) return null; - - const left: f64 = @floatFromInt(geometry.dst.x); - const top: f64 = @floatFromInt(geometry.dst.y); - const right = left + @as(f64, @floatFromInt(geometry.dst.w)); - const bottom = top + @as(f64, @floatFromInt(geometry.dst.h)); - var x: f64 = @floatFromInt(pixel_x); - var y: f64 = @as(f64, @floatFromInt(pixel_y)) - @as(f64, pixel_offset_y); - if (clamp_to_page) { - // Half-open rectangles: keep a clamped point infinitesimally inside - // the last presented pixel instead of letting it become `right`. - const epsilon = 1.0 / 1024.0; - x = std.math.clamp(x, left, @max(left, right - epsilon)); - y = std.math.clamp(y, top, @max(top, bottom - epsilon)); - } else if (x < left or x >= right or y < top or y >= bottom) { - return null; - } - - const source_x_f = @as(f64, @floatFromInt(geometry.src.x)) + - (x - left) * @as(f64, @floatFromInt(geometry.src.w)) / - @as(f64, @floatFromInt(geometry.dst.w)); - const source_y_f = @as(f64, @floatFromInt(geometry.src.y)) + - (y - top) * @as(f64, @floatFromInt(geometry.src.h)) / - @as(f64, @floatFromInt(geometry.dst.h)); - const source_x: usize = @min(full_width - 1, @as(usize, @intFromFloat(@floor(source_x_f)))); - const band_source_y: usize = @intFromFloat(@floor(source_y_f)); - const source_y = @min(full_height - 1, band_y + band_source_y); - return .{ - .x = (@as(f32, @floatFromInt(source_x)) + 0.5) / - @as(f32, @floatFromInt(full_width)), - .y = (@as(f32, @floatFromInt(source_y)) + 0.5) / - @as(f32, @floatFromInt(full_height)), - }; - } - - pub fn openPane( - core: *pardes.Pardes, - id: usize, - path: []const u8, - page_one_based: usize, - ) !*pardes.Pane { - if (comptime !enabled) return error.PdfDisabled; - // The slot stays ours across the read: another request may make a - // pane meanwhile. - core.reserved_slots[id] = true; - defer core.reserved_slots[id] = false; - var state = if (filesystem.localPath(path) != null) - try State.open(core.pdf_gpa, path, page_one_based) - else virtual: { - const bytes = try filesystem.read(core, path); - defer core.gpa.free(bytes); - break :virtual try State.openBytes(core.pdf_gpa, path, bytes, page_one_based); - }; - errdefer state.deinit(core.pdf_gpa); - const pane = try core.newDocPane(id); - pane.pdf = state; - pane.cur_pinned = true; - if (filesystem.localPath(path) != null) core.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); - return pane; - } - - /// Release a PDF payload while its pane slot is still installed, so the host - /// can retire the corresponding directory watch before that id is reused. - pub fn deinitPane(core: *pardes.Pardes, pane: *pardes.Pane, state: *State) void { - if (comptime !enabled) return; - for (core.panes, 0..) |slot, id| { - if (slot == pane) core.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); - } - state.deinit(core.pdf_gpa); - } - - pub fn reloadPane( - core: *pardes.Pardes, - pane: *pardes.Pane, - ) !void { - if (comptime !enabled) return error.PdfDisabled; - const state = &(pane.pdf orelse return error.MissingPdfState); - try state.reload(core.pdf_gpa); - resetPageChrome(pane); - } - - pub fn isSectionsOutput(pane: *const pardes.Pane) bool { - if (comptime !enabled) return false; - const file = pane.file orelse return false; - const output = file.output orelse return false; - return switch (output.from) { - .cmd => |builtin| builtin == .PdfSections, - else => false, - }; - } - - fn refreshCleanSections(core: *pardes.Pardes, state: *State) void { - if (comptime !enabled) return; - const remembered = state.sections_output orelse return; - if (remembered.pane >= core.panes.len) return; - const result = core.panes[remembered.pane] orelse return; - if (result.serial != remembered.serial or !isSectionsOutput(result)) return; - const file = &result.file.?; - if (file.revision != remembered.revision) return; - - const content = state.renderSections(core.pdf_gpa, core.gpa) catch { - state.sections_output = null; - return; - }; - if (std.mem.eql(u8, file.content, content)) { - core.gpa.free(content); - return; - } - core.invalidateLookHover(remembered.pane); - File.setContent(core, file, content); - const rows = File.lineCount(file.content); - file.scroll = @min(file.scroll, rows - 1); - const row = @min(@as(usize, @intCast(@max(0, result.cur_row))), rows - 1); - result.cur_row = @intCast(row); - result.cur_col = @intCast(@min( - @as(usize, @intCast(@max(0, result.cur_col))), - modal.lineSlice(file.content, row).len, - )); - result.msel.active = false; - result.vsel.active = false; - result.nsel = 0; - state.sections_output.?.revision = file.revision; - } - - /// One successful watched-path transaction, including every piece of derived - /// PDF output. The caller owns generic update bookkeeping and status text. - pub fn reloadWatched( - core: *pardes.Pardes, - pane: *pardes.Pane, - ) !void { - try reloadPane(core, pane); - refreshCleanSections(core, &pane.pdf.?); - } - - fn rearmCleanSections( - core: *pardes.Pardes, - id: usize, - pane: *pardes.Pane, - state: *State, - ) bool { - const remembered = state.sections_output orelse return false; - if (remembered.pane >= core.panes.len) return false; - const result = core.panes[remembered.pane] orelse return false; - if (result.serial != remembered.serial or !isSectionsOutput(result)) return false; - const file = &result.file.?; - if (file.revision != remembered.revision) return false; - - file.scroll = 0; - result.cur_row = 0; - result.cur_col = 0; - result.msel.active = false; - result.vsel.active = false; - result.nsel = 0; - pane.search_pane = remembered.pane; - pane.search_row = null; - core.armLookWalk(remembered.pane); - core.active = id; - return true; - } - - /// Lazily materialise this pane's cached outline as a location list. All - /// PDF-specific ownership stays here; Pardes contributes only placement. - pub fn openSections(core: *pardes.Pardes, id: usize) void { - if (comptime !enabled) return; - const pane = core.panes[id] orelse return; - const state = &(pane.pdf orelse return); - if (rearmCleanSections(core, id, pane, state)) return; - const content = state.renderSections(core.pdf_gpa, core.gpa) catch return; - - const free = core.freeSlot() orelse { - core.gpa.free(content); - return; - }; - const dir = std.fs.path.dirname(state.path) orelse "/"; - const result = Output.open( - core, - free, - dir, - .{ .cmd = .PdfSections }, - "", - content, - ) catch { - core.gpa.free(content); - return; - }; - state.sections_output = .{ - .pane = free, - .serial = result.serial, - .revision = result.file.?.revision, - }; - core.placeDoc(id, free, result); - layout.compute(core); - core.active = id; - pane.search_pane = free; - pane.search_row = null; - core.armLookWalk(free); - } - - const SectionsOwner = struct { - id: usize, - pane: *pardes.Pane, - state: *State, - }; - - fn sectionsOwner(core: *pardes.Pardes, output_id: usize) ?SectionsOwner { - const output = core.panes[output_id] orelse return null; - if (!isSectionsOutput(output)) return null; - const file = output.file.?; - for (core.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const state = if (pane.pdf) |*pdf_state| pdf_state else continue; - const token = state.sections_output orelse continue; - if (token.pane == output_id and token.serial == output.serial and - token.revision == file.revision) - return .{ .id = id, .pane = pane, .state = state }; - } - return null; - } - - pub fn lookSection( - core: *pardes.Pardes, - output_id: usize, - path: []const u8, - at: look.Spot, - ) bool { - if (comptime !enabled) return false; - const output = core.panes[output_id] orelse return false; - if (!isSectionsOutput(output)) return false; - if (at.line == 0 or at.col == 0 or at.end_line != 0 or - !look.isPdfPath(path)) return false; - const owner = sectionsOwner(core, output_id) orelse return true; - - var joined_path: [4096]u8 = undefined; - const output_dir = std.fs.path.dirname(output.file.?.path) orelse "/"; - const separator = if (std.mem.endsWith(u8, output_dir, "/")) "" else "/"; - const target_path = if (std.fs.path.isAbsolute(path)) - path - else - std.fmt.bufPrint(&joined_path, "{s}{s}{s}", .{ output_dir, separator, path }) catch return true; - if (!std.mem.eql(u8, owner.state.path, target_path)) return true; - - const destination = owner.state.sectionDestination(core.pdf_gpa, at.col - 1) orelse return true; - switch (destination) { - .internal => |internal| { - core.clearNavigationSelection(owner.pane); - revealOutlineDestination(core, owner.pane, internal); - }, - .external => |uri| if (uri.len <= 256) core.emit(.{ .open_link = .from(uri) }), - .none => unreachable, - } - core.active = owner.id; - return true; - } - - pub fn resetPageChrome(pane: *pardes.Pane) void { - pane.cur_row = 0; - pane.cur_col = 0; - pane.vsel.active = false; - pane.msel.active = false; - pane.nsel = 0; - } - - pub fn activatePage( - core: *pardes.Pardes, - pane: *pardes.Pane, - page: usize, - reveal: bool, - ) void { - if (comptime !enabled) return; - const state = &(pane.pdf orelse return); - if (state.activatePage(core.pdf_gpa, page, reveal)) resetPageChrome(pane); - } - - pub fn revealOutlineDestination( - core: *pardes.Pardes, - pane: *pardes.Pane, - destination: OutlineInternalDestination, - ) void { - if (comptime !enabled) return; - activatePage(core, pane, destination.page, false); - const state = &pane.pdf.?; - state.queueOutlineReveal(destination); - // Consume immediately when geometry already exists; otherwise the PDF - // draw pass consumes the same value after the next layout transaction. - _ = ensurePaneLayout(core, pane); - } - - pub fn setPage(core: *pardes.Pardes, pane: *pardes.Pane, page: usize) void { - activatePage(core, pane, page, true); - } - - pub fn toggleFit(pane: *pardes.Pane) void { - if (comptime !enabled) return; - const state = &(pane.pdf orelse return); - state.toggleFit(); - } - - pub fn toggleTint(pane: *pardes.Pane) void { - if (comptime !enabled) return; - const state = &(pane.pdf orelse return); - state.toggleTint(); - } - - pub fn stepPanePage(core: *pardes.Pardes, pane: *pardes.Pane, delta: i64) void { - if (comptime !enabled) return; - const state = &(pane.pdf orelse return); - if (stepPage(state, core.pdf_gpa, delta)) resetPageChrome(pane); - } - - pub fn paneViewport(core: *const pardes.Pardes, pane: *const pardes.Pane) ?Viewport { - if (comptime !enabled) return null; - const rect = for (core.panes, 0..) |slot, id| { - if (slot == pane) break core.rects[id]; - } else return null; - const cols = rect.w -| config.GUTTER; - const rows = rect.h -| pardes.BOX_H; - if (cols == 0 or rows == 0) return null; - return .{ - .pixel_w = @as(u32, cols) * @as(u32, core.cell_pixels.w), - .pixel_h = @as(u32, rows) * @as(u32, core.cell_pixels.h), - }; - } - - pub fn ensurePaneLayout(core: *pardes.Pardes, pane: *pardes.Pane) ?Viewport { - if (comptime !enabled) return null; - const state = &(pane.pdf orelse return null); - const view = paneViewport(core, pane) orelse return null; - ensureLayout(state, view); - return view; - } - - pub fn tintColors(core: *const pardes.Pardes) TintColors { - if (comptime !enabled) return; - const theme = core.theme(); - return .{ - .background = theme.bg orelse theme.tag_bg, - .foreground = theme.fg orelse theme.tag_fg, - }; - } - - pub fn paneGeometry(core: *const pardes.Pardes, pane: *const pardes.Pane) ?image.NativeGeometry { - if (comptime !enabled) return null; - const state = if (pane.pdf) |*view| view else return null; - const view = paneViewport(core, pane) orelse return null; - return activeGeometry(state, view); - } - - pub fn pageAtGridRow(core: *const pardes.Pardes, pane: *const pardes.Pane, row: u16) ?usize { - if (comptime !enabled) return null; - const state = pane.pdf orelse return null; - const rect = for (core.panes, 0..) |slot, id| { - if (slot == pane) break core.rects[id]; - } else return null; - const body_y = core.bodyTop(rect); - if (row < body_y or row >= body_y + (rect.h -| pardes.BOX_H)) return null; - const local_y = @as(f64, @floatFromInt( - @as(u32, row - body_y) * core.cell_pixels.h + core.cell_pixels.h / 2, - )); - return pageAtViewportY(&state, local_y); - } - - pub fn paneNativeReady(core: *const pardes.Pardes, pane: *const pardes.Pane) bool { - if (comptime !enabled) return false; - if (!core.native_images) return false; - const state = if (pane.pdf) |*view| view else return false; - const view = paneViewport(core, pane) orelse return false; - return nativeReady(state, view); - } - - pub fn nativePageAtGridRow( - core: *const pardes.Pardes, - pane: *const pardes.Pane, - row: u16, - ) ?usize { - if (comptime !enabled) return null; - if (!core.native_images) return null; - const state = if (pane.pdf) |*view| view else return null; - const page = pageAtGridRow(core, pane, row) orelse return null; - const view = paneViewport(core, pane) orelse return null; - if (!pageReady(state, view, page)) return null; - return page; - } - - pub fn pointAt( - core: *const pardes.Pardes, - pane: *const pardes.Pane, - col: u16, - row: u16, - clamp_to_page: bool, - ) ?Point { - if (comptime !enabled) return null; - const state = pane.pdf orelse return null; - return panePointAtPage(core, pane, state.page, col, row, clamp_to_page); - } - - pub fn panePointAtPage( - core: *const pardes.Pardes, - pane: *const pardes.Pane, - page: usize, - col: u16, - row: u16, - clamp_to_page: bool, - ) ?Point { - if (comptime !enabled) return null; - const state = if (pane.pdf) |*view| view else return null; - const view = paneViewport(core, pane) orelse return null; - const rect = for (core.panes, 0..) |slot, id| { - if (slot == pane) break core.rects[id]; - } else return null; - const body_x = @as(i64, rect.x + config.GUTTER); - const body_y = @as(i64, core.bodyTop(rect)); - const px = (@as(i64, col) - body_x) * core.cell_pixels.w + core.cell_pixels.w / 2; - const py = (@as(i64, row) - body_y) * core.cell_pixels.h + core.cell_pixels.h / 2; - return pointAtPage(state, view, page, px, py, clamp_to_page); - } - - pub fn probeAt( - core: *pardes.Pardes, - pane: *pardes.Pane, - col: u16, - row: u16, - ) ?WordProbe { - if (comptime !enabled) return null; - const page = nativePageAtGridRow(core, pane, row) orelse return null; - const point = panePointAtPage(core, pane, page, col, row, false) orelse return null; - const state = &(pane.pdf orelse return null); - if (state.document.linkAt(core.pdf_gpa, page, point) catch null) |found| { - var link = found; - if (core.pdfLinkLocation(pane, link) != null) { - const quads = core.pdf_gpa.alloc(pdf.Quad, 1) catch { - link.deinit(core.pdf_gpa); - return null; - }; - const text = state.document.copyRectangle(core.pdf_gpa, page, link.quad) catch { - core.pdf_gpa.free(quads); - link.deinit(core.pdf_gpa); - return null; - }; - quads[0] = link.quad; - return .{ .page = page, .quads = quads, .text = text, .link = link }; - } - link.deinit(core.pdf_gpa); - } - return probeWord(&state.document, core.pdf_gpa, page, point) catch null; - } - - pub fn beginDrag( - core: *pardes.Pardes, - pane: *pardes.Pane, - col: u16, - row: u16, - snap_word: bool, - ) bool { - if (comptime !enabled) return false; - const hit_page = pageAtGridRow(core, pane, row) orelse return false; - if (hit_page != pane.pdf.?.page) activatePage(core, pane, hit_page, false); - const state = &pane.pdf.?; - state.clearDrag(); - const point = pointAt(core, pane, col, row, false) orelse return false; - state.drag_anchor = point; - state.drag_head = point; - if (!snap_word) return true; - if (state.selection_page == state.page) if (state.selection) |selection| if (selection.contains(point)) return true; - if (state.setSelection(core.pdf_gpa, point, point, true) == .failed) { - // Preserve the old selection transactionally, but never let an - // outside click execute its stale text. - state.clearDrag(); - return false; - } - return true; - } - - pub fn beginSelection( - core: *pardes.Pardes, - pane: *pardes.Pane, - col: u16, - row: u16, - ) bool { - return beginDrag(core, pane, col, row, true); - } - - pub fn updateSelection( - core: *pardes.Pardes, - pane: *pardes.Pane, - col: u16, - row: u16, - invalidate_raster: bool, - ) SelectionUpdate { - if (comptime !enabled) return .failed; - const state = &(pane.pdf orelse return .failed); - const anchor = state.drag_anchor orelse return .failed; - const point = pointAt(core, pane, col, row, true) orelse return .failed; - if (state.drag_head) |head| if (head.x == point.x and head.y == point.y) return .stationary; - const result = state.setSelection(core.pdf_gpa, anchor, point, invalidate_raster); - if (result != .failed) state.drag_head = point; - return result; - } - - pub fn pointerStart( - core: *pardes.Pardes, - pane: *pardes.Pane, - button: pardes.Mouse.Button, - col: u16, - row: u16, - on_tag: bool, - ) PointerDrag { - if (comptime !enabled) return .{}; - if (on_tag or !paneNativeReady(core, pane)) return .{}; - var drag: PointerDrag = .{ .native = true }; - if (button == config.look_button) { - drag.word_at = .{ .col = col, .row = row }; - } else if (button == config.select_button) { - _ = beginDrag(core, pane, col, row, false); - } else if (button == config.exec_button) { - _ = beginDrag(core, pane, col, row, true); - } - return drag; - } - - pub fn pointerUpdate( - drag: *PointerDrag, - core: *pardes.Pardes, - pane: *pardes.Pane, - col: u16, - row: u16, - ) void { - if (comptime !enabled) return; - if (!drag.native) return; - if (drag.word_at) |at| { - if (col == at.col and row == at.row) return; - if (!beginDrag(core, pane, at.col, at.row, false)) { - drag.word_at = null; - return; - } - switch (updateSelection(core, pane, col, row, false)) { - .failed => { - drag.word_at = null; - pane.pdf.?.clearDrag(); - }, - // Adjacent grid cells can still address one raster pixel. Keep - // click mode and retry farther out. - .stationary => {}, - .unchanged => drag.word_at = null, - .changed => { - drag.word_at = null; - drag.selection_changed = true; - }, - } - return; - } - switch (updateSelection(core, pane, col, row, false)) { - .failed => pane.pdf.?.clearDrag(), - .stationary, .unchanged => {}, - .changed => drag.selection_changed = true, - } - } - - pub fn pointerCancel(pane: *pardes.Pane, drag: PointerDrag) void { - if (comptime !enabled) return; - if (drag.native) if (pane.pdf) |*state| { - if (drag.selection_changed) state.invalidateRaster(state.page); - state.clearDrag(); - }; - } - - pub fn pointerRelease( - core: *pardes.Pardes, - pane: *pardes.Pane, - drag: PointerDrag, - button: pardes.Mouse.Button, - chorded: bool, - ) PointerRelease { - if (comptime !enabled) return .{}; - const state = &(pane.pdf orelse return .{}); - const slot = @intFromEnum(button); - const grid_selection = pane.sel[slot]; - pane.sel[slot].state = .none; // native quads, not projected text cells - - // Drag updates changed live geometry/text while leaving baked pixels - // stable. Commit exactly once before any chord/Exec/Look can clear state. - if (drag.selection_changed) state.invalidateRaster(state.page); - if (chorded) { - state.clearDrag(); - return .{}; - } - if (drag.word_at) |at| { - const maybe_probe = probeAt(core, pane, at.col, at.row); - state.clearDrag(); - const probe = maybe_probe orelse return .{}; - // A neighboring visible page becomes current before Look dispatch. - // WordProbe owns its text/quads independently of that state change. - if (probe.page != state.page) activatePage(core, pane, probe.page, false); - const text = probe.text; - return .{ .action = .look, .text = text, .probe = probe }; - } - if (button == config.select_button) { - const dragged = grid_selection.c0 != grid_selection.c1 or - grid_selection.r0 != grid_selection.r1; - if (!dragged) state.clearSelection(core.pdf_gpa); - pane.cur_pinned = true; - pane.mode = .normal; - pane.msel.active = false; - pane.vsel.active = false; - pane.normal.clear(); - pane.nsel = 0; - state.clearDrag(); - return .{}; - } - if (state.drag_anchor == null or state.selection_text.len == 0) { - state.clearDrag(); - return .{}; - } - const text = state.selection_text; - state.clearDrag(); - return .{ - .action = if (button == config.look_button) .look else .exec, - .text = text, - }; - } - - pub fn highlightInput( - core: *pardes.Pardes, - pane_id: usize, - pane: *const pardes.Pane, - ) HighlightInput { - if (comptime !enabled) return; - const hover_quads: []const Quad = if (core.pdf_hover_preview) |preview| - if (preview.pane == pane_id and preview.serial == pane.serial) - preview.probe.quads - else - &.{} - else - &.{}; - const hover_page = if (hover_quads.len > 0) core.pdf_hover_preview.?.probe.page else null; - const link_hover = hover_quads.len > 0 and core.pdf_hover_preview.?.probe.link != null; - const selection_color = core.theme().sel_bg; - return .{ - .hover_quads = hover_quads, - .hover_page = hover_page, - .hover_color = if (link_hover) core.theme().box else selection_color, - .selection_color = selection_color, - .live = core.native_image_patches, - }; - } - - pub fn panPane( - core: *pardes.Pardes, - pane: *pardes.Pane, - axis: PanAxis, - direction: i8, - display_pixels: u32, - ) PanResult { - if (comptime !enabled) return .unavailable; - const placed = paneGeometry(core, pane) orelse return .unavailable; - const state = &(pane.pdf orelse return .unavailable); - return panPixels(state, placed, axis, direction, display_pixels); - } - - pub fn scrollPane(core: *pardes.Pardes, pane: *pardes.Pane, delta_pixels: f64) bool { - if (comptime !enabled) return false; - const tz = tracy.zone(@src(), "pdf.scroll_notch"); - defer tz.end(); - const state = &(pane.pdf orelse return false); - const view = ensurePaneLayout(core, pane) orelse return false; - const result = scrollDocument(state, view, delta_pixels) orelse return false; - if (result.active_page != state.page) activatePage(core, pane, result.active_page, false); - return true; - } - - pub fn verticalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void { - if (comptime !enabled) return; - if (!core.native_images) return stepPanePage(core, pane, direction); - const rows: u32 = @intCast(@max(1, config.wheel_rows)); - const pixels = scaledStep(core.cell_pixels.h, rows); - _ = scrollPane(core, pane, @as(f64, @floatFromInt(pixels)) * direction); - } - - pub fn horizontalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void { - if (comptime !enabled) return; - const state = pane.pdf orelse return; - if (!core.native_images or state.fit != .height) return; - const cols: u32 = @intCast(@max(1, config.wheel_cols)); - _ = panPane(core, pane, .horizontal, direction, scaledStep(core.cell_pixels.w, cols)); - } - - pub fn draw( - core: *pardes.Pardes, - pane: *pardes.Pane, - rect: pardes.Rect, - pane_id: usize, - text_x: u16, - text_width: u16, - ) bool { - if (comptime !enabled) return false; - if (!core.native_images or rect.h <= pardes.BOX_H) return false; - const state = &(pane.pdf orelse return false); - const view = paneViewport(core, pane) orelse return false; - const key = TintKey{ .mode = state.tint, .colors = tintColors(core) }; - const visible = renderFrame( - state, - core.pdf_gpa, - core.scratch.allocator(), - view, - pardes.pdf_raster_policy, - key, - highlightInput(core, pane_id, pane), - ); - var placed_any = false; - var page = visible.first; - const visible_end = visible.first + visible.len; - while (page < visible_end) : (page += 1) { - const placed = placedRaster(state, view, page) orelse continue; - const slot = rasterForPage(state, page).?; - const patch: ?pardes.ImagePatch = if (slot.patch_from != 0 and - slot.patch_rows.start < slot.patch_rows.end) - .{ - .from = slot.patch_from, - .y = @intCast(slot.patch_rows.start - slot.band_y), - .h = @intCast(slot.patch_rows.end - slot.patch_rows.start), - } - else - null; - if (!core.appendImagePlace(.{ - .pane = @intCast(pane_id), - .serial = pane.serial, - .native = .{ - .revision = placed.revision, - .page = @intCast(placed.page), - .fit = switch (placed.fit) { - .width => .width, - .height => .height, - }, - .pan_x = placed.pan_x, - .geometry = placed.geometry, - .pixel_offset_y = placed.pixel_offset_y, - .paper_bg = if (pardes.platform == .macos) - (if (key.mode == .disabled) .{ 255, 255, 255 } else key.colors.background) - else - null, - }, - .x = text_x, - // Below the notice chips, like an image: a placed page is - // drawn after the cells and would paint a chip out. - .y = core.bodyTop(rect) + pane.notices.span(), - .w = text_width, - .h = (rect.h -| pardes.BOX_H) -| pane.notices.span(), - .rgba = placed.rgba, - .iw = placed.width, - // The texture contains the retained band, not the full page. - .ih = placed.band_height, - .patch = patch, - })) break; - // A shell now holds (or will fetch whole) this revision. - slot.patch_from = slot.revision; - slot.patch_rows = .{ .start = 0, .end = 0 }; - placed_any = true; - } - if (!placed_any) return false; - - // This frame has spent the motion used to choose its raster band. - state.scroll_travel = 0; - const body_y = core.bodyTop(rect); - const body_h = rect.h -| pardes.BOX_H; - const chrome = core.chromeTheme(); - const theme = core.theme(); - const pane_bg: pardes.Color = if (theme.bg) |color| .{ .rgb = color } else .default; - // The rail runs past the notice bands; only the thumb tracks the text. - const rail_y = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; - core.surface.fill(rect.x, rail_y, 1, rect.h -| pardes.BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); - core.surface.fill(rect.x + 1, rail_y, 1, rect.h -| pardes.BOX_H, .{ .bg = pane_bg }); - - const track_h: usize = body_h; - const total = @max(@as(u64, 1), state.document_height); - const len = @max( - @as(usize, 1), - @as(usize, @intCast(@min( - @as(u64, track_h), - @as(u64, track_h) * view.pixel_h / total, - ))), - ); - const offset: u64 = @intFromFloat(@floor(state.document_scroll_y)); - const pos: usize = @intCast(@min( - @as(u64, track_h -| 1), - @as(u64, track_h) * offset / total, - )); - var y = pos; - while (y < track_h and y < pos + len) : (y += 1) - core.surface.fill( - rect.x, - body_y + @as(u16, @intCast(y)), - 1, - 1, - .{ .bg = .{ .rgb = chrome.scroll_thumb } }, - ); - return true; - } - - pub const SectionRows = if (enabled) struct { - pub fn usableDestination(destination: pdf.OutlineDestination) ?pdf.OutlineDestination { - return switch (destination) { - .internal => destination, - .external => |uri| if (safeHttpUri(uri)) destination else null, - .none => null, - }; - } - - fn safeHttpUri(uri: []const u8) bool { - // Effect.open_link is inline and cannot carry a larger URL. Omitting - // it here is preferable to rendering a row which can never act. - if (uri.len > 256) return false; - var has_scheme = false; - for (config.url_schemes) |scheme| { - if (std.mem.startsWith(u8, uri, scheme)) { - has_scheme = true; - break; - } - } - if (!has_scheme) return false; - for (uri) |byte| if (byte <= 0x20 or byte == 0x7f) return false; - return true; - } - - pub fn resolve(entries: []const pdf.OutlineEntry, ordinal: usize) ?pdf.OutlineDestination { - if (ordinal >= entries.len) return null; - const entry = entries[ordinal]; - if (entry.destination != .none) return usableDestination(entry.destination); - var i = ordinal + 1; - while (i < entries.len and entries[i].depth > entry.depth) : (i += 1) - if (usableDestination(entries[i].destination)) |destination| return destination; - return null; - } - - pub fn resolveOrdinals( - gpa: std.mem.Allocator, - entries: []const pdf.OutlineEntry, - ) ![]usize { - const unresolved = std.math.maxInt(usize); - const ordinals = try gpa.alloc(usize, entries.len); - @memset(ordinals, unresolved); - - const Pending = struct { depth: u8, ordinal: usize }; - var pending: [256]Pending = undefined; - var pending_len: usize = 0; - for (entries, 0..) |entry, ordinal| { - while (pending_len > 0 and pending[pending_len - 1].depth >= entry.depth) - pending_len -= 1; - - if (usableDestination(entry.destination) != null) { - ordinals[ordinal] = ordinal; - for (pending[0..pending_len]) |ancestor| - ordinals[ancestor.ordinal] = ordinal; - pending_len = 0; - } else if (entry.destination == .none) { - pending[pending_len] = .{ .depth = entry.depth, .ordinal = ordinal }; - pending_len += 1; - } - } - return ordinals; - } - - fn cleanTitle(out: ?[]u8, title: ?[]const u8) usize { - const raw = title orelse { - if (out) |buf| @memcpy(buf[0..10], "[untitled]"); - return 10; - }; - var at: usize = 0; - var i: usize = 0; - var wrote = false; - var pending_space = false; - while (i < raw.len) { - const n: usize = std.unicode.utf8ByteSequenceLength(raw[i]) catch { - pending_space = wrote; - i += 1; - continue; - }; - if (i + n > raw.len) { - pending_space = wrote; - break; - } - const cp = std.unicode.utf8Decode(raw[i .. i + n]) catch { - pending_space = wrote; - i += n; - continue; - }; - const whitespace_or_control = cp <= 0x20 or cp == 0x7f or - (cp >= 0x80 and cp <= 0x9f) or cp == 0x2028 or cp == 0x2029; - if (whitespace_or_control) { - pending_space = wrote; - } else { - if (pending_space) { - if (out) |buf| buf[at] = ' '; - at += 1; - } - if (out) |buf| @memcpy(buf[at..][0..n], raw[i .. i + n]); - at += n; - wrote = true; - pending_space = false; - } - i += n; - } - if (!wrote) { - if (out) |buf| @memcpy(buf[0..13], "[empty title]"); - return 13; - } - return at; - } - - pub fn render(gpa: std.mem.Allocator, path: []const u8, entries: []const pdf.OutlineEntry) ![]u8 { - const target = std.fs.path.basename(path); - const ordinals = try resolveOrdinals(gpa, entries); - defer gpa.free(ordinals); - var total: usize = 0; - for (entries, 0..) |entry, ordinal| { - const resolved = ordinals[ordinal]; - if (resolved == std.math.maxInt(usize)) continue; - const destination = usableDestination(entries[resolved].destination) orelse unreachable; - total += switch (destination) { - .internal => |internal| std.fmt.count("{s}:{d}:{d} ", .{ target, internal.page + 1, ordinal + 1 }), - .external => |uri| std.fmt.count("{s} ", .{uri}), - .none => unreachable, - }; - total += @as(usize, entry.depth) * 2 + cleanTitle(null, entry.title) + 1; - } - const out = try gpa.alloc(u8, total); - errdefer gpa.free(out); - var at: usize = 0; - for (entries, 0..) |entry, ordinal| { - const resolved = ordinals[ordinal]; - if (resolved == std.math.maxInt(usize)) continue; - const destination = usableDestination(entries[resolved].destination) orelse unreachable; - const prefix = switch (destination) { - .internal => |internal| try std.fmt.bufPrint(out[at..], "{s}:{d}:{d} ", .{ target, internal.page + 1, ordinal + 1 }), - .external => |uri| try std.fmt.bufPrint(out[at..], "{s} ", .{uri}), - .none => unreachable, - }; - at += prefix.len; - const indent = @as(usize, entry.depth) * 2; - @memset(out[at..][0..indent], ' '); - at += indent; - at += cleanTitle(out[at..], entry.title); - out[at] = '\n'; - at += 1; - } - return out; - } - } else struct {}; -}; +pub const Pdf = @import("pdf_view.zig"); pub const Terminal = @import("Terminal.zig"); diff --git a/src/pdf_view.zig b/src/pdf_view.zig new file mode 100644 index 00000000..106252a0 --- /dev/null +++ b/src/pdf_view.zig @@ -0,0 +1,2802 @@ +//! A PDF pane: the MuPDF document it views, page rasters and their placement, +//! scrolling, search, pointer selection, and the sections outline. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const layout = @import("layout.zig"); +const config = @import("config.zig"); +const modal = @import("modal.zig"); +const filesystem = @import("fs.zig"); +const tracy = @import("tracy.zig"); +const image = @import("image.zig"); +const look = @import("look.zig"); +const File = panes.File; +const Output = panes.Output; + +pub const enabled = @import("pardes_config").mupdf; +pub const pdf = if (enabled) @import("mupdf") else struct { + pub const PageSize = struct { width: f32, height: f32 }; + pub const Raster = struct { + width: usize = 0, + height: usize = 0, + stride: usize = 0, + len: usize = 0, + pub const Band = struct { y: usize = 0, height: usize = 0, len: usize = 0 }; + pub fn wholePage(_: @This()) Band { + return .{}; + } + pub fn band(_: @This(), _: usize, _: usize) Band { + return .{}; + } + }; +}; +pub const Point = if (enabled) pdf.Point else void; +pub const Quad = if (enabled) pdf.Quad else void; +pub const Document = if (enabled) pdf.Document else opaque {}; +pub const OutlineInternalDestination = if (enabled) pdf.OutlineInternalDestination else void; +const raster_max = 256; +const raster_spare = 4; +pub const page_gap_px: u32 = 8; +const band_grain: usize = 64; + +pub const FitMode = if (enabled) enum { width, height } else void; +pub const TintMode = if (enabled) pdf.TintMode else void; +pub const TintColors = if (enabled) pdf.TintColors else void; +pub const RenderRequest = if (enabled) pdf.RenderRequest else void; + +/// Dump records must remain recognizable as PDFs even in a build without +/// MuPDF, where Look deliberately treats them as ordinary files. +pub fn isPath(path: []const u8) bool { + return std.ascii.endsWithIgnoreCase(path, ".pdf"); +} + +pub const RasterPolicy = struct { + dpi: u16, + max_dimension: u16, + match_viewport: bool, +}; + +pub fn legacySavedPrefix(path: []const u8, saved_tag: []const u8) ?[]const u8 { + if (std.mem.startsWith(u8, saved_tag, path) and std.mem.startsWith(u8, saved_tag[path.len..], " [")) { + const start = path.len + 2; + const end = std.mem.indexOfScalarPos(u8, saved_tag, start, ']') orelse return null; + var parts = std.mem.splitScalar(u8, saved_tag[start..end], '/'); + _ = std.fmt.parseInt(usize, parts.next() orelse return null, 10) catch return null; + _ = std.fmt.parseInt(usize, parts.next() orelse return null, 10) catch return null; + if (parts.next() != null) return null; + return saved_tag[0 .. end + 1]; + } + if (!std.mem.startsWith(u8, saved_tag, "pdf ")) return null; + const marker = " PdfSections "; + const marker_at = std.mem.indexOf(u8, saved_tag, marker) orelse return null; + const path_at = marker_at + marker.len; + if (!std.mem.startsWith(u8, saved_tag[path_at..], path)) return null; + return saved_tag[0 .. path_at + path.len]; +} + +pub const TintKey = if (enabled) struct { + mode: TintMode, + colors: pdf.TintColors, + + pub fn eql(a: @This(), b: @This()) bool { + return a.mode == b.mode and + (a.mode == .disabled or std.meta.eql(a.colors, b.colors)); + } +} else void; + +pub const Highlight = if (enabled) pdf.Highlight else void; +pub const Highlights = if (enabled) struct { + const Page = struct { page: usize, items: []const Highlight }; + pages: [3]Page = undefined, + len: usize = 0, + /// Repaint whenever the set changes, not only when a page's raster was + /// invalidated (`HighlightInput.live`). + live: bool = false, + + pub fn forPage(highlights: @This(), page: usize) []const Highlight { + for (highlights.pages[0..highlights.len]) |group| + if (group.page == page) return group.items; + return &.{}; + } +} else void; + +pub const HighlightInput = if (enabled) struct { + hover_quads: []const Quad = &.{}, + hover_page: ?usize = null, + hover_color: [3]u8, + selection_color: [3]u8, + live: bool = false, +} else void; + +pub fn buildHighlights( + state: *const State, + arena: std.mem.Allocator, + input: HighlightInput, +) !Highlights { + if (comptime !enabled) return; + const search_len = if (state.search_results) |results| results.quads.len else 0; + const selection_len = if (state.selection) |selection| selection.quads.len else 0; + const items = try arena.alloc(Highlight, input.hover_quads.len + search_len + selection_len); + var result: Highlights = .{ .live = input.live }; + var n: usize = 0; + // Hover, search and selection can belong to three different pages. + // Group them once so raster rendering can borrow a contiguous slice. + for ([_]?usize{ input.hover_page, state.page, state.selection_page }) |candidate| { + const page = candidate orelse continue; + var seen = false; + for (result.pages[0..result.len]) |group| { + if (group.page == page) seen = true; + } + if (seen) continue; + const start = n; + if (input.hover_page == page) for (input.hover_quads) |quad| { + items[n] = pdf.Highlight.init(quad, .{ + input.hover_color[0], input.hover_color[1], input.hover_color[2], 0x2c, + }, .custom); + n += 1; + }; + if (state.page == page) if (state.search_results) |results| { + for (results.quads) |item| { + items[n] = pdf.Highlight.init(item.quad, .{ 0xff, 0xd5, 0x4f, 0x70 }, .search); + n += 1; + } + }; + if (state.selection_page == page) if (state.selection) |selection| { + for (selection.quads) |quad| { + items[n] = pdf.Highlight.init(quad, .{ + input.selection_color[0], input.selection_color[1], input.selection_color[2], 0x78, + }, .selection); + n += 1; + } + }; + result.pages[result.len] = .{ .page = page, .items = items[start..n] }; + result.len += 1; + } + return result; +} + +test "PDF selections retain their owning page across page focus" { + if (comptime !enabled) return; + const gpa = std.testing.allocator; + var state = try State.open(gpa, "docs/design.pdf", 1); + defer state.deinit(gpa); + try std.testing.expect(state.page_count > 1); + var found = try state.document.search(gpa, 0, "Pardes"); + defer found.deinit(gpa); + const quad = found.quads[0].quad; + const point: Point = .{ + .x = (quad.ul.x + quad.ur.x + quad.ll.x + quad.lr.x) / 4, + .y = (quad.ul.y + quad.ur.y + quad.ll.y + quad.lr.y) / 4, + }; + try std.testing.expectEqual(.changed, state.setSelection(gpa, point, point, true)); + const selected = try gpa.dupe(u8, state.selection_text); + defer gpa.free(selected); + try std.testing.expect(selected.len > 0); + try std.testing.expect(state.focusLocation(gpa, 2, 0)); + try std.testing.expectEqual(@as(?usize, 0), state.selection_page); + try std.testing.expectEqualStrings(selected, state.selection_text); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const highlights = try buildHighlights(&state, arena.allocator(), .{ + .hover_quads = &.{quad}, + .hover_page = 1, + .hover_color = .{ 1, 2, 3 }, + .selection_color = .{ 4, 5, 6 }, + }); + try std.testing.expectEqual(state.selection.?.quads.len, highlights.forPage(0).len); + try std.testing.expectEqual(@as(usize, 1), highlights.forPage(1).len); + try std.testing.expectEqual(@as(usize, 0), highlights.forPage(2).len); + try std.testing.expect(state.focusLocation(gpa, 1, 0)); + try std.testing.expectEqualStrings(selected, state.selection_text); + try std.testing.expectEqual(.unchanged, state.setSelection(gpa, point, point, true)); + try std.testing.expect(state.focusLocation(gpa, 2, 0)); + state.rasters[0] = .{ .valid = true, .page = 0, .tried = true, .decorated = true }; + state.rasters_len = 1; + try std.testing.expectEqual(.changed, state.setSelection(gpa, point, point, false)); + try std.testing.expectEqual(@as(?usize, 1), state.selection_page); + try std.testing.expect(!state.rasters[0].tried); + state.clearSelection(gpa); + try std.testing.expect(state.selection_page == null); + try std.testing.expectEqual(@as(usize, 0), state.selection_text.len); +} + +pub const Raster = if (enabled) struct { + valid: bool = false, + page: usize = 0, + rgba: []u8 = &.{}, + /// Full page shape; rgba contains only the band below. + iw: usize = 0, + ih: usize = 0, + band_y: usize = 0, + band_h: usize = 0, + request: pdf.RenderRequest = .{}, + request_valid: bool = false, + tried: bool = false, + decorated: bool = false, + tint_key: ?TintKey = null, + revision: u32 = 0, + /// `rgba` before its highlights and tint, kept once the page has been + /// highlighted: a highlight change repaints rows from it instead of + /// rendering the page again. + clean: []u8 = &.{}, + /// The highlights baked into `rgba` (gpa-owned), so a change repaints + /// only the rows of the quads that differ. + baked: []Highlight = &.{}, + /// `baked` is a true record (false after a render could not copy it). + baked_valid: bool = false, + /// Page rows changed since revision `patch_from`, the one last handed + /// to a shell; 0 when the pixels were replaced wholesale since. + patch_from: u32 = 0, + patch_rows: pdf.Document.Rows = .{ .start = 0, .end = 0 }, +} else void; + +pub const SectionsOutput = if (enabled) struct { + pane: usize, + serial: u32, + revision: u32, +} else void; + +pub const SelectionUpdate = enum { failed, stationary, unchanged, changed }; + +pub const State = if (enabled) struct { + path: []u8, + document: Document, + page: usize = 0, + page_count: usize, + page_sizes: []pdf.PageSize, + page_starts: []u64, + page_heights: []u32, + document_height: u64 = 0, + layout_viewport_w: u32 = 0, + layout_viewport_h: u32 = 0, + layout_fit: FitMode = .width, + layout_valid: bool = false, + document_scroll_y: f64 = 0, + scroll_to_page_pending: bool = true, + rasters: [raster_max]Raster = undefined, + rasters_len: usize = 0, + spare: [raster_spare][]u8 = @splat(&.{}), + spare_len: usize = 0, + layout_anchor_pending: bool = false, + layout_anchor_page: usize = 0, + layout_anchor_fraction: f64 = 0, + next_raster_revision: u32 = 0, + scroll_travel: f64 = 0, + fit: FitMode = .width, + tint: TintMode = .filtered, + pan_x: u16 = 0, + pan_y: u16 = 0, + highlights_dirty: bool = false, + search_reveal_pending: bool = false, + search_results: ?pdf.SearchResults = null, + selection: ?pdf.Selection = null, + selection_page: ?usize = null, + selection_text: []u8 = &.{}, + selection_anchor: ?Point = null, + selection_head: ?Point = null, + drag_anchor: ?Point = null, + drag_head: ?Point = null, + text: []u8 = &.{}, + text_tried: bool = false, + text_scroll: usize = 0, + text_scroll_clamp_pending: bool = false, + search_query: []u8 = &.{}, + search_hit: usize = 0, + reveal_viewport_w: u32 = 0, + reveal_viewport_h: u32 = 0, + reveal_fit: FitMode = .width, + reveal_viewport_valid: bool = false, + outline: ?pdf.Outline = null, + outline_tried: bool = false, + sections_output: ?SectionsOutput = null, + outline_reveal_pending: ?pdf.OutlineInternalDestination = null, + + /// Read whole and opened from memory (the bridge copies), never from + /// the file itself: MuPDF reads a file lazily at every page, and the + /// path may be a mount this editor serves, which only a read that + /// gives the turn up can come back from (`filesystem.readFile`). + pub fn open(gpa: std.mem.Allocator, path: []const u8, page_one_based: usize) !@This() { + const local = filesystem.localPath(path) orelse return error.NonLocalPath; + const bytes = try filesystem.readFile(gpa, local); + defer gpa.free(bytes); + return initDocument(gpa, path, try Document.openBytes(bytes), page_one_based); + } + + pub fn openBytes(gpa: std.mem.Allocator, path: []const u8, bytes: []const u8, page_one_based: usize) !@This() { + return initDocument(gpa, path, try Document.openBytes(bytes), page_one_based); + } + + fn initDocument(gpa: std.mem.Allocator, path: []const u8, opened: Document, page_one_based: usize) !@This() { + var document = opened; + errdefer document.deinit(); + const page_sizes = try gpa.alloc(pdf.PageSize, document.pages); + errdefer gpa.free(page_sizes); + for (page_sizes, 0..) |*size, page| size.* = try document.pageSize(page); + const page_starts = try gpa.alloc(u64, document.pages); + errdefer gpa.free(page_starts); + const page_heights = try gpa.alloc(u32, document.pages); + errdefer gpa.free(page_heights); + const owned_path = try gpa.dupe(u8, path); + errdefer gpa.free(owned_path); + return .{ + .path = owned_path, + .document = document, + .page = if (page_one_based > 0) + @min(page_one_based - 1, document.pages - 1) + else + 0, + .page_count = document.pages, + .page_sizes = page_sizes, + .page_starts = page_starts, + .page_heights = page_heights, + }; + } + + pub fn reload(state: *@This(), gpa: std.mem.Allocator) !void { + const preserve_anchor = !state.scroll_to_page_pending and + (state.layout_anchor_pending or + (state.layout_valid and state.page_count > 0 and state.document_height > 0)); + var anchor_page: usize = state.layout_anchor_page; + var anchor_fraction: f64 = state.layout_anchor_fraction; + if (preserve_anchor and !state.layout_anchor_pending) { + anchor_page = pageAtOffset(state, state.document_scroll_y); + const start: f64 = @floatFromInt(state.page_starts[anchor_page]); + const height: f64 = @floatFromInt(@max(@as(u32, 1), state.page_heights[anchor_page])); + anchor_fraction = std.math.clamp( + (state.document_scroll_y - start) / height, + 0, + 1, + ); + } + + var fresh = try @This().open(gpa, state.path, state.page + 1); + errdefer fresh.deinit(gpa); + if (state.search_query.len > 0) + fresh.search_query = try gpa.dupe(u8, state.search_query); + + fresh.fit = state.fit; + fresh.tint = state.tint; + fresh.pan_x = state.pan_x; + fresh.pan_y = state.pan_y; + fresh.text_scroll = state.text_scroll; + fresh.text_scroll_clamp_pending = true; + fresh.search_hit = state.search_hit; + fresh.highlights_dirty = fresh.search_query.len > 0; + fresh.search_reveal_pending = state.search_reveal_pending; + fresh.reveal_viewport_w = state.reveal_viewport_w; + fresh.reveal_viewport_h = state.reveal_viewport_h; + fresh.reveal_fit = state.reveal_fit; + fresh.reveal_viewport_valid = state.reveal_viewport_valid; + // Revisions are part of the backend texture key. Resetting this counter + // while the pane serial stays live can alias a cached pre-reload page. + fresh.next_raster_revision = state.next_raster_revision; + fresh.sections_output = state.sections_output; + if (preserve_anchor) { + fresh.scroll_to_page_pending = false; + fresh.layout_anchor_pending = true; + fresh.layout_anchor_page = anchor_page; + fresh.layout_anchor_fraction = anchor_fraction; + } + + var old = state.*; + state.* = fresh; + old.deinit(gpa); + } + + pub fn invalidateRaster(state: *@This(), page: usize) void { + if (rasterForPage(state, page)) |raster| raster.tried = false; + } + + pub fn invalidateAllRasters(state: *@This()) void { + for (state.rasters[0..state.rasters_len]) |*raster| { + if (raster.valid) raster.tried = false; + } + } + + fn retireRgba(state: *@This(), gpa: std.mem.Allocator, rgba: []u8) void { + if (rgba.len == 0) return; + if (state.spare_len == state.spare.len) return gpa.free(rgba); + state.spare[state.spare_len] = rgba; + state.spare_len += 1; + } + + fn retireRaster(state: *@This(), gpa: std.mem.Allocator, raster: *Raster) void { + if (raster.clean.len > 0) gpa.free(raster.clean); + gpa.free(raster.baked); + state.retireRgba(gpa, raster.rgba); + raster.* = .{}; + } + + fn claimRgba(state: *@This(), gpa: std.mem.Allocator, bytes: usize) ?[]u8 { + for (state.spare[0..state.spare_len], 0..) |candidate, index| { + if (candidate.len != bytes) continue; + state.spare_len -= 1; + state.spare[index] = state.spare[state.spare_len]; + return candidate; + } + return gpa.alloc(u8, bytes) catch null; + } + + fn trimSpares(state: *@This(), gpa: std.mem.Allocator) void { + while (state.spare_len > 1) { + state.spare_len -= 1; + gpa.free(state.spare[state.spare_len]); + } + } + + fn dropSearchResults(state: *@This(), gpa: std.mem.Allocator) void { + if (state.search_results) |*results| results.deinit(gpa); + state.search_results = null; + } + + fn dropSelection(state: *@This(), gpa: std.mem.Allocator) void { + if (state.selection) |*selection| selection.deinit(gpa); + state.selection = null; + state.selection_page = null; + if (state.selection_text.len > 0) gpa.free(state.selection_text); + state.selection_text = &.{}; + state.selection_anchor = null; + state.selection_head = null; + } + + pub fn setSelection( + state: *@This(), + gpa: std.mem.Allocator, + start: Point, + end: Point, + invalidate_raster: bool, + ) SelectionUpdate { + if (state.selection != null and state.selection_page == state.page and + state.selection_anchor != null and state.selection_head != null and + state.selection_anchor.?.x == start.x and state.selection_anchor.?.y == start.y and + state.selection_head.?.x == end.x and state.selection_head.?.y == end.y) return .unchanged; + var selection = state.document.select(gpa, state.page, start, end) catch return .failed; + const text = state.document.copySelection( + gpa, + state.page, + selection.start, + selection.end, + ) catch { + selection.deinit(gpa); + return .failed; + }; + + const old_page = state.selection_page; + state.dropSelection(gpa); + state.selection = selection; + state.selection_page = state.page; + state.selection_text = text; + state.selection_anchor = start; + state.selection_head = end; + if (old_page) |page| if (page != state.page) state.invalidateRaster(page); + if (invalidate_raster) state.invalidateRaster(state.page); + return .changed; + } + + pub fn clearDrag(state: *@This()) void { + state.drag_anchor = null; + state.drag_head = null; + } + + pub fn clearSelection(state: *@This(), gpa: std.mem.Allocator) void { + const page = state.selection_page; + state.dropSelection(gpa); + if (page) |selected_page| state.invalidateRaster(selected_page); + } + + pub fn cancelChrome(state: *@This(), gpa: std.mem.Allocator) void { + state.clearDrag(); + state.clearSelection(gpa); + if (state.search_query.len == 0) return; + state.dropSearchQuery(gpa); + state.invalidateRaster(state.page); + } + + fn invalidatePage(state: *@This(), gpa: std.mem.Allocator) void { + state.dropSearchResults(gpa); + state.clearDrag(); + if (state.text.len > 0) gpa.free(state.text); + state.text = &.{}; + state.text_tried = false; + state.text_scroll = 0; + state.text_scroll_clamp_pending = false; + state.highlights_dirty = state.search_query.len > 0; + state.search_reveal_pending = state.search_query.len > 0; + state.search_hit = 0; + } + + fn dropSearchQuery(state: *@This(), gpa: std.mem.Allocator) void { + if (state.search_query.len > 0) gpa.free(state.search_query); + state.search_query = &.{}; + state.search_hit = 0; + state.dropSearchResults(gpa); + state.highlights_dirty = false; + state.search_reveal_pending = false; + } + + pub fn setSearchQuery(state: *@This(), gpa: std.mem.Allocator, query: []const u8) !void { + if (std.mem.eql(u8, state.search_query, query)) return; + const owned = try gpa.dupe(u8, query); + state.dropSearchQuery(gpa); + state.search_query = owned; + state.highlights_dirty = query.len > 0; + state.search_reveal_pending = query.len > 0; + state.invalidateRaster(state.page); + } + + pub fn ensureText(state: *@This(), gpa: std.mem.Allocator) []const u8 { + if (!state.text_tried) { + state.text_tried = true; + state.text = state.document.pageText(gpa, state.page) catch &.{}; + } + if (state.text_scroll_clamp_pending) { + const lines = std.mem.count(u8, state.text, "\n") + 1; + state.text_scroll = @min(state.text_scroll, lines - 1); + state.text_scroll_clamp_pending = false; + } + return state.text; + } + + pub fn resolveSearch(state: *@This(), gpa: std.mem.Allocator) void { + if (!state.highlights_dirty) return; + state.highlights_dirty = false; + state.dropSearchResults(gpa); + if (state.search_query.len == 0) return; + const results = state.document.search(gpa, state.page, state.search_query) catch return; + state.search_hit = if (results.hit_count == 0) + 0 + else + @min(state.search_hit, results.hit_count - 1); + state.search_results = results; + } + + pub fn ensureOutline(state: *@This(), gpa: std.mem.Allocator) ?*const pdf.Outline { + if (!state.outline_tried) { + state.outline_tried = true; + state.outline = state.document.outline(gpa) catch null; + } + return if (state.outline) |*outline| outline else null; + } + + pub fn renderSections( + state: *@This(), + pdf_gpa: std.mem.Allocator, + output_gpa: std.mem.Allocator, + ) ![]u8 { + const entries: []const pdf.OutlineEntry = if (state.ensureOutline(pdf_gpa)) |outline| + outline.entries + else + &.{}; + return SectionRows.render(output_gpa, state.path, entries); + } + + pub fn sectionDestination( + state: *@This(), + gpa: std.mem.Allocator, + ordinal: usize, + ) ?pdf.OutlineDestination { + const outline = state.ensureOutline(gpa) orelse return null; + return SectionRows.resolve(outline.entries, ordinal); + } + + /// Apply the one-based page/hit location encoded in a PDF search row. + /// Returns whether host pane cursor chrome must be reset. + pub fn focusLocation( + state: *@This(), + gpa: std.mem.Allocator, + line: usize, + column: usize, + ) bool { + const changed = line > 0 and state.activatePage(gpa, line - 1, true); + if (column > 0 and state.search_query.len > 0) { + state.search_hit = column - 1; + state.search_reveal_pending = true; + } + return changed; + } + + /// Change the document page while leaving pane cursor/selection chrome to + /// the UI adapter. Returns whether that pane-local chrome must be reset. + pub fn activatePage( + state: *@This(), + gpa: std.mem.Allocator, + page: usize, + reveal: bool, + ) bool { + state.outline_reveal_pending = null; + const next = @min(page, state.page_count -| 1); + const changed = next != state.page; + if (changed) { + state.invalidatePage(gpa); + state.page = next; + } + if (reveal) { + state.scroll_to_page_pending = true; + if (state.layout_valid) { + state.document_scroll_y = @floatFromInt(state.page_starts[next]); + state.scroll_to_page_pending = false; + } + } else { + state.search_reveal_pending = false; + } + return changed; + } + + pub fn toggleFit(state: *@This()) void { + state.fit = if (state.fit == .width) .height else .width; + state.pan_x = 0; + state.pan_y = 0; + state.layout_valid = false; + state.scroll_to_page_pending = true; + state.search_reveal_pending = state.search_query.len > 0; + } + + pub fn toggleTint(state: *@This()) void { + state.tint = state.tint.next(); + state.invalidateAllRasters(); + } + + pub fn queueOutlineReveal( + state: *@This(), + destination: pdf.OutlineInternalDestination, + ) void { + state.scroll_to_page_pending = false; + state.layout_anchor_pending = false; + state.outline_reveal_pending = destination; + } + + pub fn deinit(state: *@This(), gpa: std.mem.Allocator) void { + gpa.free(state.path); + for (state.rasters[0..state.rasters_len]) |raster| { + if (raster.rgba.len > 0) gpa.free(raster.rgba); + if (raster.clean.len > 0) gpa.free(raster.clean); + gpa.free(raster.baked); + } + for (state.spare[0..state.spare_len]) |rgba| gpa.free(rgba); + gpa.free(state.page_sizes); + gpa.free(state.page_starts); + gpa.free(state.page_heights); + if (state.text.len > 0) gpa.free(state.text); + if (state.search_query.len > 0) gpa.free(state.search_query); + if (state.search_results) |*results| results.deinit(gpa); + if (state.selection) |*selection| selection.deinit(gpa); + if (state.selection_text.len > 0) gpa.free(state.selection_text); + if (state.outline) |*outline| outline.deinit(gpa); + state.document.deinit(); + state.* = undefined; + } +} else void; + +pub const SearchOutput = struct { + bytes: usize = 0, + rows: usize = 0, + anchor: ?usize = null, +}; + +pub fn textLines( + state: *State, + gpa: std.mem.Allocator, + arena: std.mem.Allocator, +) ![]const []const u8 { + if (comptime !enabled) return &.{}; + const page_text = state.ensureText(gpa); + const lines = try arena.alloc([]const u8, std.mem.count(u8, page_text, "\n") + 1); + var it = std.mem.splitScalar(u8, page_text, '\n'); + var n: usize = 0; + while (it.next()) |line| : (n += 1) lines[n] = line; + return lines; +} + +pub fn visibleText( + state: *State, + gpa: std.mem.Allocator, + arena: std.mem.Allocator, + max_rows: usize, +) ![]const u8 { + if (comptime !enabled) return ""; + const page_text = state.ensureText(gpa); + var start: usize = 0; + for (0..state.text_scroll) |_| { + const newline = std.mem.indexOfScalarPos(u8, page_text, start, '\n') orelse + return arena.dupe(u8, ""); + start = newline + 1; + } + if (max_rows == 0) return arena.dupe(u8, ""); + + var end = start; + var row: usize = 0; + while (row < max_rows) : (row += 1) { + const newline = std.mem.indexOfScalarPos(u8, page_text, end, '\n') orelse { + end = page_text.len; + break; + }; + if (row + 1 == max_rows) { + end = newline; + break; + } + end = newline + 1; + } + return arena.dupe(u8, page_text[start..end]); +} + +/// Materialize exact MuPDF logical hits as `path:PAGE:HIT query` rows. The +/// same hit numbering drives persistent highlights and later reveal actions. +pub fn searchRows( + state: *State, + gpa: std.mem.Allocator, + arena: std.mem.Allocator, + pattern: []const u8, + from_cursor: bool, + out: []u8, +) !SearchOutput { + if (comptime !enabled) return .{}; + try state.setSearchQuery(gpa, pattern); + const shown = std.fs.path.basename(state.path); + var result: SearchOutput = .{}; + const max_hits = 512; + var snippet_len = @min(pattern.len, 200); + while (snippet_len > 0 and snippet_len < pattern.len and pattern[snippet_len] & 0xc0 == 0x80) + snippet_len -= 1; + const snippet = pattern[0..snippet_len]; + for (0..state.page_count) |page| { + if (result.rows >= max_hits) break; + var found = try state.document.search(gpa, page, pattern); + defer found.deinit(gpa); + + const cursor_hit: ?usize = if (from_cursor and page == state.page and state.selection_page == page) cursor: { + const selection = state.selection orelse break :cursor null; + for (found.quads) |item| { + const q = item.quad; + const center: Point = .{ + .x = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4, + .y = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4, + }; + if (selection.contains(center)) break :cursor item.hit; + } + break :cursor null; + } else null; + + for (0..found.hit_count) |hit_index| { + if (result.rows >= max_hits) break; + const line = try std.fmt.allocPrint(arena, "{s}:{d}:{d} {s}\n", .{ + shown, page + 1, hit_index + 1, snippet, + }); + if (line.len > out.len - result.bytes) return result; + if (from_cursor and + (page < state.page or + (page == state.page and cursor_hit != null and hit_index <= cursor_hit.?))) + result.anchor = result.rows; + @memcpy(out[result.bytes..][0..line.len], line); + result.bytes += line.len; + result.rows += 1; + } + } + return result; +} + +pub const Viewport = struct { pixel_w: u32, pixel_h: u32 }; +pub const VisiblePages = struct { first: usize = 0, len: usize = 0 }; +pub const PanAxis = enum { horizontal, vertical }; +pub const PanResult = enum { moved, edge, unavailable }; +pub const ScrollResult = struct { active_page: usize }; +pub const CellPixels = struct { w: u16, h: u16 }; +pub const NormalHost = enum { + none, + leader, + command_line, + search, + search_forward, + search_backward, +}; +pub const NormalResult = struct { + host: NormalHost = .none, + page_changed: bool = false, +}; + +const PlacedGeometry = struct { + geometry: image.NativeGeometry, + pixel_offset_y: f32, +}; + +pub const PlacedRaster = if (enabled) struct { + page: usize, + revision: u32, + fit: FitMode, + pan_x: u16, + geometry: image.NativeGeometry, + pixel_offset_y: f32, + rgba: []const u8, + width: usize, + band_height: usize, +} else void; + +const VisibleRows = struct { + base: image.NativeGeometry, + y0: u32, + y1: u32, + dst_y: u32, + dst_h: u32, + pixel_offset_y: f32, +}; + +pub fn renderRequest(viewport: Viewport, policy: RasterPolicy) RenderRequest { + if (comptime !enabled) return; + return .{ + .dpi = policy.dpi, + .minimum_width = if (policy.match_viewport) viewport.pixel_w else 0, + .minimum_height = if (policy.match_viewport) viewport.pixel_h else 0, + .max_dimension = policy.max_dimension, + }; +} + +fn pageHeight(size: pdf.PageSize, viewport: Viewport, fit: FitMode) u32 { + if (comptime !enabled) return 0; + if (fit == .height) return viewport.pixel_h; + const scaled = @as(f64, @floatFromInt(viewport.pixel_w)) * + @as(f64, size.height) / @as(f64, size.width); + return @max(1, @as(u32, @intFromFloat(@min( + @as(f64, @floatFromInt(std.math.maxInt(u32))), + @round(scaled), + )))); +} + +fn pageAtOffset(state: *const State, offset: f64) usize { + if (comptime !enabled) return 0; + const y: u64 = @intFromFloat(std.math.clamp( + @floor(offset), + 0, + @as(f64, @floatFromInt(state.document_height -| 1)), + )); + var lo: usize = 0; + var hi: usize = state.page_count; + while (lo + 1 < hi) { + const mid = lo + (hi - lo) / 2; + if (state.page_starts[mid] <= y) lo = mid else hi = mid; + } + const end = state.page_starts[lo] + state.page_heights[lo]; + return if (y >= end and lo + 1 < state.page_count) lo + 1 else lo; +} + +fn pageVisible(state: *const State, page: usize, viewport: Viewport) bool { + if (comptime !enabled) return false; + const top = @as(f64, @floatFromInt(state.page_starts[page])) - state.document_scroll_y; + const bottom = top + @as(f64, @floatFromInt(state.page_heights[page])); + return bottom > 0 and top < @as(f64, @floatFromInt(viewport.pixel_h)); +} + +pub fn visiblePages(state: *const State, viewport: Viewport) VisiblePages { + if (comptime !enabled) return .{}; + var out: VisiblePages = .{}; + var page = pageAtOffset(state, state.document_scroll_y); + if (page > 0 and pageVisible(state, page - 1, viewport)) page -= 1; + out.first = page; + while (page < state.page_count) : (page += 1) { + const top = @as(f64, @floatFromInt(state.page_starts[page])) - state.document_scroll_y; + if (top >= @as(f64, @floatFromInt(viewport.pixel_h))) break; + if (pageVisible(state, page, viewport)) out.len += 1; + } + return out; +} + +fn visibleContains(visible: VisiblePages, page: usize) bool { + return page >= visible.first and page - visible.first < visible.len; +} + +pub fn rasterForPage(state: *State, page: usize) ?*Raster { + if (comptime !enabled) return null; + for (state.rasters[0..state.rasters_len]) |*raster| + if (raster.valid and raster.page == page) return raster; + return null; +} + +fn rasterForPageConst(state: *const State, page: usize) ?*const Raster { + if (comptime !enabled) return null; + for (state.rasters[0..state.rasters_len]) |*raster| + if (raster.valid and raster.page == page) return raster; + return null; +} + +fn visibleRows( + state: *const State, + viewport: Viewport, + page: usize, + iw: usize, + ih: usize, +) ?VisibleRows { + if (comptime !enabled) return null; + const page_h = state.page_heights[page]; + const base = image.nativeGeometry( + iw, + ih, + viewport.pixel_w, + page_h, + switch (state.fit) { + .width => .width, + .height => .height, + }, + state.pan_x, + 0, + ) orelse return null; + if (base.dst.h == 0 or base.src.h == 0) return null; + + const scroll_floor = @floor(state.document_scroll_y); + const fractional: f32 = @floatCast(state.document_scroll_y - scroll_floor); + const scroll_i: i64 = @intFromFloat(@min( + scroll_floor, + @as(f64, @floatFromInt(std.math.maxInt(i64))), + )); + const start_i: i64 = @intCast(@min( + state.page_starts[page], + @as(u64, std.math.maxInt(i64)), + )); + const full_y = start_i - scroll_i + @as(i64, base.dst.y); + const full_bottom = full_y + @as(i64, base.dst.h); + const visible_y = @max(@as(i64, 0), full_y); + const visible_bottom = @min(@as(i64, viewport.pixel_h), full_bottom); + if (visible_bottom <= visible_y) return null; + + const rel_y0: u64 = @intCast(visible_y - full_y); + const rel_y1: u64 = @intCast(visible_bottom - full_y); + const src_y0: u32 = base.src.y + @as(u32, @intCast( + rel_y0 * base.src.h / base.dst.h, + )); + const src_y1: u32 = base.src.y + @as(u32, @intCast(@min( + @as(u64, base.src.h), + (rel_y1 * base.src.h + base.dst.h - 1) / base.dst.h, + ))); + if (src_y1 <= src_y0) return null; + return .{ + .base = base, + .y0 = src_y0, + .y1 = src_y1, + .dst_y = @intCast(visible_y), + .dst_h = @intCast(visible_bottom - visible_y), + .pixel_offset_y = -fractional, + }; +} + +fn placedGeometry( + state: *const State, + raster: *const Raster, + viewport: Viewport, + page: usize, +) ?PlacedGeometry { + if (comptime !enabled) return null; + const rows = visibleRows(state, viewport, page, raster.iw, raster.ih) orelse return null; + const band_y: u32 = @intCast(raster.band_y); + const band_end: u32 = @intCast(raster.band_y + raster.band_h); + if (rows.y0 < band_y or rows.y1 > band_end) return null; + return .{ + .geometry = .{ + .src = .{ + .x = rows.base.src.x, + .y = rows.y0 - band_y, + .w = rows.base.src.w, + .h = rows.y1 - rows.y0, + }, + .dst = .{ + .x = rows.base.dst.x, + .y = rows.dst_y, + .w = rows.base.dst.w, + .h = rows.dst_h, + }, + }, + .pixel_offset_y = rows.pixel_offset_y, + }; +} + +pub fn placedRaster(state: *const State, viewport: Viewport, page: usize) ?PlacedRaster { + if (comptime !enabled) return null; + const raster = rasterForPageConst(state, page) orelse return null; + if (raster.rgba.len == 0) return null; + const placed = placedGeometry(state, raster, viewport, page) orelse return null; + return .{ + .page = page, + .revision = raster.revision, + .fit = state.fit, + .pan_x = state.pan_x, + .geometry = placed.geometry, + .pixel_offset_y = placed.pixel_offset_y, + .rgba = raster.rgba, + .width = raster.iw, + .band_height = raster.band_h, + }; +} + +pub fn activeGeometry(state: *const State, viewport: Viewport) ?image.NativeGeometry { + if (comptime !enabled) return null; + const raster = rasterForPageConst(state, state.page) orelse return null; + const placed = placedGeometry(state, raster, viewport, state.page) orelse return null; + return placed.geometry; +} + +pub fn pageAtViewportY(state: *const State, local_y: f64) ?usize { + if (comptime !enabled) return null; + if (!state.layout_valid or !std.math.isFinite(local_y) or local_y < 0) return null; + const document_y = state.document_scroll_y + local_y; + const page = pageAtOffset(state, document_y); + const start: f64 = @floatFromInt(state.page_starts[page]); + if (document_y < start or + document_y >= start + @as(f64, @floatFromInt(state.page_heights[page]))) return null; + return page; +} + +pub fn pageReady(state: *const State, viewport: Viewport, page: usize) bool { + if (comptime !enabled) return false; + return placedRaster(state, viewport, page) != null; +} + +pub fn nativeReady(state: *const State, viewport: Viewport) bool { + if (comptime !enabled) return false; + for (state.rasters[0..state.rasters_len]) |*raster| { + if (raster.valid and raster.rgba.len > 0 and + placedGeometry(state, raster, viewport, raster.page) != null) return true; + } + return false; +} + +pub fn pointAtPage( + state: *const State, + viewport: Viewport, + page: usize, + px: i64, + py: i64, + clamp_to_page: bool, +) ?Point { + if (comptime !enabled) return null; + const raster = rasterForPageConst(state, page) orelse return null; + if (raster.rgba.len == 0) return null; + const placed = placedGeometry(state, raster, viewport, page) orelse return null; + return pointAtGeometry( + placed.geometry, + placed.pixel_offset_y, + raster.iw, + raster.ih, + raster.band_y, + px, + py, + clamp_to_page, + ); +} + +fn slotShape(slot: *const Raster) pdf.Raster { + const stride = slot.iw * 4; + return .{ .width = slot.iw, .height = slot.ih, .stride = stride, .len = stride * slot.ih }; +} + +fn flinging(state: *const State, viewport: Viewport) bool { + if (comptime !enabled) return false; + return state.scroll_travel >= @as(f64, @floatFromInt(viewport.pixel_h)); +} + +fn wantedBand( + state: *const State, + viewport: Viewport, + page: usize, + shape: pdf.Raster, + is_flinging: bool, +) pdf.Raster.Band { + if (!is_flinging) return shape.wholePage(); + const rows = visibleRows(state, viewport, page, shape.width, shape.height) orelse + return shape.wholePage(); + const first = (@as(usize, rows.y0) / band_grain) * band_grain; + const last = std.math.divCeil(usize, @as(usize, rows.y1), band_grain) catch + return shape.wholePage(); + return shape.band(first, last * band_grain - first); +} + +fn reconcile( + state: *State, + gpa: std.mem.Allocator, + request: RenderRequest, + tint_key: TintKey, + highlights: Highlights, + visible: VisiblePages, + viewport: Viewport, +) void { + if (comptime !enabled) return; + const tz = tracy.zone(@src(), "pdf.reconcile"); + defer tz.end(); + + // Remove first so arriving pages can claim departing page buffers. Only + // the final visible set can be seen, so a fling skips crossed-over pages. + var index: usize = 0; + while (index < state.rasters_len) { + if (visibleContains(visible, state.rasters[index].page)) { + index += 1; + continue; + } + state.retireRaster(gpa, &state.rasters[index]); + state.rasters_len -= 1; + if (index != state.rasters_len) + state.rasters[index] = state.rasters[state.rasters_len]; + } + + const is_flinging = flinging(state, viewport); + var page = visible.first; + const end = visible.first + visible.len; + while (page < end) : (page += 1) { + var raster = rasterForPage(state, page); + if (raster == null) { + if (state.rasters_len == state.rasters.len) continue; + state.rasters[state.rasters_len] = .{ .valid = true, .page = page }; + state.rasters_len += 1; + raster = &state.rasters[state.rasters_len - 1]; + } + const slot = raster.?; + const page_highlights = highlights.forPage(page); + const decorated = page_highlights.len > 0; + const base_stale = !slot.request_valid or !slot.request.eql(request) or + slot.tint_key == null or !slot.tint_key.?.eql(tint_key) or + slot.rgba.len == 0 or slot.band_h == 0; + const uncovered = !base_stale and uncovered: { + const want = wantedBand(state, viewport, page, slotShape(slot), is_flinging); + break :uncovered slot.band_y > want.y or + slot.band_y + slot.band_h < want.y + want.height; + }; + if (!base_stale and !uncovered) { + if (slot.tried and slot.decorated == decorated and + !(highlights.live and !sameHighlights(slot.baked, page_highlights))) continue; + // Invalidated, but it already shows exactly these highlights + // (a preview withdrawn that was never drawn, on every pointer + // move over a page): nothing to render. + if (slot.baked_valid and sameHighlights(slot.baked, page_highlights)) { + slot.tried = true; + continue; + } + // Only the highlights moved: repaint their rows in place. + if (repaintHighlights(state, gpa, slot, request, tint_key, page_highlights)) continue; + } + + slot.tried = true; + slot.request = request; + slot.request_valid = true; + const shape_or_null = shape: { + const tz_measure = tracy.zone(@src(), "pdf.measure"); + defer tz_measure.end(); + break :shape state.document.measureRenderAt(page, request) catch null; + }; + const shape = shape_or_null orelse continue; + const want = wantedBand(state, viewport, page, shape, is_flinging); + const fresh = state.claimRgba(gpa, want.len) orelse continue; + const filled = filled: { + { + const tz_render = tracy.zone(@src(), "pdf.render_into"); + defer tz_render.end(); + // A highlighted page keeps its clean rows for repaints. + const keep_clean = pardes.platform != .macos and (decorated or slot.clean.len > 0); + state.document.renderIntoAtWithPaper( + page, + request, + shape, + want, + if (keep_clean) &.{} else page_highlights, + fresh, + pardes.platform == .macos, + ) catch break :filled false; + if (slot.clean.len != 0 and (!keep_clean or slot.clean.len != fresh.len)) { + gpa.free(slot.clean); + slot.clean = &.{}; + } + if (keep_clean) { + if (slot.clean.len == 0) slot.clean = gpa.alloc(u8, fresh.len) catch &.{}; + if (slot.clean.len == fresh.len) @memcpy(slot.clean, fresh); + state.document.paintHighlightsAt(page, request, shape, want, page_highlights, fresh) catch + break :filled false; + } + } + const tz_tint = tracy.zone(@src(), "pdf.tint"); + defer tz_tint.end(); + pdf.tintRgba(fresh, tint_key.mode, tint_key.colors) catch + break :filled false; + break :filled true; + }; + if (!filled) { + state.retireRgba(gpa, fresh); + // `clean` may already hold the band that failed. + if (slot.clean.len > 0) gpa.free(slot.clean); + slot.clean = &.{}; + continue; + } + + state.retireRgba(gpa, slot.rgba); + slot.rgba = fresh; + slot.iw = shape.width; + slot.ih = shape.height; + slot.band_y = want.y; + slot.band_h = want.height; + slot.decorated = decorated; + slot.tint_key = tint_key; + if (gpa.dupe(Highlight, page_highlights)) |copy| { + gpa.free(slot.baked); + slot.baked = copy; + slot.baked_valid = true; + } else |_| { + // Unrecorded highlights cannot be compared or diffed. + slot.baked_valid = false; + if (slot.clean.len > 0) gpa.free(slot.clean); + slot.clean = &.{}; + } + slot.patch_from = 0; + slot.patch_rows = .{ .start = 0, .end = 0 }; + state.next_raster_revision +%= 1; + if (state.next_raster_revision == 0) state.next_raster_revision = 1; + slot.revision = state.next_raster_revision; + } + state.trimSpares(gpa); +} + +/// Repaint only the rows where the old and new highlights differ: the +/// clean rows kept from the page's last render, MuPDF's highlight pass +/// (the whole new set) over them, the per-pixel tint — the operations a +/// full render performs, in its order, on fewer rows and without running +/// the page again. False leaves the slot for the full path. +fn repaintHighlights( + state: *State, + gpa: std.mem.Allocator, + slot: *Raster, + request: RenderRequest, + tint_key: TintKey, + page_highlights: []const Highlight, +) bool { + const tz = tracy.zone(@src(), "pdf.repaint_highlights"); + defer tz.end(); + if (slot.clean.len != slot.rgba.len or !slot.baked_valid) return false; + if (sameHighlights(slot.baked, page_highlights)) { + slot.tried = true; + return true; + } + const baked = gpa.dupe(Highlight, page_highlights) catch return false; + const changed = changedHighlights(gpa, slot.baked, page_highlights) catch { + gpa.free(baked); + return false; + }; + defer gpa.free(changed); + var dirty = state.document.highlightRows(slot.page, request, changed) catch { + gpa.free(baked); + return false; + }; + slot.tried = true; + dirty.start = @max(dirty.start, slot.band_y); + dirty.end = @min(dirty.end, slot.band_y + slot.band_h); + if (dirty.start < dirty.end) { + const shape = slotShape(slot); + const band = shape.band(dirty.start, dirty.end - dirty.start); + const offset = (dirty.start - slot.band_y) * shape.stride; + const out = slot.rgba[offset..][0..band.len]; + @memcpy(out, slot.clean[offset..][0..band.len]); + // On failure the rows are half-made: let the full path redo them. + state.document.paintHighlightsAt(slot.page, request, shape, band, page_highlights, out) catch { + gpa.free(baked); + slot.tried = false; + return false; + }; + pdf.tintRgba(out, tint_key.mode, tint_key.colors) catch { + gpa.free(baked); + slot.tried = false; + return false; + }; + slot.patch_rows = unionRows(slot.patch_rows, dirty); + state.next_raster_revision +%= 1; + if (state.next_raster_revision == 0) state.next_raster_revision = 1; + slot.revision = state.next_raster_revision; + } + gpa.free(slot.baked); + slot.baked = baked; + slot.decorated = page_highlights.len > 0; + return true; +} + +fn sameHighlights(a: []const Highlight, b: []const Highlight) bool { + return std.mem.eql(u8, std.mem.sliceAsBytes(a), std.mem.sliceAsBytes(b)); +} + +/// The highlights in one set and not the other, as multisets (a quad +/// painted twice blends twice). When only the order changed, blending +/// order did, so everything counts. +// ponytail: quadratic match; past 64k comparisons every quad counts. +fn changedHighlights(gpa: std.mem.Allocator, old: []const Highlight, new: []const Highlight) ![]Highlight { + const out = try gpa.alloc(Highlight, old.len + new.len); + errdefer gpa.free(out); + var n: usize = 0; + if (old.len * new.len <= 1 << 16) { + const matched = try gpa.alloc(bool, new.len); + defer gpa.free(matched); + @memset(matched, false); + for (old) |h| { + for (new, matched) |candidate, *used| { + if (!used.* and std.mem.eql(u8, std.mem.asBytes(&h), std.mem.asBytes(&candidate))) { + used.* = true; + break; + } + } else { + out[n] = h; + n += 1; + } + } + for (new, matched) |h, used| if (!used) { + out[n] = h; + n += 1; + }; + } + if (n == 0) { + @memcpy(out[0..old.len], old); + @memcpy(out[old.len..], new); + return out; + } + // Freed by length: hand back exactly what the caller will free. + return gpa.realloc(out, n); +} + +fn unionRows(a: pdf.Document.Rows, b: pdf.Document.Rows) pdf.Document.Rows { + if (a.start >= a.end) return b; + if (b.start >= b.end) return a; + return .{ .start = @min(a.start, b.start), .end = @max(a.end, b.end) }; +} + +pub fn renderFrame( + state: *State, + gpa: std.mem.Allocator, + arena: std.mem.Allocator, + viewport: Viewport, + policy: RasterPolicy, + tint_key: TintKey, + highlight_input: HighlightInput, +) VisiblePages { + if (comptime !enabled) return .{}; + ensureLayout(state, viewport); + state.resolveSearch(gpa); + const highlights = buildHighlights(state, arena, highlight_input) catch Highlights{}; + const request = renderRequest(viewport, policy); + var visible = visiblePages(state, viewport); + reconcile(state, gpa, request, tint_key, highlights, visible, viewport); + + rearmSearchReveal(state, viewport); + revealSearch(state, viewport, activeGeometry(state, viewport)); + visible = visiblePages(state, viewport); + reconcile(state, gpa, request, tint_key, highlights, visible, viewport); + return visible; +} + +pub fn normalizedPixel(value: f32, dimension: usize) u32 { + const scaled = std.math.clamp(value, 0, 1) * @as(f32, @floatFromInt(dimension)); + return @intCast(@min(dimension - 1, @as(usize, @intFromFloat(scaled)))); +} + +pub fn scaledStep(base: u32, count: u32) u32 { + return @intCast(@min( + @as(u64, std.math.maxInt(u32)), + @as(u64, base) * @max(@as(u64, 1), count), + )); +} + +pub fn scrollDocument(state: *State, viewport: Viewport, delta_pixels: f64) ?ScrollResult { + if (comptime !enabled) return null; + if (!std.math.isFinite(delta_pixels) or delta_pixels == 0) return null; + const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h)); + const next = std.math.clamp(state.document_scroll_y + delta_pixels, 0, max_scroll); + if (next == state.document_scroll_y) return null; + state.scroll_travel += @abs(next - state.document_scroll_y); + state.document_scroll_y = next; + return .{ .active_page = pageAtOffset(state, next) }; +} + +pub fn panPixels( + state: *State, + geometry: image.NativeGeometry, + axis: PanAxis, + direction: i8, + display_pixels: u32, +) PanResult { + if (comptime !enabled) return .unavailable; + const raster = rasterForPage(state, state.page) orelse return .unavailable; + const source_full: u32 = @intCast(switch (axis) { + .horizontal => raster.iw, + .vertical => raster.ih, + }); + const crop = switch (axis) { + .horizontal => geometry.src.w, + .vertical => geometry.src.h, + }; + const source_at = switch (axis) { + .horizontal => geometry.src.x, + .vertical => geometry.src.y, + }; + const displayed = @max(@as(u32, 1), switch (axis) { + .horizontal => geometry.dst.w, + .vertical => geometry.dst.h, + }); + const overflow = source_full -| crop; + if (overflow == 0 or + (direction < 0 and source_at == 0) or + (direction > 0 and source_at >= overflow)) return .edge; + + const source_step = @max( + @as(u64, 1), + (@as(u64, display_pixels) * @as(u64, crop) + displayed - 1) / displayed, + ); + const normalized_step: u32 = @intCast(@min( + @as(u64, std.math.maxInt(u16)), + @max( + @as(u64, 1), + (source_step * std.math.maxInt(u16) + overflow - 1) / overflow, + ), + )); + const position = switch (axis) { + .horizontal => &state.pan_x, + .vertical => &state.pan_y, + }; + if (direction > 0) { + position.* = @intCast(@min( + @as(u32, std.math.maxInt(u16)), + @as(u32, position.*) + normalized_step, + )); + } else { + position.* -|= @intCast(normalized_step); + } + return .moved; +} + +fn setHorizontalEdge(state: *State, geometry: image.NativeGeometry, end: bool) void { + if (comptime !enabled) return; + const raster = rasterForPage(state, state.page) orelse return; + if (raster.iw <= geometry.src.w) return; + state.pan_x = if (end) std.math.maxInt(u16) else 0; +} + +fn rearmSearchReveal(state: *State, viewport: Viewport) void { + if (comptime !enabled) return; + if (state.search_query.len == 0) return; + if (!state.reveal_viewport_valid or + state.reveal_viewport_w != viewport.pixel_w or + state.reveal_viewport_h != viewport.pixel_h or + state.reveal_fit != state.fit) + state.search_reveal_pending = true; +} + +pub fn revealSearch( + state: *State, + viewport: Viewport, + geometry: ?image.NativeGeometry, +) void { + if (comptime !enabled) return; + if (!state.search_reveal_pending) return; + state.reveal_viewport_w = viewport.pixel_w; + state.reveal_viewport_h = viewport.pixel_h; + state.reveal_fit = state.fit; + state.reveal_viewport_valid = true; + const results = state.search_results orelse { + state.search_reveal_pending = false; + return; + }; + if (results.hit_count == 0 or results.quads.len == 0) { + state.search_reveal_pending = false; + return; + } + state.search_hit = @min(state.search_hit, results.hit_count - 1); + const q = for (results.quads) |item| { + if (item.hit == state.search_hit) break item.quad; + } else { + state.search_reveal_pending = false; + return; + }; + state.search_reveal_pending = false; + const center_x = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4; + const center_y = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4; + if (state.fit == .width) { + ensureLayout(state, viewport); + const page_y = @as(f64, @floatFromInt(state.page_starts[state.page])) + + @as(f64, center_y) * @as(f64, @floatFromInt(state.page_heights[state.page])); + const wanted = page_y - @as(f64, @floatFromInt(viewport.pixel_h)) / 2; + const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h)); + state.document_scroll_y = std.math.clamp(wanted, 0, max_scroll); + return; + } + const placed = geometry orelse return; + const raster = rasterForPage(state, state.page) orelse return; + const full: u32 = @intCast(raster.iw); + const at = normalizedPixel(center_x, raster.iw); + if (at >= placed.src.x and at < placed.src.x + placed.src.w) return; + const overflow = full -| placed.src.w; + if (overflow == 0) return; + const wanted = @min(overflow, at -| placed.src.w / 2); + state.pan_x = @intCast( + (@as(u64, wanted) * std.math.maxInt(u16) + overflow / 2) / overflow, + ); +} + +pub fn stepPage(state: *State, gpa: std.mem.Allocator, delta: i64) bool { + const current: i64 = @intCast(state.page); + const last: i64 = @intCast(state.page_count -| 1); + return state.activatePage( + gpa, + @intCast(std.math.clamp(current + delta, 0, last)), + true, + ); +} + +fn scrollNormal( + state: *State, + gpa: std.mem.Allocator, + viewport: ?Viewport, + delta_pixels: f64, +) bool { + const view = viewport orelse return false; + ensureLayout(state, view); + const result = scrollDocument(state, view, delta_pixels) orelse return false; + return result.active_page != state.page and + state.activatePage(gpa, result.active_page, false); +} + +fn moveRows( + state: *State, + gpa: std.mem.Allocator, + native_images: bool, + viewport: ?Viewport, + cell_pixels: CellPixels, + direction: i8, + count: u32, +) bool { + if (!native_images) { + const pages: i64 = @intCast(@max(@as(u32, 1), count)); + return stepPage(state, gpa, if (direction > 0) pages else -pages); + } + return scrollNormal( + state, + gpa, + viewport, + @as(f64, @floatFromInt(scaledStep(cell_pixels.h, count))) * direction, + ); +} + +fn movePage( + state: *State, + gpa: std.mem.Allocator, + native_images: bool, + viewport: ?Viewport, + cell_pixels: CellPixels, + direction: i8, + kind: modal.Normal.Page, + count: u32, +) bool { + if (!native_images) { + const pages: i64 = @intCast(@max(@as(u32, 1), count)); + return stepPage(state, gpa, if (direction > 0) pages else -pages); + } + const base: u32 = switch (kind) { + .half_down, .half_up => if (viewport) |view| + @max(@as(u32, 1), view.pixel_h / 2) + else + cell_pixels.h, + .down, .up => if (viewport) |view| view.pixel_h else cell_pixels.h, + }; + return scrollNormal( + state, + gpa, + viewport, + @as(f64, @floatFromInt(scaledStep(base, count))) * direction, + ); +} + +pub fn applyNormal( + state: *State, + gpa: std.mem.Allocator, + semantic: modal.Normal.Action, + native_images: bool, + cell_pixels: CellPixels, + viewport: ?Viewport, + geometry: ?image.NativeGeometry, +) NormalResult { + if (comptime !enabled) return .{}; + var result: NormalResult = .{}; + switch (semantic) { + .escape => state.cancelChrome(gpa), + .move => |move| switch (move.motion) { + .down => result.page_changed = moveRows( + state, + gpa, + native_images, + viewport, + cell_pixels, + 1, + move.count, + ), + .up => result.page_changed = moveRows( + state, + gpa, + native_images, + viewport, + cell_pixels, + -1, + move.count, + ), + .left => if (native_images) if (geometry) |placed| { + _ = panPixels(state, placed, .horizontal, -1, scaledStep(cell_pixels.w, move.count)); + }, + .right => if (native_images) if (geometry) |placed| { + _ = panPixels(state, placed, .horizontal, 1, scaledStep(cell_pixels.w, move.count)); + }, + else => {}, + }, + .goto => |go| switch (go.target) { + .file_start => result.page_changed = state.activatePage( + gpa, + if (go.explicit_count) go.count -| 1 else 0, + true, + ), + .last_line => result.page_changed = state.activatePage(gpa, state.page_count -| 1, true), + .line_start, .first_nonws => if (native_images) if (geometry) |placed| + setHorizontalEdge(state, placed, false), + .line_end => if (native_images) if (geometry) |placed| + setHorizontalEdge(state, placed, true), + .line_down => result.page_changed = moveRows( + state, + gpa, + native_images, + viewport, + cell_pixels, + 1, + go.count, + ), + .line_up => result.page_changed = moveRows( + state, + gpa, + native_images, + viewport, + cell_pixels, + -1, + go.count, + ), + else => {}, + }, + .line => |line| switch (line) { + .start, .first_nonws => if (native_images) if (geometry) |placed| + setHorizontalEdge(state, placed, false), + .end => if (native_images) if (geometry) |placed| + setHorizontalEdge(state, placed, true), + }, + .goto_line => |go| { + if (go.explicit) + result.page_changed = state.activatePage(gpa, go.count -| 1, true); + }, + .page => |page| result.page_changed = switch (page.kind) { + .half_down, .down => movePage( + state, + gpa, + native_images, + viewport, + cell_pixels, + 1, + page.kind, + page.count, + ), + .half_up, .up => movePage( + state, + gpa, + native_images, + viewport, + cell_pixels, + -1, + page.kind, + page.count, + ), + }, + .view => |view| result.page_changed = switch (view) { + .scroll_down => moveRows(state, gpa, native_images, viewport, cell_pixels, 1, 1), + .scroll_up => moveRows(state, gpa, native_images, viewport, cell_pixels, -1, 1), + else => false, + }, + .leader => result.host = .leader, + .command_line => result.host = .command_line, + .search => result.host = .search, + .search_step => |direction| result.host = if (direction == .forward) + .search_forward + else + .search_backward, + else => {}, + } + return result; +} + +pub fn captureLayoutAnchor(state: *State) void { + if (comptime !enabled) return; + if (!state.layout_valid or state.page_count == 0 or state.document_height == 0) return; + const page = pageAtOffset(state, state.document_scroll_y); + const start: f64 = @floatFromInt(state.page_starts[page]); + const height: f64 = @floatFromInt(@max(@as(u32, 1), state.page_heights[page])); + state.layout_anchor_page = page; + state.layout_anchor_fraction = std.math.clamp((state.document_scroll_y - start) / height, 0, 1); + state.layout_anchor_pending = true; +} + +fn consumeOutlineReveal(state: *State, viewport: Viewport) void { + const destination = state.outline_reveal_pending orelse return; + state.outline_reveal_pending = null; + const page = @min(destination.page, state.page_count -| 1); + const size = state.page_sizes[page]; + const raw_y = destination.y orelse 0; + const y = if (std.math.isFinite(raw_y)) std.math.clamp(raw_y, 0, size.height) else 0; + state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[page])) + + @as(f64, y) / @as(f64, size.height) * @as(f64, @floatFromInt(state.page_heights[page])); + + if (destination.x) |raw_x| if (state.fit == .height and std.math.isFinite(raw_x)) { + const display_width = @as(f64, @floatFromInt(viewport.pixel_h)) * + @as(f64, size.width) / @as(f64, size.height); + const viewport_width: f64 = @floatFromInt(viewport.pixel_w); + if (display_width > viewport_width) { + const x = std.math.clamp(raw_x, 0, size.width); + const target = @as(f64, x) / @as(f64, size.width) * display_width; + const overflow = display_width - viewport_width; + const wanted = std.math.clamp(target - viewport_width / 2, 0, overflow); + state.pan_x = @intFromFloat(@round( + wanted / overflow * @as(f64, std.math.maxInt(u16)), + )); + } + }; + state.search_reveal_pending = false; + state.reveal_viewport_w = viewport.pixel_w; + state.reveal_viewport_h = viewport.pixel_h; + state.reveal_fit = state.fit; + state.reveal_viewport_valid = true; +} + +pub fn ensureLayout(state: *State, viewport: Viewport) void { + if (comptime !enabled) return; + const tz = tracy.zone(@src(), "pdf.ensure_layout"); + defer tz.end(); + if (state.layout_valid and !state.scroll_to_page_pending and + !state.layout_anchor_pending and + (state.layout_viewport_w != viewport.pixel_w or + state.layout_viewport_h != viewport.pixel_h)) captureLayoutAnchor(state); + if (!state.layout_valid or state.layout_viewport_w != viewport.pixel_w or + state.layout_viewport_h != viewport.pixel_h or state.layout_fit != state.fit) + { + var at: u64 = 0; + for (state.page_sizes, 0..) |size, page| { + state.page_starts[page] = at; + const height = pageHeight(size, viewport, state.fit); + state.page_heights[page] = height; + at = std.math.add(u64, at, height) catch std.math.maxInt(u64); + if (page + 1 < state.page_count) + at = std.math.add(u64, at, page_gap_px) catch std.math.maxInt(u64); + } + state.document_height = at; + state.layout_viewport_w = viewport.pixel_w; + state.layout_viewport_h = viewport.pixel_h; + state.layout_fit = state.fit; + state.layout_valid = true; + if (state.scroll_to_page_pending) { + state.document_scroll_y = @floatFromInt(state.page_starts[state.page]); + state.scroll_to_page_pending = false; + state.layout_anchor_pending = false; + } else if (state.layout_anchor_pending) { + const page = @min(state.layout_anchor_page, state.page_count -| 1); + state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[page])) + + state.layout_anchor_fraction * @as(f64, @floatFromInt(state.page_heights[page])); + state.layout_anchor_pending = false; + } + } + consumeOutlineReveal(state, viewport); + const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h)); + state.document_scroll_y = std.math.clamp(state.document_scroll_y, 0, max_scroll); +} + +pub const WordProbe = if (enabled) struct { + page: usize, + quads: []pdf.Quad, + text: []u8, + link: ?pdf.Link = null, + + pub fn deinit(probe: *@This(), gpa: std.mem.Allocator) void { + if (probe.link) |*link| link.deinit(gpa); + gpa.free(probe.quads); + gpa.free(probe.text); + probe.* = undefined; + } +} else void; + +pub const PointerDrag = if (enabled) struct { + native: bool = false, + /// Right-button Look probes this cell on release without borrowing or + /// replacing the pane's persistent MuPDF selection. + word_at: ?struct { col: u16, row: u16 } = null, + /// Drag updates keep selection geometry/text live, but their expensive + /// baked raster highlight is committed once on release. + selection_changed: bool = false, +} else struct {}; + +pub const PointerAction = enum { look, exec }; + +pub const PointerRelease = if (enabled) struct { + action: ?PointerAction = null, + text: []const u8 = &.{}, + probe: ?WordProbe = null, + + pub fn deinit(release: *@This(), gpa: std.mem.Allocator) void { + if (release.probe) |*probe| probe.deinit(gpa); + release.* = undefined; + } +} else struct { + pub fn deinit(_: *@This(), _: std.mem.Allocator) void {} +}; + +pub fn probeWord( + document: *Document, + gpa: std.mem.Allocator, + page: usize, + point: if (enabled) pdf.Point else void, +) !?WordProbe { + if (comptime !enabled) return null; + var selection = try document.select(gpa, page, point, point); + errdefer selection.deinit(gpa); + const text = try document.copySelection(gpa, page, selection.start, selection.end); + errdefer gpa.free(text); + if (selection.quads.len == 0 or text.len == 0) { + selection.deinit(gpa); + gpa.free(text); + return null; + } + // Transfer the quad allocation out of Selection. There is intentionally + // no Selection.deinit on this success path: WordProbe is now its owner. + return .{ .page = page, .quads = selection.quads, .text = text }; +} + +pub fn pointAtGeometry( + geometry: image.NativeGeometry, + pixel_offset_y: f32, + full_width: usize, + full_height: usize, + band_y: usize, + pixel_x: i64, + pixel_y: i64, + clamp_to_page: bool, +) ?Point { + if (comptime !enabled) return null; + if (full_width == 0 or full_height == 0 or + geometry.src.w == 0 or geometry.src.h == 0 or + geometry.dst.w == 0 or geometry.dst.h == 0) return null; + + const left: f64 = @floatFromInt(geometry.dst.x); + const top: f64 = @floatFromInt(geometry.dst.y); + const right = left + @as(f64, @floatFromInt(geometry.dst.w)); + const bottom = top + @as(f64, @floatFromInt(geometry.dst.h)); + var x: f64 = @floatFromInt(pixel_x); + var y: f64 = @as(f64, @floatFromInt(pixel_y)) - @as(f64, pixel_offset_y); + if (clamp_to_page) { + // Half-open rectangles: keep a clamped point infinitesimally inside + // the last presented pixel instead of letting it become `right`. + const epsilon = 1.0 / 1024.0; + x = std.math.clamp(x, left, @max(left, right - epsilon)); + y = std.math.clamp(y, top, @max(top, bottom - epsilon)); + } else if (x < left or x >= right or y < top or y >= bottom) { + return null; + } + + const source_x_f = @as(f64, @floatFromInt(geometry.src.x)) + + (x - left) * @as(f64, @floatFromInt(geometry.src.w)) / + @as(f64, @floatFromInt(geometry.dst.w)); + const source_y_f = @as(f64, @floatFromInt(geometry.src.y)) + + (y - top) * @as(f64, @floatFromInt(geometry.src.h)) / + @as(f64, @floatFromInt(geometry.dst.h)); + const source_x: usize = @min(full_width - 1, @as(usize, @intFromFloat(@floor(source_x_f)))); + const band_source_y: usize = @intFromFloat(@floor(source_y_f)); + const source_y = @min(full_height - 1, band_y + band_source_y); + return .{ + .x = (@as(f32, @floatFromInt(source_x)) + 0.5) / + @as(f32, @floatFromInt(full_width)), + .y = (@as(f32, @floatFromInt(source_y)) + 0.5) / + @as(f32, @floatFromInt(full_height)), + }; +} + +pub fn openPane( + core: *pardes.Pardes, + id: usize, + path: []const u8, + page_one_based: usize, +) !*pardes.Pane { + if (comptime !enabled) return error.PdfDisabled; + // The slot stays ours across the read: another request may make a + // pane meanwhile. + core.reserved_slots[id] = true; + defer core.reserved_slots[id] = false; + var state = if (filesystem.localPath(path) != null) + try State.open(core.pdf_gpa, path, page_one_based) + else virtual: { + const bytes = try filesystem.read(core, path); + defer core.gpa.free(bytes); + break :virtual try State.openBytes(core.pdf_gpa, path, bytes, page_one_based); + }; + errdefer state.deinit(core.pdf_gpa); + const pane = try core.newDocPane(id); + pane.pdf = state; + pane.cur_pinned = true; + if (filesystem.localPath(path) != null) core.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + return pane; +} + +/// Release a PDF payload while its pane slot is still installed, so the host +/// can retire the corresponding directory watch before that id is reused. +pub fn deinitPane(core: *pardes.Pardes, pane: *pardes.Pane, state: *State) void { + if (comptime !enabled) return; + for (core.panes, 0..) |slot, id| { + if (slot == pane) core.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); + } + state.deinit(core.pdf_gpa); +} + +pub fn reloadPane( + core: *pardes.Pardes, + pane: *pardes.Pane, +) !void { + if (comptime !enabled) return error.PdfDisabled; + const state = &(pane.pdf orelse return error.MissingPdfState); + try state.reload(core.pdf_gpa); + resetPageChrome(pane); +} + +pub fn isSectionsOutput(pane: *const pardes.Pane) bool { + if (comptime !enabled) return false; + const file = pane.file orelse return false; + const output = file.output orelse return false; + return switch (output.from) { + .cmd => |builtin| builtin == .PdfSections, + else => false, + }; +} + +fn refreshCleanSections(core: *pardes.Pardes, state: *State) void { + if (comptime !enabled) return; + const remembered = state.sections_output orelse return; + if (remembered.pane >= core.panes.len) return; + const result = core.panes[remembered.pane] orelse return; + if (result.serial != remembered.serial or !isSectionsOutput(result)) return; + const file = &result.file.?; + if (file.revision != remembered.revision) return; + + const content = state.renderSections(core.pdf_gpa, core.gpa) catch { + state.sections_output = null; + return; + }; + if (std.mem.eql(u8, file.content, content)) { + core.gpa.free(content); + return; + } + core.invalidateLookHover(remembered.pane); + File.setContent(core, file, content); + const rows = File.lineCount(file.content); + file.scroll = @min(file.scroll, rows - 1); + const row = @min(@as(usize, @intCast(@max(0, result.cur_row))), rows - 1); + result.cur_row = @intCast(row); + result.cur_col = @intCast(@min( + @as(usize, @intCast(@max(0, result.cur_col))), + modal.lineSlice(file.content, row).len, + )); + result.msel.active = false; + result.vsel.active = false; + result.nsel = 0; + state.sections_output.?.revision = file.revision; +} + +/// One successful watched-path transaction, including every piece of derived +/// PDF output. The caller owns generic update bookkeeping and status text. +pub fn reloadWatched( + core: *pardes.Pardes, + pane: *pardes.Pane, +) !void { + try reloadPane(core, pane); + refreshCleanSections(core, &pane.pdf.?); +} + +fn rearmCleanSections( + core: *pardes.Pardes, + id: usize, + pane: *pardes.Pane, + state: *State, +) bool { + const remembered = state.sections_output orelse return false; + if (remembered.pane >= core.panes.len) return false; + const result = core.panes[remembered.pane] orelse return false; + if (result.serial != remembered.serial or !isSectionsOutput(result)) return false; + const file = &result.file.?; + if (file.revision != remembered.revision) return false; + + file.scroll = 0; + result.cur_row = 0; + result.cur_col = 0; + result.msel.active = false; + result.vsel.active = false; + result.nsel = 0; + pane.search_pane = remembered.pane; + pane.search_row = null; + core.armLookWalk(remembered.pane); + core.active = id; + return true; +} + +/// Lazily materialise this pane's cached outline as a location list. All +/// PDF-specific ownership stays here; Pardes contributes only placement. +pub fn openSections(core: *pardes.Pardes, id: usize) void { + if (comptime !enabled) return; + const pane = core.panes[id] orelse return; + const state = &(pane.pdf orelse return); + if (rearmCleanSections(core, id, pane, state)) return; + const content = state.renderSections(core.pdf_gpa, core.gpa) catch return; + + const free = core.freeSlot() orelse { + core.gpa.free(content); + return; + }; + const dir = std.fs.path.dirname(state.path) orelse "/"; + const result = Output.open( + core, + free, + dir, + .{ .cmd = .PdfSections }, + "", + content, + ) catch { + core.gpa.free(content); + return; + }; + state.sections_output = .{ + .pane = free, + .serial = result.serial, + .revision = result.file.?.revision, + }; + core.placeDoc(id, free, result); + layout.compute(core); + core.active = id; + pane.search_pane = free; + pane.search_row = null; + core.armLookWalk(free); +} + +const SectionsOwner = struct { + id: usize, + pane: *pardes.Pane, + state: *State, +}; + +fn sectionsOwner(core: *pardes.Pardes, output_id: usize) ?SectionsOwner { + const output = core.panes[output_id] orelse return null; + if (!isSectionsOutput(output)) return null; + const file = output.file.?; + for (core.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const state = if (pane.pdf) |*pdf_state| pdf_state else continue; + const token = state.sections_output orelse continue; + if (token.pane == output_id and token.serial == output.serial and + token.revision == file.revision) + return .{ .id = id, .pane = pane, .state = state }; + } + return null; +} + +pub fn lookSection( + core: *pardes.Pardes, + output_id: usize, + path: []const u8, + at: look.Spot, +) bool { + if (comptime !enabled) return false; + const output = core.panes[output_id] orelse return false; + if (!isSectionsOutput(output)) return false; + if (at.line == 0 or at.col == 0 or at.end_line != 0 or + !look.isPdfPath(path)) return false; + const owner = sectionsOwner(core, output_id) orelse return true; + + var joined_path: [4096]u8 = undefined; + const output_dir = std.fs.path.dirname(output.file.?.path) orelse "/"; + const separator = if (std.mem.endsWith(u8, output_dir, "/")) "" else "/"; + const target_path = if (std.fs.path.isAbsolute(path)) + path + else + std.fmt.bufPrint(&joined_path, "{s}{s}{s}", .{ output_dir, separator, path }) catch return true; + if (!std.mem.eql(u8, owner.state.path, target_path)) return true; + + const destination = owner.state.sectionDestination(core.pdf_gpa, at.col - 1) orelse return true; + switch (destination) { + .internal => |internal| { + core.clearNavigationSelection(owner.pane); + revealOutlineDestination(core, owner.pane, internal); + }, + .external => |uri| if (uri.len <= 256) core.emit(.{ .open_link = .from(uri) }), + .none => unreachable, + } + core.active = owner.id; + return true; +} + +pub fn resetPageChrome(pane: *pardes.Pane) void { + pane.cur_row = 0; + pane.cur_col = 0; + pane.vsel.active = false; + pane.msel.active = false; + pane.nsel = 0; +} + +pub fn activatePage( + core: *pardes.Pardes, + pane: *pardes.Pane, + page: usize, + reveal: bool, +) void { + if (comptime !enabled) return; + const state = &(pane.pdf orelse return); + if (state.activatePage(core.pdf_gpa, page, reveal)) resetPageChrome(pane); +} + +pub fn revealOutlineDestination( + core: *pardes.Pardes, + pane: *pardes.Pane, + destination: OutlineInternalDestination, +) void { + if (comptime !enabled) return; + activatePage(core, pane, destination.page, false); + const state = &pane.pdf.?; + state.queueOutlineReveal(destination); + // Consume immediately when geometry already exists; otherwise the PDF + // draw pass consumes the same value after the next layout transaction. + _ = ensurePaneLayout(core, pane); +} + +pub fn setPage(core: *pardes.Pardes, pane: *pardes.Pane, page: usize) void { + activatePage(core, pane, page, true); +} + +pub fn toggleFit(pane: *pardes.Pane) void { + if (comptime !enabled) return; + const state = &(pane.pdf orelse return); + state.toggleFit(); +} + +pub fn toggleTint(pane: *pardes.Pane) void { + if (comptime !enabled) return; + const state = &(pane.pdf orelse return); + state.toggleTint(); +} + +pub fn stepPanePage(core: *pardes.Pardes, pane: *pardes.Pane, delta: i64) void { + if (comptime !enabled) return; + const state = &(pane.pdf orelse return); + if (stepPage(state, core.pdf_gpa, delta)) resetPageChrome(pane); +} + +pub fn paneViewport(core: *const pardes.Pardes, pane: *const pardes.Pane) ?Viewport { + if (comptime !enabled) return null; + const rect = for (core.panes, 0..) |slot, id| { + if (slot == pane) break core.rects[id]; + } else return null; + const cols = rect.w -| config.GUTTER; + const rows = rect.h -| pardes.BOX_H; + if (cols == 0 or rows == 0) return null; + return .{ + .pixel_w = @as(u32, cols) * @as(u32, core.cell_pixels.w), + .pixel_h = @as(u32, rows) * @as(u32, core.cell_pixels.h), + }; +} + +pub fn ensurePaneLayout(core: *pardes.Pardes, pane: *pardes.Pane) ?Viewport { + if (comptime !enabled) return null; + const state = &(pane.pdf orelse return null); + const view = paneViewport(core, pane) orelse return null; + ensureLayout(state, view); + return view; +} + +pub fn tintColors(core: *const pardes.Pardes) TintColors { + if (comptime !enabled) return; + const theme = core.theme(); + return .{ + .background = theme.bg orelse theme.tag_bg, + .foreground = theme.fg orelse theme.tag_fg, + }; +} + +pub fn paneGeometry(core: *const pardes.Pardes, pane: *const pardes.Pane) ?image.NativeGeometry { + if (comptime !enabled) return null; + const state = if (pane.pdf) |*view| view else return null; + const view = paneViewport(core, pane) orelse return null; + return activeGeometry(state, view); +} + +pub fn pageAtGridRow(core: *const pardes.Pardes, pane: *const pardes.Pane, row: u16) ?usize { + if (comptime !enabled) return null; + const state = pane.pdf orelse return null; + const rect = for (core.panes, 0..) |slot, id| { + if (slot == pane) break core.rects[id]; + } else return null; + const body_y = core.bodyTop(rect); + if (row < body_y or row >= body_y + (rect.h -| pardes.BOX_H)) return null; + const local_y = @as(f64, @floatFromInt( + @as(u32, row - body_y) * core.cell_pixels.h + core.cell_pixels.h / 2, + )); + return pageAtViewportY(&state, local_y); +} + +pub fn paneNativeReady(core: *const pardes.Pardes, pane: *const pardes.Pane) bool { + if (comptime !enabled) return false; + if (!core.native_images) return false; + const state = if (pane.pdf) |*view| view else return false; + const view = paneViewport(core, pane) orelse return false; + return nativeReady(state, view); +} + +pub fn nativePageAtGridRow( + core: *const pardes.Pardes, + pane: *const pardes.Pane, + row: u16, +) ?usize { + if (comptime !enabled) return null; + if (!core.native_images) return null; + const state = if (pane.pdf) |*view| view else return null; + const page = pageAtGridRow(core, pane, row) orelse return null; + const view = paneViewport(core, pane) orelse return null; + if (!pageReady(state, view, page)) return null; + return page; +} + +pub fn pointAt( + core: *const pardes.Pardes, + pane: *const pardes.Pane, + col: u16, + row: u16, + clamp_to_page: bool, +) ?Point { + if (comptime !enabled) return null; + const state = pane.pdf orelse return null; + return panePointAtPage(core, pane, state.page, col, row, clamp_to_page); +} + +pub fn panePointAtPage( + core: *const pardes.Pardes, + pane: *const pardes.Pane, + page: usize, + col: u16, + row: u16, + clamp_to_page: bool, +) ?Point { + if (comptime !enabled) return null; + const state = if (pane.pdf) |*view| view else return null; + const view = paneViewport(core, pane) orelse return null; + const rect = for (core.panes, 0..) |slot, id| { + if (slot == pane) break core.rects[id]; + } else return null; + const body_x = @as(i64, rect.x + config.GUTTER); + const body_y = @as(i64, core.bodyTop(rect)); + const px = (@as(i64, col) - body_x) * core.cell_pixels.w + core.cell_pixels.w / 2; + const py = (@as(i64, row) - body_y) * core.cell_pixels.h + core.cell_pixels.h / 2; + return pointAtPage(state, view, page, px, py, clamp_to_page); +} + +pub fn probeAt( + core: *pardes.Pardes, + pane: *pardes.Pane, + col: u16, + row: u16, +) ?WordProbe { + if (comptime !enabled) return null; + const page = nativePageAtGridRow(core, pane, row) orelse return null; + const point = panePointAtPage(core, pane, page, col, row, false) orelse return null; + const state = &(pane.pdf orelse return null); + if (state.document.linkAt(core.pdf_gpa, page, point) catch null) |found| { + var link = found; + if (core.pdfLinkLocation(pane, link) != null) { + const quads = core.pdf_gpa.alloc(pdf.Quad, 1) catch { + link.deinit(core.pdf_gpa); + return null; + }; + const text = state.document.copyRectangle(core.pdf_gpa, page, link.quad) catch { + core.pdf_gpa.free(quads); + link.deinit(core.pdf_gpa); + return null; + }; + quads[0] = link.quad; + return .{ .page = page, .quads = quads, .text = text, .link = link }; + } + link.deinit(core.pdf_gpa); + } + return probeWord(&state.document, core.pdf_gpa, page, point) catch null; +} + +pub fn beginDrag( + core: *pardes.Pardes, + pane: *pardes.Pane, + col: u16, + row: u16, + snap_word: bool, +) bool { + if (comptime !enabled) return false; + const hit_page = pageAtGridRow(core, pane, row) orelse return false; + if (hit_page != pane.pdf.?.page) activatePage(core, pane, hit_page, false); + const state = &pane.pdf.?; + state.clearDrag(); + const point = pointAt(core, pane, col, row, false) orelse return false; + state.drag_anchor = point; + state.drag_head = point; + if (!snap_word) return true; + if (state.selection_page == state.page) if (state.selection) |selection| if (selection.contains(point)) return true; + if (state.setSelection(core.pdf_gpa, point, point, true) == .failed) { + // Preserve the old selection transactionally, but never let an + // outside click execute its stale text. + state.clearDrag(); + return false; + } + return true; +} + +pub fn beginSelection( + core: *pardes.Pardes, + pane: *pardes.Pane, + col: u16, + row: u16, +) bool { + return beginDrag(core, pane, col, row, true); +} + +pub fn updateSelection( + core: *pardes.Pardes, + pane: *pardes.Pane, + col: u16, + row: u16, + invalidate_raster: bool, +) SelectionUpdate { + if (comptime !enabled) return .failed; + const state = &(pane.pdf orelse return .failed); + const anchor = state.drag_anchor orelse return .failed; + const point = pointAt(core, pane, col, row, true) orelse return .failed; + if (state.drag_head) |head| if (head.x == point.x and head.y == point.y) return .stationary; + const result = state.setSelection(core.pdf_gpa, anchor, point, invalidate_raster); + if (result != .failed) state.drag_head = point; + return result; +} + +pub fn pointerStart( + core: *pardes.Pardes, + pane: *pardes.Pane, + button: pardes.Mouse.Button, + col: u16, + row: u16, + on_tag: bool, +) PointerDrag { + if (comptime !enabled) return .{}; + if (on_tag or !paneNativeReady(core, pane)) return .{}; + var drag: PointerDrag = .{ .native = true }; + if (button == config.look_button) { + drag.word_at = .{ .col = col, .row = row }; + } else if (button == config.select_button) { + _ = beginDrag(core, pane, col, row, false); + } else if (button == config.exec_button) { + _ = beginDrag(core, pane, col, row, true); + } + return drag; +} + +pub fn pointerUpdate( + drag: *PointerDrag, + core: *pardes.Pardes, + pane: *pardes.Pane, + col: u16, + row: u16, +) void { + if (comptime !enabled) return; + if (!drag.native) return; + if (drag.word_at) |at| { + if (col == at.col and row == at.row) return; + if (!beginDrag(core, pane, at.col, at.row, false)) { + drag.word_at = null; + return; + } + switch (updateSelection(core, pane, col, row, false)) { + .failed => { + drag.word_at = null; + pane.pdf.?.clearDrag(); + }, + // Adjacent grid cells can still address one raster pixel. Keep + // click mode and retry farther out. + .stationary => {}, + .unchanged => drag.word_at = null, + .changed => { + drag.word_at = null; + drag.selection_changed = true; + }, + } + return; + } + switch (updateSelection(core, pane, col, row, false)) { + .failed => pane.pdf.?.clearDrag(), + .stationary, .unchanged => {}, + .changed => drag.selection_changed = true, + } +} + +pub fn pointerCancel(pane: *pardes.Pane, drag: PointerDrag) void { + if (comptime !enabled) return; + if (drag.native) if (pane.pdf) |*state| { + if (drag.selection_changed) state.invalidateRaster(state.page); + state.clearDrag(); + }; +} + +pub fn pointerRelease( + core: *pardes.Pardes, + pane: *pardes.Pane, + drag: PointerDrag, + button: pardes.Mouse.Button, + chorded: bool, +) PointerRelease { + if (comptime !enabled) return .{}; + const state = &(pane.pdf orelse return .{}); + const slot = @intFromEnum(button); + const grid_selection = pane.sel[slot]; + pane.sel[slot].state = .none; // native quads, not projected text cells + + // Drag updates changed live geometry/text while leaving baked pixels + // stable. Commit exactly once before any chord/Exec/Look can clear state. + if (drag.selection_changed) state.invalidateRaster(state.page); + if (chorded) { + state.clearDrag(); + return .{}; + } + if (drag.word_at) |at| { + const maybe_probe = probeAt(core, pane, at.col, at.row); + state.clearDrag(); + const probe = maybe_probe orelse return .{}; + // A neighboring visible page becomes current before Look dispatch. + // WordProbe owns its text/quads independently of that state change. + if (probe.page != state.page) activatePage(core, pane, probe.page, false); + const text = probe.text; + return .{ .action = .look, .text = text, .probe = probe }; + } + if (button == config.select_button) { + const dragged = grid_selection.c0 != grid_selection.c1 or + grid_selection.r0 != grid_selection.r1; + if (!dragged) state.clearSelection(core.pdf_gpa); + pane.cur_pinned = true; + pane.mode = .normal; + pane.msel.active = false; + pane.vsel.active = false; + pane.normal.clear(); + pane.nsel = 0; + state.clearDrag(); + return .{}; + } + if (state.drag_anchor == null or state.selection_text.len == 0) { + state.clearDrag(); + return .{}; + } + const text = state.selection_text; + state.clearDrag(); + return .{ + .action = if (button == config.look_button) .look else .exec, + .text = text, + }; +} + +pub fn highlightInput( + core: *pardes.Pardes, + pane_id: usize, + pane: *const pardes.Pane, +) HighlightInput { + if (comptime !enabled) return; + const hover_quads: []const Quad = if (core.pdf_hover_preview) |preview| + if (preview.pane == pane_id and preview.serial == pane.serial) + preview.probe.quads + else + &.{} + else + &.{}; + const hover_page = if (hover_quads.len > 0) core.pdf_hover_preview.?.probe.page else null; + const link_hover = hover_quads.len > 0 and core.pdf_hover_preview.?.probe.link != null; + const selection_color = core.theme().sel_bg; + return .{ + .hover_quads = hover_quads, + .hover_page = hover_page, + .hover_color = if (link_hover) core.theme().box else selection_color, + .selection_color = selection_color, + .live = core.native_image_patches, + }; +} + +pub fn panPane( + core: *pardes.Pardes, + pane: *pardes.Pane, + axis: PanAxis, + direction: i8, + display_pixels: u32, +) PanResult { + if (comptime !enabled) return .unavailable; + const placed = paneGeometry(core, pane) orelse return .unavailable; + const state = &(pane.pdf orelse return .unavailable); + return panPixels(state, placed, axis, direction, display_pixels); +} + +pub fn scrollPane(core: *pardes.Pardes, pane: *pardes.Pane, delta_pixels: f64) bool { + if (comptime !enabled) return false; + const tz = tracy.zone(@src(), "pdf.scroll_notch"); + defer tz.end(); + const state = &(pane.pdf orelse return false); + const view = ensurePaneLayout(core, pane) orelse return false; + const result = scrollDocument(state, view, delta_pixels) orelse return false; + if (result.active_page != state.page) activatePage(core, pane, result.active_page, false); + return true; +} + +pub fn verticalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void { + if (comptime !enabled) return; + if (!core.native_images) return stepPanePage(core, pane, direction); + const rows: u32 = @intCast(@max(1, config.wheel_rows)); + const pixels = scaledStep(core.cell_pixels.h, rows); + _ = scrollPane(core, pane, @as(f64, @floatFromInt(pixels)) * direction); +} + +pub fn horizontalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void { + if (comptime !enabled) return; + const state = pane.pdf orelse return; + if (!core.native_images or state.fit != .height) return; + const cols: u32 = @intCast(@max(1, config.wheel_cols)); + _ = panPane(core, pane, .horizontal, direction, scaledStep(core.cell_pixels.w, cols)); +} + +pub fn draw( + core: *pardes.Pardes, + pane: *pardes.Pane, + rect: pardes.Rect, + pane_id: usize, + text_x: u16, + text_width: u16, +) bool { + if (comptime !enabled) return false; + if (!core.native_images or rect.h <= pardes.BOX_H) return false; + const state = &(pane.pdf orelse return false); + const view = paneViewport(core, pane) orelse return false; + const key = TintKey{ .mode = state.tint, .colors = tintColors(core) }; + const visible = renderFrame( + state, + core.pdf_gpa, + core.scratch.allocator(), + view, + pardes.pdf_raster_policy, + key, + highlightInput(core, pane_id, pane), + ); + var placed_any = false; + var page = visible.first; + const visible_end = visible.first + visible.len; + while (page < visible_end) : (page += 1) { + const placed = placedRaster(state, view, page) orelse continue; + const slot = rasterForPage(state, page).?; + const patch: ?pardes.ImagePatch = if (slot.patch_from != 0 and + slot.patch_rows.start < slot.patch_rows.end) + .{ + .from = slot.patch_from, + .y = @intCast(slot.patch_rows.start - slot.band_y), + .h = @intCast(slot.patch_rows.end - slot.patch_rows.start), + } + else + null; + if (!core.appendImagePlace(.{ + .pane = @intCast(pane_id), + .serial = pane.serial, + .native = .{ + .revision = placed.revision, + .page = @intCast(placed.page), + .fit = switch (placed.fit) { + .width => .width, + .height => .height, + }, + .pan_x = placed.pan_x, + .geometry = placed.geometry, + .pixel_offset_y = placed.pixel_offset_y, + .paper_bg = if (pardes.platform == .macos) + (if (key.mode == .disabled) .{ 255, 255, 255 } else key.colors.background) + else + null, + }, + .x = text_x, + // Below the notice chips, like an image: a placed page is + // drawn after the cells and would paint a chip out. + .y = core.bodyTop(rect) + pane.notices.span(), + .w = text_width, + .h = (rect.h -| pardes.BOX_H) -| pane.notices.span(), + .rgba = placed.rgba, + .iw = placed.width, + // The texture contains the retained band, not the full page. + .ih = placed.band_height, + .patch = patch, + })) break; + // A shell now holds (or will fetch whole) this revision. + slot.patch_from = slot.revision; + slot.patch_rows = .{ .start = 0, .end = 0 }; + placed_any = true; + } + if (!placed_any) return false; + + // This frame has spent the motion used to choose its raster band. + state.scroll_travel = 0; + const body_y = core.bodyTop(rect); + const body_h = rect.h -| pardes.BOX_H; + const chrome = core.chromeTheme(); + const theme = core.theme(); + const pane_bg: pardes.Color = if (theme.bg) |color| .{ .rgb = color } else .default; + // The rail runs past the notice bands; only the thumb tracks the text. + const rail_y = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; + core.surface.fill(rect.x, rail_y, 1, rect.h -| pardes.BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); + core.surface.fill(rect.x + 1, rail_y, 1, rect.h -| pardes.BOX_H, .{ .bg = pane_bg }); + + const track_h: usize = body_h; + const total = @max(@as(u64, 1), state.document_height); + const len = @max( + @as(usize, 1), + @as(usize, @intCast(@min( + @as(u64, track_h), + @as(u64, track_h) * view.pixel_h / total, + ))), + ); + const offset: u64 = @intFromFloat(@floor(state.document_scroll_y)); + const pos: usize = @intCast(@min( + @as(u64, track_h -| 1), + @as(u64, track_h) * offset / total, + )); + var y = pos; + while (y < track_h and y < pos + len) : (y += 1) + core.surface.fill( + rect.x, + body_y + @as(u16, @intCast(y)), + 1, + 1, + .{ .bg = .{ .rgb = chrome.scroll_thumb } }, + ); + return true; +} + +pub const SectionRows = if (enabled) struct { + pub fn usableDestination(destination: pdf.OutlineDestination) ?pdf.OutlineDestination { + return switch (destination) { + .internal => destination, + .external => |uri| if (safeHttpUri(uri)) destination else null, + .none => null, + }; + } + + fn safeHttpUri(uri: []const u8) bool { + // Effect.open_link is inline and cannot carry a larger URL. Omitting + // it here is preferable to rendering a row which can never act. + if (uri.len > 256) return false; + var has_scheme = false; + for (config.url_schemes) |scheme| { + if (std.mem.startsWith(u8, uri, scheme)) { + has_scheme = true; + break; + } + } + if (!has_scheme) return false; + for (uri) |byte| if (byte <= 0x20 or byte == 0x7f) return false; + return true; + } + + pub fn resolve(entries: []const pdf.OutlineEntry, ordinal: usize) ?pdf.OutlineDestination { + if (ordinal >= entries.len) return null; + const entry = entries[ordinal]; + if (entry.destination != .none) return usableDestination(entry.destination); + var i = ordinal + 1; + while (i < entries.len and entries[i].depth > entry.depth) : (i += 1) + if (usableDestination(entries[i].destination)) |destination| return destination; + return null; + } + + pub fn resolveOrdinals( + gpa: std.mem.Allocator, + entries: []const pdf.OutlineEntry, + ) ![]usize { + const unresolved = std.math.maxInt(usize); + const ordinals = try gpa.alloc(usize, entries.len); + @memset(ordinals, unresolved); + + const Pending = struct { depth: u8, ordinal: usize }; + var pending: [256]Pending = undefined; + var pending_len: usize = 0; + for (entries, 0..) |entry, ordinal| { + while (pending_len > 0 and pending[pending_len - 1].depth >= entry.depth) + pending_len -= 1; + + if (usableDestination(entry.destination) != null) { + ordinals[ordinal] = ordinal; + for (pending[0..pending_len]) |ancestor| + ordinals[ancestor.ordinal] = ordinal; + pending_len = 0; + } else if (entry.destination == .none) { + pending[pending_len] = .{ .depth = entry.depth, .ordinal = ordinal }; + pending_len += 1; + } + } + return ordinals; + } + + fn cleanTitle(out: ?[]u8, title: ?[]const u8) usize { + const raw = title orelse { + if (out) |buf| @memcpy(buf[0..10], "[untitled]"); + return 10; + }; + var at: usize = 0; + var i: usize = 0; + var wrote = false; + var pending_space = false; + while (i < raw.len) { + const n: usize = std.unicode.utf8ByteSequenceLength(raw[i]) catch { + pending_space = wrote; + i += 1; + continue; + }; + if (i + n > raw.len) { + pending_space = wrote; + break; + } + const cp = std.unicode.utf8Decode(raw[i .. i + n]) catch { + pending_space = wrote; + i += n; + continue; + }; + const whitespace_or_control = cp <= 0x20 or cp == 0x7f or + (cp >= 0x80 and cp <= 0x9f) or cp == 0x2028 or cp == 0x2029; + if (whitespace_or_control) { + pending_space = wrote; + } else { + if (pending_space) { + if (out) |buf| buf[at] = ' '; + at += 1; + } + if (out) |buf| @memcpy(buf[at..][0..n], raw[i .. i + n]); + at += n; + wrote = true; + pending_space = false; + } + i += n; + } + if (!wrote) { + if (out) |buf| @memcpy(buf[0..13], "[empty title]"); + return 13; + } + return at; + } + + pub fn render(gpa: std.mem.Allocator, path: []const u8, entries: []const pdf.OutlineEntry) ![]u8 { + const target = std.fs.path.basename(path); + const ordinals = try resolveOrdinals(gpa, entries); + defer gpa.free(ordinals); + var total: usize = 0; + for (entries, 0..) |entry, ordinal| { + const resolved = ordinals[ordinal]; + if (resolved == std.math.maxInt(usize)) continue; + const destination = usableDestination(entries[resolved].destination) orelse unreachable; + total += switch (destination) { + .internal => |internal| std.fmt.count("{s}:{d}:{d} ", .{ target, internal.page + 1, ordinal + 1 }), + .external => |uri| std.fmt.count("{s} ", .{uri}), + .none => unreachable, + }; + total += @as(usize, entry.depth) * 2 + cleanTitle(null, entry.title) + 1; + } + const out = try gpa.alloc(u8, total); + errdefer gpa.free(out); + var at: usize = 0; + for (entries, 0..) |entry, ordinal| { + const resolved = ordinals[ordinal]; + if (resolved == std.math.maxInt(usize)) continue; + const destination = usableDestination(entries[resolved].destination) orelse unreachable; + const prefix = switch (destination) { + .internal => |internal| try std.fmt.bufPrint(out[at..], "{s}:{d}:{d} ", .{ target, internal.page + 1, ordinal + 1 }), + .external => |uri| try std.fmt.bufPrint(out[at..], "{s} ", .{uri}), + .none => unreachable, + }; + at += prefix.len; + const indent = @as(usize, entry.depth) * 2; + @memset(out[at..][0..indent], ' '); + at += indent; + at += cleanTitle(out[at..], entry.title); + out[at] = '\n'; + at += 1; + } + return out; + } +} else struct {}; -- cgit v1.3 From fa5260c120268f1c1e3dbd2a17264e5896476576 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:44:52 -0300 Subject: Move the screen types out of pardes.zig into surface.zig Pure move: Color, FontRole, CellStyle, Cell, AsciiDiff, PanelCellDiff, ImageCacheKey, NativePlacement, ImagePatch, ImagePlace and Surface, with their eight tests, go verbatim to the new surface.zig with the imports they use. pardes.zig keeps one `pub const X = @import("surface.zig").X;` line per type, as it already does for Pane, Rect and the tag layers, so the shells' `pardes.Cell` / `pardes.Surface` spellings do not change. Surface.print, clearRect and overlayDash become pub because render calls them from pardes.zig. surface.zig is added to pardes.zig's test block and to the embedded source list. Co-Authored-By: Claude Opus 5.5 --- src/fs.zig | 1 + src/pardes.zig | 781 ++++++-------------------------------------------------- src/surface.zig | 647 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 730 insertions(+), 699 deletions(-) create mode 100644 src/surface.zig (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index 3dccdf7f..e1fe0b9c 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -36,6 +36,7 @@ else const source_files = [_]Source{ .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, + .{ .path = "src/surface.zig", .contents = @embedFile("surface.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/pardes.zig b/src/pardes.zig index 1159dd73..23cb1734 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,18 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +/// The screen types live in surface.zig; every shell names them through here. +pub const Color = @import("surface.zig").Color; +pub const FontRole = @import("surface.zig").FontRole; +pub const CellStyle = @import("surface.zig").CellStyle; +pub const Cell = @import("surface.zig").Cell; +pub const AsciiDiff = @import("surface.zig").AsciiDiff; +pub const PanelCellDiff = @import("surface.zig").PanelCellDiff; +pub const ImageCacheKey = @import("surface.zig").ImageCacheKey; +pub const NativePlacement = @import("surface.zig").NativePlacement; +pub const ImagePatch = @import("surface.zig").ImagePatch; +pub const ImagePlace = @import("surface.zig").ImagePlace; +pub const Surface = @import("surface.zig").Surface; pub const builtins = @import("builtins.zig"); const limits = memory.limits; const selection_pipe = @import("selection_pipe.zig"); @@ -413,6 +425,7 @@ pub const Loc = struct { }; test { + _ = @import("surface.zig"); _ = @import("body_layer.zig"); _ = @import("tag_layer.zig"); } @@ -3718,636 +3731,6 @@ const initial_chrome = ChromeTheme.fromTheme(&themes[0]); // ---- the boundary types ---- -pub const Color = union(enum) { default, index: u8, rgb: [3]u8 }; - -pub const FontRole = enum(u8) { body, tagline }; - -pub const CellStyle = struct { - fg: Color = .default, - bg: Color = .default, - bold: bool = false, - dim: bool = false, - italic: bool = false, - blink: bool = false, - reverse: bool = false, - invisible: bool = false, - strikethrough: bool = false, - ul: enum(u3) { off, single, double, curly, dotted, dashed } = .off, - font_role: FontRole = .body, -}; - -pub const Cell = struct { - text: [7]u8 = @splat(' '), - len: u8 = 1, - style: CellStyle = .{}, - default: bool = true, - /// The look-hover affordance is on this cell: the word under the pointer - /// is a real Look or Exec operand, and hosts that draw the quiet tint as - /// more than a flat fill — macOS renders it as a glass overlay — read - /// this instead of guessing from the background colour, which a real - /// selection shares. - hover: bool = false, - - pub fn grapheme(c: *const Cell) []const u8 { - return c.text[0..c.len]; - } - - pub fn visuallyEqual(a: *const Cell, b: *const Cell) bool { - if (a.default or b.default) return a.default and b.default; - return a.len == b.len and - std.mem.eql(u8, a.grapheme(), b.grapheme()) and - std.meta.eql(a.style, b.style); - } - - pub fn printableAscii(c: *const Cell) ?u8 { - if (c.default) return ' '; - if (c.len != 1) return null; - const byte = c.text[0]; - return if (byte >= ' ' and byte <= '~') byte else null; - } -}; - -pub const AsciiDiff = struct { - from: u8, - to: u8, - - /// Long printable-byte walks complete in about the same time as the other - /// panel effects. Extra distance is crossed by eased character skips. - pub const max_movement_frames = layout.ascii_max_movement_frames; - - pub fn between(old: *const Cell, new: *const Cell) ?AsciiDiff { - const from = old.printableAscii() orelse return null; - const to = new.printableAscii() orelse return null; - if (from == to) return null; - return .{ .from = from, .to = to }; - } - - pub fn distance(diff: AsciiDiff) u8 { - return if (diff.from < diff.to) diff.to - diff.from else diff.from - diff.to; - } - - pub fn movementFrames(diff: AsciiDiff) u16 { - return @min(@as(u16, diff.distance()), max_movement_frames); - } - - pub fn frameCount(diff: AsciiDiff) u16 { - return diff.movementFrames() + 1; - } - - pub fn byteAt(diff: AsciiDiff, frame: u16) u8 { - const movements: u32 = diff.movementFrames(); - const at: u32 = @min(@as(u32, frame), movements); - const delta: u8 = @intCast(easedDistance(diff.distance(), movements, at)); - return if (diff.from < diff.to) diff.from + delta else diff.from - delta; - } - - fn easedDistance(span: u8, movements: u32, at: u32) u32 { - if (movements == 0 or at >= movements) return span; - const n: u64 = at; - const d: u64 = movements; - const shape = n * n * n * (10 * d * d + 6 * n * n - 15 * d * n); - const denominator = d * d * d * d * d; - return @intCast((@as(u64, span) * shape + denominator / 2) / denominator); - } - - pub fn complete(diff: AsciiDiff, frame: u16) bool { - return diff.byteAt(frame) == diff.to; - } -}; - -pub const PanelCellDiff = union(enum) { - unchanged, - visual, - ascii: AsciiDiff, - - pub fn between(old: *const Cell, new: *const Cell) PanelCellDiff { - if (old.visuallyEqual(new)) return .unchanged; - if (AsciiDiff.between(old, new)) |diff| return .{ .ascii = diff }; - return .visual; - } - - pub fn changed(diff: PanelCellDiff) bool { - return diff != .unchanged; - } -}; - -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 "ASCII cell diffs ease long byte walks in both directions" { - var low: Cell = .{ .default = false }; - low.text[0] = 'A'; - var high: Cell = .{ .default = false }; - high.text[0] = 'F'; - - const rising = AsciiDiff.between(&low, &high).?; - try std.testing.expectEqual(@as(u16, 6), rising.frameCount()); - try std.testing.expectEqual(@as(u8, 'A'), rising.byteAt(0)); - try std.testing.expectEqual(@as(u8, 'A'), rising.byteAt(1)); - try std.testing.expectEqual(@as(u8, 'C'), rising.byteAt(2)); - try std.testing.expectEqual(@as(u8, 'F'), rising.byteAt(4)); - try std.testing.expectEqual(@as(u8, 'F'), rising.byteAt(500)); - - const falling = AsciiDiff.between(&high, &low).?; - try std.testing.expectEqual(@as(u8, 'D'), falling.byteAt(2)); - try std.testing.expectEqual(@as(u8, 'A'), falling.byteAt(4)); - - low.text[0] = ' '; - high.text[0] = '~'; - const long_rising = AsciiDiff.between(&low, &high).?; - try std.testing.expectEqual(@as(u16, 13), long_rising.frameCount()); - try std.testing.expectEqual(@as(u8, ' '), long_rising.byteAt(0)); - try std.testing.expectEqual(@as(u8, '#'), long_rising.byteAt(2)); - try std.testing.expectEqual(@as(u8, 'O'), long_rising.byteAt(6)); - try std.testing.expectEqual(@as(u8, '{'), long_rising.byteAt(10)); - try std.testing.expectEqual(@as(u8, '~'), long_rising.byteAt(12)); - - const long_falling = AsciiDiff.between(&high, &low).?; - try std.testing.expectEqual(@as(u8, 'O'), long_falling.byteAt(6)); - try std.testing.expectEqual(@as(u8, ' '), long_falling.byteAt(12)); - - // The shape itself is the contract: never backwards, and the widest step - // is in the middle of the walk rather than at either end. - var previous = long_rising.byteAt(0); - var first_step: u8 = 0; - var middle_step: u8 = 0; - var frame: u16 = 1; - while (frame <= long_rising.movementFrames()) : (frame += 1) { - const byte = long_rising.byteAt(frame); - try std.testing.expect(byte >= previous); - const step = byte - previous; - if (frame == 1) first_step = step; - if (frame == 6) middle_step = step; - previous = byte; - } - try std.testing.expect(middle_step > first_step); - try std.testing.expect(middle_step > long_rising.byteAt(12) - long_rising.byteAt(11)); -} - -test "ASCII diff classification skips stable and non-ASCII glyphs" { - var old: Cell = .{ .default = false }; - old.text[0] = 'x'; - var style_only = old; - style_only.style.bold = true; - try std.testing.expectEqual(PanelCellDiff.visual, PanelCellDiff.between(&old, &style_only)); - - var changed = old; - changed.text[0] = 'z'; - try std.testing.expectEqual(AsciiDiff{ .from = 'x', .to = 'z' }, PanelCellDiff.between(&old, &changed).ascii); - - var unicode = old; - unicode.text[0..2].* = .{ 0xc3, 0xa9 }; - unicode.len = 2; - try std.testing.expectEqual(PanelCellDiff.visual, PanelCellDiff.between(&old, &unicode)); -} - -pub const ImageCacheKey = if (pdf_enabled) struct { - serial: u32, - page: u32, - revision: u32, - - pub fn eql(a: @This(), b: @This()) bool { - return a.serial == b.serial and a.page == b.page and - a.revision == b.revision; - } -} else struct { - serial: u32, - - pub fn eql(a: @This(), b: @This()) bool { - return a.serial == b.serial; - } -}; - -const PdfFitMode = panes.Pdf.FitMode; -const PdfTintMode = panes.Pdf.TintMode; - -/// Dynamic placement exists only for native PDF pages. Static image panes need -/// only their pane identity, so feature-off builds carry a zero-bit payload. -pub const NativePlacement = if (pdf_enabled) struct { - revision: u32 = 0, - page: u32 = 0, - fit: image.NativeFit = .contain, - pan_x: u16 = 0, - pan_y: u16 = 0, - /// Continuous-document pages supply their already-clipped geometry. - /// Static images and legacy callers leave this null and derive fit/pan. - geometry: ?image.NativeGeometry = null, - /// Subpixel vertical displacement retained from proportional SDL wheel dy. - pixel_offset_y: f32 = 0, - /// Separate paper behind straight-alpha PDF content; null for other images. - paper_bg: ?[3]u8 = null, -} else struct {}; - -pub const ImagePatch = struct { from: u32, y: u32, h: u32 }; - -pub const ImagePlace = struct { - pane: u8, - /// Pane slots are reused. This identity makes a cached GPU texture or - /// kitty image unambiguously belong to the pane which supplied the bytes. - serial: u32, - native: NativePlacement = .{}, - x: u16, - y: u16, - w: u16, - h: u16, - rgba: []const u8, - iw: usize, - ih: usize, - /// Rows [y, y+h) of `rgba` are the only ones that differ from the - /// same pane page at revision `from`: a shell still holding that one may - /// update just these rows instead of taking the whole image again. - patch: ?ImagePatch = null, - - pub fn cacheKey(place: ImagePlace) ImageCacheKey { - if (comptime pdf_enabled) - return .{ - .serial = place.serial, - .page = place.native.page, - .revision = place.native.revision, - }; - return .{ .serial = place.serial }; - } -}; - -test "pixel attachment cache key follows both pane lifetime and rendered revision" { - if (comptime pdf_enabled) { - const first = ImageCacheKey{ .serial = 41, .page = 7, .revision = 3 }; - try std.testing.expect(first.eql(.{ .serial = 41, .page = 7, .revision = 3 })); - try std.testing.expect(!first.eql(.{ .serial = 41, .page = 8, .revision = 3 })); - try std.testing.expect(!first.eql(.{ .serial = 41, .page = 7, .revision = 4 })); - try std.testing.expect(!first.eql(.{ .serial = 42, .page = 7, .revision = 3 })); - } else { - const first = ImageCacheKey{ .serial = 41 }; - try std.testing.expect(first.eql(.{ .serial = 41 })); - try std.testing.expect(!first.eql(.{ .serial = 42 })); - } - try std.testing.expectEqual(pdf_enabled, @hasField(ImageCacheKey, "revision")); - try std.testing.expectEqual(pdf_enabled, @hasField(NativePlacement, "fit")); - try std.testing.expectEqual(pdf_enabled, @hasField(CellPixels, "w")); - if (comptime !pdf_enabled) { - try std.testing.expectEqual(@as(usize, 4), @sizeOf(ImageCacheKey)); - try std.testing.expectEqual(@as(usize, 0), @sizeOf(NativePlacement)); - try std.testing.expectEqual(@as(usize, 0), @sizeOf(CellPixels)); - try std.testing.expectEqual(@as(usize, 0), @sizeOf(panes.Pdf.PointerDrag)); - } -} - -test "pixel attachment fit and pan do not invalidate cached pixels" { - if (comptime !pdf_enabled) return; - var place = ImagePlace{ - .pane = 0, - .serial = 41, - .native = .{ .revision = 3 }, - .x = 0, - .y = 0, - .w = 1, - .h = 1, - .rgba = &.{ 0, 0, 0, 255 }, - .iw = 1, - .ih = 1, - }; - const key = place.cacheKey(); - place.native.fit = .width; - place.native.pan_x = 1234; - place.native.pan_y = 65535; - try std.testing.expect(key.eql(place.cacheKey())); -} - -/// The canonical interface: what a frame of pardes IS. The tty shell writes -/// these cells to vaxis one-to-one; the SDL shells rasterize them. -pub const Surface = struct { - pub const PointerShape = enum(u8) { arrow, link, target }; - pointer_shape: PointerShape = .arrow, - /// Set only for the duration of the look-hover paint, so the cells that - /// paint the quiet affordance can carry the hover bit through the ABI - /// without every selection painter learning a new parameter. - mark_hover: bool = false, - body_layers: [MAX_PANES]BodyLayer = @splat(.{}), - tag_layers: [MAX_TAG_LAYERS]TagLayer = @splat(.{}), - cols: u16 = 0, - rows: u16 = 0, - cells: []Cell = &.{}, - /// bar: draw an insert-style thin cursor instead of the block - cursor: ?struct { x: u16, y: u16, bar: bool = false } = null, - images: []?ImagePlace = &.{}, - nimages: usize = 0, - panel_tracks: [MAX_PANES * 2]layout.Track = undefined, - npanel_tracks: usize = 0, - previous_cells: []const Cell = &.{}, - previous_body_layers: []const BodyLayer = &.{}, - previous_tag_layers: []const TagLayer = &.{}, - cell_diffs: []const PanelCellDiff = &.{}, - - pub fn tagLayers(s: *const Surface) []const TagLayer { - return &s.tag_layers; - } - - pub fn bodyLayers(s: *const Surface) []const BodyLayer { - return &s.body_layers; - } - - pub fn panelTracks(s: *const Surface) []const layout.Track { - return s.panel_tracks[0..s.npanel_tracks]; - } - - pub fn hasPanelDiff(s: *const Surface) bool { - return s.previous_cells.len == s.cells.len and - s.cell_diffs.len == s.cells.len; - } - - pub fn panelCellChanged(s: *const Surface, x: u16, y: u16) bool { - if (!s.hasPanelDiff() or x >= s.cols or y >= s.rows) return false; - return s.cell_diffs[@as(usize, y) * s.cols + x].changed(); - } - - pub fn panelCellDiff(s: *const Surface, x: u16, y: u16) PanelCellDiff { - if (!s.hasPanelDiff() or x >= s.cols or y >= s.rows) return .unchanged; - return s.cell_diffs[@as(usize, y) * s.cols + x]; - } - - pub fn at(s: *Surface, x: u16, y: u16) *Cell { - std.debug.assert(x < s.cols and y < s.rows); - const cell = &s.cells[@as(usize, y) * s.cols + x]; - // The look-hover paint runs with mark_hover set, and its cells are - // exactly the ones this marks — see render's preview block. - if (s.mark_hover) cell.hover = true; - return cell; - } - - pub fn set(s: *Surface, x: u16, y: u16, text: []const u8, style: CellStyle) void { - const c = s.at(x, y); - std.debug.assert(text.len <= c.text.len); - @memcpy(c.text[0..text.len], text); - c.len = @intCast(text.len); - c.style = style; - c.default = false; - } - - fn print(s: *Surface, x: u16, y: u16, w: u16, text: []const u8, style: CellStyle) u16 { - var col = x; - const end = x + w; - var i: usize = 0; - while (i < text.len) { - if (col >= end) break; - { - const b = text[i]; - if (b >= 0x20 and b < 0x7f and (i + 1 == text.len or text[i + 1] < 0x80)) { - s.set(col, y, text[i .. i + 1], style); - i += 1; - col += 1; - continue; - } - } - if (col >= end) break; - // n == 0: not a start byte at all. A short tail or a bad - // continuation decodes to null the same way — one U+FFFD, one byte. - const n = std.unicode.utf8ByteSequenceLength(text[i]) catch 0; - const decoded: ?u21 = if (n > 0 and i + n <= text.len) - (std.unicode.utf8Decode(text[i .. i + n]) catch null) - else - null; - var cp_slice: []const u8 = "\u{FFFD}"; - var consumed: usize = 1; - if (decoded != null) { - var git = uucode.grapheme.utf8Iterator(text[i..]); - if (git.nextGrapheme()) |g| { - const candidate = text[i .. i + g.end]; - if (std.unicode.utf8ValidateSlice(candidate)) { - cp_slice = candidate; - consumed = candidate.len; - } else { - cp_slice = text[i .. i + n]; - consumed = n; - } - } - } - i += consumed; - var cp = decoded orelse 0xFFFD; - if (cp == '\r') continue; - if (cp == '\t') { - const spaces = @min(config.tab_width, end - col); - s.fill(col, y, spaces, 1, style); - col += spaces; - continue; - } - // No other C0/C1 control or DEL reaches a font fallback either. - if (cp < ' ' or cp == 0x7f or (cp >= 0x80 and cp <= 0x9f)) { - cp = 0xFFFD; - cp_slice = "\u{FFFD}"; - } - const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) - 1 - else - @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); - if (width == 2 and col + 1 >= end) break; - var shown = cp_slice; - if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { - const cap = @typeInfo(@FieldType(Cell, "text")).array.len; - var prefix: usize = 0; - while (prefix < shown.len) { - const cp_len = std.unicode.utf8ByteSequenceLength(shown[prefix]) catch break; - if (prefix + cp_len > cap) break; - prefix += cp_len; - } - shown = if (prefix > 0) shown[0..prefix] else "\u{FFFD}"; - } - s.set(col, y, shown, style); - if (width == 2 and col + 1 < end) { - // spacer: empty cell under the wide glyph's tail - s.set(col + 1, y, "", style); - } - col += width; - } - return col; - } - - pub fn fill(s: *Surface, x: u16, y: u16, w: u16, h: u16, style: CellStyle) void { - var yy = y; - while (yy < y + h) : (yy += 1) { - var xx = x; - while (xx < x + w) : (xx += 1) s.set(xx, yy, " ", style); - } - } - - fn clearRect(s: *Surface, x: u16, y: u16, w: u16, h: u16) void { - var yy = y; - while (yy < y + h) : (yy += 1) { - var xx = x; - while (xx < x + w) : (xx += 1) s.at(xx, yy).* = .{}; - } - } - - /// swap ONLY the glyph, keeping the cell's colors — the resize-handle hint - fn overlayDash(s: *Surface, x: u16, y: u16, glyph: []const u8) void { - const c = s.at(x, y); - @memcpy(c.text[0..glyph.len], glyph); - c.len = @intCast(glyph.len); - c.default = false; - } -}; - -test "surface print expands configured tabs and normalizes other controls" { - const tab_cells: usize = @as(usize, config.tab_width) * 2; - const replacement_cells = 5; - const cell_count = tab_cells + replacement_cells + 1; - var cells: [cell_count]Cell = @splat(.{}); - var surface = Surface{ .cols = cells.len, .rows = 1, .cells = &cells }; - - const end = surface.print(0, 0, cells.len, "\t\t\x00\x0b\x0c\r\x7f\xc2\x85A", .{}); - try std.testing.expectEqual(@as(u16, cells.len), end); - for (cells[0..tab_cells]) |cell| - try std.testing.expectEqualStrings(" ", cell.grapheme()); - for (cells[tab_cells .. tab_cells + replacement_cells]) |cell| - try std.testing.expectEqualStrings("\u{FFFD}", cell.grapheme()); - try std.testing.expectEqualStrings("A", cells[cell_count - 1].grapheme()); -} - -test "surface print keeps combining and wide graphemes in their display cells" { - var cells: [8]Cell = @splat(.{}); - var surface = Surface{ .cols = cells.len, .rows = 1, .cells = &cells }; - - const end = surface.print(0, 0, cells.len, "e\u{301}界👩🏽\u{200d}🚀1\u{fe0f}\u{20e3}A", .{}); - try std.testing.expectEqual(@as(u16, 8), end); - try std.testing.expectEqualStrings("e\u{301}", cells[0].grapheme()); - try std.testing.expectEqualStrings("界", cells[1].grapheme()); - try std.testing.expectEqualStrings("", cells[2].grapheme()); - try std.testing.expectEqualStrings("👩", cells[3].grapheme()); - try std.testing.expectEqualStrings("", cells[4].grapheme()); - try std.testing.expectEqualStrings("1\u{fe0f}\u{20e3}", cells[5].grapheme()); - try std.testing.expectEqualStrings("", cells[6].grapheme()); - try std.testing.expectEqualStrings("A", cells[7].grapheme()); -} - -test "the ASCII fast path in surface print paints what the general arm paints" { - const ref = struct { - fn print(s: *Surface, x: u16, y: u16, w: u16, text: []const u8, style: CellStyle) u16 { - var col = x; - const end = x + w; - var i: usize = 0; - while (i < text.len) { - if (col >= end) break; - const n = std.unicode.utf8ByteSequenceLength(text[i]) catch 0; - const decoded: ?u21 = if (n > 0 and i + n <= text.len) - (std.unicode.utf8Decode(text[i .. i + n]) catch null) - else - null; - var cp_slice: []const u8 = "\u{FFFD}"; - var consumed: usize = 1; - if (decoded != null) { - var git = uucode.grapheme.utf8Iterator(text[i..]); - if (git.nextGrapheme()) |g| { - const candidate = text[i .. i + g.end]; - if (std.unicode.utf8ValidateSlice(candidate)) { - cp_slice = candidate; - consumed = candidate.len; - } else { - cp_slice = text[i .. i + n]; - consumed = n; - } - } - } - i += consumed; - var cp = decoded orelse 0xFFFD; - if (cp == '\r') continue; - if (cp == '\t') { - const spaces = @min(config.tab_width, end - col); - s.fill(col, y, spaces, 1, style); - col += spaces; - continue; - } - if (cp < ' ' or cp == 0x7f or (cp >= 0x80 and cp <= 0x9f)) { - cp = 0xFFFD; - cp_slice = "\u{FFFD}"; - } - const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) - 1 - else - @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); - if (width == 2 and col + 1 >= end) break; - var shown = cp_slice; - if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { - const cap = @typeInfo(@FieldType(Cell, "text")).array.len; - var prefix: usize = 0; - while (prefix < shown.len) { - const cp_len = std.unicode.utf8ByteSequenceLength(shown[prefix]) catch break; - if (prefix + cp_len > cap) break; - prefix += cp_len; - } - shown = if (prefix > 0) shown[0..prefix] else "\u{FFFD}"; - } - s.set(col, y, shown, style); - if (width == 2 and col + 1 < end) s.set(col + 1, y, "", style); - col += width; - } - return col; - } - }.print; - - const H = struct { - fn check(text: []const u8) !void { - // Every width from 0 past the end, because clipping interacts with the fast path: the - // wide-glyph bail at the right edge is only reachable from the general arm. - var w: u16 = 0; - while (w <= text.len + 4) : (w += 1) { - var fast_cells: [64]Cell = @splat(.{}); - var slow_cells: [64]Cell = @splat(.{}); - var fast = Surface{ .cols = fast_cells.len, .rows = 1, .cells = &fast_cells }; - var slow = Surface{ .cols = slow_cells.len, .rows = 1, .cells = &slow_cells }; - const got = fast.print(0, 0, w, text, .{}); - const want = ref(&slow, 0, 0, w, text, .{}); - std.testing.expectEqual(want, got) catch |e| { - std.debug.print("print end column: {any} w={d}\n", .{ text, w }); - return e; - }; - for (fast_cells, slow_cells, 0..) |f, sc, col| { - std.testing.expectEqualStrings(sc.grapheme(), f.grapheme()) catch |e| { - std.debug.print("print cell {d}: {any} w={d}\n", .{ col, text, w }); - return e; - }; - try std.testing.expectEqual(sc.default, f.default); - } - } - } - }; - - const neighbours = [_][]const u8{ - "", "x", "\u{301}", "\u{200d}\u{1f680}", - "\u{903}", "\u{fe0f}", "\u{20e3}", "\u{4e16}", - "\u{1f642}", "\xff", "\xe4\xb8", "\xe4\x28\xb8", - "\u{1f1e6}\u{1f1e7}", - }; - // Every byte 0x20..0x7e takes the fast path; \t, \r, the rest of the C0 controls and DEL are - // excluded by its range test and must keep the general arm's tab expansion and U+FFFD. - var buf: [16]u8 = undefined; - var b: u8 = 0; - while (b < 0x80) : (b += 1) { - buf[0] = b; - for (neighbours) |tail| { - @memcpy(buf[1..][0..tail.len], tail); - try H.check(buf[0 .. 1 + tail.len]); - @memcpy(buf[0..tail.len], tail); - buf[tail.len] = b; - try H.check(buf[0 .. tail.len + 1]); - } - } - - // Runs long enough that the fast path starts, hands over and restarts inside one call. - try H.check("ascii \u{4e16}\u{754c} e\u{301} \xff ok\t\r!"); - try H.check("plain"); -} - test "insert and normal modes edit complete Unicode graphemes" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); @@ -6530,77 +5913,77 @@ pub const Pardes = struct { p.opts.mounts = &.{}; p.boot = Boot.of(opts); switch (p.boot) { - .document => { - const path = opts.file.?; - const opened = initial_doc: { - if (comptime pdf_enabled) if (look.isPdfPath(path)) - break :initial_doc panes.Pdf.openPane(p, 0, path, opts.file_line); - if (look.isImagePath(path)) - break :initial_doc panes.Image.create(p, 0, path, &.{}); - break :initial_doc panes.File.open(p, 0, path, opts.file_line); - }; - if (opened) |_| {} else |err| { - if (err == error.OutOfMemory) return err; - const why = switch (@as(anyerror, err)) { - error.PermissionDenied => "permission denied", - error.FileNotFound => "no file of that name", - error.IsDirectory => "that is a directory, and not one that could be read", - error.PathTooLong => "that path is too long", - error.FileTooLarge => "that file is too large to open", - error.NotAFile => "that is a pipe or a device, not a document", - else => @errorName(err), + .document => { + const path = opts.file.?; + const opened = initial_doc: { + if (comptime pdf_enabled) if (look.isPdfPath(path)) + break :initial_doc panes.Pdf.openPane(p, 0, path, opts.file_line); + if (look.isImagePath(path)) + break :initial_doc panes.Image.create(p, 0, path, &.{}); + break :initial_doc panes.File.open(p, 0, path, opts.file_line); }; - const content = try std.fmt.allocPrint(gpa, "cannot open\n\n\t{s}\n\n{s}\n", .{ path, why }); + if (opened) |_| {} else |err| { + if (err == error.OutOfMemory) return err; + const why = switch (@as(anyerror, err)) { + error.PermissionDenied => "permission denied", + error.FileNotFound => "no file of that name", + error.IsDirectory => "that is a directory, and not one that could be read", + error.PathTooLong => "that path is too long", + error.FileTooLarge => "that file is too large to open", + error.NotAFile => "that is a pipe or a device, not a document", + else => @errorName(err), + }; + const content = try std.fmt.allocPrint(gpa, "cannot open\n\n\t{s}\n\n{s}\n", .{ path, why }); + errdefer gpa.free(content); + _ = try panes.Output.open(p, 0, std.fs.path.dirname(path) orelse "/", .errors, "", content); + } + p.oneColumn(); + }, + .missing => { + const missing = opts.missing.?; + const content = try std.fmt.allocPrint( + gpa, + "file or directory not found\n\n\t{s}\n", + .{missing.word}, + ); errdefer gpa.free(content); - _ = try panes.Output.open(p, 0, std.fs.path.dirname(path) orelse "/", .errors, "", content); - } - p.oneColumn(); - }, - .missing => { - const missing = opts.missing.?; - const content = try std.fmt.allocPrint( - gpa, - "file or directory not found\n\n\t{s}\n", - .{missing.word}, - ); - errdefer gpa.free(content); - _ = try panes.Output.open(p, 0, missing.dir, .errors, "", content); - p.oneColumn(); - }, - .embedded => { - const content = try p.gpa.dupe(u8, boot_buffer); - errdefer p.gpa.free(content); - _ = try panes.Output.open(p, 0, "", .{ .cmd = .New }, "", content); - p.oneColumn(); - }, - .tty, .tty_shell => { - _ = try p.newShell(0, ""); - p.panes[0].?.mode = .tty; - p.oneColumn(); - // A bare tty is still an editor: it opens with somewhere to put - // text under the shell. The shell keeps the keyboard. - if (p.boot == .tty) { - p.newScratchBelow(0); - p.active = 0; - } - }, - .classic => { - _ = try p.newShell(0, ""); - _ = try p.newShell(1, ""); - _ = try p.newShell(2, ""); - for (p.panes[0..3]) |slot| slot.?.greet = true; - p.ncol = 2; - p.col_n[0] = 2; - p.col_panes[0][0] = 0; - p.col_panes[0][1] = 1; - p.col_n[1] = 1; - p.col_panes[1][0] = 2; - }, - .shell => { - _ = try p.newShell(0, ""); - p.panes[0].?.greet = true; - p.oneColumn(); - }, + _ = try panes.Output.open(p, 0, missing.dir, .errors, "", content); + p.oneColumn(); + }, + .embedded => { + const content = try p.gpa.dupe(u8, boot_buffer); + errdefer p.gpa.free(content); + _ = try panes.Output.open(p, 0, "", .{ .cmd = .New }, "", content); + p.oneColumn(); + }, + .tty, .tty_shell => { + _ = try p.newShell(0, ""); + p.panes[0].?.mode = .tty; + p.oneColumn(); + // A bare tty is still an editor: it opens with somewhere to put + // text under the shell. The shell keeps the keyboard. + if (p.boot == .tty) { + p.newScratchBelow(0); + p.active = 0; + } + }, + .classic => { + _ = try p.newShell(0, ""); + _ = try p.newShell(1, ""); + _ = try p.newShell(2, ""); + for (p.panes[0..3]) |slot| slot.?.greet = true; + p.ncol = 2; + p.col_n[0] = 2; + p.col_panes[0][0] = 0; + p.col_panes[0][1] = 1; + p.col_n[1] = 1; + p.col_panes[1][0] = 2; + }, + .shell => { + _ = try p.newShell(0, ""); + p.panes[0].?.greet = true; + p.oneColumn(); + }, } p.sync(); p.applyStartupConfig(); diff --git a/src/surface.zig b/src/surface.zig new file mode 100644 index 00000000..a9e69cca --- /dev/null +++ b/src/surface.zig @@ -0,0 +1,647 @@ +//! The canonical screen every shell draws: cells, their styles and diffs, +//! the image placements laid over them, and the Surface that holds a frame. +const pardes = @import("pardes.zig"); +const std = @import("std"); +const layout = @import("layout.zig"); +const uucode = @import("uucode"); +const vaxis = @import("vaxis"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const pdf_enabled = panes.Pdf.enabled; +const image = @import("image.zig"); +const MAX_PANES = pardes.MAX_PANES; +const BodyLayer = @import("body_layer.zig").Layer; +const TagLayer = @import("tag_layer.zig").Layer; +const MAX_TAG_LAYERS = pardes.MAX_TAG_LAYERS; +const CellPixels = pardes.CellPixels; + +pub const Color = union(enum) { default, index: u8, rgb: [3]u8 }; + +pub const FontRole = enum(u8) { body, tagline }; + +pub const CellStyle = struct { + fg: Color = .default, + bg: Color = .default, + bold: bool = false, + dim: bool = false, + italic: bool = false, + blink: bool = false, + reverse: bool = false, + invisible: bool = false, + strikethrough: bool = false, + ul: enum(u3) { off, single, double, curly, dotted, dashed } = .off, + font_role: FontRole = .body, +}; + +pub const Cell = struct { + text: [7]u8 = @splat(' '), + len: u8 = 1, + style: CellStyle = .{}, + default: bool = true, + /// The look-hover affordance is on this cell: the word under the pointer + /// is a real Look or Exec operand, and hosts that draw the quiet tint as + /// more than a flat fill — macOS renders it as a glass overlay — read + /// this instead of guessing from the background colour, which a real + /// selection shares. + hover: bool = false, + + pub fn grapheme(c: *const Cell) []const u8 { + return c.text[0..c.len]; + } + + pub fn visuallyEqual(a: *const Cell, b: *const Cell) bool { + if (a.default or b.default) return a.default and b.default; + return a.len == b.len and + std.mem.eql(u8, a.grapheme(), b.grapheme()) and + std.meta.eql(a.style, b.style); + } + + pub fn printableAscii(c: *const Cell) ?u8 { + if (c.default) return ' '; + if (c.len != 1) return null; + const byte = c.text[0]; + return if (byte >= ' ' and byte <= '~') byte else null; + } +}; + +pub const AsciiDiff = struct { + from: u8, + to: u8, + + /// Long printable-byte walks complete in about the same time as the other + /// panel effects. Extra distance is crossed by eased character skips. + pub const max_movement_frames = layout.ascii_max_movement_frames; + + pub fn between(old: *const Cell, new: *const Cell) ?AsciiDiff { + const from = old.printableAscii() orelse return null; + const to = new.printableAscii() orelse return null; + if (from == to) return null; + return .{ .from = from, .to = to }; + } + + pub fn distance(diff: AsciiDiff) u8 { + return if (diff.from < diff.to) diff.to - diff.from else diff.from - diff.to; + } + + pub fn movementFrames(diff: AsciiDiff) u16 { + return @min(@as(u16, diff.distance()), max_movement_frames); + } + + pub fn frameCount(diff: AsciiDiff) u16 { + return diff.movementFrames() + 1; + } + + pub fn byteAt(diff: AsciiDiff, frame: u16) u8 { + const movements: u32 = diff.movementFrames(); + const at: u32 = @min(@as(u32, frame), movements); + const delta: u8 = @intCast(easedDistance(diff.distance(), movements, at)); + return if (diff.from < diff.to) diff.from + delta else diff.from - delta; + } + + fn easedDistance(span: u8, movements: u32, at: u32) u32 { + if (movements == 0 or at >= movements) return span; + const n: u64 = at; + const d: u64 = movements; + const shape = n * n * n * (10 * d * d + 6 * n * n - 15 * d * n); + const denominator = d * d * d * d * d; + return @intCast((@as(u64, span) * shape + denominator / 2) / denominator); + } + + pub fn complete(diff: AsciiDiff, frame: u16) bool { + return diff.byteAt(frame) == diff.to; + } +}; + +pub const PanelCellDiff = union(enum) { + unchanged, + visual, + ascii: AsciiDiff, + + pub fn between(old: *const Cell, new: *const Cell) PanelCellDiff { + if (old.visuallyEqual(new)) return .unchanged; + if (AsciiDiff.between(old, new)) |diff| return .{ .ascii = diff }; + return .visual; + } + + pub fn changed(diff: PanelCellDiff) bool { + return diff != .unchanged; + } +}; + +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 "ASCII cell diffs ease long byte walks in both directions" { + var low: Cell = .{ .default = false }; + low.text[0] = 'A'; + var high: Cell = .{ .default = false }; + high.text[0] = 'F'; + + const rising = AsciiDiff.between(&low, &high).?; + try std.testing.expectEqual(@as(u16, 6), rising.frameCount()); + try std.testing.expectEqual(@as(u8, 'A'), rising.byteAt(0)); + try std.testing.expectEqual(@as(u8, 'A'), rising.byteAt(1)); + try std.testing.expectEqual(@as(u8, 'C'), rising.byteAt(2)); + try std.testing.expectEqual(@as(u8, 'F'), rising.byteAt(4)); + try std.testing.expectEqual(@as(u8, 'F'), rising.byteAt(500)); + + const falling = AsciiDiff.between(&high, &low).?; + try std.testing.expectEqual(@as(u8, 'D'), falling.byteAt(2)); + try std.testing.expectEqual(@as(u8, 'A'), falling.byteAt(4)); + + low.text[0] = ' '; + high.text[0] = '~'; + const long_rising = AsciiDiff.between(&low, &high).?; + try std.testing.expectEqual(@as(u16, 13), long_rising.frameCount()); + try std.testing.expectEqual(@as(u8, ' '), long_rising.byteAt(0)); + try std.testing.expectEqual(@as(u8, '#'), long_rising.byteAt(2)); + try std.testing.expectEqual(@as(u8, 'O'), long_rising.byteAt(6)); + try std.testing.expectEqual(@as(u8, '{'), long_rising.byteAt(10)); + try std.testing.expectEqual(@as(u8, '~'), long_rising.byteAt(12)); + + const long_falling = AsciiDiff.between(&high, &low).?; + try std.testing.expectEqual(@as(u8, 'O'), long_falling.byteAt(6)); + try std.testing.expectEqual(@as(u8, ' '), long_falling.byteAt(12)); + + // The shape itself is the contract: never backwards, and the widest step + // is in the middle of the walk rather than at either end. + var previous = long_rising.byteAt(0); + var first_step: u8 = 0; + var middle_step: u8 = 0; + var frame: u16 = 1; + while (frame <= long_rising.movementFrames()) : (frame += 1) { + const byte = long_rising.byteAt(frame); + try std.testing.expect(byte >= previous); + const step = byte - previous; + if (frame == 1) first_step = step; + if (frame == 6) middle_step = step; + previous = byte; + } + try std.testing.expect(middle_step > first_step); + try std.testing.expect(middle_step > long_rising.byteAt(12) - long_rising.byteAt(11)); +} + +test "ASCII diff classification skips stable and non-ASCII glyphs" { + var old: Cell = .{ .default = false }; + old.text[0] = 'x'; + var style_only = old; + style_only.style.bold = true; + try std.testing.expectEqual(PanelCellDiff.visual, PanelCellDiff.between(&old, &style_only)); + + var changed = old; + changed.text[0] = 'z'; + try std.testing.expectEqual(AsciiDiff{ .from = 'x', .to = 'z' }, PanelCellDiff.between(&old, &changed).ascii); + + var unicode = old; + unicode.text[0..2].* = .{ 0xc3, 0xa9 }; + unicode.len = 2; + try std.testing.expectEqual(PanelCellDiff.visual, PanelCellDiff.between(&old, &unicode)); +} + +pub const ImageCacheKey = if (pdf_enabled) struct { + serial: u32, + page: u32, + revision: u32, + + pub fn eql(a: @This(), b: @This()) bool { + return a.serial == b.serial and a.page == b.page and + a.revision == b.revision; + } +} else struct { + serial: u32, + + pub fn eql(a: @This(), b: @This()) bool { + return a.serial == b.serial; + } +}; + +const PdfFitMode = panes.Pdf.FitMode; + +const PdfTintMode = panes.Pdf.TintMode; + +/// Dynamic placement exists only for native PDF pages. Static image panes need +/// only their pane identity, so feature-off builds carry a zero-bit payload. +pub const NativePlacement = if (pdf_enabled) struct { + revision: u32 = 0, + page: u32 = 0, + fit: image.NativeFit = .contain, + pan_x: u16 = 0, + pan_y: u16 = 0, + /// Continuous-document pages supply their already-clipped geometry. + /// Static images and legacy callers leave this null and derive fit/pan. + geometry: ?image.NativeGeometry = null, + /// Subpixel vertical displacement retained from proportional SDL wheel dy. + pixel_offset_y: f32 = 0, + /// Separate paper behind straight-alpha PDF content; null for other images. + paper_bg: ?[3]u8 = null, +} else struct {}; + +pub const ImagePatch = struct { from: u32, y: u32, h: u32 }; + +pub const ImagePlace = struct { + pane: u8, + /// Pane slots are reused. This identity makes a cached GPU texture or + /// kitty image unambiguously belong to the pane which supplied the bytes. + serial: u32, + native: NativePlacement = .{}, + x: u16, + y: u16, + w: u16, + h: u16, + rgba: []const u8, + iw: usize, + ih: usize, + /// Rows [y, y+h) of `rgba` are the only ones that differ from the + /// same pane page at revision `from`: a shell still holding that one may + /// update just these rows instead of taking the whole image again. + patch: ?ImagePatch = null, + + pub fn cacheKey(place: ImagePlace) ImageCacheKey { + if (comptime pdf_enabled) + return .{ + .serial = place.serial, + .page = place.native.page, + .revision = place.native.revision, + }; + return .{ .serial = place.serial }; + } +}; + +test "pixel attachment cache key follows both pane lifetime and rendered revision" { + if (comptime pdf_enabled) { + const first = ImageCacheKey{ .serial = 41, .page = 7, .revision = 3 }; + try std.testing.expect(first.eql(.{ .serial = 41, .page = 7, .revision = 3 })); + try std.testing.expect(!first.eql(.{ .serial = 41, .page = 8, .revision = 3 })); + try std.testing.expect(!first.eql(.{ .serial = 41, .page = 7, .revision = 4 })); + try std.testing.expect(!first.eql(.{ .serial = 42, .page = 7, .revision = 3 })); + } else { + const first = ImageCacheKey{ .serial = 41 }; + try std.testing.expect(first.eql(.{ .serial = 41 })); + try std.testing.expect(!first.eql(.{ .serial = 42 })); + } + try std.testing.expectEqual(pdf_enabled, @hasField(ImageCacheKey, "revision")); + try std.testing.expectEqual(pdf_enabled, @hasField(NativePlacement, "fit")); + try std.testing.expectEqual(pdf_enabled, @hasField(CellPixels, "w")); + if (comptime !pdf_enabled) { + try std.testing.expectEqual(@as(usize, 4), @sizeOf(ImageCacheKey)); + try std.testing.expectEqual(@as(usize, 0), @sizeOf(NativePlacement)); + try std.testing.expectEqual(@as(usize, 0), @sizeOf(CellPixels)); + try std.testing.expectEqual(@as(usize, 0), @sizeOf(panes.Pdf.PointerDrag)); + } +} + +test "pixel attachment fit and pan do not invalidate cached pixels" { + if (comptime !pdf_enabled) return; + var place = ImagePlace{ + .pane = 0, + .serial = 41, + .native = .{ .revision = 3 }, + .x = 0, + .y = 0, + .w = 1, + .h = 1, + .rgba = &.{ 0, 0, 0, 255 }, + .iw = 1, + .ih = 1, + }; + const key = place.cacheKey(); + place.native.fit = .width; + place.native.pan_x = 1234; + place.native.pan_y = 65535; + try std.testing.expect(key.eql(place.cacheKey())); +} + +/// The canonical interface: what a frame of pardes IS. The tty shell writes +/// these cells to vaxis one-to-one; the SDL shells rasterize them. +pub const Surface = struct { + pub const PointerShape = enum(u8) { arrow, link, target }; + pointer_shape: PointerShape = .arrow, + /// Set only for the duration of the look-hover paint, so the cells that + /// paint the quiet affordance can carry the hover bit through the ABI + /// without every selection painter learning a new parameter. + mark_hover: bool = false, + body_layers: [MAX_PANES]BodyLayer = @splat(.{}), + tag_layers: [MAX_TAG_LAYERS]TagLayer = @splat(.{}), + cols: u16 = 0, + rows: u16 = 0, + cells: []Cell = &.{}, + /// bar: draw an insert-style thin cursor instead of the block + cursor: ?struct { x: u16, y: u16, bar: bool = false } = null, + images: []?ImagePlace = &.{}, + nimages: usize = 0, + panel_tracks: [MAX_PANES * 2]layout.Track = undefined, + npanel_tracks: usize = 0, + previous_cells: []const Cell = &.{}, + previous_body_layers: []const BodyLayer = &.{}, + previous_tag_layers: []const TagLayer = &.{}, + cell_diffs: []const PanelCellDiff = &.{}, + + pub fn tagLayers(s: *const Surface) []const TagLayer { + return &s.tag_layers; + } + + pub fn bodyLayers(s: *const Surface) []const BodyLayer { + return &s.body_layers; + } + + pub fn panelTracks(s: *const Surface) []const layout.Track { + return s.panel_tracks[0..s.npanel_tracks]; + } + + pub fn hasPanelDiff(s: *const Surface) bool { + return s.previous_cells.len == s.cells.len and + s.cell_diffs.len == s.cells.len; + } + + pub fn panelCellChanged(s: *const Surface, x: u16, y: u16) bool { + if (!s.hasPanelDiff() or x >= s.cols or y >= s.rows) return false; + return s.cell_diffs[@as(usize, y) * s.cols + x].changed(); + } + + pub fn panelCellDiff(s: *const Surface, x: u16, y: u16) PanelCellDiff { + if (!s.hasPanelDiff() or x >= s.cols or y >= s.rows) return .unchanged; + return s.cell_diffs[@as(usize, y) * s.cols + x]; + } + + pub fn at(s: *Surface, x: u16, y: u16) *Cell { + std.debug.assert(x < s.cols and y < s.rows); + const cell = &s.cells[@as(usize, y) * s.cols + x]; + // The look-hover paint runs with mark_hover set, and its cells are + // exactly the ones this marks — see render's preview block. + if (s.mark_hover) cell.hover = true; + return cell; + } + + pub fn set(s: *Surface, x: u16, y: u16, text: []const u8, style: CellStyle) void { + const c = s.at(x, y); + std.debug.assert(text.len <= c.text.len); + @memcpy(c.text[0..text.len], text); + c.len = @intCast(text.len); + c.style = style; + c.default = false; + } + + pub fn print(s: *Surface, x: u16, y: u16, w: u16, text: []const u8, style: CellStyle) u16 { + var col = x; + const end = x + w; + var i: usize = 0; + while (i < text.len) { + if (col >= end) break; + { + const b = text[i]; + if (b >= 0x20 and b < 0x7f and (i + 1 == text.len or text[i + 1] < 0x80)) { + s.set(col, y, text[i .. i + 1], style); + i += 1; + col += 1; + continue; + } + } + if (col >= end) break; + // n == 0: not a start byte at all. A short tail or a bad + // continuation decodes to null the same way — one U+FFFD, one byte. + const n = std.unicode.utf8ByteSequenceLength(text[i]) catch 0; + const decoded: ?u21 = if (n > 0 and i + n <= text.len) + (std.unicode.utf8Decode(text[i .. i + n]) catch null) + else + null; + var cp_slice: []const u8 = "\u{FFFD}"; + var consumed: usize = 1; + if (decoded != null) { + var git = uucode.grapheme.utf8Iterator(text[i..]); + if (git.nextGrapheme()) |g| { + const candidate = text[i .. i + g.end]; + if (std.unicode.utf8ValidateSlice(candidate)) { + cp_slice = candidate; + consumed = candidate.len; + } else { + cp_slice = text[i .. i + n]; + consumed = n; + } + } + } + i += consumed; + var cp = decoded orelse 0xFFFD; + if (cp == '\r') continue; + if (cp == '\t') { + const spaces = @min(config.tab_width, end - col); + s.fill(col, y, spaces, 1, style); + col += spaces; + continue; + } + // No other C0/C1 control or DEL reaches a font fallback either. + if (cp < ' ' or cp == 0x7f or (cp >= 0x80 and cp <= 0x9f)) { + cp = 0xFFFD; + cp_slice = "\u{FFFD}"; + } + const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) + 1 + else + @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); + if (width == 2 and col + 1 >= end) break; + var shown = cp_slice; + if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { + const cap = @typeInfo(@FieldType(Cell, "text")).array.len; + var prefix: usize = 0; + while (prefix < shown.len) { + const cp_len = std.unicode.utf8ByteSequenceLength(shown[prefix]) catch break; + if (prefix + cp_len > cap) break; + prefix += cp_len; + } + shown = if (prefix > 0) shown[0..prefix] else "\u{FFFD}"; + } + s.set(col, y, shown, style); + if (width == 2 and col + 1 < end) { + // spacer: empty cell under the wide glyph's tail + s.set(col + 1, y, "", style); + } + col += width; + } + return col; + } + + pub fn fill(s: *Surface, x: u16, y: u16, w: u16, h: u16, style: CellStyle) void { + var yy = y; + while (yy < y + h) : (yy += 1) { + var xx = x; + while (xx < x + w) : (xx += 1) s.set(xx, yy, " ", style); + } + } + + pub fn clearRect(s: *Surface, x: u16, y: u16, w: u16, h: u16) void { + var yy = y; + while (yy < y + h) : (yy += 1) { + var xx = x; + while (xx < x + w) : (xx += 1) s.at(xx, yy).* = .{}; + } + } + + /// swap ONLY the glyph, keeping the cell's colors — the resize-handle hint + pub fn overlayDash(s: *Surface, x: u16, y: u16, glyph: []const u8) void { + const c = s.at(x, y); + @memcpy(c.text[0..glyph.len], glyph); + c.len = @intCast(glyph.len); + c.default = false; + } +}; + +test "surface print expands configured tabs and normalizes other controls" { + const tab_cells: usize = @as(usize, config.tab_width) * 2; + const replacement_cells = 5; + const cell_count = tab_cells + replacement_cells + 1; + var cells: [cell_count]Cell = @splat(.{}); + var surface = Surface{ .cols = cells.len, .rows = 1, .cells = &cells }; + + const end = surface.print(0, 0, cells.len, "\t\t\x00\x0b\x0c\r\x7f\xc2\x85A", .{}); + try std.testing.expectEqual(@as(u16, cells.len), end); + for (cells[0..tab_cells]) |cell| + try std.testing.expectEqualStrings(" ", cell.grapheme()); + for (cells[tab_cells .. tab_cells + replacement_cells]) |cell| + try std.testing.expectEqualStrings("\u{FFFD}", cell.grapheme()); + try std.testing.expectEqualStrings("A", cells[cell_count - 1].grapheme()); +} + +test "surface print keeps combining and wide graphemes in their display cells" { + var cells: [8]Cell = @splat(.{}); + var surface = Surface{ .cols = cells.len, .rows = 1, .cells = &cells }; + + const end = surface.print(0, 0, cells.len, "e\u{301}界👩🏽\u{200d}🚀1\u{fe0f}\u{20e3}A", .{}); + try std.testing.expectEqual(@as(u16, 8), end); + try std.testing.expectEqualStrings("e\u{301}", cells[0].grapheme()); + try std.testing.expectEqualStrings("界", cells[1].grapheme()); + try std.testing.expectEqualStrings("", cells[2].grapheme()); + try std.testing.expectEqualStrings("👩", cells[3].grapheme()); + try std.testing.expectEqualStrings("", cells[4].grapheme()); + try std.testing.expectEqualStrings("1\u{fe0f}\u{20e3}", cells[5].grapheme()); + try std.testing.expectEqualStrings("", cells[6].grapheme()); + try std.testing.expectEqualStrings("A", cells[7].grapheme()); +} + +test "the ASCII fast path in surface print paints what the general arm paints" { + const ref = struct { + fn print(s: *Surface, x: u16, y: u16, w: u16, text: []const u8, style: CellStyle) u16 { + var col = x; + const end = x + w; + var i: usize = 0; + while (i < text.len) { + if (col >= end) break; + const n = std.unicode.utf8ByteSequenceLength(text[i]) catch 0; + const decoded: ?u21 = if (n > 0 and i + n <= text.len) + (std.unicode.utf8Decode(text[i .. i + n]) catch null) + else + null; + var cp_slice: []const u8 = "\u{FFFD}"; + var consumed: usize = 1; + if (decoded != null) { + var git = uucode.grapheme.utf8Iterator(text[i..]); + if (git.nextGrapheme()) |g| { + const candidate = text[i .. i + g.end]; + if (std.unicode.utf8ValidateSlice(candidate)) { + cp_slice = candidate; + consumed = candidate.len; + } else { + cp_slice = text[i .. i + n]; + consumed = n; + } + } + } + i += consumed; + var cp = decoded orelse 0xFFFD; + if (cp == '\r') continue; + if (cp == '\t') { + const spaces = @min(config.tab_width, end - col); + s.fill(col, y, spaces, 1, style); + col += spaces; + continue; + } + if (cp < ' ' or cp == 0x7f or (cp >= 0x80 and cp <= 0x9f)) { + cp = 0xFFFD; + cp_slice = "\u{FFFD}"; + } + const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) + 1 + else + @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); + if (width == 2 and col + 1 >= end) break; + var shown = cp_slice; + if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { + const cap = @typeInfo(@FieldType(Cell, "text")).array.len; + var prefix: usize = 0; + while (prefix < shown.len) { + const cp_len = std.unicode.utf8ByteSequenceLength(shown[prefix]) catch break; + if (prefix + cp_len > cap) break; + prefix += cp_len; + } + shown = if (prefix > 0) shown[0..prefix] else "\u{FFFD}"; + } + s.set(col, y, shown, style); + if (width == 2 and col + 1 < end) s.set(col + 1, y, "", style); + col += width; + } + return col; + } + }.print; + + const H = struct { + fn check(text: []const u8) !void { + // Every width from 0 past the end, because clipping interacts with the fast path: the + // wide-glyph bail at the right edge is only reachable from the general arm. + var w: u16 = 0; + while (w <= text.len + 4) : (w += 1) { + var fast_cells: [64]Cell = @splat(.{}); + var slow_cells: [64]Cell = @splat(.{}); + var fast = Surface{ .cols = fast_cells.len, .rows = 1, .cells = &fast_cells }; + var slow = Surface{ .cols = slow_cells.len, .rows = 1, .cells = &slow_cells }; + const got = fast.print(0, 0, w, text, .{}); + const want = ref(&slow, 0, 0, w, text, .{}); + std.testing.expectEqual(want, got) catch |e| { + std.debug.print("print end column: {any} w={d}\n", .{ text, w }); + return e; + }; + for (fast_cells, slow_cells, 0..) |f, sc, col| { + std.testing.expectEqualStrings(sc.grapheme(), f.grapheme()) catch |e| { + std.debug.print("print cell {d}: {any} w={d}\n", .{ col, text, w }); + return e; + }; + try std.testing.expectEqual(sc.default, f.default); + } + } + } + }; + + const neighbours = [_][]const u8{ + "", "x", "\u{301}", "\u{200d}\u{1f680}", + "\u{903}", "\u{fe0f}", "\u{20e3}", "\u{4e16}", + "\u{1f642}", "\xff", "\xe4\xb8", "\xe4\x28\xb8", + "\u{1f1e6}\u{1f1e7}", + }; + // Every byte 0x20..0x7e takes the fast path; \t, \r, the rest of the C0 controls and DEL are + // excluded by its range test and must keep the general arm's tab expansion and U+FFFD. + var buf: [16]u8 = undefined; + var b: u8 = 0; + while (b < 0x80) : (b += 1) { + buf[0] = b; + for (neighbours) |tail| { + @memcpy(buf[1..][0..tail.len], tail); + try H.check(buf[0 .. 1 + tail.len]); + @memcpy(buf[0..tail.len], tail); + buf[tail.len] = b; + try H.check(buf[0 .. tail.len + 1]); + } + } + + // Runs long enough that the fast path starts, hands over and restarts inside one call. + try H.check("ascii \u{4e16}\u{754c} e\u{301} \xff ok\t\r!"); + try H.check("plain"); +} -- cgit v1.3 From 41bbbd05dccb02631ed785d19ed54fb4edfcc471 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:49:28 -0300 Subject: Move colour themes out of pardes.zig into colors.zig Pure move, no behaviour change: the Theme type, the curated palettes, fold and the themes ring with its two comptime checks, themeContrast, mix, ChromeTheme, ChromeAnimation and initial_chrome, the Pardes methods that load theme files and switch themes (nextThemeFileGeneration, requestThemeFile, ThemeFileRequest, themeFileRequest, failThemeFile, loadThemeFile, finishThemeInitialization, invalidateThemeDependentRasters, setThemeIndex), and the ten theme tests go verbatim to colors.zig. The methods become free functions taking `p: *Pardes`; their call sites change from `p.setThemeIndex(i)` to `colors.setThemeIndex(p, i)` (37 of them, in pardes.zig, builtins.zig, file_watch.zig, macos.zig and two test files). pardes.zig keeps `pub const Theme/themes/native_theme_count/ ChromeTheme = colors.X;` for the shells that name them, and sync and enterTagEdit become pub because a moved test calls them. Co-Authored-By: Claude Opus 5.5 --- src/builtins.zig | 5 +- src/colors.zig | 681 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/file_watch.zig | 15 +- src/fs.zig | 1 + src/macos.zig | 13 +- src/pardes.zig | 700 ++--------------------------------------------------- test/output.zig | 2 +- test/pdf.zig | 6 +- 8 files changed, 725 insertions(+), 698 deletions(-) create mode 100644 src/colors.zig (limited to 'src/fs.zig') diff --git a/src/builtins.zig b/src/builtins.zig index ac336ce0..ad2c5f6a 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1,6 +1,7 @@ //! Command structs and runtime settings form the builtin registry; bindings live in config.zig. const std = @import("std"); const pardes = @import("pardes.zig"); +const colors = @import("colors.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; const panes = @import("panes.zig"); @@ -304,7 +305,7 @@ pub const Msg = struct { pub const NextColor = struct { pub fn run(c: Ctx) void { - c.p.setThemeIndex((@as(usize, c.p.settings.theme) + 1) % pardes.themes.len); + colors.setThemeIndex(c.p, (@as(usize, c.p.settings.theme) + 1) % pardes.themes.len); } }; @@ -320,7 +321,7 @@ pub const ThemeFile = struct { pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime enabled) - c.p.requestThemeFile(c.id, c.arg orelse return) + colors.requestThemeFile(c.p, c.id, c.arg orelse return) else unreachable; } diff --git a/src/colors.zig b/src/colors.zig new file mode 100644 index 00000000..d6e1d535 --- /dev/null +++ b/src/colors.zig @@ -0,0 +1,681 @@ +//! Colour themes: the Theme type, the curated and generated ring, chrome +//! colours and their animation, theme files, and switching themes at runtime. +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const std = @import("std"); +const layout = @import("layout.zig"); +const Color = @import("surface.zig").Color; +const FontRole = @import("surface.zig").FontRole; +const config = @import("config.zig"); +const pdf_enabled = panes.Pdf.enabled; +const platform = pardes.platform; +const theme_animation = @import("pardes_config").theme_animation; +const hosted = pardes.hosted; +const MAX_PANES = pardes.MAX_PANES; +const BOX_H = pardes.BOX_H; +const Pardes = pardes.Pardes; + +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); + return out; +} + +pub const Theme = struct { + name: []const u8, + bg: ?[3]u8, + fg: ?[3]u8, + sel_bg: [3]u8, + sel_fg: [3]u8, + tag_bg: [3]u8, + tag_fg: [3]u8, + box: [3]u8, // move box, focused pane + box_dim: [3]u8, // move box, everything else + kw: [3]u8, + str: [3]u8, + num: [3]u8, + comment: [3]u8, + lineno: [3]u8, + scroll_track: [3]u8, + scroll_thumb: [3]u8, + palette: ?[16][3]u8, + + // Pardes UI roles. Optional so existing ThemeFile documents and imported + // editor palettes keep working; ChromeTheme resolves their legacy defaults. + tag_active_bg: ?[3]u8 = null, + tag_active_fg: ?[3]u8 = null, + /// Filename/output-name accent, also used by the Tty command. + tag_name_fg: ?[3]u8 = null, + /// Active tint; absence preserves the shared name tint or active tag ink. + tag_active_name_fg: ?[3]u8 = null, + /// Column grips stay distinct from pane grips in both focus states. + column_box: ?[3]u8 = null, + column_box_dim: ?[3]u8 = null, + border: ?[3]u8 = null, + search_bg: ?[3]u8 = null, + search_fg: ?[3]u8 = null, + diagnostic_error: ?[3]u8 = null, + diagnostic_warning: ?[3]u8 = null, + diagnostic_info: ?[3]u8 = null, + diagnostic_hint: ?[3]u8 = null, + // The current line number is a quiet foreground cue, not a tag-colored + // background block. Older themes fall back to their normal gutter ink. + lineno_active: ?[3]u8 = null, +}; + +const curated = struct { + pub const orchard = @import("themes/orchard.zig"); + pub const dusk = @import("themes/dusk.zig"); + pub const ink = @import("themes/ink.zig"); + pub const paper = @import("themes/paper.zig"); + pub const daybreak = @import("themes/daybreak.zig"); + pub const atelier = @import("themes/atelier.zig"); + pub const forge = @import("themes/forge.zig"); + pub const lagoon = @import("themes/lagoon.zig"); + pub const solarium = @import("themes/solarium.zig"); + pub const spectrum = @import("themes/spectrum.zig"); + pub const harvest = @import("themes/harvest.zig"); + pub const clay = @import("themes/clay.zig"); + pub const forge_black = @import("themes/forge_black.zig"); + pub const forge_soft = @import("themes/forge_soft.zig"); + pub const orchard_black = @import("themes/orchard_black.zig"); + pub const helix = @import("themes/helix.zig"); + pub const dark = @import("themes/dark.zig"); + pub const acme = @import("themes/acme.zig"); +}; + +fn fold(comptime C: type) [@typeInfo(C).@"struct".decls.len]Theme { + comptime { + @setEvalBranchQuota(400000); + var out: [@typeInfo(C).@"struct".decls.len]Theme = undefined; + for (@typeInfo(C).@"struct".decls, 0..) |d, i| { + var t: Theme = undefined; + const source = @field(C, d.name).theme; + for (@typeInfo(Theme).@"struct".fields) |f| { + @field(t, f.name) = if (@hasField(@TypeOf(source), f.name)) + @field(source, f.name) + else if (f.default_value_ptr) |ptr| + @as(*const f.type, @ptrCast(@alignCast(ptr))).* + else + @compileError("theme " ++ d.name ++ " is missing " ++ f.name); + } + out[i] = t; + } + return out; + } +} + +pub const themes = fold(curated) ++ fold(@import("generated_themes")); + +/// Original and classic-inspired Pardes palettes precede retained imports. +pub const native_theme_count = 15; + +fn themeContrast(a: [3]u8, b: [3]u8) f64 { + var luminance: [2]f64 = .{ 0, 0 }; + for ([2][3]u8{ a, b }, 0..) |rgb, i| { + for (rgb, [3]f64{ 0.2126, 0.7152, 0.0722 }) |channel, weight| { + const srgb = @as(f64, @floatFromInt(channel)) / 255; + const linear = if (srgb <= 0.04045) srgb / 12.92 else std.math.pow(f64, (srgb + 0.055) / 1.055, 2.4); + luminance[i] += weight * linear; + } + } + return (@max(luminance[0], luminance[1]) + 0.05) / (@min(luminance[0], luminance[1]) + 0.05); +} + +comptime { + if (themes.len > std.math.maxInt(u16) + 1) + @compileError("runtime config theme index no longer fits u16"); +} + +comptime { + @setEvalBranchQuota(20000); + const ours = fold(curated).len; + for (themes[0..ours]) |c| for (themes[ours..]) |g| if (std.mem.eql(u8, c.name, g.name)) + @compileError("theme name \"" ++ c.name ++ "\" is both ours and generated; rename the vendored source"); +} + +pub const ChromeTheme = struct { + tag_bg: [3]u8, + tag_fg: [3]u8, + tag_active_bg: [3]u8, + tag_active_fg: [3]u8, + tag_name_fg: [3]u8, + tag_active_name_fg: [3]u8, + border: [3]u8, + search_bg: [3]u8, + search_fg: [3]u8, + diagnostic_error: [3]u8, + diagnostic_warning: [3]u8, + diagnostic_info: [3]u8, + diagnostic_hint: [3]u8, + box: [3]u8, + box_dim: [3]u8, + column_box: [3]u8, + column_box_dim: [3]u8, + lineno: [3]u8, + scroll_track: [3]u8, + scroll_thumb: [3]u8, + + pub fn fromTheme(th: *const Theme) ChromeTheme { + return .{ + .tag_bg = th.tag_bg, + .tag_fg = th.tag_fg, + .tag_active_bg = th.tag_active_bg orelse th.tag_bg, + .tag_active_fg = th.tag_active_fg orelse th.tag_fg, + .tag_name_fg = th.tag_name_fg orelse th.tag_fg, + .tag_active_name_fg = th.tag_active_name_fg orelse (th.tag_name_fg orelse (th.tag_active_fg orelse th.tag_fg)), + .border = th.border orelse th.scroll_track, + .search_bg = th.search_bg orelse th.sel_bg, + .search_fg = th.search_fg orelse th.sel_fg, + .diagnostic_error = th.diagnostic_error orelse (th.fg orelse th.tag_fg), + .diagnostic_warning = th.diagnostic_warning orelse (th.fg orelse th.tag_fg), + .diagnostic_info = th.diagnostic_info orelse (th.fg orelse th.tag_fg), + .diagnostic_hint = th.diagnostic_hint orelse (th.fg orelse th.tag_fg), + .box = th.box, + .box_dim = th.box_dim, + .column_box = th.column_box orelse th.num, + .column_box_dim = th.column_box_dim orelse mix(th.column_box orelse th.num, th.tag_bg), + .lineno = th.lineno, + .scroll_track = th.scroll_track, + .scroll_thumb = th.scroll_thumb, + }; + } + + pub fn interpolate(from: ChromeTheme, to: ChromeTheme, step: u16, steps: u16) ChromeTheme { + var out: ChromeTheme = undefined; + inline for (@typeInfo(ChromeTheme).@"struct".fields) |field| + @field(out, field.name) = layout.Animation.interpolateRgb(@field(from, field.name), @field(to, field.name), step, steps); + return out; + } +}; + +pub const ChromeAnimation = if (theme_animation) + layout.Animation.Transition(ChromeTheme) +else + layout.Animation.Immediate(ChromeTheme); + +pub const initial_chrome = ChromeTheme.fromTheme(&themes[0]); + +fn nextThemeFileGeneration(p: *Pardes) u32 { + p.theme_file_generation +%= 1; + if (p.theme_file_generation == 0) p.theme_file_generation = 1; + return p.theme_file_generation; +} + +pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { + if (comptime !hosted) return; + const input = std.mem.trim(u8, argument, " \t\r\n"); + if (input.len == 0 or !std.mem.endsWith(u8, input, ".zon")) { + p.reportError(id, "theme file", error.InvalidThemePath); + return; + } + + const absolute = std.fs.path.isAbsolute(input); + if (!absolute and p.opts.config_dir == null) { + p.reportError(id, "theme file", error.NoConfigDirectory); + return; + } + + var joined: [4095]u8 = undefined; + const resolved = if (absolute) input else path: { + const dir = p.opts.config_dir.?; + const separator = std.Io.Dir.path.sep; + const needs_separator = dir.len > 0 and dir[dir.len - 1] != separator; + const len = dir.len + @intFromBool(needs_separator) + input.len; + if (len > joined.len) { + p.reportError(id, "theme file", error.PathTooLong); + return; + } + @memcpy(joined[0..dir.len], dir); + var at = dir.len; + if (needs_separator) { + joined[at] = separator; + at += 1; + } + @memcpy(joined[at..][0..input.len], input); + break :path joined[0..len]; + }; + if (!p.theme_file_path.set(resolved)) { + p.reportError(id, "theme file", error.PathTooLong); + return; + } + p.theme_file_pane = @intCast(@min(id, MAX_PANES - 1)); + const generation = nextThemeFileGeneration(p); + p.emit(.{ .theme_file = .{ .generation = generation, .on = true } }); +} + +pub const ThemeFileRequest = struct { + path: []const u8, + pane: u8, +}; + +/// Borrow the current request while a native host performs its synchronous +/// read. A later command invalidates an already-queued generation. +pub fn themeFileRequest(p: *const Pardes, generation: u32) ?ThemeFileRequest { + if (generation == 0 or generation != p.theme_file_generation) return null; + const path = p.theme_file_path.get(); + if (path.len == 0) return null; + return .{ .path = path, .pane = p.theme_file_pane }; +} + +pub fn failThemeFile(p: *Pardes, generation: u32, err: anyerror) void { + const request = themeFileRequest(p, generation) orelse return; + p.reportError(request.pane, "theme file", err); +} + +pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bool) bool { + // ZON's generated field dispatch grows with the complete theme schema. + @setEvalBranchQuota(10000); + const request = themeFileRequest(p, generation) orelse return false; + if (bytes.len > 1024 * 1024) { + p.reportError(request.pane, "theme file", error.ThemeFileTooLarge); + return false; + } + const source = p.gpa.dupeZ(u8, bytes) catch |err| { + p.reportError(request.pane, "theme file", err); + return false; + }; + defer p.gpa.free(source); + var diagnostics: std.zon.parse.Diagnostics = .{}; + defer diagnostics.deinit(p.gpa); + const parsed = std.zon.parse.fromSliceAlloc(Theme, p.gpa, source, &diagnostics, .{}) catch |err| { + p.reportError(request.pane, "theme file", err); + return false; + }; + if (parsed.name.len == 0 or parsed.name.len > 255) { + std.zon.parse.free(p.gpa, parsed); + p.reportError(request.pane, "theme file", error.InvalidThemeName); + return false; + } + + const target_chrome = ChromeTheme.fromTheme(&parsed); + if (animate and p.animate_theme_changes) + p.chrome_animation.retarget(target_chrome) + else + p.chrome_animation.snap(target_chrome); + const old = p.custom_theme; + p.custom_theme = parsed; + if (old) |theme_value| std.zon.parse.free(p.gpa, theme_value); + invalidateThemeDependentRasters(p); + _ = p.scratch.reset(.retain_capacity); + p.sync(); + return true; +} + +pub fn finishThemeInitialization(p: *Pardes) void { + p.chrome_animation.snap(ChromeTheme.fromTheme(p.theme())); + p.animate_theme_changes = true; +} + +fn invalidateThemeDependentRasters(p: *Pardes) void { + if (comptime pdf_enabled) for (p.panes) |slot| { + const pane = slot orelse continue; + const pv = &(pane.pdf orelse continue); + if (pv.tint != .disabled) pv.invalidateAllRasters(); + }; +} + +pub fn setThemeIndex(p: *Pardes, index: usize) void { + if (index >= themes.len or + (p.custom_theme == null and p.theme_file_path.get().len == 0 and + index == @as(usize, p.settings.theme))) return; + const target_chrome = ChromeTheme.fromTheme(&themes[index]); + if (p.animate_theme_changes) + p.chrome_animation.retarget(target_chrome) + else + p.chrome_animation.snap(target_chrome); + if (p.custom_theme) |theme_value| { + p.custom_theme = null; + std.zon.parse.free(p.gpa, theme_value); + } + if (p.theme_file_path.get().len > 0) { + p.theme_file_path.clear(); + const generation = nextThemeFileGeneration(p); + p.emit(.{ .theme_file = .{ .generation = generation, .on = false } }); + } + p.settings.theme = @intCast(index); + invalidateThemeDependentRasters(p); +} + +test "ThemeFile parses ZON atomically and Theme returns to the compiled ring" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ + .tty_only = true, + .config_dir = "/tmp/pardes-config", + }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + requestThemeFile(p, 0, "themes/mine.zon"); + const request_effect = while (p.nextEffect()) |effect| switch (effect) { + .theme_file => |request| break request, + else => {}, + } else return error.MissingThemeFileEffect; + try std.testing.expect(request_effect.on); + const request = themeFileRequest(p, request_effect.generation) orelse + return error.MissingThemeFileRequest; + try std.testing.expectEqualStrings("/tmp/pardes-config/themes/mine.zon", request.path); + + var custom = themes[0]; + custom.name = "mine"; + custom.bg = .{ 1, 2, 3 }; + custom.tag_bg = .{ 4, 5, 6 }; + var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer encoded.deinit(); + try std.zon.stringify.serialize(custom, .{ .whitespace = true }, &encoded.writer); + try std.testing.expect(loadThemeFile(p, request_effect.generation, encoded.written(), false)); + try std.testing.expectEqualStrings("mine", p.theme().name); + try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), p.theme().bg); + try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*); + + // A half-written save is rejected without disturbing the last good value. + try std.testing.expect(!loadThemeFile(p, request_effect.generation, ".{ .name = ", true)); + try std.testing.expectEqualStrings("mine", p.theme().name); + try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), p.theme().bg); + + setThemeIndex(p, 0); + try std.testing.expectEqualStrings(themes[0].name, p.theme().name); + try std.testing.expect(themeFileRequest(p, request_effect.generation) == null); + const stop = while (p.nextEffect()) |effect| switch (effect) { + .theme_file => |theme_file| break theme_file, + else => {}, + } else return error.MissingThemeFileStop; + try std.testing.expect(!stop.on); +} + +test "runtime theme changes animate chrome and retarget without a jump" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const first = p.chromeTheme().*; + try std.testing.expect(!p.animationActive()); + + const dark_index = for (themes, 0..) |th, i| { + if (std.mem.eql(u8, th.name, "dark")) break i; + } else return error.MissingDarkTheme; + const acme_index = for (themes, 0..) |th, i| { + if (std.mem.eql(u8, th.name, "acme")) break i; + } else return error.MissingAcmeTheme; + + setThemeIndex(p, dark_index); + // Target semantics are immediate, while the displayed chrome begins at + // the exact previous frame. + try std.testing.expectEqualStrings("dark", p.theme().name); + try std.testing.expectEqual(first, p.chromeTheme().*); + try std.testing.expect(p.animationActive()); + p.update(.tick); + p.update(.tick); + p.update(.tick); + const midflight = p.chromeTheme().*; + try std.testing.expect(!std.meta.eql(first, midflight)); + + setThemeIndex(p, acme_index); + try std.testing.expectEqualStrings("acme", p.theme().name); + try std.testing.expectEqual(midflight, p.chromeTheme().*); + try std.testing.expect(p.animationActive()); + for (0..layout.Animation.transition_steps) |_| p.update(.tick); + try std.testing.expect(!p.animationActive()); + try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*); + // Extra ticks are inert at the exact endpoint. + p.update(.tick); + try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*); +} + +test "render uses target content colors while chrome is in flight" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + const source_chrome = p.chromeTheme().*; + const acme_index = for (themes, 0..) |th, i| { + if (std.mem.eql(u8, th.name, "acme")) break i; + } else return error.MissingAcmeTheme; + setThemeIndex(p, acme_index); + + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const surface = try p.render(frame.allocator()); + // The anchored topbar has not advanced from its source frame. + try std.testing.expectEqual( + Color{ .rgb = source_chrome.tag_bg }, + surface.at(0, 0).style.bg, + ); + const topbar_cell = surface.at(0, 0); + try std.testing.expect(!std.mem.eql(u8, topbar_cell.grapheme(), " ")); + try std.testing.expectEqual(FontRole.tagline, topbar_cell.style.font_role); + const r = p.rects[0]; + const tag_cell = find_tag_cell: { + var x = r.x + config.GUTTER; + while (x < r.x + r.w) : (x += 1) { + const cell = surface.at(x, r.y); + if (!std.mem.eql(u8, cell.grapheme(), " ")) break :find_tag_cell cell; + } + return error.MissingTagText; + }; + try std.testing.expectEqual(FontRole.tagline, tag_cell.style.font_role); + try std.testing.expectEqual(FontRole.tagline, surface.at(r.x, r.y).style.font_role); + try std.testing.expectEqual(FontRole.tagline, surface.at(r.x + r.w - 1, r.y).style.font_role); + // The document/terminal page does not ride the chrome animation: acme's + // target background is already present in the same render. + const body = surface.at(r.x + r.w - 1, r.y + r.h - 1); + try std.testing.expectEqual(FontRole.body, body.style.font_role); + try std.testing.expectEqual( + Color{ .rgb = p.theme().bg.? }, + body.style.bg, + ); + try std.testing.expect(p.animationActive()); +} + +test "native themes keep text and UI roles readable on their own surfaces" { + const names = [_][]const u8{ "orchard", "dusk", "ink", "paper", "daybreak", "atelier", "forge", "lagoon", "solarium", "spectrum", "harvest", "clay", "forge_black", "forge_soft", "orchard_black" }; + try std.testing.expectEqual(names.len, native_theme_count); + for (themes[0..names.len], names) |th, name| { + try std.testing.expectEqualStrings(name, th.name); + const chrome = ChromeTheme.fromTheme(&th); + const minimum: f64 = if (std.mem.eql(u8, name, "ink") or std.mem.eql(u8, name, "daybreak")) 7 else 4.5; + const text_colors = [_][3]u8{ + th.fg.?, th.kw, th.str, th.num, th.comment, + chrome.diagnostic_error, chrome.diagnostic_warning, chrome.diagnostic_info, chrome.diagnostic_hint, + }; + for (text_colors) |fg| try std.testing.expect(themeContrast(fg, th.bg.?) >= minimum); + // Gutters are orientation aids, not source text: stay visible without + // competing with comments or pulling attention away from the body. + try std.testing.expect(themeContrast(th.lineno, th.bg.?) >= 2.5); + try std.testing.expect(themeContrast(th.lineno, th.bg.?) <= 4); + try std.testing.expect(themeContrast(th.lineno_active.?, th.bg.?) >= themeContrast(th.lineno, th.bg.?)); + try std.testing.expect(themeContrast(th.lineno_active.?, th.bg.?) <= 4.5); + try std.testing.expect(themeContrast(th.comment, th.bg.?) >= 5); + try std.testing.expect(themeContrast(th.comment, th.bg.?) >= themeContrast(th.lineno, th.bg.?) + 2); + try std.testing.expect(themeContrast(th.tag_fg, th.tag_bg) >= minimum); + try std.testing.expect(themeContrast(chrome.tag_active_fg, chrome.tag_active_bg) >= minimum); + try std.testing.expect(th.tag_name_fg != null); + try std.testing.expect(themeContrast(chrome.tag_name_fg, th.tag_bg) >= minimum); + try std.testing.expect(themeContrast(chrome.tag_active_name_fg, chrome.tag_active_bg) >= minimum); + // Focus stays on the same tonal surface, rather than inverting a + // whole command strip. Text remains readable in both states. + try std.testing.expect(themeContrast(chrome.tag_active_bg, th.tag_bg) <= 1.6); + try std.testing.expect(themeContrast(chrome.tag_active_fg, th.tag_fg) <= 1.6); + try std.testing.expect(themeContrast(th.sel_fg, th.sel_bg) >= minimum); + try std.testing.expect(themeContrast(chrome.search_fg, chrome.search_bg) >= minimum); + // ANSI black can intentionally match the page (for backgrounds). All + // other ANSI foregrounds, including bright black, remain legible. + for (th.palette.?[1..]) |fg| try std.testing.expect(themeContrast(fg, th.bg.?) >= minimum); + } +} + +test "native filename tints change hue without changing perceived lightness" { + const Perceptual = struct { + fn lab(rgb: [3]u8) [3]f64 { + var linear: [3]f64 = undefined; + for (rgb, 0..) |channel, i| { + const value = @as(f64, @floatFromInt(channel)) / 255; + linear[i] = if (value <= 0.04045) value / 12.92 else std.math.pow(f64, (value + 0.055) / 1.055, 2.4); + } + const r = linear[0]; + const g = linear[1]; + const b = linear[2]; + const l = std.math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const m = std.math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const n = std.math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + return .{ + 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * n, + 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * n, + 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * n, + }; + } + }; + for (themes[0..native_theme_count]) |th| { + try std.testing.expect(th.tag_name_fg != null and th.tag_active_name_fg != null); + const chrome = ChromeTheme.fromTheme(&th); + const pairs = [2][2][3]u8{ + .{ chrome.tag_fg, chrome.tag_name_fg }, + .{ chrome.tag_active_fg, chrome.tag_active_name_fg }, + }; + for (pairs) |pair| { + const base = Perceptual.lab(pair[0]); + const name = Perceptual.lab(pair[1]); + // Half a lightness point allows 8-bit quantization without a + // basename becoming visibly brighter or darker than its tag. + try std.testing.expectApproxEqAbs(base[0], name[0], 0.005); + const base_chroma = @sqrt(base[1] * base[1] + base[2] * base[2]); + const name_chroma = @sqrt(name[1] * name[1] + name[2] * name[2]); + try std.testing.expect(base_chroma > 0.005 and name_chroma > 0.02); + // A normalized dot product <= cos(60 degrees) means a clear + // hue difference, independent of saturation or lightness. + const hue_cosine = (base[1] * name[1] + base[2] * name[2]) / (base_chroma * name_chroma); + try std.testing.expect(hue_cosine <= 0.5); + } + } +} + +test "native dark palettes choose near-black or deliberately soft contrast" { + for (themes[0..native_theme_count]) |th| { + if (themeContrast(th.bg.?, .{ 0, 0, 0 }) > 10) continue; // light paper + const soft = std.mem.eql(u8, th.name, "dusk") or std.mem.eql(u8, th.name, "lagoon") or + std.mem.eql(u8, th.name, "solarium") or std.mem.eql(u8, th.name, "forge_soft"); + if (soft) { + try std.testing.expect(themeContrast(th.fg.?, th.bg.?) >= 4.5); + try std.testing.expect(themeContrast(th.fg.?, th.bg.?) <= 7); + } else { + for (th.bg.?) |channel| try std.testing.expect(channel <= 0x14); + try std.testing.expect(themeContrast(th.fg.?, th.bg.?) >= 14); + } + } + const forge = curated.forge.theme; + try std.testing.expectEqual(forge.bg[0], forge.bg[1]); + // Forge chrome is cool-neutral, never the old green-over-blue mint cast. + for ([_][3]u8{ forge.tag_bg, forge.tag_active_bg, forge.box, forge.border }) |rgb| + try std.testing.expect(rgb[2] >= rgb[1]); + try std.testing.expectEqual([3]u8{ 0, 0, 0 }, @as([3]u8, curated.forge_black.theme.bg)); + try std.testing.expectEqual([3]u8{ 0, 0, 0 }, @as([3]u8, curated.orchard_black.theme.bg)); +} + +test "line numbers stay quiet without a current-line tag background" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile("first\nsecond\n"); + pane.cur_pinned = true; + pane.cur_row = 0; + var custom = themes[0]; + custom.name = try gpa.dupe(u8, "quiet-gutter"); + custom.lineno = .{ 70, 70, 70 }; + custom.lineno_active = .{ 95, 95, 95 }; + p.custom_theme = custom; + p.sync(); + const x = p.rects[0].x + config.GUTTER; + const y = p.rects[0].y + BOX_H; + for ([_]bool{ false, true }) |focus_tint| { + p.settings.focus_tint = focus_tint; + const surface = try p.render(p.scratch.allocator()); + try std.testing.expectEqual(Color{ .rgb = .{ 95, 95, 95 } }, surface.at(x, y).style.fg); + try std.testing.expectEqual(Color{ .rgb = .{ 70, 70, 70 } }, surface.at(x, y + 1).style.fg); + try std.testing.expectEqual(Color{ .rgb = custom.bg.? }, surface.at(x, y).style.bg); + try std.testing.expect(surface.at(x, y).style.bold); + try std.testing.expect(!surface.at(x, y + 1).style.bold); + } + // Old ThemeFile palettes need no new field, and do not regain the block. + p.custom_theme.?.lineno_active = null; + const fallback = try p.render(p.scratch.allocator()); + try std.testing.expectEqual(Color{ .rgb = .{ 70, 70, 70 } }, fallback.at(x, y).style.fg); + try std.testing.expectEqual(Color{ .rgb = custom.bg.? }, fallback.at(x, y).style.bg); + try std.testing.expect(fallback.at(x, y).style.bold); + // Moving the caret clears the previous cue; editing the tag parks it. + pane.cur_row = 1; + const moved = try p.render(p.scratch.allocator()); + try std.testing.expect(!moved.at(x, y).style.bold); + try std.testing.expect(moved.at(x, y + 1).style.bold); + p.enterTagEdit(pane, -1); + const tag_edit = try p.render(p.scratch.allocator()); + try std.testing.expect(!tag_edit.at(x, y + 1).style.bold); +} + +test "legacy ThemeFile documents inherit Pardes UI roles without new fields" { + @setEvalBranchQuota(10000); + var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer encoded.deinit(); + try std.zon.stringify.serialize(curated.helix.theme, .{ .whitespace = true }, &encoded.writer); + const source = try std.testing.allocator.dupeZ(u8, encoded.written()); + defer std.testing.allocator.free(source); + const parsed = try std.zon.parse.fromSliceAlloc(Theme, std.testing.allocator, source, null, .{}); + defer std.zon.parse.free(std.testing.allocator, parsed); + try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_bg); + try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_name_fg); + try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_name_fg); + try std.testing.expectEqual(@as(?[3]u8, null), parsed.column_box); + try std.testing.expectEqual(@as(?[3]u8, null), parsed.column_box_dim); + try std.testing.expectEqual(@as(?[3]u8, null), parsed.search_bg); + const chrome = ChromeTheme.fromTheme(&parsed); + try std.testing.expectEqual(parsed.tag_bg, chrome.tag_active_bg); + try std.testing.expectEqual(parsed.tag_fg, chrome.tag_name_fg); + try std.testing.expectEqual(chrome.tag_active_fg, chrome.tag_active_name_fg); + try std.testing.expectEqual(parsed.num, chrome.column_box); + try std.testing.expectEqual(mix(parsed.num, parsed.tag_bg), chrome.column_box_dim); + try std.testing.expectEqual(parsed.sel_bg, chrome.search_bg); + try std.testing.expectEqual(parsed.fg.?, chrome.diagnostic_error); +} + +test "column grip colors remain distinct from pane grips across native themes" { + for (themes[0..native_theme_count]) |th| { + try std.testing.expect(th.column_box != null and th.column_box_dim != null); + const chrome = ChromeTheme.fromTheme(&th); + for ([_][2][3]u8{ + .{ chrome.box, chrome.column_box }, + .{ chrome.box_dim, chrome.column_box_dim }, + }) |pair| { + var distance: u32 = 0; + for (pair[0], pair[1]) |a, b| { + const delta = @as(i32, a) - b; + distance += @intCast(delta * delta); + } + try std.testing.expect(distance >= 30 * 30); + } + } + var custom = themes[0]; + custom.column_box = .{ 90, 130, 170 }; + custom.column_box_dim = null; + var chrome = ChromeTheme.fromTheme(&custom); + try std.testing.expectEqual(custom.column_box.?, chrome.column_box); + try std.testing.expectEqual(mix(custom.column_box.?, custom.tag_bg), chrome.column_box_dim); + custom.column_box_dim = .{ 40, 60, 80 }; + chrome = ChromeTheme.fromTheme(&custom); + try std.testing.expectEqual(custom.column_box_dim.?, chrome.column_box_dim); +} + +test "custom filename tints preserve optional active fallback precedence" { + var theme = themes[0]; + theme.tag_name_fg = null; + theme.tag_active_name_fg = null; + var chrome = ChromeTheme.fromTheme(&theme); + try std.testing.expectEqual(theme.tag_fg, chrome.tag_name_fg); + try std.testing.expectEqual(theme.tag_active_fg.?, chrome.tag_active_name_fg); + theme.tag_name_fg = .{ 120, 130, 140 }; + chrome = ChromeTheme.fromTheme(&theme); + try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_name_fg); + try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_active_name_fg); + theme.tag_active_name_fg = .{ 150, 160, 170 }; + chrome = ChromeTheme.fromTheme(&theme); + try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_name_fg); + try std.testing.expectEqual(theme.tag_active_name_fg.?, chrome.tag_active_name_fg); + theme.tag_name_fg = null; + chrome = ChromeTheme.fromTheme(&theme); + try std.testing.expectEqual(theme.tag_fg, chrome.tag_name_fg); + try std.testing.expectEqual(theme.tag_active_name_fg.?, chrome.tag_active_name_fg); +} diff --git a/src/file_watch.zig b/src/file_watch.zig index dfcce65f..2d1c0d25 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -13,6 +13,7 @@ const builtin = @import("builtin"); const libc = std.c; const linux = std.os.linux; const pardes = @import("pardes.zig"); +const colors = @import("colors.zig"); const filesystem = @import("fs.zig"); const message = pardes.Pardes.Message; @@ -551,13 +552,13 @@ pub fn applyThemeEffect( ) bool { watchPath(fd, watches, theme_slot, null, 0, .{ .text = 0 }); if (!on) return false; - const request = core.themeFileRequest(generation) orelse return false; + const request = colors.themeFileRequest(core, generation) orelse return false; const bytes = filesystem.readFile(gpa, request.path) catch |err| { - core.failThemeFile(generation, err); + colors.failThemeFile(core, generation, err); return false; }; defer gpa.free(bytes); - if (!core.loadThemeFile(generation, bytes, animate)) return false; + if (!colors.loadThemeFile(core, generation, bytes, animate)) return false; const hash = std.hash.Wyhash.hash(0, bytes); watchPath(fd, watches, theme_slot, request.path, generation, .{ .text = hash }); if (watches[theme_slot] == null) return false; @@ -574,7 +575,7 @@ pub fn reloadTheme( announce: bool, ) bool { const watched = watches[theme_slot] orelse return false; - const request = core.themeFileRequest(watched.serial) orelse return false; + const request = colors.themeFileRequest(core, watched.serial) orelse return false; // Same re-arm as reloadPane's, for the same reason: a .zon saved by rename // moves the inode the file filter is on. if (comptime builtin.os.tag == .macos) { @@ -582,7 +583,7 @@ pub fn reloadTheme( } const bytes = filesystem.readFile(gpa, request.path) catch |err| { core.invalidate(); - core.failThemeFile(watched.serial, err); + colors.failThemeFile(core, watched.serial, err); return false; }; defer gpa.free(bytes); @@ -591,7 +592,7 @@ pub fn reloadTheme( .text => |accepted| if (accepted == hash) return false, .pdf => unreachable, } - if (!core.loadThemeFile(watched.serial, bytes, true)) return false; + if (!colors.loadThemeFile(core, watched.serial, bytes, true)) return false; core.invalidate(); const live = if (watches[theme_slot]) |*entry| entry else return false; if (live.serial != watched.serial) return false; @@ -784,7 +785,7 @@ test "theme watch reloads valid ZON and keeps the last theme across a bad save" const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); while (core.nextEffect()) |_| {} - core.requestThemeFile(0, path); + colors.requestThemeFile(core, 0, path); const request = while (core.nextEffect()) |effect| switch (effect) { .theme_file => |theme_file| break theme_file, else => {}, diff --git a/src/fs.zig b/src/fs.zig index e1fe0b9c..86154fc1 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -37,6 +37,7 @@ const source_files = [_]Source{ .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, .{ .path = "src/surface.zig", .contents = @embedFile("surface.zig") }, + .{ .path = "src/colors.zig", .contents = @embedFile("colors.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/macos.zig b/src/macos.zig index b19c5996..402b3c12 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -6,6 +6,7 @@ const builtin = @import("builtin"); const posix = std.posix; const libc = std.c; const pardes = @import("pardes.zig"); +const colors = @import("colors.zig"); const look = @import("look.zig"); const message = pardes.Pardes.Message; const layout = @import("layout.zig"); @@ -1133,13 +1134,13 @@ fn setThemeFileWatch(st: *State, request_generation: u32, on: bool, animate: boo const stopped = st.file_watches.stop(st.gpa, theme_watch_pane); hostWatchFile(theme_watch_pane, stopped, null, 0); if (!on) return; - const request = st.core.themeFileRequest(request_generation) orelse return; + const request = colors.themeFileRequest(st.core, request_generation) orelse return; const bytes = filesystem.readFile(st.gpa, request.path) catch |err| { - st.core.failThemeFile(request_generation, err); + colors.failThemeFile(st.core, request_generation, err); return; }; defer st.gpa.free(bytes); - if (!st.core.loadThemeFile(request_generation, bytes, animate)) return; + if (!colors.loadThemeFile(st.core, request_generation, bytes, animate)) return; const callback_generation = st.file_watches.replace( st.gpa, theme_watch_pane, @@ -1154,10 +1155,10 @@ fn setThemeFileWatch(st: *State, request_generation: u32, on: bool, animate: boo fn reloadWatchedTheme(st: *State, announce: bool) bool { const watched = if (st.file_watches.entries[theme_watch_pane]) |*entry| entry else return false; - const request = st.core.themeFileRequest(watched.serial) orelse return false; + const request = colors.themeFileRequest(st.core, watched.serial) orelse return false; if (!std.mem.eql(u8, watched.path, request.path)) return false; const bytes = filesystem.readFile(st.gpa, watched.path) catch |err| { - st.core.failThemeFile(watched.serial, err); + colors.failThemeFile(st.core, watched.serial, err); return false; }; defer st.gpa.free(bytes); @@ -1166,7 +1167,7 @@ fn reloadWatchedTheme(st: *State, announce: bool) bool { .text => |accepted| if (accepted == hash) return false, .pdf => unreachable, } - if (!st.core.loadThemeFile(watched.serial, bytes, true)) return false; + if (!colors.loadThemeFile(st.core, watched.serial, bytes, true)) return false; const live = if (st.file_watches.entries[theme_watch_pane]) |*entry| entry else return false; if (live.serial != watched.serial) return false; live.generation_on_disk = .{ .text = hash }; diff --git a/src/pardes.zig b/src/pardes.zig index 23cb1734..cb020d89 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,11 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const colors = @import("colors.zig"); +pub const Theme = colors.Theme; +pub const themes = colors.themes; +pub const native_theme_count = colors.native_theme_count; +pub const ChromeTheme = colors.ChromeTheme; /// The screen types live in surface.zig; every shell names them through here. pub const Color = @import("surface.zig").Color; pub const FontRole = @import("surface.zig").FontRole; @@ -425,6 +430,7 @@ pub const Loc = struct { }; test { + _ = @import("colors.zig"); _ = @import("surface.zig"); _ = @import("body_layer.zig"); _ = @import("tag_layer.zig"); @@ -1001,52 +1007,6 @@ test "startup config runs builtin lines in order and isolates bad lines" { }; } -test "ThemeFile parses ZON atomically and Theme returns to the compiled ring" { - if (platform == .web) return; - const p = try Pardes.init(std.testing.allocator, .{ - .tty_only = true, - .config_dir = "/tmp/pardes-config", - }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - p.requestThemeFile(0, "themes/mine.zon"); - const request_effect = while (p.nextEffect()) |effect| switch (effect) { - .theme_file => |request| break request, - else => {}, - } else return error.MissingThemeFileEffect; - try std.testing.expect(request_effect.on); - const request = p.themeFileRequest(request_effect.generation) orelse - return error.MissingThemeFileRequest; - try std.testing.expectEqualStrings("/tmp/pardes-config/themes/mine.zon", request.path); - - var custom = themes[0]; - custom.name = "mine"; - custom.bg = .{ 1, 2, 3 }; - custom.tag_bg = .{ 4, 5, 6 }; - var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer encoded.deinit(); - try std.zon.stringify.serialize(custom, .{ .whitespace = true }, &encoded.writer); - try std.testing.expect(p.loadThemeFile(request_effect.generation, encoded.written(), false)); - try std.testing.expectEqualStrings("mine", p.theme().name); - try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), p.theme().bg); - try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*); - - // A half-written save is rejected without disturbing the last good value. - try std.testing.expect(!p.loadThemeFile(request_effect.generation, ".{ .name = ", true)); - try std.testing.expectEqualStrings("mine", p.theme().name); - try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), p.theme().bg); - - p.setThemeIndex(0); - try std.testing.expectEqualStrings(themes[0].name, p.theme().name); - try std.testing.expect(p.themeFileRequest(request_effect.generation) == null); - const stop = while (p.nextEffect()) |effect| switch (effect) { - .theme_file => |theme_file| break theme_file, - else => {}, - } else return error.MissingThemeFileStop; - try std.testing.expect(!stop.on); -} - test "scene effects keep the idle frontend animation clock active" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -1062,86 +1022,6 @@ test "scene effects keep the idle frontend animation clock active" { try std.testing.expect(!p.animationActive()); } -test "runtime theme changes animate chrome and retarget without a jump" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const first = p.chromeTheme().*; - try std.testing.expect(!p.animationActive()); - - const dark_index = for (themes, 0..) |th, i| { - if (std.mem.eql(u8, th.name, "dark")) break i; - } else return error.MissingDarkTheme; - const acme_index = for (themes, 0..) |th, i| { - if (std.mem.eql(u8, th.name, "acme")) break i; - } else return error.MissingAcmeTheme; - - p.setThemeIndex(dark_index); - // Target semantics are immediate, while the displayed chrome begins at - // the exact previous frame. - try std.testing.expectEqualStrings("dark", p.theme().name); - try std.testing.expectEqual(first, p.chromeTheme().*); - try std.testing.expect(p.animationActive()); - p.update(.tick); - p.update(.tick); - p.update(.tick); - const midflight = p.chromeTheme().*; - try std.testing.expect(!std.meta.eql(first, midflight)); - - p.setThemeIndex(acme_index); - try std.testing.expectEqualStrings("acme", p.theme().name); - try std.testing.expectEqual(midflight, p.chromeTheme().*); - try std.testing.expect(p.animationActive()); - for (0..layout.Animation.transition_steps) |_| p.update(.tick); - try std.testing.expect(!p.animationActive()); - try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*); - // Extra ticks are inert at the exact endpoint. - p.update(.tick); - try std.testing.expectEqual(ChromeTheme.fromTheme(p.theme()), p.chromeTheme().*); -} - -test "render uses target content colors while chrome is in flight" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - const source_chrome = p.chromeTheme().*; - const acme_index = for (themes, 0..) |th, i| { - if (std.mem.eql(u8, th.name, "acme")) break i; - } else return error.MissingAcmeTheme; - p.setThemeIndex(acme_index); - - var frame = std.heap.ArenaAllocator.init(std.testing.allocator); - defer frame.deinit(); - const surface = try p.render(frame.allocator()); - // The anchored topbar has not advanced from its source frame. - try std.testing.expectEqual( - Color{ .rgb = source_chrome.tag_bg }, - surface.at(0, 0).style.bg, - ); - const topbar_cell = surface.at(0, 0); - try std.testing.expect(!std.mem.eql(u8, topbar_cell.grapheme(), " ")); - try std.testing.expectEqual(FontRole.tagline, topbar_cell.style.font_role); - const r = p.rects[0]; - const tag_cell = find_tag_cell: { - var x = r.x + config.GUTTER; - while (x < r.x + r.w) : (x += 1) { - const cell = surface.at(x, r.y); - if (!std.mem.eql(u8, cell.grapheme(), " ")) break :find_tag_cell cell; - } - return error.MissingTagText; - }; - try std.testing.expectEqual(FontRole.tagline, tag_cell.style.font_role); - try std.testing.expectEqual(FontRole.tagline, surface.at(r.x, r.y).style.font_role); - try std.testing.expectEqual(FontRole.tagline, surface.at(r.x + r.w - 1, r.y).style.font_role); - // The document/terminal page does not ride the chrome animation: acme's - // target background is already present in the same render. - const body = surface.at(r.x + r.w - 1, r.y + r.h - 1); - try std.testing.expectEqual(FontRole.body, body.style.font_role); - try std.testing.expectEqual( - Color{ .rgb = p.theme().bg.? }, - body.style.bg, - ); - try std.testing.expect(p.animationActive()); -} - test "topbar hover highlights exactly the executable word" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -3293,342 +3173,6 @@ const tutor_text = @embedFile("tutor.txt"); // ---- theme ---- -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); - return out; -} - -pub const Theme = struct { - name: []const u8, - bg: ?[3]u8, - fg: ?[3]u8, - sel_bg: [3]u8, - sel_fg: [3]u8, - tag_bg: [3]u8, - tag_fg: [3]u8, - box: [3]u8, // move box, focused pane - box_dim: [3]u8, // move box, everything else - kw: [3]u8, - str: [3]u8, - num: [3]u8, - comment: [3]u8, - lineno: [3]u8, - scroll_track: [3]u8, - scroll_thumb: [3]u8, - palette: ?[16][3]u8, - - // Pardes UI roles. Optional so existing ThemeFile documents and imported - // editor palettes keep working; ChromeTheme resolves their legacy defaults. - tag_active_bg: ?[3]u8 = null, - tag_active_fg: ?[3]u8 = null, - /// Filename/output-name accent, also used by the Tty command. - tag_name_fg: ?[3]u8 = null, - /// Active tint; absence preserves the shared name tint or active tag ink. - tag_active_name_fg: ?[3]u8 = null, - /// Column grips stay distinct from pane grips in both focus states. - column_box: ?[3]u8 = null, - column_box_dim: ?[3]u8 = null, - border: ?[3]u8 = null, - search_bg: ?[3]u8 = null, - search_fg: ?[3]u8 = null, - diagnostic_error: ?[3]u8 = null, - diagnostic_warning: ?[3]u8 = null, - diagnostic_info: ?[3]u8 = null, - diagnostic_hint: ?[3]u8 = null, - // The current line number is a quiet foreground cue, not a tag-colored - // background block. Older themes fall back to their normal gutter ink. - lineno_active: ?[3]u8 = null, -}; - -const curated = struct { - pub const orchard = @import("themes/orchard.zig"); - pub const dusk = @import("themes/dusk.zig"); - pub const ink = @import("themes/ink.zig"); - pub const paper = @import("themes/paper.zig"); - pub const daybreak = @import("themes/daybreak.zig"); - pub const atelier = @import("themes/atelier.zig"); - pub const forge = @import("themes/forge.zig"); - pub const lagoon = @import("themes/lagoon.zig"); - pub const solarium = @import("themes/solarium.zig"); - pub const spectrum = @import("themes/spectrum.zig"); - pub const harvest = @import("themes/harvest.zig"); - pub const clay = @import("themes/clay.zig"); - pub const forge_black = @import("themes/forge_black.zig"); - pub const forge_soft = @import("themes/forge_soft.zig"); - pub const orchard_black = @import("themes/orchard_black.zig"); - pub const helix = @import("themes/helix.zig"); - pub const dark = @import("themes/dark.zig"); - pub const acme = @import("themes/acme.zig"); -}; - -fn fold(comptime C: type) [@typeInfo(C).@"struct".decls.len]Theme { - comptime { - @setEvalBranchQuota(400000); - var out: [@typeInfo(C).@"struct".decls.len]Theme = undefined; - for (@typeInfo(C).@"struct".decls, 0..) |d, i| { - var t: Theme = undefined; - const source = @field(C, d.name).theme; - for (@typeInfo(Theme).@"struct".fields) |f| { - @field(t, f.name) = if (@hasField(@TypeOf(source), f.name)) - @field(source, f.name) - else if (f.default_value_ptr) |ptr| - @as(*const f.type, @ptrCast(@alignCast(ptr))).* - else - @compileError("theme " ++ d.name ++ " is missing " ++ f.name); - } - out[i] = t; - } - return out; - } -} - -pub const themes = fold(curated) ++ fold(@import("generated_themes")); - -/// Original and classic-inspired Pardes palettes precede retained imports. -pub const native_theme_count = 15; - -fn themeContrast(a: [3]u8, b: [3]u8) f64 { - var luminance: [2]f64 = .{ 0, 0 }; - for ([2][3]u8{ a, b }, 0..) |rgb, i| { - for (rgb, [3]f64{ 0.2126, 0.7152, 0.0722 }) |channel, weight| { - const srgb = @as(f64, @floatFromInt(channel)) / 255; - const linear = if (srgb <= 0.04045) srgb / 12.92 else std.math.pow(f64, (srgb + 0.055) / 1.055, 2.4); - luminance[i] += weight * linear; - } - } - return (@max(luminance[0], luminance[1]) + 0.05) / (@min(luminance[0], luminance[1]) + 0.05); -} - -test "native themes keep text and UI roles readable on their own surfaces" { - const names = [_][]const u8{ "orchard", "dusk", "ink", "paper", "daybreak", "atelier", "forge", "lagoon", "solarium", "spectrum", "harvest", "clay", "forge_black", "forge_soft", "orchard_black" }; - try std.testing.expectEqual(names.len, native_theme_count); - for (themes[0..names.len], names) |th, name| { - try std.testing.expectEqualStrings(name, th.name); - const chrome = ChromeTheme.fromTheme(&th); - const minimum: f64 = if (std.mem.eql(u8, name, "ink") or std.mem.eql(u8, name, "daybreak")) 7 else 4.5; - const text_colors = [_][3]u8{ - th.fg.?, th.kw, th.str, th.num, th.comment, - chrome.diagnostic_error, chrome.diagnostic_warning, chrome.diagnostic_info, chrome.diagnostic_hint, - }; - for (text_colors) |fg| try std.testing.expect(themeContrast(fg, th.bg.?) >= minimum); - // Gutters are orientation aids, not source text: stay visible without - // competing with comments or pulling attention away from the body. - try std.testing.expect(themeContrast(th.lineno, th.bg.?) >= 2.5); - try std.testing.expect(themeContrast(th.lineno, th.bg.?) <= 4); - try std.testing.expect(themeContrast(th.lineno_active.?, th.bg.?) >= themeContrast(th.lineno, th.bg.?)); - try std.testing.expect(themeContrast(th.lineno_active.?, th.bg.?) <= 4.5); - try std.testing.expect(themeContrast(th.comment, th.bg.?) >= 5); - try std.testing.expect(themeContrast(th.comment, th.bg.?) >= themeContrast(th.lineno, th.bg.?) + 2); - try std.testing.expect(themeContrast(th.tag_fg, th.tag_bg) >= minimum); - try std.testing.expect(themeContrast(chrome.tag_active_fg, chrome.tag_active_bg) >= minimum); - try std.testing.expect(th.tag_name_fg != null); - try std.testing.expect(themeContrast(chrome.tag_name_fg, th.tag_bg) >= minimum); - try std.testing.expect(themeContrast(chrome.tag_active_name_fg, chrome.tag_active_bg) >= minimum); - // Focus stays on the same tonal surface, rather than inverting a - // whole command strip. Text remains readable in both states. - try std.testing.expect(themeContrast(chrome.tag_active_bg, th.tag_bg) <= 1.6); - try std.testing.expect(themeContrast(chrome.tag_active_fg, th.tag_fg) <= 1.6); - try std.testing.expect(themeContrast(th.sel_fg, th.sel_bg) >= minimum); - try std.testing.expect(themeContrast(chrome.search_fg, chrome.search_bg) >= minimum); - // ANSI black can intentionally match the page (for backgrounds). All - // other ANSI foregrounds, including bright black, remain legible. - for (th.palette.?[1..]) |fg| try std.testing.expect(themeContrast(fg, th.bg.?) >= minimum); - } -} - -test "native filename tints change hue without changing perceived lightness" { - const Perceptual = struct { - fn lab(rgb: [3]u8) [3]f64 { - var linear: [3]f64 = undefined; - for (rgb, 0..) |channel, i| { - const value = @as(f64, @floatFromInt(channel)) / 255; - linear[i] = if (value <= 0.04045) value / 12.92 else std.math.pow(f64, (value + 0.055) / 1.055, 2.4); - } - const r = linear[0]; - const g = linear[1]; - const b = linear[2]; - const l = std.math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); - const m = std.math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); - const n = std.math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); - return .{ - 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * n, - 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * n, - 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * n, - }; - } - }; - for (themes[0..native_theme_count]) |th| { - try std.testing.expect(th.tag_name_fg != null and th.tag_active_name_fg != null); - const chrome = ChromeTheme.fromTheme(&th); - const pairs = [2][2][3]u8{ - .{ chrome.tag_fg, chrome.tag_name_fg }, - .{ chrome.tag_active_fg, chrome.tag_active_name_fg }, - }; - for (pairs) |pair| { - const base = Perceptual.lab(pair[0]); - const name = Perceptual.lab(pair[1]); - // Half a lightness point allows 8-bit quantization without a - // basename becoming visibly brighter or darker than its tag. - try std.testing.expectApproxEqAbs(base[0], name[0], 0.005); - const base_chroma = @sqrt(base[1] * base[1] + base[2] * base[2]); - const name_chroma = @sqrt(name[1] * name[1] + name[2] * name[2]); - try std.testing.expect(base_chroma > 0.005 and name_chroma > 0.02); - // A normalized dot product <= cos(60 degrees) means a clear - // hue difference, independent of saturation or lightness. - const hue_cosine = (base[1] * name[1] + base[2] * name[2]) / (base_chroma * name_chroma); - try std.testing.expect(hue_cosine <= 0.5); - } - } -} - -test "native dark palettes choose near-black or deliberately soft contrast" { - for (themes[0..native_theme_count]) |th| { - if (themeContrast(th.bg.?, .{ 0, 0, 0 }) > 10) continue; // light paper - const soft = std.mem.eql(u8, th.name, "dusk") or std.mem.eql(u8, th.name, "lagoon") or - std.mem.eql(u8, th.name, "solarium") or std.mem.eql(u8, th.name, "forge_soft"); - if (soft) { - try std.testing.expect(themeContrast(th.fg.?, th.bg.?) >= 4.5); - try std.testing.expect(themeContrast(th.fg.?, th.bg.?) <= 7); - } else { - for (th.bg.?) |channel| try std.testing.expect(channel <= 0x14); - try std.testing.expect(themeContrast(th.fg.?, th.bg.?) >= 14); - } - } - const forge = curated.forge.theme; - try std.testing.expectEqual(forge.bg[0], forge.bg[1]); - // Forge chrome is cool-neutral, never the old green-over-blue mint cast. - for ([_][3]u8{ forge.tag_bg, forge.tag_active_bg, forge.box, forge.border }) |rgb| - try std.testing.expect(rgb[2] >= rgb[1]); - try std.testing.expectEqual([3]u8{ 0, 0, 0 }, @as([3]u8, curated.forge_black.theme.bg)); - try std.testing.expectEqual([3]u8{ 0, 0, 0 }, @as([3]u8, curated.orchard_black.theme.bg)); -} - -test "line numbers stay quiet without a current-line tag background" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = try p.setTestFile("first\nsecond\n"); - pane.cur_pinned = true; - pane.cur_row = 0; - var custom = themes[0]; - custom.name = try gpa.dupe(u8, "quiet-gutter"); - custom.lineno = .{ 70, 70, 70 }; - custom.lineno_active = .{ 95, 95, 95 }; - p.custom_theme = custom; - p.sync(); - const x = p.rects[0].x + config.GUTTER; - const y = p.rects[0].y + BOX_H; - for ([_]bool{ false, true }) |focus_tint| { - p.settings.focus_tint = focus_tint; - const surface = try p.render(p.scratch.allocator()); - try std.testing.expectEqual(Color{ .rgb = .{ 95, 95, 95 } }, surface.at(x, y).style.fg); - try std.testing.expectEqual(Color{ .rgb = .{ 70, 70, 70 } }, surface.at(x, y + 1).style.fg); - try std.testing.expectEqual(Color{ .rgb = custom.bg.? }, surface.at(x, y).style.bg); - try std.testing.expect(surface.at(x, y).style.bold); - try std.testing.expect(!surface.at(x, y + 1).style.bold); - } - // Old ThemeFile palettes need no new field, and do not regain the block. - p.custom_theme.?.lineno_active = null; - const fallback = try p.render(p.scratch.allocator()); - try std.testing.expectEqual(Color{ .rgb = .{ 70, 70, 70 } }, fallback.at(x, y).style.fg); - try std.testing.expectEqual(Color{ .rgb = custom.bg.? }, fallback.at(x, y).style.bg); - try std.testing.expect(fallback.at(x, y).style.bold); - // Moving the caret clears the previous cue; editing the tag parks it. - pane.cur_row = 1; - const moved = try p.render(p.scratch.allocator()); - try std.testing.expect(!moved.at(x, y).style.bold); - try std.testing.expect(moved.at(x, y + 1).style.bold); - p.enterTagEdit(pane, -1); - const tag_edit = try p.render(p.scratch.allocator()); - try std.testing.expect(!tag_edit.at(x, y + 1).style.bold); -} - -test "legacy ThemeFile documents inherit Pardes UI roles without new fields" { - @setEvalBranchQuota(10000); - var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer encoded.deinit(); - try std.zon.stringify.serialize(curated.helix.theme, .{ .whitespace = true }, &encoded.writer); - const source = try std.testing.allocator.dupeZ(u8, encoded.written()); - defer std.testing.allocator.free(source); - const parsed = try std.zon.parse.fromSliceAlloc(Theme, std.testing.allocator, source, null, .{}); - defer std.zon.parse.free(std.testing.allocator, parsed); - try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_bg); - try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_name_fg); - try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_name_fg); - try std.testing.expectEqual(@as(?[3]u8, null), parsed.column_box); - try std.testing.expectEqual(@as(?[3]u8, null), parsed.column_box_dim); - try std.testing.expectEqual(@as(?[3]u8, null), parsed.search_bg); - const chrome = ChromeTheme.fromTheme(&parsed); - try std.testing.expectEqual(parsed.tag_bg, chrome.tag_active_bg); - try std.testing.expectEqual(parsed.tag_fg, chrome.tag_name_fg); - try std.testing.expectEqual(chrome.tag_active_fg, chrome.tag_active_name_fg); - try std.testing.expectEqual(parsed.num, chrome.column_box); - try std.testing.expectEqual(mix(parsed.num, parsed.tag_bg), chrome.column_box_dim); - try std.testing.expectEqual(parsed.sel_bg, chrome.search_bg); - try std.testing.expectEqual(parsed.fg.?, chrome.diagnostic_error); -} - -test "column grip colors remain distinct from pane grips across native themes" { - for (themes[0..native_theme_count]) |th| { - try std.testing.expect(th.column_box != null and th.column_box_dim != null); - const chrome = ChromeTheme.fromTheme(&th); - for ([_][2][3]u8{ - .{ chrome.box, chrome.column_box }, - .{ chrome.box_dim, chrome.column_box_dim }, - }) |pair| { - var distance: u32 = 0; - for (pair[0], pair[1]) |a, b| { - const delta = @as(i32, a) - b; - distance += @intCast(delta * delta); - } - try std.testing.expect(distance >= 30 * 30); - } - } - var custom = themes[0]; - custom.column_box = .{ 90, 130, 170 }; - custom.column_box_dim = null; - var chrome = ChromeTheme.fromTheme(&custom); - try std.testing.expectEqual(custom.column_box.?, chrome.column_box); - try std.testing.expectEqual(mix(custom.column_box.?, custom.tag_bg), chrome.column_box_dim); - custom.column_box_dim = .{ 40, 60, 80 }; - chrome = ChromeTheme.fromTheme(&custom); - try std.testing.expectEqual(custom.column_box_dim.?, chrome.column_box_dim); -} - -test "custom filename tints preserve optional active fallback precedence" { - var theme = themes[0]; - theme.tag_name_fg = null; - theme.tag_active_name_fg = null; - var chrome = ChromeTheme.fromTheme(&theme); - try std.testing.expectEqual(theme.tag_fg, chrome.tag_name_fg); - try std.testing.expectEqual(theme.tag_active_fg.?, chrome.tag_active_name_fg); - theme.tag_name_fg = .{ 120, 130, 140 }; - chrome = ChromeTheme.fromTheme(&theme); - try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_name_fg); - try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_active_name_fg); - theme.tag_active_name_fg = .{ 150, 160, 170 }; - chrome = ChromeTheme.fromTheme(&theme); - try std.testing.expectEqual(theme.tag_name_fg.?, chrome.tag_name_fg); - try std.testing.expectEqual(theme.tag_active_name_fg.?, chrome.tag_active_name_fg); - theme.tag_name_fg = null; - chrome = ChromeTheme.fromTheme(&theme); - try std.testing.expectEqual(theme.tag_fg, chrome.tag_name_fg); - try std.testing.expectEqual(theme.tag_active_name_fg.?, chrome.tag_active_name_fg); -} - -comptime { - if (themes.len > std.math.maxInt(u16) + 1) - @compileError("runtime config theme index no longer fits u16"); -} - -comptime { - @setEvalBranchQuota(20000); - const ours = fold(curated).len; - for (themes[0..ours]) |c| for (themes[ours..]) |g| if (std.mem.eql(u8, c.name, g.name)) - @compileError("theme name \"" ++ c.name ++ "\" is both ours and generated; rename the vendored source"); -} - const boot_buffer = \\x selects a line, Tab runs it. 0x optional. \\ @@ -3668,67 +3212,6 @@ test "every line of the board's boot buffer renders whole" { try std.testing.expect(std.mem.indexOf(u8, boot_buffer, "\nGpio\n") != null); } -pub const ChromeTheme = struct { - tag_bg: [3]u8, - tag_fg: [3]u8, - tag_active_bg: [3]u8, - tag_active_fg: [3]u8, - tag_name_fg: [3]u8, - tag_active_name_fg: [3]u8, - border: [3]u8, - search_bg: [3]u8, - search_fg: [3]u8, - diagnostic_error: [3]u8, - diagnostic_warning: [3]u8, - diagnostic_info: [3]u8, - diagnostic_hint: [3]u8, - box: [3]u8, - box_dim: [3]u8, - column_box: [3]u8, - column_box_dim: [3]u8, - lineno: [3]u8, - scroll_track: [3]u8, - scroll_thumb: [3]u8, - - pub fn fromTheme(th: *const Theme) ChromeTheme { - return .{ - .tag_bg = th.tag_bg, - .tag_fg = th.tag_fg, - .tag_active_bg = th.tag_active_bg orelse th.tag_bg, - .tag_active_fg = th.tag_active_fg orelse th.tag_fg, - .tag_name_fg = th.tag_name_fg orelse th.tag_fg, - .tag_active_name_fg = th.tag_active_name_fg orelse (th.tag_name_fg orelse (th.tag_active_fg orelse th.tag_fg)), - .border = th.border orelse th.scroll_track, - .search_bg = th.search_bg orelse th.sel_bg, - .search_fg = th.search_fg orelse th.sel_fg, - .diagnostic_error = th.diagnostic_error orelse (th.fg orelse th.tag_fg), - .diagnostic_warning = th.diagnostic_warning orelse (th.fg orelse th.tag_fg), - .diagnostic_info = th.diagnostic_info orelse (th.fg orelse th.tag_fg), - .diagnostic_hint = th.diagnostic_hint orelse (th.fg orelse th.tag_fg), - .box = th.box, - .box_dim = th.box_dim, - .column_box = th.column_box orelse th.num, - .column_box_dim = th.column_box_dim orelse mix(th.column_box orelse th.num, th.tag_bg), - .lineno = th.lineno, - .scroll_track = th.scroll_track, - .scroll_thumb = th.scroll_thumb, - }; - } - - pub fn interpolate(from: ChromeTheme, to: ChromeTheme, step: u16, steps: u16) ChromeTheme { - var out: ChromeTheme = undefined; - inline for (@typeInfo(ChromeTheme).@"struct".fields) |field| - @field(out, field.name) = layout.Animation.interpolateRgb(@field(from, field.name), @field(to, field.name), step, steps); - return out; - } -}; - -const ChromeAnimation = if (theme_animation) - layout.Animation.Transition(ChromeTheme) -else - layout.Animation.Immediate(ChromeTheme); -const initial_chrome = ChromeTheme.fromTheme(&themes[0]); - // ---- the boundary types ---- test "insert and normal modes edit complete Unicode graphemes" { @@ -4004,7 +3487,7 @@ test "Look hover waits without mutating the pane and input cancels it" { _ = frame.reset(.retain_capacity); const surface = try p.render(frame.allocator()); - const expected_bg = mix(p.theme().bg orelse p.theme().tag_bg, mix(p.theme().bg orelse p.theme().tag_bg, p.theme().sel_bg)); + const expected_bg = colors.mix(p.theme().bg orelse p.theme().tag_bg, colors.mix(p.theme().bg orelse p.theme().tag_bg, p.theme().sel_bg)); try std.testing.expectEqual(Color{ .rgb = expected_bg }, surface.at(word_x, body_y).style.bg); // Background traffic in another pane does not change the text or geometry @@ -5763,7 +5246,7 @@ pub const Pardes = struct { theme_file_path: config.Runtime.Text(limits.host_path_cap) = .{}, theme_file_generation: u32 = 0, theme_file_pane: u8 = 0, - chrome_animation: ChromeAnimation = ChromeAnimation.init(initial_chrome), + chrome_animation: colors.ChromeAnimation = colors.ChromeAnimation.init(colors.initial_chrome), animate_theme_changes: bool = false, native_images: bool = false, /// The shell can take a changed image a few rows at a time (a texture row @@ -5987,7 +5470,7 @@ pub const Pardes = struct { } p.sync(); p.applyStartupConfig(); - p.finishThemeInitialization(); + colors.finishThemeInitialization(p); p.sync(); p.presentation.enabled = true; // A config init that opens a file with `Look …` armed the pulse before @@ -6476,112 +5959,6 @@ pub const Pardes = struct { p.font_request_taken = false; } - fn nextThemeFileGeneration(p: *Pardes) u32 { - p.theme_file_generation +%= 1; - if (p.theme_file_generation == 0) p.theme_file_generation = 1; - return p.theme_file_generation; - } - - pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { - if (comptime !hosted) return; - const input = std.mem.trim(u8, argument, " \t\r\n"); - if (input.len == 0 or !std.mem.endsWith(u8, input, ".zon")) { - p.reportError(id, "theme file", error.InvalidThemePath); - return; - } - - const absolute = std.fs.path.isAbsolute(input); - if (!absolute and p.opts.config_dir == null) { - p.reportError(id, "theme file", error.NoConfigDirectory); - return; - } - - var joined: [4095]u8 = undefined; - const resolved = if (absolute) input else path: { - const dir = p.opts.config_dir.?; - const separator = std.Io.Dir.path.sep; - const needs_separator = dir.len > 0 and dir[dir.len - 1] != separator; - const len = dir.len + @intFromBool(needs_separator) + input.len; - if (len > joined.len) { - p.reportError(id, "theme file", error.PathTooLong); - return; - } - @memcpy(joined[0..dir.len], dir); - var at = dir.len; - if (needs_separator) { - joined[at] = separator; - at += 1; - } - @memcpy(joined[at..][0..input.len], input); - break :path joined[0..len]; - }; - if (!p.theme_file_path.set(resolved)) { - p.reportError(id, "theme file", error.PathTooLong); - return; - } - p.theme_file_pane = @intCast(@min(id, MAX_PANES - 1)); - const generation = p.nextThemeFileGeneration(); - p.emit(.{ .theme_file = .{ .generation = generation, .on = true } }); - } - - pub const ThemeFileRequest = struct { - path: []const u8, - pane: u8, - }; - - /// Borrow the current request while a native host performs its synchronous - /// read. A later command invalidates an already-queued generation. - pub fn themeFileRequest(p: *const Pardes, generation: u32) ?ThemeFileRequest { - if (generation == 0 or generation != p.theme_file_generation) return null; - const path = p.theme_file_path.get(); - if (path.len == 0) return null; - return .{ .path = path, .pane = p.theme_file_pane }; - } - - pub fn failThemeFile(p: *Pardes, generation: u32, err: anyerror) void { - const request = p.themeFileRequest(generation) orelse return; - p.reportError(request.pane, "theme file", err); - } - - pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bool) bool { - // ZON's generated field dispatch grows with the complete theme schema. - @setEvalBranchQuota(10000); - const request = p.themeFileRequest(generation) orelse return false; - if (bytes.len > 1024 * 1024) { - p.reportError(request.pane, "theme file", error.ThemeFileTooLarge); - return false; - } - const source = p.gpa.dupeZ(u8, bytes) catch |err| { - p.reportError(request.pane, "theme file", err); - return false; - }; - defer p.gpa.free(source); - var diagnostics: std.zon.parse.Diagnostics = .{}; - defer diagnostics.deinit(p.gpa); - const parsed = std.zon.parse.fromSliceAlloc(Theme, p.gpa, source, &diagnostics, .{}) catch |err| { - p.reportError(request.pane, "theme file", err); - return false; - }; - if (parsed.name.len == 0 or parsed.name.len > 255) { - std.zon.parse.free(p.gpa, parsed); - p.reportError(request.pane, "theme file", error.InvalidThemeName); - return false; - } - - const target_chrome = ChromeTheme.fromTheme(&parsed); - if (animate and p.animate_theme_changes) - p.chrome_animation.retarget(target_chrome) - else - p.chrome_animation.snap(target_chrome); - const old = p.custom_theme; - p.custom_theme = parsed; - if (old) |theme_value| std.zon.parse.free(p.gpa, theme_value); - p.invalidateThemeDependentRasters(); - _ = p.scratch.reset(.retain_capacity); - p.sync(); - return true; - } - pub const Message = struct { const libc = std.c; const Tm = extern struct { @@ -7492,7 +6869,7 @@ pub const Pardes = struct { pane.tag_init = true; } - fn enterTagEdit(p: *Pardes, pane: *Pane, col: i32) void { + pub fn enterTagEdit(p: *Pardes, pane: *Pane, col: i32) void { if (pane.tag_edit and pane.prompt == .none) pane.tag_saved_col = pane.tag_col; const edit0: i32 = @intCast((p.tagPrefix(pane) catch return).len); p.seedTail(pane); @@ -12735,7 +12112,7 @@ pub const Pardes = struct { .theme => { const want = std.mem.trim(u8, arg orelse return, " \t\r\n"); for (themes, 0..) |t, i| if (std.mem.eql(u8, t.name, want)) { - p.setThemeIndex(i); + colors.setThemeIndex(p, i); return; }; }, @@ -13033,7 +12410,7 @@ pub const Pardes = struct { p.active = @min(st.active, MAX_PANES - 1); p.sync(); p.applyStartupConfig(); - p.finishThemeInitialization(); + colors.finishThemeInitialization(p); p.sync(); p.presentation.enabled = true; _ = p.takeHaptic(); // see init: a restored session is not a gesture @@ -13281,7 +12658,7 @@ pub const Pardes = struct { /// Recompute geometry, push grid-size changes to each emulator + pty, fire /// deferred greetings. The mirror of the prototype's loop epilogue. - fn sync(p: *Pardes) void { + pub fn sync(p: *Pardes) void { if (p.header_column != null and p.columnBarHeight() == 0) { p.exitHeader(); } @@ -13363,41 +12740,6 @@ pub const Pardes = struct { return p.haptic; } - fn finishThemeInitialization(p: *Pardes) void { - p.chrome_animation.snap(ChromeTheme.fromTheme(p.theme())); - p.animate_theme_changes = true; - } - - fn invalidateThemeDependentRasters(p: *Pardes) void { - if (comptime pdf_enabled) for (p.panes) |slot| { - const pane = slot orelse continue; - const pv = &(pane.pdf orelse continue); - if (pv.tint != .disabled) pv.invalidateAllRasters(); - }; - } - - pub fn setThemeIndex(p: *Pardes, index: usize) void { - if (index >= themes.len or - (p.custom_theme == null and p.theme_file_path.get().len == 0 and - index == @as(usize, p.settings.theme))) return; - const target_chrome = ChromeTheme.fromTheme(&themes[index]); - if (p.animate_theme_changes) - p.chrome_animation.retarget(target_chrome) - else - p.chrome_animation.snap(target_chrome); - if (p.custom_theme) |theme_value| { - p.custom_theme = null; - std.zon.parse.free(p.gpa, theme_value); - } - if (p.theme_file_path.get().len > 0) { - p.theme_file_path.clear(); - const generation = p.nextThemeFileGeneration(); - p.emit(.{ .theme_file = .{ .generation = generation, .on = false } }); - } - p.settings.theme = @intCast(index); - p.invalidateThemeDependentRasters(); - } - pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit { for (p.surface.tagLayers()) |*layer| { if (layer.cols == 0 or layer.kind != tag_hit.kind or layer.id != tag_hit.id or layer.serial != tag_hit.serial) continue; @@ -14370,7 +13712,7 @@ pub const Pardes = struct { } if (p.look_hover_preview) |preview| { if (preview.pane == id and preview.serial == pane.serial) if (preview.sel) |sel| if (@min(sel.r0, sel.r1) < BOX_H) { - const preview_bg = mix(page_rgb, mix(page_rgb, th.sel_bg)); + const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); p.paintPointerSelection(pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); }; } @@ -14450,9 +13792,9 @@ pub const Pardes = struct { const accent2 = if (std.mem.eql(u8, &th.num, &th.str)) th.comment else th.num; const sel_btn = [3][3]u8{ - mix(th.sel_bg, mix(th.sel_bg, th.kw)), - mix(th.sel_bg, mix(th.sel_bg, th.str)), - mix(th.sel_bg, mix(th.sel_bg, accent2)), + colors.mix(th.sel_bg, colors.mix(th.sel_bg, th.kw)), + colors.mix(th.sel_bg, colors.mix(th.sel_bg, th.str)), + colors.mix(th.sel_bg, colors.mix(th.sel_bg, accent2)), }; if (p.look_hover_preview) |preview| { if (preview.pane == id and preview.serial == pane.serial) { @@ -14460,7 +13802,7 @@ pub const Pardes = struct { // win over this quiet affordance. mark_hover carries the // cells this paints out to the hosts as the affordance rect — // macOS composes its glass overlay over exactly these. - const preview_bg = mix(page_rgb, mix(page_rgb, th.sel_bg)); + const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); if (preview.file_word) |word| panes.File.paintWordSelection(p, pane, r, word.row, word.lo, word.hi, preview_bg) else if (preview.sel) |sel| @@ -14480,7 +13822,7 @@ pub const Pardes = struct { if ((pane.mode == .normal or modal_hover) and pane.msel.active) { const hover_only = modal_hover and pane.mode != .normal; const modal_bg = if (hover_only) - mix(page_rgb, mix(page_rgb, th.sel_bg)) + colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) else th.sel_bg; const lo = @min(pane.msel.r0, pane.msel.r1); @@ -14517,11 +13859,11 @@ pub const Pardes = struct { const bnd = cellBounds(sr); const hover_only = primary and modal_hover and pane.mode != .normal and !preview; const bg = if (hover_only) - mix(page_rgb, mix(page_rgb, th.sel_bg)) + colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) else if (primary) th.sel_bg else - mix(th.sel_bg, page_rgb); + colors.mix(th.sel_bg, page_rgb); var vr: i32 = 0; while (vr + @as(i32, BOX_H) < @as(i32, body_bottom)) : (vr += 1) { const w = pane.wrapAt(vr); diff --git a/test/output.zig b/test/output.zig index cda5f556..ebea79d4 100644 --- a/test/output.zig +++ b/test/output.zig @@ -950,7 +950,7 @@ test "ThemeSel groups native themes first and skips headings in both directions" const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); const source = try p.setTestFile("notes\n"); - p.setThemeIndex(pardes.themes.len - 1); + pardes.colors.setThemeIndex(p, pardes.themes.len - 1); const original_theme = p.settings.theme; try std.testing.expect(p.executeBuiltinLine(0, "ThemeSel")); const tid = source.search_pane orelse return error.MissingThemeList; diff --git a/test/pdf.zig b/test/pdf.zig index 930cc5c0..25d0de76 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -1310,7 +1310,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { const dark_index = for (themes, 0..) |th, i| { if (std.mem.eql(u8, th.name, "dark")) break i; } else return error.MissingDarkTheme; - p.setThemeIndex(dark_index); + pardes.colors.setThemeIndex(p, dark_index); const colors = panes.Pdf.tintColors(p); try std.testing.expectEqual(p.theme().tag_bg, colors.background); try std.testing.expectEqual(p.theme().tag_fg, colors.foreground); @@ -1386,7 +1386,7 @@ test "PDF tint and tinted theme changes rebuild every visible raster only" { const dark_index = for (themes, 0..) |th, i| { if (std.mem.eql(u8, th.name, "dark")) break i; } else return error.MissingDarkTheme; - p.setThemeIndex(dark_index); + pardes.colors.setThemeIndex(p, dark_index); for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(!raster.tried); _ = frame.reset(.retain_capacity); const themed_surface = try p.render(frame.allocator()); @@ -1440,7 +1440,7 @@ test "PDF tint and tinted theme changes rebuild every visible raster only" { if (std.mem.eql(u8, th.name, "acme")) break i; } else return error.MissingAcmeTheme; for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(raster.tried); - p.setThemeIndex(acme_index); + pardes.colors.setThemeIndex(p, acme_index); // Disabled keys ignore theme colors, so neither explicit invalidation nor // the per-raster key comparison asks MuPDF for replacement pixels. for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(raster.tried); -- cgit v1.3 From fc2bc13e9f45099d4e2fe086e2a52aab7de8ad5c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:59:17 -0300 Subject: Move the message row out of pardes.zig into Messages.zig Pure move, no behaviour change: the Message stamp helpers, LoggedMessage, setStatus, setMessage, showMessage, dismissMessage, dismissLine, advanceMessages, advanceLine, messagesAnimating, MessageMotion, messageFrames, messageMotion, noticeText, noticeLife, blendRgb, logMessage, messageLog, reportError, the notice painters (leaderText, noticeCols, Printed, printRight), collectNotices, and the six message tests go verbatim to Messages.zig. The methods become free functions taking `p: *Pardes`. setStatus, setMessage and reportError are called from ~170 places as `p.setMessage(..)`, so Pardes keeps three declaration aliases (`pub const setMessage = Messages.setMessage;`) and those call sites stay as they are; every other call changes from `p.x(..)` to `Messages.x(p, ..)` (46 of them). The five shells' `pardes.Pardes.Message` become `pardes.Messages.Message`. The message ring's fields stay on Pardes for now; moving them into Messages is a separate change. Co-Authored-By: Claude Opus 5.5 --- src/Messages.zig | 773 ++++++++++++++++++++++++++++++++++++++++++++++ src/Output.zig | 3 +- src/detached/server.zig | 2 +- src/file_watch.zig | 2 +- src/fs.zig | 1 + src/gui/gui.zig | 2 +- src/macos.zig | 2 +- src/ninep/events.zig | 2 +- src/pardes.zig | 790 ++---------------------------------------------- src/tty/tty.zig | 2 +- 10 files changed, 805 insertions(+), 774 deletions(-) create mode 100644 src/Messages.zig (limited to 'src/fs.zig') diff --git a/src/Messages.zig b/src/Messages.zig new file mode 100644 index 00000000..6b041369 --- /dev/null +++ b/src/Messages.zig @@ -0,0 +1,773 @@ +//! The message row: messages and statuses a pane shows between its body and +//! its tagline, how each line falls in, lingers and dissolves, the notices +//! built from them every frame, and the log of everything said. +const pardes = @import("pardes.zig"); +const memory = @import("memory.zig"); +const std = @import("std"); +const layout = @import("layout.zig"); +const ctlfs = @import("ninep/tree.zig"); +const panes = @import("panes.zig"); +const CellStyle = @import("surface.zig").CellStyle; +const Surface = @import("surface.zig").Surface; +const limits = memory.limits; +const config = @import("config.zig"); +const platform = pardes.platform; +const Pane = panes.Pane; +const MAX_PANES = pardes.MAX_PANES; +const BOX_H = pardes.BOX_H; +const Key = pardes.Key; +const Rect = layout.Rect; +const Pardes = pardes.Pardes; + +pub const LoggedMessage = struct { + pub const cap = 256; + text: [cap]u8 = undefined, + len: u16 = 0, + /// The serial of the pane that said it, or 0 for none in particular. A + /// serial, not a slot: slots are reused, so an old line would name + /// whichever pane took the slot since. + serial: u32 = 0, + /// How many times in a row. Saturating: a key held down against the same + /// refusal is one event, not four hundred. + repeats: u16 = 0, + + pub fn slice(m: *const LoggedMessage) []const u8 { + return m.text[0..m.len]; + } +}; + +/// `SPC` plus the chord keys typed so far, spaced out the way the help +/// index spells a leader path. +fn leaderText(p: *const Pardes, buf: *[16]u8) []const u8 { + buf.* = @splat(' '); + @memcpy(buf[0..3], "SPC"); + var at: usize = 3; + for (p.leader_keys[0..p.leader_n]) |ch| { + if (at + 2 > buf.len) break; + buf[at + 1] = ch; + at += 2; + } + return buf[0..at]; +} + +/// How wide a notice chip is, in grid columns: its own text plus a blank +/// cell either side. A notice is an OVERLAY over the body's top rows, not +/// a row taken from them, so it is sized to its message and never to the +/// pane. Counted in GRID columns rather than scaled into the tagline face +/// it is drawn in, because the canonical grid is what a terminal client +/// draws and a chip narrower than its own text there would clip it; the +/// tagline face simply leaves a little more room inside the chip. +pub fn noticeCols(p: *const Pardes, text: []const u8, limit: u16) u16 { + _ = p; + if (limit == 0) return 0; + return @intCast(std.math.clamp(panes.File.displayWidth(text) + 2, 1, @as(usize, limit))); +} + +const Printed = struct { left: u16, dropped: usize }; + +/// Prints `text` flush with the right edge of the band, and answers the +/// column it started at so a cursor can follow it. Text wider than the +/// band loses its HEAD: the end is the part that says something -- a +/// path's file name, an error's reason -- and `dropped` is how many +/// columns of it went. +pub fn printRight(s: *Surface, x: u16, row: u16, w: u16, text: []const u8, style: CellStyle) Printed { + const width = panes.File.displayWidth(text); + if (width <= w) { + const left: u16 = @intCast(x + w - width); + _ = s.print(left, row, @intCast(width), text, style); + return .{ .left = left, .dropped = 0 }; + } + // Whole glyphs only: a cut inside a wide one would leave the rest a + // column too wide and clip its LAST glyph instead of the first. + var dropped = width - w; + var start = panes.File.rawAtDisplay(text, dropped); + if (panes.File.rawDisplayCol(text, start) < dropped) { + dropped += 1; + start = panes.File.rawAtDisplay(text, dropped); + } + const left: u16 = @intCast(x + w - (width - dropped)); + _ = s.print(left, row, @intCast(width - dropped), text[start..], style); + return .{ .left = left, .dropped = dropped }; +} + +pub const Message = struct { + const libc = std.c; + const Tm = extern struct { + sec: c_int, + min: c_int, + hour: c_int, + mday: c_int, + mon: c_int, + year: c_int, + wday: c_int, + yday: c_int, + isdst: c_int, + gmtoff: c_long, + zone: ?[*:0]const u8, + }; + extern "c" fn localtime_r(timep: *const libc.time_t, result: *Tm) ?*Tm; + + pub fn body(text: []const u8) []const u8 { + if (text.len < 10) return text; + if (text[2] != ':' or text[5] != ':' or text[8] != ' ' or text[9] != ' ') return text; + for ([_]usize{ 0, 1, 3, 4, 6, 7 }) |i| { + if (!std.ascii.isDigit(text[i]) and text[i] != '-') return text; + } + return text[10..]; + } + + pub fn stamp(buf: []u8, verb: []const u8, subject: []const u8) []const u8 { + var clock: [8]u8 = "--:--:--".*; + const notime = if (libc.getenv("PARDES_NOTIME")) |v| std.mem.span(v).len != 0 else false; + if (!notime) { + var ts: libc.timespec = undefined; + _ = libc.clock_gettime(.REALTIME, &ts); + const secs: libc.time_t = ts.sec; + var tm: Tm = undefined; + if (localtime_r(&secs, &tm) != null) { + _ = std.fmt.bufPrint(&clock, "{d:0>2}:{d:0>2}:{d:0>2}", .{ + @as(u32, @intCast(tm.hour)), + @as(u32, @intCast(tm.min)), + @as(u32, @intCast(tm.sec)), + }) catch {}; + } + } + const head = std.fmt.bufPrint(buf, "{s} {s} ", .{ &clock, verb }) catch return buf[0..0]; + const room = buf.len - head.len; + const tail = if (subject.len <= room) subject else subject[subject.len - room ..]; + @memcpy(buf[head.len..][0..tail.len], tail); + return buf[0 .. head.len + tail.len]; + } +}; + +/// A status updates the message line in place (a progress count does not +/// pile up); a message is an event, and stacks. +pub fn setStatus(p: *Pardes, id: usize, text: []const u8) void { + showMessage(p, id, text, false); +} + +pub fn setMessage(p: *Pardes, id: usize, text: []const u8) void { + logMessage(p, id, text); + showMessage(p, id, text, true); +} + +fn showMessage(p: *Pardes, id: usize, text: []const u8, stack: bool) void { + if (id >= MAX_PANES) return; + const pane = p.panes[id] orelse return; + // One row of printable text: a language server's multi-line report + // reads as one line, and the cut never leaves half a glyph behind. + var n: usize = @min(text.len, pane.msg.len); + if (n < text.len) { + while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1; + } + const same = pane.msg_len == n and for (text[0..n], pane.msg[0..n]) |c, have| { + if ((if (c < 0x20 or c == 0x7f) ' ' else c) != have) break false; + } else true; + // A new event moves the line on screen up the stack, where it keeps + // its own timing, and falls in below it. + // Only an event stacks on an event: an announcement or a status + // stands in for whatever comes next. + if (stack and pane.msg_len > 0 and !same and !pane.msg_announcement and !pane.msg_status) + pane.pushOlderMessage(); + if (pane.msg_len == 0) pane.msg_slot = pane.freeMessageSlot(); + pane.msg_announcement = false; + pane.msg_status = !stack; + const arrives = pane.msg_len == 0 or pane.msg_life.phase == .leaving; + for (text[0..n], pane.msg[0..n]) |c, *cell| cell.* = if (c < 0x20 or c == 0x7f) ' ' else c; + pane.msg_len = @intCast(n); + p.needs_frame = true; + if (arrives) { + pane.msg_life = .{ .phase = if (p.settings.message_animation and n > 0) .entering else .shown }; + } else if (pane.msg_life.phase == .lingering or + (pane.msg_life.phase == .entering and !p.settings.message_animation)) + { + // The same line again, or a status update: fresh, so it stays. + pane.msg_life = .{}; + } else { + pane.msg_life.dismissed = false; + } +} + +/// The key or click that used to clear the message row now starts each +/// line's exit: it stays `message_linger_ms`, then dissolves. A line +/// already on its way out keeps its own timing. +pub fn dismissMessage(p: *Pardes, pane: *Pane) void { + if (pane.msg_len > 0 and dismissLine(p, &pane.msg_life)) { + pane.msg_len = 0; + pane.msg_life = .{}; + } + var i: usize = 0; + while (i < pane.msg_older_len) { + if (dismissLine(p, &pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1; + } +} + +/// Start one line's exit; true when it is gone at once (no linger, no +/// animation). +fn dismissLine(p: *const Pardes, life: *Pane.MessageLife) bool { + switch (life.phase) { + .lingering, .leaving => return false, + // A falling line lands first, then lingers -- unless falling was + // just turned off, and nothing will land it. + .entering => if (p.settings.message_animation) { + life.dismissed = true; + return false; + }, + .shown => {}, + } + life.frame = 0; + if (p.settings.message_linger_ms > 0) { + life.phase = .lingering; + } else if (p.settings.message_animation) { + life.phase = .leaving; + } else return true; + return false; +} + +/// One animation frame of every message line. Each one that moves owes +/// a frame, the one that finishes included: a tick asks for none itself. +pub fn advanceMessages(p: *Pardes) void { + for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.msg_len > 0 and pane.msg_life.phase != .shown) { + p.needs_frame = true; + if (advanceLine(p, &pane.msg_life)) { + pane.msg_len = 0; + pane.msg_life = .{}; + } + } + var i: usize = 0; + while (i < pane.msg_older_len) { + if (pane.msg_older[i].life.phase != .shown) p.needs_frame = true; + if (advanceLine(p, &pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1; + } + } +} + +/// One frame of one line's life; true once it has left. +fn advanceLine(p: *const Pardes, life: *Pane.MessageLife) bool { + if (life.phase == .shown) return false; + life.frame +|= 1; + switch (life.phase) { + .shown => {}, + .entering => if (life.frame >= messageFrames(p.settings.message_fall_ms)) { + life.* = .{ .phase = if (life.dismissed) .lingering else .shown }; + }, + .lingering => if (life.frame >= messageFrames(p.settings.message_linger_ms)) { + if (!p.settings.message_animation) return true; + life.* = .{ .phase = .leaving }; + }, + .leaving => if (life.frame >= messageFrames(p.settings.message_dissolve_ms)) return true, + } + return false; +} + +/// Is any message line moving (and so owed ticks)? +pub fn messagesAnimating(pane: *const Pane) bool { + if (pane.msg_len > 0 and pane.msg_life.phase != .shown) return true; + for (pane.msg_older[0..pane.msg_older_len]) |line| if (line.life.phase != .shown) return true; + return false; +} + +/// How present a message is (1 = fully) and how far above its row it +/// still is (rows): a fall that decelerates into place with its colour +/// arriving ahead of it, and a dissolve. +pub const MessageMotion = struct { alpha: f32 = 1, slide: f32 = 0 }; + +/// Animation frames a message timing lasts; at least one. +pub fn messageFrames(ms: u16) u16 { + return @intCast(@max(1, (@as(u32, ms) + layout.Animation.frame_ms - 1) / layout.Animation.frame_ms)); +} + +pub fn messageMotion(p: *const Pardes, life: Pane.MessageLife) MessageMotion { + const fall_frames = messageFrames(p.settings.message_fall_ms); + const dissolve_frames = messageFrames(p.settings.message_dissolve_ms); + return switch (life.phase) { + .shown, .lingering => .{ .alpha = 1, .slide = 0 }, + .entering => blk: { + const t = @as(f32, @floatFromInt(@min(life.frame, fall_frames))) / @as(f32, @floatFromInt(fall_frames)); + // Out of the gate fast and easing into its row (a cubic + // ease-out), so it is there the moment it is said and the + // last frames only settle it. No overshoot: at a row's height + // and a dozen frames, a follow-through is a pixel or two that + // reads as a jitter, not a bounce. + const left = 1 - t; + // The colour leads the motion: solid by half way, so what + // lands is already legible rather than still fading up. + const faded = 1 - @min(1, 2 * t); + break :blk .{ .alpha = 1 - faded * faded, .slide = -(left * left * left) }; + }, + .leaving => blk: { + // Counted to its last frame rather than past it, so that frame + // shows it gone and it never blinks out from part way. + const last = @max(1, dissolve_frames - 1); + const t = @as(f32, @floatFromInt(@min(life.frame, last))) / @as(f32, @floatFromInt(last)); + // An exit eases in: still readable for a beat, then away + // faster and faster. It stays where it is -- the lines + // stacked around it do not move either. + break :blk .{ .alpha = 1 - t * t, .slide = 0 }; + }, + }; +} + +/// What notice band `i` says. The grid pass and the band layers both +/// read it here, so a terminal and a pixel shell show the same line. +pub fn noticeText(p: *const Pardes, pane: *const Pane, i: usize, leader_buf: *[16]u8) []const u8 { + return switch (pane.notices.kinds[i]) { + .message => pane.msg[0..pane.msg_len], + .older => pane.msg_older[pane.notices.index[i]].slice(), + .leader => leaderText(p, leader_buf), + .prompt => pane.promptText() orelse "", + }; +} + +/// The life of the message line notice `i` shows, if it shows one. +pub fn noticeLife(pane: *const Pane, i: usize) ?Pane.MessageLife { + return switch (pane.notices.kinds[i]) { + .message => pane.msg_life, + .older => pane.msg_older[pane.notices.index[i]].life, + .leader, .prompt => null, + }; +} + +pub fn blendRgb(from: [3]u8, to: [3]u8, amount: f32) [3]u8 { + var out: [3]u8 = undefined; + for (&out, from, to) |*o, a, b| { + const af: f32 = @floatFromInt(a); + const bf: f32 = @floatFromInt(b); + o.* = @intFromFloat(@round(bf + (af - bf) * std.math.clamp(amount, 0, 1))); + } + return out; +} + +fn logMessage(p: *Pardes, id: usize, text: []const u8) void { + if (text.len == 0) return; + const serial: u32 = if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; + const kept = text[0..@min(text.len, LoggedMessage.cap)]; + // /log hears every one: a client that retried and failed the same way + // is waiting on that second line. Only the +Messages view collapses. + ctlfs.events.noteMessage(p, serial, kept); + if (p.messages_len > 0) { + const last = &p.messages[(p.messages_head + limits.message_log - 1) % limits.message_log]; + if (last.serial == serial and + std.mem.eql(u8, Message.body(last.slice()), Message.body(kept))) + { + // The NEWEST wording wins, so the row carries the latest clock + // rather than the moment the run started. + last.len = @intCast(kept.len); + @memcpy(last.text[0..last.len], kept); + last.repeats +|= 1; + return; + } + } + const slot = &p.messages[p.messages_head]; + slot.len = @intCast(kept.len); + @memcpy(slot.text[0..slot.len], kept); + slot.serial = serial; + slot.repeats = 1; + p.messages_head = (p.messages_head + 1) % limits.message_log; + p.messages_len = @min(p.messages_len + 1, limits.message_log); +} + +/// The log oldest-first, which is reading order. +pub fn messageLog(p: *const Pardes, i: usize) ?*const LoggedMessage { + if (i >= p.messages_len) return null; + const first = (p.messages_head + limits.message_log - p.messages_len) % limits.message_log; + return &p.messages[(first + i) % limits.message_log]; +} + +pub fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) void { + var buf: [256]u8 = undefined; + const text = std.fmt.bufPrint(&buf, "{s}: {s}", .{ operation, @errorName(err) }) catch operation; + setMessage(p, id, text); +} + +/// 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 +/// them instead of letting the last one win the row. +pub fn collectNotices(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { + pane.notices.len = 0; + if (r.w <= config.GUTTER or r.h <= BOX_H) return; + // Oldest message line on top, so lines already up do not move when a + // new one lands under them; when rows run out the oldest go first. + for (pane.msg_older[0..pane.msg_older_len], 0..) |line, i| pane.notices.pushAt(.older, @intCast(i), line.slot); + if (pane.msg_len > 0) pane.notices.pushAt(.message, 0, pane.msg_slot); + if (id == p.active and p.leader_on) pane.notices.push(.leader); + if (pane.promptText()) |text| if (text.len > 0) pane.notices.push(.prompt); + // A pane only has so many rows to give. When they do not all fit the + // LAST ones survive, because the prompt is last and it is the one + // carrying the cursor: a prompt you cannot see is a prompt you type + // into blind. A two-row pane spends its only body row on one notice, + // which is what the single shared row used to do anyway. + const room: u8 = @intCast(@min(@as(u16, Pane.Notices.max), r.h - BOX_H)); + const n = &pane.notices; + if (n.span() <= room) return; + // Too short for the gaps: close them up in screen order, and if even + // that does not fit, the top bands go. + var i: usize = 1; + while (i < n.len) : (i += 1) { + var j = i; + while (j > 0 and n.row[j - 1] > n.row[j]) : (j -= 1) { + std.mem.swap(Pane.Notices.Kind, &n.kinds[j - 1], &n.kinds[j]); + std.mem.swap(u8, &n.index[j - 1], &n.index[j]); + std.mem.swap(u8, &n.row[j - 1], &n.row[j]); + } + } + const drop = n.len -| room; + for (0..n.len - drop) |k| { + n.kinds[k] = n.kinds[k + drop]; + n.index[k] = n.index[k + drop]; + n.row[k] = @intCast(k); + } + n.len -= @intCast(drop); +} + +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 }); + defer p.deinit(); + + setMessage(p, 0, "14:32:07 saved /x.zig"); + setMessage(p, 0, "14:32:09 saved /x.zig"); // same event, later clock + setMessage(p, 0, "save: AccessDenied"); + + try std.testing.expectEqual(@as(usize, 2), p.messages_len); + const first = messageLog(p, 0).?; + try std.testing.expectEqual(@as(u16, 2), first.repeats); + // ...and the NEWEST wording is what survives, so the row carries the last + // time it happened rather than the first. + try std.testing.expectEqualStrings("14:32:09 saved /x.zig", first.slice()); + try std.testing.expectEqualStrings("save: AccessDenied", messageLog(p, 1).?.slice()); + try std.testing.expect(messageLog(p, 2) == null); + + // The same text from a DIFFERENT pane is a different event: one pane's + // failure must not be recorded as another's. + p.newScratchBelow(0); + const other = p.active; + setMessage(p, other, "save: AccessDenied"); + try std.testing.expectEqual(@as(usize, 3), p.messages_len); + try std.testing.expectEqual(p.panes[other].?.serial, messageLog(p, 2).?.serial); + + // Progress is NOT logged: it arrives several times a second for a whole + // index and would push everything else out (`setStatus`). + setStatus(p, 0, "14:32:10 lsp rust-analyzer: Indexing 47%"); + try std.testing.expectEqual(@as(usize, 3), p.messages_len); + + // The ring wraps rather than grows, and still reads oldest-first. + for (0..limits.message_log + 5) |i| { + var buf: [32]u8 = undefined; + setMessage(p, 0, std.fmt.bufPrint(&buf, "line {d}", .{i}) catch unreachable); + } + try std.testing.expectEqual(@as(usize, limits.message_log), p.messages_len); + try std.testing.expectEqualStrings("line 5", messageLog(p, 0).?.slice()); + var last_buf: [32]u8 = undefined; + const want_last = std.fmt.bufPrint(&last_buf, "line {d}", .{limits.message_log + 4}) catch unreachable; + try std.testing.expectEqualStrings(want_last, messageLog(p, limits.message_log - 1).?.slice()); +} + +test "Msg writes the transient row by hand, bare or with text, and input ends it" { + const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const row = struct { + fn of(pp: *Pardes, i: usize) []const u8 { + const pane = pp.panes[i].?; + return pane.msg[0..pane.msg_len]; + } + }.of; + + // the whole tail, spaces and all: the row is a sentence, not a word + try std.testing.expect(p.executeBuiltinLine(2, "Msg saved /etc/hosts")); + try std.testing.expectEqualStrings("saved /etc/hosts", row(p, 2)); + // ...on the pane that ran it, and nowhere else + try std.testing.expectEqualStrings("", row(p, 0)); + + // Bare, it reports ITSELF through reportError — the `: ` + // every failed save and refused Look arrives in. + try std.testing.expect(p.executeBuiltinLine(2, "Msg")); + try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); + + // Input starts its exit: it lingers, dissolves, and is gone. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); + for (0..200) |_| p.update(.tick); + try std.testing.expectEqualStrings("", row(p, 2)); + // ...and with neither linger nor animation it is as old as your last input. + try std.testing.expect(p.executeBuiltinLine(2, "MessageAnimation off")); + try std.testing.expect(p.executeBuiltinLine(2, "MessageLinger 0")); + try std.testing.expect(p.executeBuiltinLine(2, "Msg gone")); + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqualStrings("", row(p, 2)); + + // Longer than the row's buffer is CUT, never refused and never overrun: + // this word is the only way to reach that boundary without a 300-byte path. + var long: [600]u8 = @splat('x'); + var line: [608]u8 = undefined; + const cmd = try std.fmt.bufPrint(&line, "Msg {s}", .{&long}); + try std.testing.expect(p.executeBuiltinLine(2, cmd)); + try std.testing.expectEqual(p.panes[2].?.msg.len, row(p, 2).len); +} + +test "a message falls in, lingers past the input that dismisses it, and dissolves" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[p.active].?; + try std.testing.expect(p.settings.message_animation); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageLinger 160")); + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + try std.testing.expect(p.animationActive()); + // An ease-out fall: starts a whole row up and unseen, covers most of the + // way at once and settles into its row, landing exactly on it without + // passing it. Its colour is whole by half way. + const start = messageMotion(p, pane.msg_life); + try std.testing.expectEqual(@as(f32, -1), start.slide); + try std.testing.expectEqual(@as(f32, 0), start.alpha); + const fall = messageFrames(p.settings.message_fall_ms); + var last = start; + var first_step: f32 = 0; + var last_step: f32 = 0; + for (0..fall) |frame| { + p.needs_frame = false; + p.update(.tick); + // Every tick that moves it owes a frame, the landing one included. + try std.testing.expect(p.needs_frame); + const now = messageMotion(p, pane.msg_life); + try std.testing.expect(now.slide >= last.slide and now.slide <= 0); + try std.testing.expect(now.alpha >= last.alpha); + if (frame == 0) first_step = now.slide - last.slide; + // Never slower to colour up than to arrive, and solid by half way. + try std.testing.expect(now.alpha >= 1 + now.slide); + if (2 * (frame + 1) >= fall) try std.testing.expectEqual(@as(f32, 1), now.alpha); + last_step = now.slide - last.slide; + last = now; + } + try std.testing.expect(first_step > 4 * last_step); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expectEqual(@as(f32, 0), messageMotion(p, pane.msg_life).slide); + try std.testing.expect(!p.animationActive()); + // Shown until input, like always; the same line again does not re-enter. + for (0..100) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + // Input (a key that announces nothing): 160 ms of lingering (ten frames), unaffected by more input... + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + for (0..9) |_| { + p.update(.tick); + p.update(.{ .key = .{ .cp = 'h' } }); + } + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + p.update(.tick); + // ...then an ease-in dissolve: it lets go slowly and goes faster and + // faster, in place, its last frame showing it gone. + try std.testing.expectEqual(Pane.MessagePhase.leaving, pane.msg_life.phase); + const dissolve = messageFrames(p.settings.message_dissolve_ms); + var alpha: f32 = 1; + var first_drop: f32 = 0; + var last_drop: f32 = 0; + for (0..dissolve) |frame| { + const now = messageMotion(p, pane.msg_life); + try std.testing.expect(now.alpha <= alpha); + try std.testing.expectEqual(@as(f32, 0), now.slide); + if (frame == 1) first_drop = alpha - now.alpha; + last_drop = alpha - now.alpha; + alpha = now.alpha; + p.needs_frame = false; + p.update(.tick); + } + try std.testing.expectEqual(@as(f32, 0), alpha); + try std.testing.expect(first_drop > 0 and first_drop < last_drop); + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); + try std.testing.expect(!p.animationActive()); + // The tick that clears it still owes the frame that shows it gone. + try std.testing.expect(p.needs_frame); + + // Dismissed mid-fall: it lands, then lingers. + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg again")); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + p.update(.tick); + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + for (0..messageFrames(p.settings.message_fall_ms)) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + // Shown again while lingering: fresh, so it stays; a status update to a + // line on screen swaps its text in place instead of falling again. + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg again")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + setStatus(p, p.active, "progress 50%"); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expectEqualStrings("progress 50%", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + // The fall and the dissolve are timings of their own, in milliseconds. + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageFall 48")); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageDissolve 0")); + try std.testing.expectEqual(@as(u16, 3), messageFrames(p.settings.message_fall_ms)); + try std.testing.expectEqual(@as(u16, 1), messageFrames(p.settings.message_dissolve_ms)); + // The Config report reads back as configuration. + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageAnimation")); + try std.testing.expect(!p.settings.message_animation); + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg plain")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); +} + +test "messages stack, oldest on top, each on its own timing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[p.active].?; + try std.testing.expect(p.executeBuiltinLine(p.active, "Verbose off")); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageLinger 160")); + // `Verbose off` announced itself before it took effect. + pane.msg_len = 0; + pane.msg_life = .{}; + const fall = messageFrames(p.settings.message_fall_ms); + setMessage(p, p.active, "first"); + for (0..fall) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + // A second message stacks under the first instead of replacing it. + setMessage(p, p.active, "second"); + try std.testing.expectEqual(@as(u8, 1), pane.msg_older_len); + try std.testing.expectEqualStrings("first", pane.msg_older[0].slice()); + try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + collectNotices(p, pane, p.rects[p.active], p.active); + try std.testing.expectEqual(Pane.Notices.Kind.older, pane.notices.kinds[0]); + try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[1]); + // One key dismisses both, but each runs its own clock: the first starts + // lingering now, the second only once it has landed. + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_older[0].life.phase); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + const linger = messageFrames(p.settings.message_linger_ms); + const dissolve = messageFrames(p.settings.message_dissolve_ms); + for (0..linger + dissolve) |_| p.update(.tick); + // The first is gone; the second, a fall later, is still dissolving. + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(Pane.MessagePhase.leaving, pane.msg_life.phase); + for (0..fall) |_| p.update(.tick); + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); + try std.testing.expect(!p.animationActive()); + // A status ticking in place does not pile up. + setStatus(p, p.active, "lsp 10%"); + setStatus(p, p.active, "lsp 20%"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + // Lines keep their rows: when the top one leaves, the one under it does + // not move up, and the next message fills the gap instead. + setMessage(p, p.active, "top"); + setMessage(p, p.active, "under"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older[0].slot); + try std.testing.expectEqual(@as(u8, 1), pane.msg_slot); + pane.removeOlderMessage(0); + collectNotices(p, pane, p.rects[p.active], p.active); + try std.testing.expectEqual(@as(u8, 1), pane.notices.row[0]); + try std.testing.expectEqual(@as(u8, 2), pane.notices.span()); + setMessage(p, p.active, "fills"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_slot); + try std.testing.expectEqual(@as(u8, 1), pane.msg_older[0].slot); + // The stack keeps the newest few. + for ([_][]const u8{ "a", "b", "c", "d", "e" }) |text| setMessage(p, p.active, text); + try std.testing.expectEqual(@as(u8, Pane.message_stack), pane.msg_older_len); + try std.testing.expectEqualStrings("b", pane.msg_older[0].slice()); + try std.testing.expectEqualStrings("e", pane.msg[0..pane.msg_len]); +} + +test "a builtin announces itself on the message row, and Verbose silences it" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = p.panes[p.active].?; + + p.sync(); + try std.testing.expect(p.settings.verbose); + // Wrap, not Collapse: a builtin that folds its own pane away leaves no row + // for its announcement, which is correct and not what this is testing. + try std.testing.expect(p.executeBuiltinLine(p.active, "Wrap")); + try std.testing.expectEqualStrings("Wrap", pane.msg[0..pane.msg_len]); + + // The notice list is what the paint pass reads, so the announcement has to + // reach it, not just the buffer. + collectNotices(p, pane, p.rects[p.active], p.active); + try std.testing.expect(pane.notices.len > 0); + try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[0]); + + // ...and it is carried as a tagline band, not a body row: that is what + // gives it the tagline's height, its small font and its border. + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const r = p.rects[p.active]; + const band = for (p.surface.tagLayers()) |*layer| { + if (layer.cols != 0 and layer.kind == .notice) break layer; + } else return error.NoNoticeBand; + try std.testing.expectEqual(@as(u16, 1), band.viewport.h); + try std.testing.expectEqual(if (p.settings.tag_bottom) r.y else r.y + BOX_H, band.viewport.y); + // Right aligned: the text ends at the band's right edge. + const line = band.cells[0..band.cols]; + var last: usize = line.len; + while (last > 0 and line[last - 1].grapheme()[0] == ' ') last -= 1; + try std.testing.expect(last > 0); + try std.testing.expect(line[0].grapheme()[0] == ' '); + + // Msg owns the row itself, so it does not announce over its own text. + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); + try std.testing.expectEqualStrings("hello", pane.msg[0..pane.msg_len]); + + pane.msg_len = 0; + p.settings.verbose = false; + try std.testing.expect(p.executeBuiltinLine(p.active, "Wrap")); + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); +} + +test "notices stack over the body's top rows without moving them" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const id = p.active; + const pane = p.panes[id].?; + p.sync(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + + const r = p.rects[id]; + const top = p.bodyTop(r); + + // A message and a leader prefix at once: two chips, in the order + // collectNotices chose, each one row tall and each one row further down. + try std.testing.expect(p.executeBuiltinLine(id, "Msg first")); + p.leader_on = true; + p.leader_n = 0; + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try std.testing.expectEqual(@as(u8, 2), pane.notices.len); + // An overlay, not a reservation: the body still starts where it did. + try std.testing.expectEqual(top, p.bodyTop(r)); + + var seen: usize = 0; + for (p.surface.tagLayers()) |*layer| { + if (layer.cols == 0 or layer.kind != .notice) continue; + try std.testing.expectEqual(@as(u16, 1), layer.viewport.h); + // Sized to its own message, right up against the pane's right edge -- + // not the width of the pane. + try std.testing.expectEqual(r.x + r.w, layer.viewport.x + layer.viewport.w); + try std.testing.expect(layer.viewport.w < r.w - config.GUTTER); + try std.testing.expect(layer.viewport.y == top or layer.viewport.y == top + 1); + try std.testing.expectEqual(pane.notices.left[layer.viewport.y - top], layer.viewport.x); + seen += 1; + } + try std.testing.expectEqual(@as(usize, 2), seen); + // "first" is longer than "SPC", so its chip is wider. + try std.testing.expect(pane.notices.left[0] < pane.notices.left[1]); + + // Gone with the notices: no stale chip left behind. + p.leader_on = false; + pane.msg_len = 0; + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + for (p.surface.tagLayers()) |*layer| + try std.testing.expect(layer.cols == 0 or layer.kind != .notice); +} diff --git a/src/Output.zig b/src/Output.zig index 00122b16..3b8100ac 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -3,6 +3,7 @@ const panes = @import("panes.zig"); const std = @import("std"); const pardes = @import("pardes.zig"); +const Messages = @import("Messages.zig"); const config = @import("config.zig"); const Pardes = pardes.Pardes; const modal = @import("modal.zig"); @@ -684,7 +685,7 @@ pub fn openMessages(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var i: usize = 0; - while (p.messageLog(i)) |m| : (i += 1) { + while (Messages.messageLog(p, i)) |m| : (i += 1) { if (m.serial != 0) try out.writer.print("{d}: ", .{m.serial}); try out.writer.writeAll(m.slice()); if (m.repeats > 1) try out.writer.print(" (x{d})", .{m.repeats}); diff --git a/src/detached/server.zig b/src/detached/server.zig index c8d4b45e..e33354cf 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -15,7 +15,7 @@ const ninep_io = @import("../9p_io.zig"); const look = @import("../look.zig"); -const message = pardes.Pardes.Message; +const message = pardes.Messages.Message; const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); diff --git a/src/file_watch.zig b/src/file_watch.zig index 2d1c0d25..5d998470 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -15,7 +15,7 @@ const linux = std.os.linux; const pardes = @import("pardes.zig"); const colors = @import("colors.zig"); const filesystem = @import("fs.zig"); -const message = pardes.Pardes.Message; +const message = pardes.Messages.Message; pub const Identity = struct { inode: std.Io.File.INode, diff --git a/src/fs.zig b/src/fs.zig index 86154fc1..5817b3a4 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -38,6 +38,7 @@ const source_files = [_]Source{ .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, .{ .path = "src/surface.zig", .contents = @embedFile("surface.zig") }, .{ .path = "src/colors.zig", .contents = @embedFile("colors.zig") }, + .{ .path = "src/Messages.zig", .contents = @embedFile("Messages.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 6174c0d8..86c69ff6 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -8,7 +8,7 @@ const ghostty_vt = @import("ghostty-vt"); // 256-color palette for .index cells const pardes = @import("../pardes.zig"); const config = @import("../config.zig"); const look = @import("../look.zig"); -const message = pardes.Pardes.Message; +const message = pardes.Messages.Message; const file_watch = @import("../file_watch.zig"); const deck = @import("deck.zig"); const crt = @import("crt.zig"); diff --git a/src/macos.zig b/src/macos.zig index b4e03c13..cab8212a 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -8,7 +8,7 @@ const libc = std.c; const pardes = @import("pardes.zig"); const colors = @import("colors.zig"); const look = @import("look.zig"); -const message = pardes.Pardes.Message; +const message = pardes.Messages.Message; const layout = @import("layout.zig"); const file_watch = @import("file_watch.zig"); const image = if (pardes.pdf_enabled) @import("image.zig") else struct {}; diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 8d5ba16c..0e8d7bb7 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -149,7 +149,7 @@ pub fn noteLog(p: *Pardes, kind: LogKind, pane: *Pane) void { /// Records `msg ` for what the editor said, `-` for no pane. pub fn noteMessage(p: *Pardes, serial: u32, text: []const u8) void { - var buf: [pardes.LoggedMessage.cap + 32]u8 = undefined; + var buf: [pardes.Messages.LoggedMessage.cap + 32]u8 = undefined; pushLog(p, (if (serial == 0) std.fmt.bufPrint(&buf, "msg - {s}\n", .{text}) else diff --git a/src/pardes.zig b/src/pardes.zig index 6fefe081..c171c669 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const Messages = @import("Messages.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; pub const themes = colors.themes; @@ -430,6 +431,7 @@ pub const Loc = struct { }; test { + _ = @import("Messages.zig"); _ = @import("selection_pipe.zig"); _ = @import("colors.zig"); _ = @import("surface.zig"); @@ -637,49 +639,6 @@ test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" try std.testing.expectEqual(@as(i32, 1), pane.cur_row); } -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 }); - defer p.deinit(); - - p.setMessage(0, "14:32:07 saved /x.zig"); - p.setMessage(0, "14:32:09 saved /x.zig"); // same event, later clock - p.setMessage(0, "save: AccessDenied"); - - try std.testing.expectEqual(@as(usize, 2), p.messages_len); - const first = p.messageLog(0).?; - try std.testing.expectEqual(@as(u16, 2), first.repeats); - // ...and the NEWEST wording is what survives, so the row carries the last - // time it happened rather than the first. - try std.testing.expectEqualStrings("14:32:09 saved /x.zig", first.slice()); - try std.testing.expectEqualStrings("save: AccessDenied", p.messageLog(1).?.slice()); - try std.testing.expect(p.messageLog(2) == null); - - // The same text from a DIFFERENT pane is a different event: one pane's - // failure must not be recorded as another's. - p.newScratchBelow(0); - const other = p.active; - p.setMessage(other, "save: AccessDenied"); - try std.testing.expectEqual(@as(usize, 3), p.messages_len); - try std.testing.expectEqual(p.panes[other].?.serial, p.messageLog(2).?.serial); - - // Progress is NOT logged: it arrives several times a second for a whole - // index and would push everything else out (`setStatus`). - p.setStatus(0, "14:32:10 lsp rust-analyzer: Indexing 47%"); - try std.testing.expectEqual(@as(usize, 3), p.messages_len); - - // The ring wraps rather than grows, and still reads oldest-first. - for (0..limits.message_log + 5) |i| { - var buf: [32]u8 = undefined; - p.setMessage(0, std.fmt.bufPrint(&buf, "line {d}", .{i}) catch unreachable); - } - try std.testing.expectEqual(@as(usize, limits.message_log), p.messages_len); - try std.testing.expectEqualStrings("line 5", p.messageLog(0).?.slice()); - var last_buf: [32]u8 = undefined; - const want_last = std.fmt.bufPrint(&last_buf, "line {d}", .{limits.message_log + 4}) catch unreachable; - try std.testing.expectEqualStrings(want_last, p.messageLog(limits.message_log - 1).?.slice()); -} - 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 }); @@ -2332,216 +2291,6 @@ test "a builtin that needs a pane reports capacity failure when every slot is fu try std.testing.expect(std.mem.indexOf(u8, p.panes[0].?.msg[0..p.panes[0].?.msg_len], "help: NoPaneSlots") != null); } -test "Msg writes the transient row by hand, bare or with text, and input ends it" { - const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const row = struct { - fn of(pp: *Pardes, i: usize) []const u8 { - const pane = pp.panes[i].?; - return pane.msg[0..pane.msg_len]; - } - }.of; - - // the whole tail, spaces and all: the row is a sentence, not a word - try std.testing.expect(p.executeBuiltinLine(2, "Msg saved /etc/hosts")); - try std.testing.expectEqualStrings("saved /etc/hosts", row(p, 2)); - // ...on the pane that ran it, and nowhere else - try std.testing.expectEqualStrings("", row(p, 0)); - - // Bare, it reports ITSELF through reportError — the `: ` - // every failed save and refused Look arrives in. - try std.testing.expect(p.executeBuiltinLine(2, "Msg")); - try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); - - // Input starts its exit: it lingers, dissolves, and is gone. - p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); - for (0..200) |_| p.update(.tick); - try std.testing.expectEqualStrings("", row(p, 2)); - // ...and with neither linger nor animation it is as old as your last input. - try std.testing.expect(p.executeBuiltinLine(2, "MessageAnimation off")); - try std.testing.expect(p.executeBuiltinLine(2, "MessageLinger 0")); - try std.testing.expect(p.executeBuiltinLine(2, "Msg gone")); - p.update(.{ .key = .{ .cp = 'h' } }); - try std.testing.expectEqualStrings("", row(p, 2)); - - // Longer than the row's buffer is CUT, never refused and never overrun: - // this word is the only way to reach that boundary without a 300-byte path. - var long: [600]u8 = @splat('x'); - var line: [608]u8 = undefined; - const cmd = try std.fmt.bufPrint(&line, "Msg {s}", .{&long}); - try std.testing.expect(p.executeBuiltinLine(2, cmd)); - try std.testing.expectEqual(p.panes[2].?.msg.len, row(p, 2).len); -} - -test "a message falls in, lingers past the input that dismisses it, and dissolves" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[p.active].?; - try std.testing.expect(p.settings.message_animation); - try std.testing.expect(p.executeBuiltinLine(p.active, "MessageLinger 160")); - try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); - try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); - try std.testing.expect(p.animationActive()); - // An ease-out fall: starts a whole row up and unseen, covers most of the - // way at once and settles into its row, landing exactly on it without - // passing it. Its colour is whole by half way. - const start = p.messageMotion(pane.msg_life); - try std.testing.expectEqual(@as(f32, -1), start.slide); - try std.testing.expectEqual(@as(f32, 0), start.alpha); - const fall = Pardes.messageFrames(p.settings.message_fall_ms); - var last = start; - var first_step: f32 = 0; - var last_step: f32 = 0; - for (0..fall) |frame| { - p.needs_frame = false; - p.update(.tick); - // Every tick that moves it owes a frame, the landing one included. - try std.testing.expect(p.needs_frame); - const now = p.messageMotion(pane.msg_life); - try std.testing.expect(now.slide >= last.slide and now.slide <= 0); - try std.testing.expect(now.alpha >= last.alpha); - if (frame == 0) first_step = now.slide - last.slide; - // Never slower to colour up than to arrive, and solid by half way. - try std.testing.expect(now.alpha >= 1 + now.slide); - if (2 * (frame + 1) >= fall) try std.testing.expectEqual(@as(f32, 1), now.alpha); - last_step = now.slide - last.slide; - last = now; - } - try std.testing.expect(first_step > 4 * last_step); - try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); - try std.testing.expectEqual(@as(f32, 0), p.messageMotion(pane.msg_life).slide); - try std.testing.expect(!p.animationActive()); - // Shown until input, like always; the same line again does not re-enter. - for (0..100) |_| p.update(.tick); - try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); - try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); - try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); - // Input (a key that announces nothing): 160 ms of lingering (ten frames), unaffected by more input... - p.update(.{ .key = .{ .cp = 'h' } }); - try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); - for (0..9) |_| { - p.update(.tick); - p.update(.{ .key = .{ .cp = 'h' } }); - } - try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); - p.update(.tick); - // ...then an ease-in dissolve: it lets go slowly and goes faster and - // faster, in place, its last frame showing it gone. - try std.testing.expectEqual(Pane.MessagePhase.leaving, pane.msg_life.phase); - const dissolve = Pardes.messageFrames(p.settings.message_dissolve_ms); - var alpha: f32 = 1; - var first_drop: f32 = 0; - var last_drop: f32 = 0; - for (0..dissolve) |frame| { - const now = p.messageMotion(pane.msg_life); - try std.testing.expect(now.alpha <= alpha); - try std.testing.expectEqual(@as(f32, 0), now.slide); - if (frame == 1) first_drop = alpha - now.alpha; - last_drop = alpha - now.alpha; - alpha = now.alpha; - p.needs_frame = false; - p.update(.tick); - } - try std.testing.expectEqual(@as(f32, 0), alpha); - try std.testing.expect(first_drop > 0 and first_drop < last_drop); - try std.testing.expectEqual(@as(u16, 0), pane.msg_len); - try std.testing.expect(!p.animationActive()); - // The tick that clears it still owes the frame that shows it gone. - try std.testing.expect(p.needs_frame); - - // Dismissed mid-fall: it lands, then lingers. - try std.testing.expect(p.executeBuiltinLine(p.active, "Msg again")); - try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); - p.update(.tick); - p.update(.{ .key = .{ .cp = 'h' } }); - try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); - for (0..Pardes.messageFrames(p.settings.message_fall_ms)) |_| p.update(.tick); - try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); - // Shown again while lingering: fresh, so it stays; a status update to a - // line on screen swaps its text in place instead of falling again. - try std.testing.expect(p.executeBuiltinLine(p.active, "Msg again")); - try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); - p.setStatus(p.active, "progress 50%"); - try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); - try std.testing.expectEqualStrings("progress 50%", pane.msg[0..pane.msg_len]); - try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); - // The fall and the dissolve are timings of their own, in milliseconds. - try std.testing.expect(p.executeBuiltinLine(p.active, "MessageFall 48")); - try std.testing.expect(p.executeBuiltinLine(p.active, "MessageDissolve 0")); - try std.testing.expectEqual(@as(u16, 3), Pardes.messageFrames(p.settings.message_fall_ms)); - try std.testing.expectEqual(@as(u16, 1), Pardes.messageFrames(p.settings.message_dissolve_ms)); - // The Config report reads back as configuration. - try std.testing.expect(p.executeBuiltinLine(p.active, "MessageAnimation")); - try std.testing.expect(!p.settings.message_animation); - try std.testing.expect(p.executeBuiltinLine(p.active, "Msg plain")); - try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); -} - -test "messages stack, oldest on top, each on its own timing" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[p.active].?; - try std.testing.expect(p.executeBuiltinLine(p.active, "Verbose off")); - try std.testing.expect(p.executeBuiltinLine(p.active, "MessageLinger 160")); - // `Verbose off` announced itself before it took effect. - pane.msg_len = 0; - pane.msg_life = .{}; - const fall = Pardes.messageFrames(p.settings.message_fall_ms); - p.setMessage(p.active, "first"); - for (0..fall) |_| p.update(.tick); - try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); - // A second message stacks under the first instead of replacing it. - p.setMessage(p.active, "second"); - try std.testing.expectEqual(@as(u8, 1), pane.msg_older_len); - try std.testing.expectEqualStrings("first", pane.msg_older[0].slice()); - try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]); - try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); - p.collectNotices(pane, p.rects[p.active], p.active); - try std.testing.expectEqual(Pane.Notices.Kind.older, pane.notices.kinds[0]); - try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[1]); - // One key dismisses both, but each runs its own clock: the first starts - // lingering now, the second only once it has landed. - p.update(.{ .key = .{ .cp = 'h' } }); - try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_older[0].life.phase); - try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); - const linger = Pardes.messageFrames(p.settings.message_linger_ms); - const dissolve = Pardes.messageFrames(p.settings.message_dissolve_ms); - for (0..linger + dissolve) |_| p.update(.tick); - // The first is gone; the second, a fall later, is still dissolving. - try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); - try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]); - try std.testing.expectEqual(Pane.MessagePhase.leaving, pane.msg_life.phase); - for (0..fall) |_| p.update(.tick); - try std.testing.expectEqual(@as(u16, 0), pane.msg_len); - try std.testing.expect(!p.animationActive()); - // A status ticking in place does not pile up. - p.setStatus(p.active, "lsp 10%"); - p.setStatus(p.active, "lsp 20%"); - try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); - // Lines keep their rows: when the top one leaves, the one under it does - // not move up, and the next message fills the gap instead. - p.setMessage(p.active, "top"); - p.setMessage(p.active, "under"); - try std.testing.expectEqual(@as(u8, 0), pane.msg_older[0].slot); - try std.testing.expectEqual(@as(u8, 1), pane.msg_slot); - pane.removeOlderMessage(0); - p.collectNotices(pane, p.rects[p.active], p.active); - try std.testing.expectEqual(@as(u8, 1), pane.notices.row[0]); - try std.testing.expectEqual(@as(u8, 2), pane.notices.span()); - p.setMessage(p.active, "fills"); - try std.testing.expectEqual(@as(u8, 0), pane.msg_slot); - try std.testing.expectEqual(@as(u8, 1), pane.msg_older[0].slot); - // The stack keeps the newest few. - for ([_][]const u8{ "a", "b", "c", "d", "e" }) |text| p.setMessage(p.active, text); - try std.testing.expectEqual(@as(u8, Pane.message_stack), pane.msg_older_len); - try std.testing.expectEqualStrings("b", pane.msg_older[0].slice()); - try std.testing.expectEqualStrings("e", pane.msg[0..pane.msg_len]); -} - test "Font keeps requested and acknowledged faces as separate plain state" { if (comptime !font_picker) return; // there is no Font builtin on tty or web const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); @@ -4851,23 +4600,6 @@ pub const Options = struct { rows: u16 = 24, }; -pub const LoggedMessage = struct { - pub const cap = 256; - text: [cap]u8 = undefined, - len: u16 = 0, - /// The serial of the pane that said it, or 0 for none in particular. A - /// serial, not a slot: slots are reused, so an old line would name - /// whichever pane took the slot since. - serial: u32 = 0, - /// How many times in a row. Saturating: a key held down against the same - /// refusal is one event, not four hundred. - repeats: u16 = 0, - - pub fn slice(m: *const LoggedMessage) []const u8 { - return m.text[0..m.len]; - } -}; - pub const Haptic = enum { none, exec, look }; /// Zero-sized off macOS, the way PdfSlot is off -Dmupdf: no other shell reads @@ -5035,7 +4767,7 @@ pub const Pardes = struct { fallback: host_io.Fallback, /// The message-row log: a fixed ring, never allocated, never grown. See /// `logMessage` and the `Messages` builtin. - messages: [limits.message_log]LoggedMessage = @splat(.{}), + messages: [limits.message_log]Messages.LoggedMessage = @splat(.{}), /// Next slot to write. `messages_len` saturates at the ring's size. messages_head: usize = 0, messages_len: usize = 0, @@ -5067,6 +4799,12 @@ pub const Pardes = struct { /// for — see panes.Terminal.RowsCache for the lifetime rule shell_rows: panes.Terminal.RowsCache = .{}, + /// The message row's entry points, called from everywhere as + /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. + pub const setStatus = Messages.setStatus; + pub const setMessage = Messages.setMessage; + pub const reportError = Messages.reportError; + pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes { const image_gpa = opts.image_allocator orelse gpa; const pdf_gpa = opts.pdf_allocator orelse gpa; @@ -5177,60 +4915,6 @@ pub const Pardes = struct { return p; } - /// `SPC` plus the chord keys typed so far, spaced out the way the help - /// index spells a leader path. - fn leaderText(p: *const Pardes, buf: *[16]u8) []const u8 { - buf.* = @splat(' '); - @memcpy(buf[0..3], "SPC"); - var at: usize = 3; - for (p.leader_keys[0..p.leader_n]) |ch| { - if (at + 2 > buf.len) break; - buf[at + 1] = ch; - at += 2; - } - return buf[0..at]; - } - - /// How wide a notice chip is, in grid columns: its own text plus a blank - /// cell either side. A notice is an OVERLAY over the body's top rows, not - /// a row taken from them, so it is sized to its message and never to the - /// pane. Counted in GRID columns rather than scaled into the tagline face - /// it is drawn in, because the canonical grid is what a terminal client - /// draws and a chip narrower than its own text there would clip it; the - /// tagline face simply leaves a little more room inside the chip. - fn noticeCols(p: *const Pardes, text: []const u8, limit: u16) u16 { - _ = p; - if (limit == 0) return 0; - return @intCast(std.math.clamp(panes.File.displayWidth(text) + 2, 1, @as(usize, limit))); - } - - const Printed = struct { left: u16, dropped: usize }; - - /// Prints `text` flush with the right edge of the band, and answers the - /// column it started at so a cursor can follow it. Text wider than the - /// band loses its HEAD: the end is the part that says something -- a - /// path's file name, an error's reason -- and `dropped` is how many - /// columns of it went. - fn printRight(s: *Surface, x: u16, row: u16, w: u16, text: []const u8, style: CellStyle) Printed { - const width = panes.File.displayWidth(text); - if (width <= w) { - const left: u16 = @intCast(x + w - width); - _ = s.print(left, row, @intCast(width), text, style); - return .{ .left = left, .dropped = 0 }; - } - // Whole glyphs only: a cut inside a wide one would leave the rest a - // column too wide and clip its LAST glyph instead of the first. - var dropped = width - w; - var start = panes.File.rawAtDisplay(text, dropped); - if (panes.File.rawDisplayCol(text, start) < dropped) { - dropped += 1; - start = panes.File.rawAtDisplay(text, dropped); - } - const left: u16 = @intCast(x + w - (width - dropped)); - _ = s.print(left, row, @intCast(width - dropped), text[start..], style); - return .{ .left = left, .dropped = dropped }; - } - /// The layout every single-pane boot starts from. fn oneColumn(p: *Pardes) void { p.ncol = 1; @@ -5654,297 +5338,6 @@ pub const Pardes = struct { p.font_request_taken = false; } - pub const Message = struct { - const libc = std.c; - const Tm = extern struct { - sec: c_int, - min: c_int, - hour: c_int, - mday: c_int, - mon: c_int, - year: c_int, - wday: c_int, - yday: c_int, - isdst: c_int, - gmtoff: c_long, - zone: ?[*:0]const u8, - }; - extern "c" fn localtime_r(timep: *const libc.time_t, result: *Tm) ?*Tm; - - pub fn body(text: []const u8) []const u8 { - if (text.len < 10) return text; - if (text[2] != ':' or text[5] != ':' or text[8] != ' ' or text[9] != ' ') return text; - for ([_]usize{ 0, 1, 3, 4, 6, 7 }) |i| { - if (!std.ascii.isDigit(text[i]) and text[i] != '-') return text; - } - return text[10..]; - } - - pub fn stamp(buf: []u8, verb: []const u8, subject: []const u8) []const u8 { - var clock: [8]u8 = "--:--:--".*; - const notime = if (libc.getenv("PARDES_NOTIME")) |v| std.mem.span(v).len != 0 else false; - if (!notime) { - var ts: libc.timespec = undefined; - _ = libc.clock_gettime(.REALTIME, &ts); - const secs: libc.time_t = ts.sec; - var tm: Tm = undefined; - if (localtime_r(&secs, &tm) != null) { - _ = std.fmt.bufPrint(&clock, "{d:0>2}:{d:0>2}:{d:0>2}", .{ - @as(u32, @intCast(tm.hour)), - @as(u32, @intCast(tm.min)), - @as(u32, @intCast(tm.sec)), - }) catch {}; - } - } - const head = std.fmt.bufPrint(buf, "{s} {s} ", .{ &clock, verb }) catch return buf[0..0]; - const room = buf.len - head.len; - const tail = if (subject.len <= room) subject else subject[subject.len - room ..]; - @memcpy(buf[head.len..][0..tail.len], tail); - return buf[0 .. head.len + tail.len]; - } - }; - - /// A status updates the message line in place (a progress count does not - /// pile up); a message is an event, and stacks. - pub fn setStatus(p: *Pardes, id: usize, text: []const u8) void { - p.showMessage(id, text, false); - } - - pub fn setMessage(p: *Pardes, id: usize, text: []const u8) void { - p.logMessage(id, text); - p.showMessage(id, text, true); - } - - fn showMessage(p: *Pardes, id: usize, text: []const u8, stack: bool) void { - if (id >= MAX_PANES) return; - const pane = p.panes[id] orelse return; - // One row of printable text: a language server's multi-line report - // reads as one line, and the cut never leaves half a glyph behind. - var n: usize = @min(text.len, pane.msg.len); - if (n < text.len) { - while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1; - } - const same = pane.msg_len == n and for (text[0..n], pane.msg[0..n]) |c, have| { - if ((if (c < 0x20 or c == 0x7f) ' ' else c) != have) break false; - } else true; - // A new event moves the line on screen up the stack, where it keeps - // its own timing, and falls in below it. - // Only an event stacks on an event: an announcement or a status - // stands in for whatever comes next. - if (stack and pane.msg_len > 0 and !same and !pane.msg_announcement and !pane.msg_status) - pane.pushOlderMessage(); - if (pane.msg_len == 0) pane.msg_slot = pane.freeMessageSlot(); - pane.msg_announcement = false; - pane.msg_status = !stack; - const arrives = pane.msg_len == 0 or pane.msg_life.phase == .leaving; - for (text[0..n], pane.msg[0..n]) |c, *cell| cell.* = if (c < 0x20 or c == 0x7f) ' ' else c; - pane.msg_len = @intCast(n); - p.needs_frame = true; - if (arrives) { - pane.msg_life = .{ .phase = if (p.settings.message_animation and n > 0) .entering else .shown }; - } else if (pane.msg_life.phase == .lingering or - (pane.msg_life.phase == .entering and !p.settings.message_animation)) - { - // The same line again, or a status update: fresh, so it stays. - pane.msg_life = .{}; - } else { - pane.msg_life.dismissed = false; - } - } - - /// The key or click that used to clear the message row now starts each - /// line's exit: it stays `message_linger_ms`, then dissolves. A line - /// already on its way out keeps its own timing. - fn dismissMessage(p: *Pardes, pane: *Pane) void { - if (pane.msg_len > 0 and p.dismissLine(&pane.msg_life)) { - pane.msg_len = 0; - pane.msg_life = .{}; - } - var i: usize = 0; - while (i < pane.msg_older_len) { - if (p.dismissLine(&pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1; - } - } - - /// Start one line's exit; true when it is gone at once (no linger, no - /// animation). - fn dismissLine(p: *const Pardes, life: *Pane.MessageLife) bool { - switch (life.phase) { - .lingering, .leaving => return false, - // A falling line lands first, then lingers -- unless falling was - // just turned off, and nothing will land it. - .entering => if (p.settings.message_animation) { - life.dismissed = true; - return false; - }, - .shown => {}, - } - life.frame = 0; - if (p.settings.message_linger_ms > 0) { - life.phase = .lingering; - } else if (p.settings.message_animation) { - life.phase = .leaving; - } else return true; - return false; - } - - /// One animation frame of every message line. Each one that moves owes - /// a frame, the one that finishes included: a tick asks for none itself. - fn advanceMessages(p: *Pardes) void { - for (p.panes) |slot| { - const pane = slot orelse continue; - if (pane.msg_len > 0 and pane.msg_life.phase != .shown) { - p.needs_frame = true; - if (p.advanceLine(&pane.msg_life)) { - pane.msg_len = 0; - pane.msg_life = .{}; - } - } - var i: usize = 0; - while (i < pane.msg_older_len) { - if (pane.msg_older[i].life.phase != .shown) p.needs_frame = true; - if (p.advanceLine(&pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1; - } - } - } - - /// One frame of one line's life; true once it has left. - fn advanceLine(p: *const Pardes, life: *Pane.MessageLife) bool { - if (life.phase == .shown) return false; - life.frame +|= 1; - switch (life.phase) { - .shown => {}, - .entering => if (life.frame >= messageFrames(p.settings.message_fall_ms)) { - life.* = .{ .phase = if (life.dismissed) .lingering else .shown }; - }, - .lingering => if (life.frame >= messageFrames(p.settings.message_linger_ms)) { - if (!p.settings.message_animation) return true; - life.* = .{ .phase = .leaving }; - }, - .leaving => if (life.frame >= messageFrames(p.settings.message_dissolve_ms)) return true, - } - return false; - } - - /// Is any message line moving (and so owed ticks)? - fn messagesAnimating(pane: *const Pane) bool { - if (pane.msg_len > 0 and pane.msg_life.phase != .shown) return true; - for (pane.msg_older[0..pane.msg_older_len]) |line| if (line.life.phase != .shown) return true; - return false; - } - - /// How present a message is (1 = fully) and how far above its row it - /// still is (rows): a fall that decelerates into place with its colour - /// arriving ahead of it, and a dissolve. - const MessageMotion = struct { alpha: f32 = 1, slide: f32 = 0 }; - - /// Animation frames a message timing lasts; at least one. - pub fn messageFrames(ms: u16) u16 { - return @intCast(@max(1, (@as(u32, ms) + layout.Animation.frame_ms - 1) / layout.Animation.frame_ms)); - } - - fn messageMotion(p: *const Pardes, life: Pane.MessageLife) MessageMotion { - const fall_frames = messageFrames(p.settings.message_fall_ms); - const dissolve_frames = messageFrames(p.settings.message_dissolve_ms); - return switch (life.phase) { - .shown, .lingering => .{ .alpha = 1, .slide = 0 }, - .entering => blk: { - const t = @as(f32, @floatFromInt(@min(life.frame, fall_frames))) / @as(f32, @floatFromInt(fall_frames)); - // Out of the gate fast and easing into its row (a cubic - // ease-out), so it is there the moment it is said and the - // last frames only settle it. No overshoot: at a row's height - // and a dozen frames, a follow-through is a pixel or two that - // reads as a jitter, not a bounce. - const left = 1 - t; - // The colour leads the motion: solid by half way, so what - // lands is already legible rather than still fading up. - const faded = 1 - @min(1, 2 * t); - break :blk .{ .alpha = 1 - faded * faded, .slide = -(left * left * left) }; - }, - .leaving => blk: { - // Counted to its last frame rather than past it, so that frame - // shows it gone and it never blinks out from part way. - const last = @max(1, dissolve_frames - 1); - const t = @as(f32, @floatFromInt(@min(life.frame, last))) / @as(f32, @floatFromInt(last)); - // An exit eases in: still readable for a beat, then away - // faster and faster. It stays where it is -- the lines - // stacked around it do not move either. - break :blk .{ .alpha = 1 - t * t, .slide = 0 }; - }, - }; - } - - /// What notice band `i` says. The grid pass and the band layers both - /// read it here, so a terminal and a pixel shell show the same line. - fn noticeText(p: *const Pardes, pane: *const Pane, i: usize, leader_buf: *[16]u8) []const u8 { - return switch (pane.notices.kinds[i]) { - .message => pane.msg[0..pane.msg_len], - .older => pane.msg_older[pane.notices.index[i]].slice(), - .leader => p.leaderText(leader_buf), - .prompt => pane.promptText() orelse "", - }; - } - - /// The life of the message line notice `i` shows, if it shows one. - fn noticeLife(pane: *const Pane, i: usize) ?Pane.MessageLife { - return switch (pane.notices.kinds[i]) { - .message => pane.msg_life, - .older => pane.msg_older[pane.notices.index[i]].life, - .leader, .prompt => null, - }; - } - - fn blendRgb(from: [3]u8, to: [3]u8, amount: f32) [3]u8 { - var out: [3]u8 = undefined; - for (&out, from, to) |*o, a, b| { - const af: f32 = @floatFromInt(a); - const bf: f32 = @floatFromInt(b); - o.* = @intFromFloat(@round(bf + (af - bf) * std.math.clamp(amount, 0, 1))); - } - return out; - } - - fn logMessage(p: *Pardes, id: usize, text: []const u8) void { - if (text.len == 0) return; - const serial: u32 = if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; - const kept = text[0..@min(text.len, LoggedMessage.cap)]; - // /log hears every one: a client that retried and failed the same way - // is waiting on that second line. Only the +Messages view collapses. - ctlfs.events.noteMessage(p, serial, kept); - if (p.messages_len > 0) { - const last = &p.messages[(p.messages_head + limits.message_log - 1) % limits.message_log]; - if (last.serial == serial and - std.mem.eql(u8, Message.body(last.slice()), Message.body(kept))) - { - // The NEWEST wording wins, so the row carries the latest clock - // rather than the moment the run started. - last.len = @intCast(kept.len); - @memcpy(last.text[0..last.len], kept); - last.repeats +|= 1; - return; - } - } - const slot = &p.messages[p.messages_head]; - slot.len = @intCast(kept.len); - @memcpy(slot.text[0..slot.len], kept); - slot.serial = serial; - slot.repeats = 1; - p.messages_head = (p.messages_head + 1) % limits.message_log; - p.messages_len = @min(p.messages_len + 1, limits.message_log); - } - - /// The log oldest-first, which is reading order. - pub fn messageLog(p: *const Pardes, i: usize) ?*const LoggedMessage { - if (i >= p.messages_len) return null; - const first = (p.messages_head + limits.message_log - p.messages_len) % limits.message_log; - return &p.messages[(first + i) % limits.message_log]; - } - pub fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) void { - var buf: [256]u8 = undefined; - const text = std.fmt.bufPrint(&buf, "{s}: {s}", .{ operation, @errorName(err) }) catch operation; - p.setMessage(id, text); - } - fn applyWatchedFileChanged(p: *Pardes, id: u8, bytes: []const u8) bool { if (id >= MAX_PANES) return false; const pane = p.panes[id] orelse return false; @@ -6268,11 +5661,11 @@ pub const Pardes = struct { switch (ev) { .key, .mouse => { for (p.panes) |slot| { - if (slot) |pane| p.dismissMessage(pane); + if (slot) |pane| Messages.dismissMessage(p, pane); } p.clip_pending = null; }, - .tick => p.advanceMessages(), + .tick => Messages.advanceMessages(p), else => {}, } if (p.fs.listeners != 0) p.fs.origin = switch (ev) { @@ -12199,7 +11592,7 @@ pub const Pardes = struct { pub fn animationActive(p: *const Pardes) bool { if (p.chrome_animation.isActive() or p.look_hover_wait != null) return true; for (p.panes) |slot| if (slot) |pane| { - if (messagesAnimating(pane)) return true; + if (Messages.messagesAnimating(pane)) return true; }; const scene = p.settings.scene_effects; if (scene.crt or scene.ripple or scene.glitch) return true; @@ -12305,7 +11698,7 @@ pub const Pardes = struct { pane.body_visible_rows = 0; pane.context_row_limit = null; s.body_layers[id].rows = 0; - p.collectNotices(pane, p.rects[id], id); + Messages.collectNotices(p, pane, p.rects[id], id); try p.renderPane(arena, pane, p.rects[id], id, id == p.active); try p.renderBodyLayer(arena, pane, p.rects[id], id); } @@ -12338,21 +11731,21 @@ pub const Pardes = struct { // draws, and a band it cannot see is a message it never gets. // The GUI skips grid cells a tag layer covers, so nothing is // drawn twice there. - const text = p.noticeText(pane, i, &leader_buf); - const chip = p.noticeCols(text, tw); + const text = Messages.noticeText(p, pane, i, &leader_buf); + const chip = Messages.noticeCols(p, text, tw); if (chip == 0) continue; const cx = tx + tw - chip; pane.notices.left[i] = cx; // A message coming or going blends toward the page it sits // on; a grid cannot move it by less than a row. var style = msg_style; - if (noticeLife(pane, i)) |life| { + if (Messages.noticeLife(pane, i)) |life| { // No page colour to fade to (a terminal's own default): // the text dissolves into its chip instead. - const alpha = p.messageMotion(life).alpha; + const alpha = Messages.messageMotion(p, life).alpha; const page = th.bg orelse chrome.tag_bg; - style.fg = .{ .rgb = blendRgb(chrome.tag_fg, page, alpha) }; - style.bg = .{ .rgb = blendRgb(chrome.tag_bg, page, alpha) }; + style.fg = .{ .rgb = Messages.blendRgb(chrome.tag_fg, page, alpha) }; + style.bg = .{ .rgb = Messages.blendRgb(chrome.tag_bg, page, alpha) }; } s.fill(cx, row, chip, 1, .{ .bg = style.bg, .font_role = .tagline }); // One column short of the chip's right edge: a prompt's caret @@ -12360,7 +11753,7 @@ pub const Pardes = struct { // right would put it past the pane, off the grid, and past what // the detached wire will encode -- which drops every frame for // as long as the prompt is up. - const printed = printRight(s, cx, row, chip -| 1, text, style); + const printed = Messages.printRight(s, cx, row, chip -| 1, text, style); if (kind != .prompt or id != p.active) continue; const at = pane.promptAt() orelse continue; const prompt0 = (p.tagPrefix(pane) catch continue).len + at; @@ -12867,7 +12260,7 @@ pub const Pardes = struct { const first = p.bodyTop(r); var leader_buf: [16]u8 = undefined; for (pane.notices.slice(), 0..) |kind, i| { - const text = p.noticeText(pane, i, &leader_buf); + const text = Messages.noticeText(p, pane, i, &leader_buf); if (text.len == 0) continue; const cx = pane.notices.left[i]; if (cx == std.math.maxInt(u16) or cx >= r.x + r.w) continue; @@ -12889,7 +12282,7 @@ pub const Pardes = struct { @memcpy(line[pad..], kept); // A pixel shell slides the message in as it fades up, and // fades it on the way out. - const motion: MessageMotion = if (noticeLife(pane, i)) |life| p.messageMotion(life) else .{}; + const motion: Messages.MessageMotion = if (Messages.noticeLife(pane, i)) |life| Messages.messageMotion(p, life) else .{}; const fade = motion.alpha; const page = p.theme().bg orelse chrome.tag_bg; const layer_index = NOTICE_LAYER_BASE + id * Pane.Notices.max + i; @@ -12898,7 +12291,7 @@ pub const Pardes = struct { .y = first + @as(u16, pane.notices.row[i]), .w = chip, .h = BOX_H, - }, line, blendRgb(chrome.tag_bg, page, fade), blendRgb(chrome.tag_fg, page, fade)); + }, line, Messages.blendRgb(chrome.tag_bg, page, fade), Messages.blendRgb(chrome.tag_fg, page, fade)); p.surface.tag_layers[layer_index].slide = motion.slide; p.surface.tag_layers[layer_index].fade = fade; // The caret rides the band, where the prompt's glyphs are, @@ -12980,47 +12373,6 @@ pub const Pardes = struct { } } - /// 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 - /// them instead of letting the last one win the row. - fn collectNotices(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { - pane.notices.len = 0; - if (r.w <= config.GUTTER or r.h <= BOX_H) return; - // Oldest message line on top, so lines already up do not move when a - // new one lands under them; when rows run out the oldest go first. - for (pane.msg_older[0..pane.msg_older_len], 0..) |line, i| pane.notices.pushAt(.older, @intCast(i), line.slot); - if (pane.msg_len > 0) pane.notices.pushAt(.message, 0, pane.msg_slot); - if (id == p.active and p.leader_on) pane.notices.push(.leader); - if (pane.promptText()) |text| if (text.len > 0) pane.notices.push(.prompt); - // A pane only has so many rows to give. When they do not all fit the - // LAST ones survive, because the prompt is last and it is the one - // carrying the cursor: a prompt you cannot see is a prompt you type - // into blind. A two-row pane spends its only body row on one notice, - // which is what the single shared row used to do anyway. - const room: u8 = @intCast(@min(@as(u16, Pane.Notices.max), r.h - BOX_H)); - const n = &pane.notices; - if (n.span() <= room) return; - // Too short for the gaps: close them up in screen order, and if even - // that does not fit, the top bands go. - var i: usize = 1; - while (i < n.len) : (i += 1) { - var j = i; - while (j > 0 and n.row[j - 1] > n.row[j]) : (j -= 1) { - std.mem.swap(Pane.Notices.Kind, &n.kinds[j - 1], &n.kinds[j]); - std.mem.swap(u8, &n.index[j - 1], &n.index[j]); - std.mem.swap(u8, &n.row[j - 1], &n.row[j]); - } - } - const drop = n.len -| room; - for (0..n.len - drop) |k| { - n.kinds[k] = n.kinds[k + drop]; - n.index[k] = n.index[k + drop]; - n.row[k] = @intCast(k); - } - n.len -= @intCast(drop); - } - fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize) !void { if (!p.settings.tree_context_tag_style or pane.context_rows == 0 or pane.file == null or pane.collapsed) return; if (r.w <= config.GUTTER or r.h <= BOX_H) return; @@ -13683,102 +13035,6 @@ test "Esc back into a tty leaves its view at the prompt" { try std.testing.expectEqual(live, sp.terminal.?.vt.screens.active.pages.scrollbar().offset); } -test "a builtin announces itself on the message row, and Verbose silences it" { - if (platform == .web) return; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[p.active].?; - - p.sync(); - try std.testing.expect(p.settings.verbose); - // Wrap, not Collapse: a builtin that folds its own pane away leaves no row - // for its announcement, which is correct and not what this is testing. - try std.testing.expect(p.executeBuiltinLine(p.active, "Wrap")); - try std.testing.expectEqualStrings("Wrap", pane.msg[0..pane.msg_len]); - - // The notice list is what the paint pass reads, so the announcement has to - // reach it, not just the buffer. - p.collectNotices(pane, p.rects[p.active], p.active); - try std.testing.expect(pane.notices.len > 0); - try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[0]); - - // ...and it is carried as a tagline band, not a body row: that is what - // gives it the tagline's height, its small font and its border. - var frame = std.heap.ArenaAllocator.init(std.testing.allocator); - defer frame.deinit(); - _ = try p.render(frame.allocator()); - const r = p.rects[p.active]; - const band = for (p.surface.tagLayers()) |*layer| { - if (layer.cols != 0 and layer.kind == .notice) break layer; - } else return error.NoNoticeBand; - try std.testing.expectEqual(@as(u16, 1), band.viewport.h); - try std.testing.expectEqual(if (p.settings.tag_bottom) r.y else r.y + BOX_H, band.viewport.y); - // Right aligned: the text ends at the band's right edge. - const line = band.cells[0..band.cols]; - var last: usize = line.len; - while (last > 0 and line[last - 1].grapheme()[0] == ' ') last -= 1; - try std.testing.expect(last > 0); - try std.testing.expect(line[0].grapheme()[0] == ' '); - - // Msg owns the row itself, so it does not announce over its own text. - try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); - try std.testing.expectEqualStrings("hello", pane.msg[0..pane.msg_len]); - - pane.msg_len = 0; - p.settings.verbose = false; - try std.testing.expect(p.executeBuiltinLine(p.active, "Wrap")); - try std.testing.expectEqual(@as(u16, 0), pane.msg_len); -} - -test "notices stack over the body's top rows without moving them" { - if (platform == .web) return; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const id = p.active; - const pane = p.panes[id].?; - p.sync(); - var frame = std.heap.ArenaAllocator.init(std.testing.allocator); - defer frame.deinit(); - - const r = p.rects[id]; - const top = p.bodyTop(r); - - // A message and a leader prefix at once: two chips, in the order - // collectNotices chose, each one row tall and each one row further down. - try std.testing.expect(p.executeBuiltinLine(id, "Msg first")); - p.leader_on = true; - p.leader_n = 0; - _ = frame.reset(.retain_capacity); - _ = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(u8, 2), pane.notices.len); - // An overlay, not a reservation: the body still starts where it did. - try std.testing.expectEqual(top, p.bodyTop(r)); - - var seen: usize = 0; - for (p.surface.tagLayers()) |*layer| { - if (layer.cols == 0 or layer.kind != .notice) continue; - try std.testing.expectEqual(@as(u16, 1), layer.viewport.h); - // Sized to its own message, right up against the pane's right edge -- - // not the width of the pane. - try std.testing.expectEqual(r.x + r.w, layer.viewport.x + layer.viewport.w); - try std.testing.expect(layer.viewport.w < r.w - config.GUTTER); - try std.testing.expect(layer.viewport.y == top or layer.viewport.y == top + 1); - try std.testing.expectEqual(pane.notices.left[layer.viewport.y - top], layer.viewport.x); - seen += 1; - } - try std.testing.expectEqual(@as(usize, 2), seen); - // "first" is longer than "SPC", so its chip is wider. - try std.testing.expect(pane.notices.left[0] < pane.notices.left[1]); - - // Gone with the notices: no stale chip left behind. - p.leader_on = false; - pane.msg_len = 0; - _ = frame.reset(.retain_capacity); - _ = try p.render(frame.allocator()); - for (p.surface.tagLayers()) |*layer| - try std.testing.expect(layer.cols == 0 or layer.kind != .notice); -} - test "a prompt chip is a band with its caret, still on the grid, and only the chip swallows a click" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 751bc42e..89a476f2 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -7,7 +7,7 @@ const vaxis = @import("vaxis"); const pardes = @import("../pardes.zig"); const tracy = @import("../tracy.zig"); const look = @import("../look.zig"); -const message = pardes.Pardes.Message; +const message = pardes.Messages.Message; const file_watch = @import("../file_watch.zig"); const selection_pipe = @import("../selection_pipe.zig"); const ninep_io = @import("../9p_io.zig"); -- cgit v1.3 From 08942ef68b10d4ce478bd3c62d306f2a633d51cb Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 22:05:19 -0300 Subject: Move body drawing out of pardes.zig into body_layer.zig Pure move, no behaviour change: renderBody, renderBodyLayer, paintPointerSelection, paintSourceSelection, paintTerminalSelection and bodyText go verbatim to the end of body_layer.zig, which already held the body's layer geometry and hit-testing, so the pane body as the surface shows it is one file. The file doc now says so. The methods become free functions taking `p: *Pardes`; their 16 call sites (render and renderPane, the tag painter, selection and dump code) change from `p.renderBody(..)` to `body_layer.renderBody(p, ..)`. pardes.zig gains `pub const body_layer = @import("body_layer.zig");`; pointerSourceLine, selRegexArmed and cellBounds become pub because the moved code calls them. Co-Authored-By: Claude Opus 5.5 --- src/body_layer.zig | 433 +++++++++++++++++++++++++++++++++++++++++++++++++++- src/fs.zig | 1 + src/pardes.zig | 434 ++--------------------------------------------------- 3 files changed, 445 insertions(+), 423 deletions(-) (limited to 'src/fs.zig') diff --git a/src/body_layer.zig b/src/body_layer.zig index 14fb91ec..d7ddbfb5 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -1,9 +1,27 @@ -//! A file body's logical rows can outnumber its physical grid rows. Hosts -//! place the compact declaration rows first and clip the remaining body rows. +//! A pane body as the surface shows it. A file body's logical rows can +//! outnumber its physical grid rows: hosts place the compact declaration rows +//! first and clip the remaining body rows. After the layer types come the +//! functions that draw a body into the surface: its text, colours, selections +//! and cursor. const std = @import("std"); const pardes = @import("pardes.zig"); const config = @import("config.zig"); const limits = @import("memory.zig").limits; +const layout = @import("layout.zig"); +const modal = @import("modal.zig"); +const tracy = @import("tracy.zig"); +const panes = @import("panes.zig"); +const colors = @import("colors.zig"); +const Color = @import("surface.zig").Color; +const CellStyle = @import("surface.zig").CellStyle; +const Cell = @import("surface.zig").Cell; +const Surface = @import("surface.zig").Surface; +const pdf_enabled = panes.Pdf.enabled; +const Pane = panes.Pane; +const BOX_H = pardes.BOX_H; +const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; +const Rect = layout.Rect; +const Pardes = pardes.Pardes; pub const Metrics = struct { body_w: u16 = 1, @@ -107,3 +125,414 @@ test "compact context borders separate source gaps and preserve multiline header try std.testing.expect(!layer.hasContextBorderAfter(4)); try std.testing.expect(!layer.context_separators.isSet(4)); } + +// ---- drawing a pane body into the surface ---- + +fn paintTerminalSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { + const body = bodyText(p, p.scratch.allocator(), pane) catch return; + const raw = pane.mode == .tty; + const tx = r.x + config.GUTTER; + const width = r.w -| config.GUTTER; + const body_y = p.bodyTop(r); + var lines = std.mem.splitScalar(u8, body, '\n'); + var visible: i32 = 0; + while (lines.next()) |line| : (visible += 1) { + if (visible >= r.h -| BOX_H) break; + const source_row = if (raw) panes.Terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; + for (rows) |row| { + const target = if (row.raw_terminal) + (if (raw) row.row else pane.surfRow(row.row)) + else + (if (raw) pane.gridRow(row.row) else row.row); + if (target != source_row) continue; + var lo = row.lo; + var hi = row.hi; + if (row.raw_terminal and !raw) { + lo -|= row.prompt_bytes; + hi -|= row.prompt_bytes; + } else if (!row.raw_terminal and raw) { + const prefix = panes.Terminal.promptPrefixBytes(pane, source_row, line); + lo += prefix; + hi += prefix; + } + lo = modal.graphemeStart(line, @min(lo, line.len)); + hi = @min(hi, line.len); + if (lo >= hi) continue; + var col = panes.File.rawDisplayCol(line, lo); + const end = panes.File.rawDisplayCol(line, hi); + while (col < end and col < width) : (col += 1) { + const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); + cell.default = false; + cell.style.bg = .{ .rgb = bg }; + if (fg) |ink| cell.style.fg = .{ .rgb = ink }; + } + } + } +} + +fn paintSourceSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { + if (pane.isTerminal()) return paintTerminalSelection(p, pane, r, rows, bg, fg); + const terminal_lines = if (pane.file == null) panes.Terminal.cursorLines(p, pane) catch return else &.{}; + const tx = r.x + config.GUTTER; + const width = r.w -| config.GUTTER; + const body_y = p.bodyTop(r); + const prefix: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + var visible: i32 = 0; + while (visible < @as(i32, r.h -| BOX_H)) : (visible += 1) { + const source = pane.wrapAt(visible); + const line = Pardes.pointerSourceLine(pane, terminal_lines, source.line); + const start = @min(line.len, @as(usize, @intCast(@max(0, source.at)))); + const next = pane.wrapAt(visible + 1); + const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; + for (rows) |row| { + if (row.row != source.line) continue; + const lo = @max(start, row.lo); + const hi = @min(end, row.hi); + if (lo >= hi) continue; + var col = prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); + const last = prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start))); + while (col < last and col < width) : (col += 1) { + const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); + cell.default = false; + cell.style.bg = .{ .rgb = bg }; + if (fg) |ink| cell.style.fg = .{ .rgb = ink }; + } + } + } +} + +pub fn paintPointerSelection( + p: *Pardes, + pane: *Pane, + r: Rect, + tx: u16, + tw: u16, + tag_y: u16, + body_y: u16, + sl: Pane.Sel, + bg: [3]u8, + fg: ?[3]u8, +) void { + if (pane.pointerSelection(sl)) |rows| return paintSourceSelection(p, pane, r, rows, bg, fg); + const s = &p.surface; + const r0 = @min(sl.r0, sl.r1); + const r1 = @max(sl.r0, sl.r1); + const c0 = @max(0, @min(sl.c0, sl.c1)); + const c1 = @max(0, @max(sl.c0, sl.c1)); + var row: u16 = 0; + while (row < r.h) : (row += 1) { + if (@as(i32, row) < r0 or @as(i32, row) > r1) continue; + const sy = if (row < BOX_H) tag_y else body_y + row - BOX_H; + // File line numbers occupy a gutter only in the body. The tag is + // row zero in Sel space and starts at its real first text cell. + const scroll: i32 = if (row < BOX_H) pane.tag_scroll else 0; + var col: i32 = if (pane.file != null and row >= BOX_H) @max(c0, @as(i32, panes.File.gutterWidth(pane))) else @max(0, c0 - scroll); + const row_x = if (row < BOX_H) r.x + @min(TAG_TEXT_INSET, r.w) else tx; + const row_width = if (row < BOX_H) r.w -| TAG_TEXT_INSET else tw; + while (col <= c1 - scroll and col < row_width) : (col += 1) { + const cell = s.at(row_x + @as(u16, @intCast(col)), sy); + cell.default = false; + cell.style.bg = .{ .rgb = bg }; + if (fg) |ink| cell.style.fg = .{ .rgb = ink }; + } + } +} + +pub fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize) !void { + if (!p.settings.tree_context_tag_style or pane.context_rows == 0 or pane.file == null or pane.collapsed) return; + if (r.w <= config.GUTTER or r.h <= BOX_H) return; + const viewport_rows = r.h - BOX_H; + if (viewport_rows == 0) return; + // The canonical fixed grid remains available to terminal clients. The + // separate body layer reserves enough rows for any compact font size. + const logical_rows = @min(@as(usize, pane.rows) + pane.context_rows, pane.wrap_line.len); + if (logical_rows <= pane.context_rows) return; + pane.body_rows = @intCast(logical_rows); + const bh: usize = @max(1, p.row_metrics.body_h); + const th: usize = std.math.clamp(p.row_metrics.tagline_h, 1, bh); + const body_pixels = @as(usize, viewport_rows) * bh; + pane.context_row_limit = @intCast(@min(pane.context_rows, (body_pixels -| bh) / th)); + const context_pixels = @as(usize, pane.context_row_limit.?) * th; + pane.body_visible_rows = @intCast(@min(logical_rows, pane.context_row_limit.? + @max(1, (body_pixels -| context_pixels) / bh))); + const width = r.w - config.GUTTER; + const layer = &p.surface.body_layers[id]; + const count = logical_rows * width; + if (layer.cells.len != count) layer.cells = try p.gpa.realloc(layer.cells, count); + const temporary_cells = try arena.alloc(Cell, @as(usize, r.w) * (logical_rows + BOX_H)); + @memset(temporary_cells, .{}); + var temporary: Surface = .{ .cols = r.w, .rows = @intCast(logical_rows + BOX_H), .cells = temporary_cells }; + std.mem.swap(Surface, &p.surface, &temporary); + const synthetic: Rect = .{ .x = 0, .y = 0, .w = r.w, .h = @intCast(logical_rows + BOX_H) }; + renderBody(p, arena, pane, synthetic, id, id == p.active, false) catch |err| { + std.mem.swap(Surface, &p.surface, &temporary); + return err; + }; + std.mem.swap(Surface, &p.surface, &temporary); + const first_row: usize = if (p.settings.tag_bottom) 0 else BOX_H; + for (0..logical_rows) |row| { + const start = (row + first_row) * r.w + config.GUTTER; + @memcpy(layer.cells[row * width ..][0..width], temporary_cells[start..][0..width]); + } + layer.pane = @intCast(id); + layer.serial = pane.serial; + layer.viewport = .{ .x = r.x + config.GUTTER, .y = p.bodyTop(r), .w = width, .h = viewport_rows }; + layer.cols = width; + layer.rows = @intCast(logical_rows); + layer.context_rows = pane.context_rows; + layer.setContextLines(pane.wrap_line[0..pane.context_rows]); + layer.cursor = null; + if (temporary.cursor) |cursor| { + if (cursor.x >= config.GUTTER and cursor.y >= first_row) + layer.cursor = .{ .x = cursor.x - config.GUTTER, .y = @intCast(cursor.y - first_row), .bar = cursor.bar }; + } +} + +pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, scrollbar: bool) !void { + const s = &p.surface; + const th = p.theme(); + const chrome = p.chromeTheme(); + const tx = r.x + config.GUTTER; + const tw = r.w - config.GUTTER; + const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; + // Below the notice bands: they are stacked at the top of the body the + // way tree-sitter context rows are, so the body starts under them + // rather than being painted over by them. + const body_y = p.bodyTop(r); + const pane_bg: Color = if (th.bg) |c| .{ .rgb = c } else .default; + const page_rgb = th.bg orelse th.tag_bg; + // body: emulator rows, prompt rows hidden outside tty mode + const body_h = r.h -| BOX_H; + const body_bottom = r.h; + const body_style: CellStyle = .{ + .fg = if (th.fg) |c| .{ .rgb = c } else .default, + .bg = pane_bg, + }; + const tz_body = tracy.zone(@src(), "bodyText"); + const body = try bodyText(p, arena, pane); + tz_body.end(); + { + // The rows themselves. `bodyText` above is only the string BUILD; + // this is what writes it into the surface. + const tz_rows = tracy.zone(@src(), "paneBodyRows"); + defer tz_rows.end(); + var it = std.mem.splitScalar(u8, body, '\n'); + var i: u16 = 0; + while (it.next()) |line| : (i += 1) { + if (i >= body_h) break; + _ = s.print(tx, body_y + i, tw, line, body_style); + } + } + + const tz_color = tracy.zone(@src(), "paneRecolor"); + // File layout is independent of whether its producer requests colors. + if (pane.file) |*f| { + panes.File.drawGutter(p, pane, r, tx, tw, body_h, active); + if (p.settings.colors and pane.colorAlgo() != .none) + panes.File.recolorSyntax(p, pane, f, r, tx, tw, body_h); + panes.File.drawWrapMarkers(p, pane, r, tx, tw, body_h, pane_bg); + } else if (pane.isTerminal() and p.settings.colors) { + panes.Terminal.recolorAnsi(p, pane, r, tx, tw, body_h, body); + } + tz_color.end(); + + const accent2 = if (std.mem.eql(u8, &th.num, &th.str)) th.comment else th.num; + const sel_btn = [3][3]u8{ + colors.mix(th.sel_bg, colors.mix(th.sel_bg, th.kw)), + colors.mix(th.sel_bg, colors.mix(th.sel_bg, th.str)), + colors.mix(th.sel_bg, colors.mix(th.sel_bg, accent2)), + }; + if (p.look_hover_preview) |preview| { + if (preview.pane == id and preview.serial == pane.serial) { + // Preserve body ink, then let every real user selection below + // win over this quiet affordance. mark_hover carries the + // cells this paints out to the hosts as the affordance rect — + // macOS composes its glass overlay over exactly these. + const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); + if (preview.file_word) |word| + panes.File.paintWordSelection(p, pane, r, word.row, word.lo, word.hi, preview_bg) + else if (preview.sel) |sel| + paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); + } + } + const modal_hover = if (p.look_hover_preview) |preview| + preview.pane == id and preview.serial == pane.serial and preview.sel == null and preview.file_word == null + else + false; + for (pane.sel, 0..) |sl, b| { + if (sl.state == .none) continue; + if (sl.state == .done and b != 0) continue; + paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sl, sel_btn[b], th.sel_fg); + } + // modal line selection (helix `x`): whole body rows, normal mode only + if ((pane.mode == .normal or modal_hover) and pane.msel.active) { + const hover_only = modal_hover and pane.mode != .normal; + const modal_bg = if (hover_only) + colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) + else + th.sel_bg; + const lo = @min(pane.msel.r0, pane.msel.r1); + const hi = @max(pane.msel.r0, pane.msel.r1); + var row: u16 = BOX_H; // never paint the tag row + while (row < body_bottom) : (row += 1) { + const ar = pane.wrapAt(@as(i32, row) - @as(i32, BOX_H)).line; + if (ar < lo or ar > hi) continue; + var col: u16 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + while (col < tw) : (col += 1) { + const cell = s.at(tx + col, body_y + row - BOX_H); + cell.default = false; + cell.style.bg = .{ .rgb = modal_bg }; + if (!hover_only) cell.style.fg = .{ .rgb = th.sel_fg }; + } + } + } + const preview = Pardes.selRegexArmed(pane) != null; + const show_prim = (pane.mode == .normal and pane.vsel.active) or preview or + (modal_hover and pane.vsel.active); + const show_extra = pane.mode != .tty and pane.nsel > 0; + if (show_prim or show_extra) { + const vpfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + var si: usize = 0; + while (si <= pane.nsel) : (si += 1) { + const primary = si == pane.nsel; + if (if (primary) !show_prim else !show_extra) continue; + const sr = if (primary) Pane.SelRange{ + .row = pane.cur_row, + .col = pane.cur_col, + .arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row, + .acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col, + } else pane.sels[si]; + const bnd = Pardes.cellBounds(sr); + const hover_only = primary and modal_hover and pane.mode != .normal and !preview; + const bg = if (hover_only) + colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) + else if (primary) + th.sel_bg + else + colors.mix(th.sel_bg, page_rgb); + var vr: i32 = 0; + while (vr + @as(i32, BOX_H) < @as(i32, body_bottom)) : (vr += 1) { + const w = pane.wrapAt(vr); + if (w.line < bnd.lo_row or w.line > bnd.hi_row) continue; + const visible_line = modal.lineSlice(body, @intCast(vr)); + const cstart: i32 = if (w.line == bnd.lo_row) + (if (pane.file != null) + panes.File.displayOffset(pane, w.line, w.at, bnd.lo_col) + else + panes.File.lineDisplayOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.lo_col)))) + vpfx + else + vpfx; + const cend: i32 = if (w.line == bnd.hi_row) + (if (pane.file != null) + panes.File.displayEndOffset(pane, w.line, w.at, bnd.hi_col) + else + panes.File.lineDisplayEndOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.hi_col)))) + vpfx + else + @as(i32, tw) - 1; + var col: i32 = @max(cstart, vpfx); + while (col <= cend and col < tw) : (col += 1) { + const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); + cell.default = false; + cell.style.bg = .{ .rgb = bg }; + if (!hover_only) cell.style.fg = .{ .rgb = th.sel_fg }; + } + } + if (primary and !preview and !hover_only) continue; // the hardware cursor IS the primary's + if (hover_only) continue; // quiet preview preserves the source ink + const cw = pane.wrapRow(sr.row, sr.col); + const crow = cw.row + @as(i32, BOX_H); + const ccol = (if (pane.file != null) + panes.File.displayOffset(pane, sr.row, cw.at, sr.col) + else + panes.File.lineDisplayOffset( + modal.lineSlice(body, @intCast(@max(0, cw.row))), + @intCast(@max(0, cw.at)), + @intCast(@max(0, sr.col)), + )) + vpfx; + if (crow >= BOX_H and crow < @as(i32, body_bottom) and ccol >= vpfx and ccol < tw) { + const cell = s.at(tx + @as(u16, @intCast(ccol)), body_y + @as(u16, @intCast(crow - BOX_H))); + cell.default = false; + cell.style.bg = .{ .rgb = th.sel_fg }; + cell.style.fg = .{ .rgb = th.sel_bg }; + } + } + } + + // cursor: tracks the shell cursor until pinned by a click or a key + // (the tag cursor above wins while the tag is focused) + if (active and !pane.tag_edit) { + if (pane.mode != .tty) { + const cur = panes.Terminal.gridCursor(pane); + const goff = panes.Terminal.gridOffset(pane); + const crow = if (pane.cur_pinned) pane.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); + const ccol = if (pane.cur_pinned) pane.cur_col else @as(i32, @intCast(cur.x)); + const cwp = pane.wrapRow(crow, ccol); + const prow = cwp.row + @as(i32, BOX_H); + // Files store source-byte columns; the Surface stores display + // cells, so account for every expanded tab before the cursor. + const cx = if (pane.file != null) + @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, crow, cwp.at, ccol) + else if (pane.cur_pinned) + panes.File.lineDisplayOffset( + modal.lineSlice(body, @intCast(@max(0, cwp.row))), + @intCast(@max(0, cwp.at)), + @intCast(@max(0, ccol)), + ) + else + ccol; + if (prow >= BOX_H and cx >= 0 and prow < body_bottom and cx < tw) + s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - BOX_H)), .bar = pane.mode == .insert }; + } else if (panes.Terminal.visibleCursor(pane)) |cur| { + if (cur.y + BOX_H < body_bottom and cur.x < tw) + s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; + } + } + + if (scrollbar and body_h > 0) { + // The rail covers the notice bands too: nothing else paints those + // two gutter columns, so a gap there keeps the frame-wide border + // fill and reads as a notch cut out of the scrollbar. + const rail_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; + const rail_h = r.h -| BOX_H; + s.fill(r.x, rail_y, 1, rail_h, .{ .bg = .{ .rgb = chrome.scroll_track } }); + s.fill(r.x + 1, rail_y, 1, rail_h, .{ .bg = pane_bg }); + const sb: struct { total: usize, offset: usize, len: usize } = if (pane.file) |*f| .{ + .total = panes.File.nlines(p.gpa, f), + .offset = f.scroll, + .len = pane.rows, + } else if (pane.pdfPage()) |page| .{ + .total = if (comptime pdf_enabled) pane.pdf.?.page_count else 1, + .offset = page, + .len = 1, + } else blk: { + const gsb = panes.Terminal.scrollbar(pane); + break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len }; + }; + const track_h: usize = body_h; + const total = if (sb.total == 0) 1 else sb.total; + const len = @max(1, (track_h * @max(1, sb.len)) / total); + const pos = (track_h * sb.offset) / total; + var sy: usize = pos; + while (sy < track_h and sy < pos + len) : (sy += 1) { + s.fill(r.x, body_y + @as(u16, @intCast(sy)), 1, 1, .{ .bg = .{ .rgb = chrome.scroll_thumb } }); + } + } +} + +pub fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { + if (pane.image != null) { + const buf = try arena.alloc(u8, pane.rows -| 1); + @memset(buf, '\n'); + return buf; + } + if (pane.hasPdf()) { + if (comptime pdf_enabled) return panes.Pdf.visibleText( + &pane.pdf.?, + p.pdf_gpa, + arena, + pane.rows -| BOX_H, + ); + unreachable; + } + if (pane.file) |*f| return panes.File.bodyText(arena, pane, f, p.settings.wrap); + return panes.Terminal.bodyText(arena, pane); +} diff --git a/src/fs.zig b/src/fs.zig index 5817b3a4..4d8a5188 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -39,6 +39,7 @@ const source_files = [_]Source{ .{ .path = "src/surface.zig", .contents = @embedFile("surface.zig") }, .{ .path = "src/colors.zig", .contents = @embedFile("colors.zig") }, .{ .path = "src/Messages.zig", .contents = @embedFile("Messages.zig") }, + .{ .path = "src/body_layer.zig", .contents = @embedFile("body_layer.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/pardes.zig b/src/pardes.zig index c171c669..fe96a221 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const body_layer = @import("body_layer.zig"); pub const Messages = @import("Messages.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; @@ -6390,10 +6391,10 @@ pub const Pardes = struct { /// tag + '\n' + body: the full selectable pane text (row 0 = the tag) fn paneText(p: *Pardes, pane: *Pane) ![]u8 { const arena = p.scratch.allocator(); - return std.fmt.allocPrint(arena, "{s}\n{s}", .{ try p.tagText(arena, pane), try p.bodyText(arena, pane) }); + return std.fmt.allocPrint(arena, "{s}\n{s}", .{ try p.tagText(arena, pane), try body_layer.bodyText(p, arena, pane) }); } - fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i32) []const u8 { + pub fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i32) []const u8 { if (row < 0) return ""; if (pane.file != null) return panes.File.sourceLine(pane, row); const index: usize = @intCast(row); @@ -6408,7 +6409,7 @@ pub const Pardes = struct { pane.clearPointerSelection(slot); // Refresh the source map before translating the rendered rectangle. const raw = pane.isTerminal() and pane.mode == .tty; - const body = try p.bodyText(p.scratch.allocator(), pane); + const body = try body_layer.bodyText(p, p.scratch.allocator(), pane); const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{}; const first = @max(0, @min(gesture.r0, gesture.r1) - BOX_H); const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; @@ -6638,7 +6639,7 @@ pub const Pardes = struct { const wrapped = pane.wrapAt(visible); const raw = pane.isTerminal() and pane.mode == .tty and clicked.r0 >= BOX_H; const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line; - const raw_line = if (raw) modal.lineSlice(p.bodyText(p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; + const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; const col = if (raw) @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) else if (clicked.r0 >= BOX_H) @@ -7045,7 +7046,7 @@ pub const Pardes = struct { p.startPrompt(pane, .{ .search = if (split) config.split_marker else config.select_marker }); } - fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } { + pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } { const prompt_at = switch (pane.prompt) { .search => |at| at, else => return null, @@ -8576,7 +8577,7 @@ pub const Pardes = struct { const Bounds = struct { lo_row: i32, lo_col: i32, hi_row: i32, hi_col: i32 }; /// a range's two cells, normalized to document order - fn cellBounds(s: Pane.SelRange) Bounds { + pub fn cellBounds(s: Pane.SelRange) Bounds { if (s.row < s.arow or (s.row == s.arow and s.col < s.acol)) return .{ .lo_row = s.row, .lo_col = s.col, .hi_row = s.arow, .hi_col = s.acol }; return .{ .lo_row = s.arow, .lo_col = s.acol, .hi_row = s.row, .hi_col = s.col }; @@ -10182,7 +10183,7 @@ pub const Pardes = struct { const text = pane.rawPointerText(gesture) orelse return; if (rows.len == 0) return; const endpoint = rows[if (gesture.r1 >= gesture.r0) rows.len - 1 else 0]; - const body = p.bodyText(p.scratch.allocator(), pane) catch return; + const body = body_layer.bodyText(p, p.scratch.allocator(), pane) catch return; const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.Terminal.gridOffset(pane)))); const byte = if (gesture.c1 >= gesture.c0) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; pane.cur_row = pane.surfRow(endpoint.row); @@ -11085,7 +11086,7 @@ pub const Pardes = struct { const pane = slot orelse continue; slot_to_pane[id] = panes_len; const tag = try p.tagText(arena, pane); - const body = try p.bodyText(arena, pane); + const body = try body_layer.bodyText(p, arena, pane); const scroll: usize = @intCast(@max(0, pane.scroll())); var dp: dump.Pane = if (pane.file) |*f| try panes.File.dumpPane( arena, @@ -11700,7 +11701,7 @@ pub const Pardes = struct { s.body_layers[id].rows = 0; Messages.collectNotices(p, pane, p.rects[id], id); try p.renderPane(arena, pane, p.rects[id], id, id == p.active); - try p.renderBodyLayer(arena, pane, p.rects[id], id); + try body_layer.renderBodyLayer(p, arena, pane, p.rects[id], id); } for (&p.panes, 0..) |*slot, id| { const pane = slot.* orelse continue; @@ -12101,116 +12102,6 @@ pub const Pardes = struct { return !cell.default and !(cell.len == 1 and cell.text[0] == ' '); } - fn paintTerminalSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { - const body = p.bodyText(p.scratch.allocator(), pane) catch return; - const raw = pane.mode == .tty; - const tx = r.x + config.GUTTER; - const width = r.w -| config.GUTTER; - const body_y = p.bodyTop(r); - var lines = std.mem.splitScalar(u8, body, '\n'); - var visible: i32 = 0; - while (lines.next()) |line| : (visible += 1) { - if (visible >= r.h -| BOX_H) break; - const source_row = if (raw) panes.Terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; - for (rows) |row| { - const target = if (row.raw_terminal) - (if (raw) row.row else pane.surfRow(row.row)) - else - (if (raw) pane.gridRow(row.row) else row.row); - if (target != source_row) continue; - var lo = row.lo; - var hi = row.hi; - if (row.raw_terminal and !raw) { - lo -|= row.prompt_bytes; - hi -|= row.prompt_bytes; - } else if (!row.raw_terminal and raw) { - const prefix = panes.Terminal.promptPrefixBytes(pane, source_row, line); - lo += prefix; - hi += prefix; - } - lo = modal.graphemeStart(line, @min(lo, line.len)); - hi = @min(hi, line.len); - if (lo >= hi) continue; - var col = panes.File.rawDisplayCol(line, lo); - const end = panes.File.rawDisplayCol(line, hi); - while (col < end and col < width) : (col += 1) { - const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - if (fg) |ink| cell.style.fg = .{ .rgb = ink }; - } - } - } - } - - fn paintSourceSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { - if (pane.isTerminal()) return p.paintTerminalSelection(pane, r, rows, bg, fg); - const terminal_lines = if (pane.file == null) panes.Terminal.cursorLines(p, pane) catch return else &.{}; - const tx = r.x + config.GUTTER; - const width = r.w -| config.GUTTER; - const body_y = p.bodyTop(r); - const prefix: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; - var visible: i32 = 0; - while (visible < @as(i32, r.h -| BOX_H)) : (visible += 1) { - const source = pane.wrapAt(visible); - const line = pointerSourceLine(pane, terminal_lines, source.line); - const start = @min(line.len, @as(usize, @intCast(@max(0, source.at)))); - const next = pane.wrapAt(visible + 1); - const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; - for (rows) |row| { - if (row.row != source.line) continue; - const lo = @max(start, row.lo); - const hi = @min(end, row.hi); - if (lo >= hi) continue; - var col = prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); - const last = prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start))); - while (col < last and col < width) : (col += 1) { - const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - if (fg) |ink| cell.style.fg = .{ .rgb = ink }; - } - } - } - } - - fn paintPointerSelection( - p: *Pardes, - pane: *Pane, - r: Rect, - tx: u16, - tw: u16, - tag_y: u16, - body_y: u16, - sl: Pane.Sel, - bg: [3]u8, - fg: ?[3]u8, - ) void { - if (pane.pointerSelection(sl)) |rows| return p.paintSourceSelection(pane, r, rows, bg, fg); - const s = &p.surface; - const r0 = @min(sl.r0, sl.r1); - const r1 = @max(sl.r0, sl.r1); - const c0 = @max(0, @min(sl.c0, sl.c1)); - const c1 = @max(0, @max(sl.c0, sl.c1)); - var row: u16 = 0; - while (row < r.h) : (row += 1) { - if (@as(i32, row) < r0 or @as(i32, row) > r1) continue; - const sy = if (row < BOX_H) tag_y else body_y + row - BOX_H; - // File line numbers occupy a gutter only in the body. The tag is - // row zero in Sel space and starts at its real first text cell. - const scroll: i32 = if (row < BOX_H) pane.tag_scroll else 0; - var col: i32 = if (pane.file != null and row >= BOX_H) @max(c0, @as(i32, panes.File.gutterWidth(pane))) else @max(0, c0 - scroll); - const row_x = if (row < BOX_H) r.x + @min(TAG_TEXT_INSET, r.w) else tx; - const row_width = if (row < BOX_H) r.w -| TAG_TEXT_INSET else tw; - while (col <= c1 - scroll and col < row_width) : (col += 1) { - const cell = s.at(row_x + @as(u16, @intCast(col)), sy); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - if (fg) |ink| cell.style.fg = .{ .rgb = ink }; - } - } - } - fn renderTagLayers(p: *Pardes, arena: std.mem.Allocator) !void { const chrome = p.chromeTheme(); for (p.panes, 0..) |slot, id| { @@ -12373,55 +12264,6 @@ pub const Pardes = struct { } } - fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize) !void { - if (!p.settings.tree_context_tag_style or pane.context_rows == 0 or pane.file == null or pane.collapsed) return; - if (r.w <= config.GUTTER or r.h <= BOX_H) return; - const viewport_rows = r.h - BOX_H; - if (viewport_rows == 0) return; - // The canonical fixed grid remains available to terminal clients. The - // separate body layer reserves enough rows for any compact font size. - const logical_rows = @min(@as(usize, pane.rows) + pane.context_rows, pane.wrap_line.len); - if (logical_rows <= pane.context_rows) return; - pane.body_rows = @intCast(logical_rows); - const bh: usize = @max(1, p.row_metrics.body_h); - const th: usize = std.math.clamp(p.row_metrics.tagline_h, 1, bh); - const body_pixels = @as(usize, viewport_rows) * bh; - pane.context_row_limit = @intCast(@min(pane.context_rows, (body_pixels -| bh) / th)); - const context_pixels = @as(usize, pane.context_row_limit.?) * th; - pane.body_visible_rows = @intCast(@min(logical_rows, pane.context_row_limit.? + @max(1, (body_pixels -| context_pixels) / bh))); - const width = r.w - config.GUTTER; - const layer = &p.surface.body_layers[id]; - const count = logical_rows * width; - if (layer.cells.len != count) layer.cells = try p.gpa.realloc(layer.cells, count); - const temporary_cells = try arena.alloc(Cell, @as(usize, r.w) * (logical_rows + BOX_H)); - @memset(temporary_cells, .{}); - var temporary: Surface = .{ .cols = r.w, .rows = @intCast(logical_rows + BOX_H), .cells = temporary_cells }; - std.mem.swap(Surface, &p.surface, &temporary); - const synthetic: Rect = .{ .x = 0, .y = 0, .w = r.w, .h = @intCast(logical_rows + BOX_H) }; - p.renderBody(arena, pane, synthetic, id, id == p.active, false) catch |err| { - std.mem.swap(Surface, &p.surface, &temporary); - return err; - }; - std.mem.swap(Surface, &p.surface, &temporary); - const first_row: usize = if (p.settings.tag_bottom) 0 else BOX_H; - for (0..logical_rows) |row| { - const start = (row + first_row) * r.w + config.GUTTER; - @memcpy(layer.cells[row * width ..][0..width], temporary_cells[start..][0..width]); - } - layer.pane = @intCast(id); - layer.serial = pane.serial; - layer.viewport = .{ .x = r.x + config.GUTTER, .y = p.bodyTop(r), .w = width, .h = viewport_rows }; - layer.cols = width; - layer.rows = @intCast(logical_rows); - layer.context_rows = pane.context_rows; - layer.setContextLines(pane.wrap_line[0..pane.context_rows]); - layer.cursor = null; - if (temporary.cursor) |cursor| { - if (cursor.x >= config.GUTTER and cursor.y >= first_row) - layer.cursor = .{ .x = cursor.x - config.GUTTER, .y = @intCast(cursor.y - first_row), .bar = cursor.bar }; - } - } - fn renderPane(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool) !void { const tz = tracy.zone(@src(), "renderPane"); defer tz.end(); @@ -12487,7 +12329,7 @@ pub const Pardes = struct { return; } - try p.renderBody(arena, pane, r, id, active, true); + try body_layer.renderBody(p, arena, pane, r, id, active, true); } fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, capacity: u16) !void { @@ -12545,7 +12387,7 @@ pub const Pardes = struct { if (p.look_hover_preview) |preview| { if (preview.pane == id and preview.serial == pane.serial) if (preview.sel) |sel| if (@min(sel.r0, sel.r1) < BOX_H) { const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); - p.paintPointerSelection(pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); + body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); }; } if (pane.tag_edit and pane.tag_sel) { @@ -12570,238 +12412,7 @@ pub const Pardes = struct { for (pane.sel, 0..) |selection, button| { if (selection.state == .none or (selection.state == .done and button != 0)) continue; if (@min(selection.r0, selection.r1) >= BOX_H) continue; - p.paintPointerSelection(pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); - } - } - - fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, scrollbar: bool) !void { - const s = &p.surface; - const th = p.theme(); - const chrome = p.chromeTheme(); - const tx = r.x + config.GUTTER; - const tw = r.w - config.GUTTER; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - // Below the notice bands: they are stacked at the top of the body the - // way tree-sitter context rows are, so the body starts under them - // rather than being painted over by them. - const body_y = p.bodyTop(r); - const pane_bg: Color = if (th.bg) |c| .{ .rgb = c } else .default; - const page_rgb = th.bg orelse th.tag_bg; - // body: emulator rows, prompt rows hidden outside tty mode - const body_h = r.h -| BOX_H; - const body_bottom = r.h; - const body_style: CellStyle = .{ - .fg = if (th.fg) |c| .{ .rgb = c } else .default, - .bg = pane_bg, - }; - const tz_body = tracy.zone(@src(), "bodyText"); - const body = try p.bodyText(arena, pane); - tz_body.end(); - { - // The rows themselves. `bodyText` above is only the string BUILD; - // this is what writes it into the surface. - const tz_rows = tracy.zone(@src(), "paneBodyRows"); - defer tz_rows.end(); - var it = std.mem.splitScalar(u8, body, '\n'); - var i: u16 = 0; - while (it.next()) |line| : (i += 1) { - if (i >= body_h) break; - _ = s.print(tx, body_y + i, tw, line, body_style); - } - } - - const tz_color = tracy.zone(@src(), "paneRecolor"); - // File layout is independent of whether its producer requests colors. - if (pane.file) |*f| { - panes.File.drawGutter(p, pane, r, tx, tw, body_h, active); - if (p.settings.colors and pane.colorAlgo() != .none) - panes.File.recolorSyntax(p, pane, f, r, tx, tw, body_h); - panes.File.drawWrapMarkers(p, pane, r, tx, tw, body_h, pane_bg); - } else if (pane.isTerminal() and p.settings.colors) { - panes.Terminal.recolorAnsi(p, pane, r, tx, tw, body_h, body); - } - tz_color.end(); - - const accent2 = if (std.mem.eql(u8, &th.num, &th.str)) th.comment else th.num; - const sel_btn = [3][3]u8{ - colors.mix(th.sel_bg, colors.mix(th.sel_bg, th.kw)), - colors.mix(th.sel_bg, colors.mix(th.sel_bg, th.str)), - colors.mix(th.sel_bg, colors.mix(th.sel_bg, accent2)), - }; - if (p.look_hover_preview) |preview| { - if (preview.pane == id and preview.serial == pane.serial) { - // Preserve body ink, then let every real user selection below - // win over this quiet affordance. mark_hover carries the - // cells this paints out to the hosts as the affordance rect — - // macOS composes its glass overlay over exactly these. - const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); - if (preview.file_word) |word| - panes.File.paintWordSelection(p, pane, r, word.row, word.lo, word.hi, preview_bg) - else if (preview.sel) |sel| - p.paintPointerSelection(pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); - } - } - const modal_hover = if (p.look_hover_preview) |preview| - preview.pane == id and preview.serial == pane.serial and preview.sel == null and preview.file_word == null - else - false; - for (pane.sel, 0..) |sl, b| { - if (sl.state == .none) continue; - if (sl.state == .done and b != 0) continue; - p.paintPointerSelection(pane, r, tx, tw, tag_y, body_y, sl, sel_btn[b], th.sel_fg); - } - // modal line selection (helix `x`): whole body rows, normal mode only - if ((pane.mode == .normal or modal_hover) and pane.msel.active) { - const hover_only = modal_hover and pane.mode != .normal; - const modal_bg = if (hover_only) - colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) - else - th.sel_bg; - const lo = @min(pane.msel.r0, pane.msel.r1); - const hi = @max(pane.msel.r0, pane.msel.r1); - var row: u16 = BOX_H; // never paint the tag row - while (row < body_bottom) : (row += 1) { - const ar = pane.wrapAt(@as(i32, row) - @as(i32, BOX_H)).line; - if (ar < lo or ar > hi) continue; - var col: u16 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; - while (col < tw) : (col += 1) { - const cell = s.at(tx + col, body_y + row - BOX_H); - cell.default = false; - cell.style.bg = .{ .rgb = modal_bg }; - if (!hover_only) cell.style.fg = .{ .rgb = th.sel_fg }; - } - } - } - const preview = selRegexArmed(pane) != null; - const show_prim = (pane.mode == .normal and pane.vsel.active) or preview or - (modal_hover and pane.vsel.active); - const show_extra = pane.mode != .tty and pane.nsel > 0; - if (show_prim or show_extra) { - const vpfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; - var si: usize = 0; - while (si <= pane.nsel) : (si += 1) { - const primary = si == pane.nsel; - if (if (primary) !show_prim else !show_extra) continue; - const sr = if (primary) Pane.SelRange{ - .row = pane.cur_row, - .col = pane.cur_col, - .arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row, - .acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col, - } else pane.sels[si]; - const bnd = cellBounds(sr); - const hover_only = primary and modal_hover and pane.mode != .normal and !preview; - const bg = if (hover_only) - colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) - else if (primary) - th.sel_bg - else - colors.mix(th.sel_bg, page_rgb); - var vr: i32 = 0; - while (vr + @as(i32, BOX_H) < @as(i32, body_bottom)) : (vr += 1) { - const w = pane.wrapAt(vr); - if (w.line < bnd.lo_row or w.line > bnd.hi_row) continue; - const visible_line = modal.lineSlice(body, @intCast(vr)); - const cstart: i32 = if (w.line == bnd.lo_row) - (if (pane.file != null) - panes.File.displayOffset(pane, w.line, w.at, bnd.lo_col) - else - panes.File.lineDisplayOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.lo_col)))) + vpfx - else - vpfx; - const cend: i32 = if (w.line == bnd.hi_row) - (if (pane.file != null) - panes.File.displayEndOffset(pane, w.line, w.at, bnd.hi_col) - else - panes.File.lineDisplayEndOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.hi_col)))) + vpfx - else - @as(i32, tw) - 1; - var col: i32 = @max(cstart, vpfx); - while (col <= cend and col < tw) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - if (!hover_only) cell.style.fg = .{ .rgb = th.sel_fg }; - } - } - if (primary and !preview and !hover_only) continue; // the hardware cursor IS the primary's - if (hover_only) continue; // quiet preview preserves the source ink - const cw = pane.wrapRow(sr.row, sr.col); - const crow = cw.row + @as(i32, BOX_H); - const ccol = (if (pane.file != null) - panes.File.displayOffset(pane, sr.row, cw.at, sr.col) - else - panes.File.lineDisplayOffset( - modal.lineSlice(body, @intCast(@max(0, cw.row))), - @intCast(@max(0, cw.at)), - @intCast(@max(0, sr.col)), - )) + vpfx; - if (crow >= BOX_H and crow < @as(i32, body_bottom) and ccol >= vpfx and ccol < tw) { - const cell = s.at(tx + @as(u16, @intCast(ccol)), body_y + @as(u16, @intCast(crow - BOX_H))); - cell.default = false; - cell.style.bg = .{ .rgb = th.sel_fg }; - cell.style.fg = .{ .rgb = th.sel_bg }; - } - } - } - - // cursor: tracks the shell cursor until pinned by a click or a key - // (the tag cursor above wins while the tag is focused) - if (active and !pane.tag_edit) { - if (pane.mode != .tty) { - const cur = panes.Terminal.gridCursor(pane); - const goff = panes.Terminal.gridOffset(pane); - const crow = if (pane.cur_pinned) pane.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); - const ccol = if (pane.cur_pinned) pane.cur_col else @as(i32, @intCast(cur.x)); - const cwp = pane.wrapRow(crow, ccol); - const prow = cwp.row + @as(i32, BOX_H); - // Files store source-byte columns; the Surface stores display - // cells, so account for every expanded tab before the cursor. - const cx = if (pane.file != null) - @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, crow, cwp.at, ccol) - else if (pane.cur_pinned) - panes.File.lineDisplayOffset( - modal.lineSlice(body, @intCast(@max(0, cwp.row))), - @intCast(@max(0, cwp.at)), - @intCast(@max(0, ccol)), - ) - else - ccol; - if (prow >= BOX_H and cx >= 0 and prow < body_bottom and cx < tw) - s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - BOX_H)), .bar = pane.mode == .insert }; - } else if (panes.Terminal.visibleCursor(pane)) |cur| { - if (cur.y + BOX_H < body_bottom and cur.x < tw) - s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; - } - } - - if (scrollbar and body_h > 0) { - // The rail covers the notice bands too: nothing else paints those - // two gutter columns, so a gap there keeps the frame-wide border - // fill and reads as a notch cut out of the scrollbar. - const rail_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; - const rail_h = r.h -| BOX_H; - s.fill(r.x, rail_y, 1, rail_h, .{ .bg = .{ .rgb = chrome.scroll_track } }); - s.fill(r.x + 1, rail_y, 1, rail_h, .{ .bg = pane_bg }); - const sb: struct { total: usize, offset: usize, len: usize } = if (pane.file) |*f| .{ - .total = panes.File.nlines(p.gpa, f), - .offset = f.scroll, - .len = pane.rows, - } else if (pane.pdfPage()) |page| .{ - .total = if (comptime pdf_enabled) pane.pdf.?.page_count else 1, - .offset = page, - .len = 1, - } else blk: { - const gsb = panes.Terminal.scrollbar(pane); - break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len }; - }; - const track_h: usize = body_h; - const total = if (sb.total == 0) 1 else sb.total; - const len = @max(1, (track_h * @max(1, sb.len)) / total); - const pos = (track_h * sb.offset) / total; - var sy: usize = pos; - while (sy < track_h and sy < pos + len) : (sy += 1) { - s.fill(r.x, body_y + @as(u16, @intCast(sy)), 1, 1, .{ .bg = .{ .rgb = chrome.scroll_thumb } }); - } + body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); } } @@ -12821,25 +12432,6 @@ pub const Pardes = struct { s.nimages += 1; return true; } - - fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { - if (pane.image != null) { - const buf = try arena.alloc(u8, pane.rows -| 1); - @memset(buf, '\n'); - return buf; - } - if (pane.hasPdf()) { - if (comptime pdf_enabled) return panes.Pdf.visibleText( - &pane.pdf.?, - p.pdf_gpa, - arena, - pane.rows -| BOX_H, - ); - unreachable; - } - if (pane.file) |*f| return panes.File.bodyText(arena, pane, f, p.settings.wrap); - return panes.Terminal.bodyText(arena, pane); - } }; test "Esc alternates between two panes of the SAME kind" { -- cgit v1.3 From ff953a6236ebdf97c73deda86fd9005906a2071b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 22:09:27 -0300 Subject: Move text editing out of pardes.zig into edit.zig Pure move, no behaviour change (acme keeps this in text.c): which text a pane edits and how it maps to the screen (editText, editTextEol, setEditText, paneCursorLines, paneByteAtDisplay, pinPaneCursor, flatSurface, paneWrapWidth), insert mode (enterInsert, handleInsert, insertKey, insertTab, exitInsert, clampFileCursor), the d/c/y/p edit operations with replace, case, join, indent, comment, number, textobjects and surround, undo and redo, yank/clipboard/paste (setYank, setClipboard, ClipRequest, clipRequest, typeToTty, applyPaste, clipYank), and the pointer selections as text (PointerTextSelection, pointerTextSelection, capturePointerSelection, paneText, pointerSourceLine, selectionText, spanHas, currentSelText), with four tests, go verbatim to edit.zig. The methods become free functions taking `p: *Pardes`; calls change from `p.insertKey(..)` to `edit.insertKey(p, ..)` (pardes.zig, body_layer.zig, selection_pipe.zig, builtins.zig, test/hxdiff.zig, test/perf.zig). In executeNormalAction the `.edit => |edit|` capture becomes `|op|`, since it would now shadow the edit import. test/lspbench.zig's first anchor follows its needle into src/edit.zig. Co-Authored-By: Claude Opus 5.5 --- src/body_layer.zig | 5 +- src/builtins.zig | 11 +- src/edit.zig | 1692 +++++++++++++++++++++++++++++++++++++++++++ src/fs.zig | 1 + src/pardes.zig | 1874 +++--------------------------------------------- src/selection_pipe.zig | 3 +- test/hxdiff.zig | 2 +- test/lspbench.zig | 2 +- test/perf.zig | 2 +- 9 files changed, 1812 insertions(+), 1780 deletions(-) create mode 100644 src/edit.zig (limited to 'src/fs.zig') diff --git a/src/body_layer.zig b/src/body_layer.zig index d7ddbfb5..8c345b97 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -5,6 +5,7 @@ //! and cursor. const std = @import("std"); const pardes = @import("pardes.zig"); +const edit = @import("edit.zig"); const config = @import("config.zig"); const limits = @import("memory.zig").limits; const layout = @import("layout.zig"); @@ -180,7 +181,7 @@ fn paintSourceSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.Poi var visible: i32 = 0; while (visible < @as(i32, r.h -| BOX_H)) : (visible += 1) { const source = pane.wrapAt(visible); - const line = Pardes.pointerSourceLine(pane, terminal_lines, source.line); + const line = edit.pointerSourceLine(pane, terminal_lines, source.line); const start = @min(line.len, @as(usize, @intCast(@max(0, source.at)))); const next = pane.wrapAt(visible + 1); const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; @@ -401,7 +402,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id .arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row, .acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col, } else pane.sels[si]; - const bnd = Pardes.cellBounds(sr); + const bnd = edit.cellBounds(sr); const hover_only = primary and modal_hover and pane.mode != .normal and !preview; const bg = if (hover_only) colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) diff --git a/src/builtins.zig b/src/builtins.zig index ad2c5f6a..87679f64 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1,6 +1,7 @@ //! Command structs and runtime settings form the builtin registry; bindings live in config.zig. const std = @import("std"); const pardes = @import("pardes.zig"); +const edit = @import("edit.zig"); const colors = @import("colors.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; @@ -431,7 +432,7 @@ pub const Ascii = struct { pub const ClipYank = struct { pub fn run(c: Ctx) void { - c.p.clipYank(c.pane, false); + edit.clipYank(c.p, c.pane, false); } }; @@ -439,25 +440,25 @@ pub const ClipYank = struct { /// cursor's. One cursor makes them the same word. pub const ClipYankMain = struct { pub fn run(c: Ctx) void { - c.p.clipYank(c.pane, true); + edit.clipYank(c.p, c.pane, true); } }; pub const ClipPaste = struct { pub fn run(c: Ctx) void { - c.p.clipRequest(c.id, .after); + edit.clipRequest(c.p, c.id, .after); } }; pub const ClipPasteBefore = struct { pub fn run(c: Ctx) void { - c.p.clipRequest(c.id, .before); + edit.clipRequest(c.p, c.id, .before); } }; pub const ClipReplace = struct { pub fn run(c: Ctx) void { - c.p.clipRequest(c.id, .replace); + edit.clipRequest(c.p, c.id, .replace); } }; diff --git a/src/edit.zig b/src/edit.zig new file mode 100644 index 00000000..e44a3364 --- /dev/null +++ b/src/edit.zig @@ -0,0 +1,1692 @@ +//! Editing a pane's text (acme's text.c): which text a pane edits and how +//! its lines and cursor map to the screen, insert mode, the d/c/y/p edit +//! operations, replace, case, join, indent, comments, numbers, textobjects +//! and surround, undo, yank and paste, and the pointer selections as text. +const pardes = @import("pardes.zig"); +const std = @import("std"); +const modal = @import("modal.zig"); +const panes = @import("panes.zig"); +const body_layer = @import("body_layer.zig"); +const config = @import("config.zig"); +const pdf_enabled = panes.Pdf.enabled; +const lsp = @import("lsp/lsp.zig"); +const platform = pardes.platform; +const Pane = panes.Pane; +const TagHit = @import("tag_layer.zig").Hit; +const BOX_H = pardes.BOX_H; +const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; +const Mouse = pardes.Mouse; +const Key = pardes.Key; +const hit = pardes.hit; +const sel_slot = pardes.sel_slot; +const Effect = pardes.Effect; +const Pardes = pardes.Pardes; + +pub fn setYank(p: *Pardes, text: []const u8) void { + if (p.multi_on and !p.multi_first) { + const old = p.yank orelse ""; + const sep: []const u8 = if (text.len > 0 and text[text.len - 1] == '\n') "" else "\n"; + const joined = std.fmt.allocPrint(p.gpa, "{s}{s}{s}", .{ text, sep, old }) catch return; + if (p.yank) |y| p.gpa.free(y); + p.yank = joined; + return; + } + if (p.yank) |y| p.gpa.free(y); + p.yank = p.gpa.dupe(u8, text) catch null; +} + +pub fn setClipboard(p: *Pardes, text: []const u8) void { + setYank(p, text); + if (!p.multi_on or p.multi_first) p.emit(.{ .set_clipboard = {} }); +} + +/// Where a `SPC p` / `SPC P` / `SPC R` goes once the shell answers. +pub const ClipRequest = struct { + pane: usize, + serial: u32, + mode: enum { after, before, replace }, +}; + +pub fn clipRequest(p: *Pardes, id: usize, mode: @FieldType(ClipRequest, "mode")) void { + const pane = p.panes[id] orelse return; + p.clip_pending = .{ .pane = id, .serial = pane.serial, .mode = mode }; + p.emit(.read_clipboard); +} + +pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) void { + if (text.len == 0) return; + if (panes.Terminal.bracketedPaste(pane)) { + p.emitWrite(id, "\x1b[200~"); + p.emitWrite(id, text); + p.emitWrite(id, "\x1b[201~"); + return; + } + const cp = p.scratch.allocator().dupe(u8, text) catch return; + for (cp) |*ch| { + if (ch.* == '\n') ch.* = '\r'; + } + p.emitWrite(id, cp); +} + +pub fn applyPaste(p: *Pardes, bytes: []const u8) void { + if (p.topbar_col != null) { + p.clip_pending = null; + p.headerReplace(bytes); + return; + } + const req = p.clip_pending; + p.clip_pending = null; + if (bytes.len == 0) return; + const id = if (req) |r| r.pane else p.active; + const pane = p.panes[id] orelse return; + if (req) |r| if (pane.serial != r.serial) return; + p.active = id; + if (pane.tag_edit) { + const text = p.tagText(p.scratch.allocator(), pane) catch return; + const range: @TypeOf(Pardes.tagSelBounds(pane)) = if (pane.tag_sel) Pardes.tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; + const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; + _ = p.replaceTagText(pane, range.lo, hi, bytes); + if (Pardes.selRegexArmed(pane)) |a| p.applySelRegex(pane, a.pat, a.split); + return; + } + if (pane.isTerminal() and pane.mode == .tty) return typeToTty(p, id, pane, bytes); + switch (if (req) |r| r.mode else .after) { + .after => pasteText(p, pane, bytes, false, 1), + .before => pasteText(p, pane, bytes, true, 1), + .replace => replaceWithText(p, pane, bytes), + } +} + +pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { + if (comptime pdf_enabled) if (pane.pdf) |pv| { + if (pv.selection_text.len > 0) setClipboard(p, pv.selection_text); + return; + }; + if (pane.nsel > 0 and !main_only) { + p.replaySels(pane, .{ .normal = .{ .edit = .{ .kind = .yank, .count = 1 } } }); + } else { + const others = pane.nsel; + pane.nsel = 0; + normalYank(p, pane); + pane.nsel = others; + } + p.emit(.{ .set_clipboard = {} }); +} + +/// tag + '\n' + body: the full selectable pane text (row 0 = the tag) +pub fn paneText(p: *Pardes, pane: *Pane) ![]u8 { + const arena = p.scratch.allocator(); + return std.fmt.allocPrint(arena, "{s}\n{s}", .{ try p.tagText(arena, pane), try body_layer.bodyText(p, arena, pane) }); +} + +pub fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i32) []const u8 { + if (row < 0) return ""; + if (pane.file != null) return panes.File.sourceLine(pane, row); + const index: usize = @intCast(row); + return if (index < terminal_lines.len) terminal_lines[index] else ""; +} + +pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { + var gesture = pane.sel[slot]; + if (pane.hasPdf()) return; + if (gesture.state != .done or @min(gesture.r0, gesture.r1) < BOX_H) return; + if (pane.pointerSelection(gesture) != null) return; + pane.clearPointerSelection(slot); + // Refresh the source map before translating the rendered rectangle. + const raw = pane.isTerminal() and pane.mode == .tty; + const body = try body_layer.bodyText(p, p.scratch.allocator(), pane); + const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{}; + const first = @max(0, @min(gesture.r0, gesture.r1) - BOX_H); + const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; + const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - BOX_H); + if (first > last) return; + const rows = try p.gpa.alloc(Pane.PointerRow, @intCast(last - first + 1)); + errdefer p.gpa.free(rows); + const raw_text = if (raw) try p.gpa.dupe(u8, try selectionText(p, pane, gesture)) else null; + const prefix: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + const left = @max(0, @min(gesture.c0, gesture.c1)); + const right = @max(0, @max(gesture.c0, gesture.c1)); + for (rows, 0..) |*row, index| { + const visible = first + @as(i32, @intCast(index)); + var source = pane.wrapAt(visible); + if (raw) source = .{ .line = panes.Terminal.gridOffset(pane) + visible, .at = 0 }; + const line = if (raw) modal.lineSlice(body, @intCast(visible)) else pointerSourceLine(pane, terminal_lines, source.line); + var next = pane.wrapAt(visible + 1); + if (raw) next = .{ .line = source.line + 1, .at = 0 }; + const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; + const start: usize = @intCast(@max(0, source.at)); + const lo = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix)))); + const at = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix)))); + row.* = .{ + .row = source.line, + .lo = lo, + .hi = if (right < prefix) lo else @min(end, modal.nextGrapheme(line, at)), + .raw_terminal = raw, + .prompt_bytes = if (raw) panes.Terminal.promptPrefixBytes(pane, source.line, line) else 0, + }; + const rendered = modal.lineSlice(body, @intCast(visible)); + const prefix_end = @min(rendered.len, @as(usize, @intCast(@min(prefix, right + 1)))); + const prefix_start = @min(prefix_end, @as(usize, @intCast(left))); + row.prefix_len = @intCast(prefix_end - prefix_start); + @memcpy(row.prefix[0..row.prefix_len], rendered[prefix_start..prefix_end]); + } + pane.next_pointer_selection += 1; + gesture.source_id = pane.next_pointer_selection; + pane.sel[slot] = gesture; + pane.pointer_selections[slot] = .{ .gesture = gesture, .rows = rows, .raw_text = raw_text }; +} + +/// block-selected text, newline-joined per row; reads the rendered screen +/// so typed text and shell output select identically. Scratch-owned. +pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { + const arena = p.scratch.allocator(); + if (pane.rawPointerText(sl)) |text| return arena.dupe(u8, text); + if (pane.pointerSelection(sl)) |rows| { + const terminal_lines = if (pane.file == null) try panes.Terminal.cursorLines(p, pane) else &.{}; + var total: usize = rows.len -| 1; + for (rows) |row| { + const line = pointerSourceLine(pane, terminal_lines, row.row); + total += row.prefix_len + @min(row.hi, line.len) - @min(row.lo, line.len); + } + const result = try arena.alloc(u8, total); + var at: usize = 0; + for (rows, 0..) |row, index| { + if (index > 0) { + result[at] = '\n'; + at += 1; + } + @memcpy(result[at..][0..row.prefix_len], row.prefix[0..row.prefix_len]); + at += row.prefix_len; + const line = pointerSourceLine(pane, terminal_lines, row.row); + const bytes = line[@min(row.lo, line.len)..@min(row.hi, line.len)]; + @memcpy(result[at..][0..bytes.len], bytes); + at += bytes.len; + } + return result; + } + const r0 = @min(sl.r0, sl.r1); + const r1 = @max(sl.r0, sl.r1); + const c0: usize = @intCast(@max(0, @min(sl.c0, sl.c1))); + const c1: usize = @intCast(@max(0, @max(sl.c0, sl.c1))); + const text = try paneText(p, pane); + var total: usize = 0; + var selected: usize = 0; + var count_it = std.mem.splitAny(u8, text, "\n"); + var count_row: i32 = 0; + while (count_it.next()) |line| : (count_row += 1) { + if (count_row < r0 or count_row > r1) continue; + const b0 = @min(panes.File.renderedLineByteCol(pane, count_row, line, c0), line.len); + const b1 = modal.nextGrapheme(line, @min(panes.File.renderedLineByteCol(pane, count_row, line, c1), line.len)); + total += b1 - b0 + @intFromBool(selected > 0); + selected += 1; + } + const out = try arena.alloc(u8, total); + var at: usize = 0; + var it = std.mem.splitAny(u8, text, "\n"); + var v: i32 = 0; + var first = true; + while (it.next()) |line| : (v += 1) { + if (v < r0 or v > r1) continue; + if (!first) { + out[at] = '\n'; + at += 1; + } + first = false; + const b0 = @min(panes.File.renderedLineByteCol(pane, v, line, c0), line.len); + const b1 = modal.nextGrapheme(line, @min(panes.File.renderedLineByteCol(pane, v, line, c1), line.len)); + @memcpy(out[at..][0 .. b1 - b0], line[b0..b1]); + at += b1 - b0; + } + return out; +} + +pub fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool { + const fwd = ar < br or (ar == br and ac <= bc); + const sr, const sc = if (fwd) .{ ar, ac } else .{ br, bc }; + const er, const ec = if (fwd) .{ br, bc } else .{ ar, ac }; + return (r > sr or (r == sr and c >= sc)) and (r < er or (r == er and c <= ec)); +} + +/// the active modal selection as text (v range or x lines), if any +pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 { + if (comptime pdf_enabled) if (p.native_images) if (pane.pdf) |pv| + if (pv.selection != null and pv.selection_text.len > 0) return pv.selection_text; + if (pane.vsel.active) return vselText(p, pane); + if (!pane.msel.active) return null; + return yankRows(p, pane, @min(pane.msel.r0, pane.msel.r1), @max(pane.msel.r0, pane.msel.r1)); +} + +pub fn exitInsert(p: *Pardes, pane: *Pane) void { + pane.mode = .normal; + pane.msel.active = false; + pane.normal.clear(); + if (pane.append_at) |aa| { + pane.append_at = null; + const text = flatSurface(p, pane) catch return; + const gap = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }); + const a_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, aa.row)), .col = @intCast(@max(0, aa.col)) }); + const back = @max(a_off, modal.prevGrapheme(text, gap)); + const bc = modal.positionAt(text, back); + pane.cur_row = @intCast(bc.row); + pane.cur_col = @intCast(bc.col); + pane.vsel = .{ .active = a_off != back, .row = aa.row, .col = aa.col, .explicit = false }; + pane.cur_pinned = true; + pane.ensureCursorVisible(); + for (pane.sels[0..pane.nsel]) |*s| { + const sgap = modal.offsetAt(text, .{ .row = @intCast(@max(0, s.row)), .col = @intCast(@max(0, s.col)) }); + const b2 = if (back == gap) sgap else modal.prevGrapheme(text, sgap); + const bp = modal.positionAt(text, b2); + s.row = @intCast(bp.row); + s.col = @intCast(bp.col); + s.arow = s.row; + s.acol = s.col; + } + } +} + +pub fn paneCursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { + const arena = p.scratch.allocator(); + if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); + if (pane.hasPdf()) { + if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); + unreachable; + } + return panes.Terminal.cursorLines(p, pane); +} + +pub fn paneByteAtDisplay(p: *Pardes, pane: *Pane, row: i32, from_raw: i32, display_col: i32) i32 { + if (pane.file != null) + return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col); + const lines = paneCursorLines(p, pane) catch return @max(0, from_raw + display_col); + const local = row; + if (local < 0 or @as(usize, @intCast(local)) >= lines.len) + return @max(0, from_raw + display_col); + return @intCast(panes.File.byteAtDisplayFrom( + lines[@intCast(local)], + @intCast(@max(0, from_raw)), + @intCast(@max(0, display_col)), + )); +} + +/// Freeze the live terminal cursor into the modal coordinate space. The +/// emulator reports screen cells; editing state stores UTF-8 byte offsets. +pub fn pinPaneCursor(p: *Pardes, pane: *Pane) void { + if (pane.cur_pinned) return; + pane.pinCursor(); + if (pane.file == null and !pane.hasPdf()) + pane.cur_col = paneByteAtDisplay(p, pane, pane.cur_row, 0, pane.cur_col); +} + +pub fn flatSurface(p: *Pardes, pane: *Pane) ![]const u8 { + if (pane.file) |f| return f.content; + if (pane.hasPdf()) { + if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa); + unreachable; + } + const lines = try panes.Terminal.cursorLines(p, pane); + return panes.Terminal.flatSurface(p, pane, lines); +} + +pub fn paneWrapWidth(p: *const Pardes, pane: *const Pane) usize { + if (pane.file == null) return 0; + return panes.File.wrapWidth(pane, p.settings.wrap); +} + +/// Route shared edit operations to a file's content or a terminal overlay. +fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?panes.EditText { + if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; + if (pane.image != null or pane.hasPdf()) return null; + return panes.Terminal.editText(p, pane, lo, hi, col); +} + +fn editTextEol(p: *Pardes, pane: *Pane, b: Bounds) ?panes.EditText { + const eb = editText(p, pane, b.lo_row, b.hi_row, -1) orelse return null; + const r: usize = @intCast(@max(0, b.hi_row - eb.row0)); + if (r + 1 < modal.lineCount(eb.text)) return eb; + if (b.hi_col < @as(i32, @intCast(modal.lineSlice(eb.text, r).len))) return eb; + return editText(p, pane, b.lo_row, b.hi_row + 1, -1); +} + +/// install a rewritten editable text (frees the old one) +fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { + if (pane.file) |*f| return panes.File.setContent(p, f, new); + panes.Terminal.setEditText(p, pane, new); +} + +pub const InsertAt = enum { at, append, line_start, line_end, open_below, open_above }; + +/// Files insert only inside existing rows and at grapheme boundaries. +/// Terminal overlays can materialize virtual rows/columns, so keep those. +pub fn clampFileCursor(pane: *Pane) bool { + const file = if (pane.file) |*file| file else return false; + const old_row = pane.cur_row; + const old_col = pane.cur_col; + const last = panes.File.nlines(pane.gpa, file) -| 1; + pane.cur_row = @intCast(@min(last, @as(usize, @intCast(@max(0, pane.cur_row))))); + const line = panes.File.sourceLine(pane, pane.cur_row); + pane.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, pane.cur_col)))))); + return old_row != pane.cur_row or old_col != pane.cur_col; +} + +pub fn enterInsert(p: *Pardes, pane: *Pane, where: InsertAt, cnt: usize) void { + if (pane.hasPdf()) return; + pinPaneCursor(p, pane); + _ = clampFileCursor(pane); + // snapshot once per insert session (WITH the pre-insert selection) so + // `u` undoes the whole session and restores what was selected + pushUndo(p, pane); + pane.select = false; + pane.append_at = null; + pane.sticky_col = -1; + const text = flatSurface(p, pane) catch { + pane.mode = .insert; + pane.msel.active = false; + pane.vsel.active = false; + pane.normal.clear(); + return; + }; + const cur = pane.toModalCursor(); + const line = panes.File.textLine(pane, text, cur.row); + const b: ?Bounds = if (pane.vsel.active) vselBounds(pane) else null; + switch (where) { + .at => { + if (b) |bb| { + pane.cur_row = bb.lo_row; + pane.cur_col = bb.lo_col; + pane.vsel = .{ .active = true, .row = bb.hi_row, .col = bb.hi_col, .explicit = false }; + pane.cur_pinned = true; + } + }, + .append => { + const lo_row = if (b) |bb| bb.lo_row else pane.cur_row; + const lo_col = if (b) |bb| bb.lo_col else pane.cur_col; + const hi_row = if (b) |bb| bb.hi_row else pane.cur_row; + const hi_col = if (b) |bb| bb.hi_col else pane.cur_col; + pane.append_at = .{ .row = lo_row, .col = lo_col }; + const gap = modal.nextGrapheme(text, modal.offsetAt(text, .{ .row = @intCast(@max(0, hi_row)), .col = @intCast(@max(0, hi_col)) })); + const gc = modal.positionAt(text, gap); + pane.cur_row = @intCast(gc.row); + pane.cur_col = @intCast(gc.col); + pane.vsel = .{ .active = b != null, .row = lo_row, .col = lo_col, .explicit = false }; + pane.cur_pinned = true; + }, + .line_start => { + pane.fromModalCursor(.{ .row = cur.row, .col = modal.firstNonWs(line) }); + pane.vsel.active = false; + }, + .line_end => { + pane.cur_col = @intCast(line.len); + pane.cur_pinned = true; + pane.vsel.active = false; + }, + .open_below, .open_above => { + pane.vsel.active = false; + const below = where == .open_below; + const abs: i32 = if (b) |bb| (if (below) bb.hi_row else bb.lo_row) else pane.cur_row; + const eb = editText(p, pane, abs, abs, -1) orelse return; + const row: usize = @intCast(@max(0, abs - eb.row0)); + const ind = modal.indentText(modal.lineSlice(eb.text, row)); + const arena = p.scratch.allocator(); + const block_len = std.math.mul(usize, cnt, ind.len + 1) catch return; + const block = arena.alloc(u8, block_len) catch return; + var block_at: usize = 0; + for (0..cnt) |_| { + if (below) { + block[block_at] = '\n'; + block_at += 1; + } + @memcpy(block[block_at..][0..ind.len], ind); + block_at += ind.len; + if (!below) { + block[block_at] = '\n'; + block_at += 1; + } + } + const at: modal.Cursor = if (below) + .{ .row = row, .col = modal.lineSlice(eb.text, row).len } + else + .{ .row = row, .col = 0 }; + const new = modal.insertAt(p.gpa, eb.text, at, block) catch return; + setEditText(p, pane, new); + pane.cur_row = @as(i32, @intCast(if (below) row + 1 else row)) + eb.row0; + pane.cur_col = @intCast(ind.len); + pane.cur_pinned = true; + if (cnt > 1 and !p.multi_on) opened: { + const t2 = flatSurface(p, pane) catch break :opened; + var rs: [Pane.max_selections]modal.Selection = undefined; + const m = @min(cnt, Pane.max_selections); + for (0..m) |k| { + const o = modal.offsetAt(t2, .{ .row = @intCast(@max(0, pane.cur_row) + @as(i32, @intCast(k))), .col = ind.len }); + rs[k] = .{ .anchor = o, .head = o }; + } + pane.setRanges(t2, rs[0..m], &.{}, 0, false); + } + }, + } + pane.mode = .insert; + pane.msel.active = false; + pane.normal.clear(); + pane.ensureCursorVisible(); +} + +pub fn handleInsert(p: *Pardes, pane: *Pane, key: Key) void { + if (pane.nsel == 0) return insertKey(p, pane, key); + p.replaySels(pane, .{ .insert = key }); +} + +pub fn insertKey(p: *Pardes, pane: *Pane, key: Key) void { + // helix aliases: normalize to the base key and re-dispatch + if (hit(key, config.insert_backspace_alias)) return insertKey(p, pane, .{ .cp = Key.backspace }); + if (hit(key, config.insert_enter_alias)) return insertKey(p, pane, .{ .cp = Key.enter }); + if (hit(key, config.insert_delete_alias)) return insertKey(p, pane, .{ .cp = Key.delete }); + pane.vsel.active = false; + if (!pane.cur_pinned) pinPaneCursor(p, pane); + _ = clampFileCursor(pane); + switch (key.cp) { + Key.left, Key.right, Key.up, Key.down => { + const lines = paneCursorLines(p, pane) catch return; + const cur0 = pane.toModalCursor(); + const nc = switch (key.cp) { + Key.left => modal.charLeft(lines, cur0), + Key.right => modal.charRight(lines, cur0), + Key.up => Pane.insertVerticalCursor(lines, cur0, false), + Key.down => Pane.insertVerticalCursor(lines, cur0, true), + else => cur0, + }; + pane.fromModalCursor(nc); + pane.ensureCursorVisible(); + return; + }, + Key.page_up, Key.page_down => { + // helix binds insert pageup/pagedown to the same view + // scroll + cursor snap as normal mode + const flat = flatSurface(p, pane) catch return; + const range = pane.primaryRange(flat, 0); + const step: i32 = @intCast(@max(1, pane.rows)); + pane.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step); + return; + }, + Key.home => { + pane.cur_col = 0; + pane.cur_pinned = true; + pane.ensureCursorVisible(); + return; + }, + Key.end => { + // helix insert End: past the last char (goto_line_end_newline) + const text = flatSurface(p, pane) catch return; + const cur0 = pane.toModalCursor(); + pane.cur_col = @intCast(panes.File.textLine(pane, text, cur0.row).len); + pane.cur_pinned = true; + pane.ensureCursorVisible(); + return; + }, + else => {}, + } + const eb = editText(p, pane, pane.cur_row, pane.cur_row, pane.cur_col) orelse return; + const text = eb.text; + const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; + if (key.text.len > 0 and !key.ctrl and !key.alt) { + const new = modal.insertAt(p.gpa, text, c, key.text) catch return; + setEditText(p, pane, new); + for (key.text) |ch| { + if (ch == '\n') { + pane.cur_row += 1; + pane.cur_col = 0; + } else pane.cur_col += 1; + } + pane.cur_pinned = true; + pane.ensureCursorVisible(); + return; + } + // helix insert-mode kills (word/line; deleteSpan is exclusive) + if (hit(key, config.delete_word_backward)) { + const e2 = if (c.row == 0 and c.col == 0) + (editText(p, pane, pane.cur_row - 1, pane.cur_row, 0) orelse return) + else + eb; + const c2 = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - e2.row0)), .col = c.col }; + const g = modal.offsetAt(e2.text, c2); + if (g == 0) return; + const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .prev_word_start); + const from = @min(wr.anchor, wr.head); + const fc = modal.positionAt(e2.text, from); + const new = modal.deleteSpan(p.gpa, e2.text, fc, c2) catch return; + setEditText(p, pane, new); + pane.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; + pane.cur_col = @intCast(fc.col); + pane.cur_pinned = true; + pane.ensureCursorVisible(); + return; + } + if (hit(key, config.delete_word_forward)) { + const e2 = if (c.col >= modal.lineSlice(text, c.row).len and c.row + 1 >= modal.lineCount(text)) + (editText(p, pane, pane.cur_row, pane.cur_row + 1, pane.cur_col) orelse return) + else + eb; + const c2 = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - e2.row0)), .col = c.col }; + const g = modal.offsetAt(e2.text, c2); + const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .next_word_end); + const to = @max(wr.anchor, wr.head); + if (to <= g) return; + const new = modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to)) catch return; + setEditText(p, pane, new); + pane.cur_pinned = true; + return; + } + if (hit(key, config.kill_to_line_start)) { + const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c) catch return; + setEditText(p, pane, new); + pane.cur_col = 0; + pane.cur_pinned = true; + pane.ensureCursorVisible(); + return; + } + if (hit(key, config.kill_to_line_end)) { + const llen = modal.lineSlice(text, c.row).len; + const new = modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }) catch return; + setEditText(p, pane, new); + pane.cur_pinned = true; + return; + } + switch (key.cp) { + Key.enter => { + const line = modal.lineSlice(text, c.row); + const indent = modal.newlineIndentWidth(line, c.col); + const arena = p.scratch.allocator(); + const block = arena.alloc(u8, 1 + indent) catch return; + block[0] = '\n'; + @memset(block[1..], ' '); + const new = modal.insertAt(p.gpa, text, c, block) catch return; + setEditText(p, pane, new); + pane.cur_row += 1; + pane.cur_col = @intCast(indent); + pane.cur_pinned = true; + pane.ensureCursorVisible(); + }, + Key.backspace => { + if (pane.cur_col > 0) { + const line = modal.lineSlice(text, c.row); + const prev = modal.prevGrapheme(line, c.col); + const new = modal.deleteChar(p.gpa, text, .{ .row = c.row, .col = prev }) catch return; + setEditText(p, pane, new); + pane.cur_col = @intCast(prev); + pane.cur_pinned = true; + pane.ensureCursorVisible(); + return; + } + // at col 0: eat the newline above (join up) — a terminal grows + // its buffer over the row it is joining with + if (pane.cur_row <= 0) return; + const e2 = editText(p, pane, pane.cur_row - 1, pane.cur_row, 0) orelse return; + const row: usize = @intCast(@max(0, pane.cur_row - e2.row0)); + if (row == 0) return; + const prevlen = modal.lineSlice(e2.text, row - 1).len; + const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }) catch return; + setEditText(p, pane, new); + pane.cur_row -= 1; + pane.cur_col = @intCast(prevlen); + pane.cur_pinned = true; + pane.ensureCursorVisible(); + }, + Key.delete => { + // delete forward; at line end eat the newline (join), which on + // a terminal means the buffer swallowing the row below + const line = modal.lineSlice(text, c.row); + if (c.col < line.len) { + const new = modal.deleteChar(p.gpa, text, c) catch return; + setEditText(p, pane, new); + } else { + const e2 = editText(p, pane, pane.cur_row, pane.cur_row + 1, pane.cur_col) orelse return; + const row: usize = @intCast(@max(0, pane.cur_row - e2.row0)); + if (row + 1 >= modal.lineCount(e2.text)) return; + const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }) catch return; + setEditText(p, pane, new); + } + pane.cur_pinned = true; + }, + Key.tab => { + const ln = modal.lineSlice(text, c.row); + if (!p.multi_on and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: { + const f = pane.file orelse break :dot; + if (f.output != null or !lsp.speaks(f.path)) break :dot; + const seq = p.lsp_seq; + p.lspRequest(p.active, .completion, ""); + if (p.lsp_seq != seq) return; + } + insertTab(p, pane); + }, + else => {}, + } +} + +pub fn insertTab(p: *Pardes, pane: *Pane) void { + const eb = editText(p, pane, pane.cur_row, pane.cur_row, pane.cur_col) orelse return; + const c: modal.Cursor = .{ + .row = @intCast(@max(0, pane.cur_row - eb.row0)), + .col = @intCast(@max(0, pane.cur_col)), + }; + const pad = modal.INDENT_W - (c.col % modal.INDENT_W); + const new = modal.insertAt(p.gpa, eb.text, c, " "[0..pad]) catch return; + setEditText(p, pane, new); + pane.cur_col += @intCast(pad); + pane.cur_pinned = true; + pane.ensureCursorVisible(); +} + +const Bounds = struct { lo_row: i32, lo_col: i32, hi_row: i32, hi_col: i32 }; + +/// a range's two cells, normalized to document order +pub fn cellBounds(s: Pane.SelRange) Bounds { + if (s.row < s.arow or (s.row == s.arow and s.col < s.acol)) + return .{ .lo_row = s.row, .lo_col = s.col, .hi_row = s.arow, .hi_col = s.acol }; + return .{ .lo_row = s.arow, .lo_col = s.acol, .hi_row = s.row, .hi_col = s.col }; +} + +/// the char selection [anchor, cursor] normalized to document order +fn vselBounds(pane: *Pane) Bounds { + return cellBounds(.{ .row = pane.cur_row, .col = pane.cur_col, .arow = pane.vsel.row, .acol = pane.vsel.col }); +} + +fn vselText(p: *Pardes, pane: *Pane) []const u8 { + const arena = p.scratch.allocator(); + const b = vselBounds(pane); + const text = flatSurface(p, pane) catch return ""; + return modal.rangeText(arena, text, .{ .row = @intCast(@max(0, b.lo_row)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row)), .col = @intCast(@max(0, b.hi_col)) }) catch ""; +} + +/// join surface rows [r0, r1] (absolute) with '\n'; scratch-owned +fn yankRows(p: *Pardes, pane: *Pane, r0: i32, r1: i32) []const u8 { + const arena = p.scratch.allocator(); + const lines = paneCursorLines(p, pane) catch return ""; + const rows_count: usize = @intCast(@max(0, r1 - r0 + 1)); + var total: usize = rows_count -| 1; + var i = r0; + while (i <= r1) : (i += 1) { + if (i >= 0 and @as(usize, @intCast(i)) < lines.len) + total += lines[@intCast(i)].len; + } + const out = arena.alloc(u8, total) catch return ""; + var at: usize = 0; + i = r0; + while (i <= r1) : (i += 1) { + if (i > r0) { + out[at] = '\n'; + at += 1; + } + if (i >= 0 and @as(usize, @intCast(i)) < lines.len) { + const line = lines[@intCast(i)]; + @memcpy(out[at..][0..line.len], line); + at += line.len; + } + } + return out; +} + +pub fn normalDelete(p: *Pardes, pane: *Pane, yank: bool) void { + pane.select = false; // helix delete exits select mode + pane.sticky_col = -1; + if (pane.vsel.active) { + const b = vselBounds(pane); + if (yank) setYank(p, vselText(p, pane)); // read the range before the move + pushUndo(p, pane); + const eb = editTextEol(p, pane, b) orelse { + pane.vsel.active = false; + return; + }; + const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch { + pane.vsel.active = false; + return; + }; + setEditText(p, pane, d.content); + p.gpa.free(d.deleted); + pane.cur_row = b.lo_row; + pane.cur_col = b.lo_col; + pane.clampCursor(d.content, eb.row0); + return; + } + if (pane.msel.active) { + const r0 = @min(pane.msel.r0, pane.msel.r1); + const r1 = @max(pane.msel.r0, pane.msel.r1); + pushUndo(p, pane); + // linewise: a line's newline lives on the row below it + const eb = editText(p, pane, r0, r1 + 1, -1) orelse { + pane.msel.active = false; + return; + }; + const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, r0 - eb.row0)), @intCast(@max(0, r1 - eb.row0))) catch { + pane.msel.active = false; + return; + }; + setEditText(p, pane, d.content); + if (yank) setYank(p, d.deleted); + p.gpa.free(d.deleted); + const n = modal.lineCount(d.content); + pane.cur_row = @as(i32, @intCast(@min(@as(usize, @intCast(@max(0, r0 - eb.row0))), if (n == 0) 0 else n - 1))) + eb.row0; + pane.cur_col = 0; + pane.msel.active = false; + pane.cur_pinned = true; + pane.ensureCursorVisible(); + } else { + pushUndo(p, pane); + const eb = editTextEol(p, pane, .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }) orelse return; + const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; + if (yank) { + const arena = p.scratch.allocator(); + setYank(p, modal.rangeText(arena, eb.text, c, c) catch return); + } + // deleteRange (not deleteChar): the cursor may sit ON a '\n' + // cell, where a delete joins the lines (helix 1-wide selection) + const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return; + setEditText(p, pane, d.content); + p.gpa.free(d.deleted); + const llen = modal.lineSlice(d.content, c.row).len; + pane.cur_col = @min(pane.cur_col, @as(i32, @intCast(llen))); + } +} + +pub fn normalYank(p: *Pardes, pane: *Pane) void { + pane.select = false; + if (pane.rawPointerText(pane.sel[sel_slot])) |text| { + setYank(p, text); + return; + } + if (pane.vsel.active) { + setYank(p, vselText(p, pane)); + return; + } + if (pane.msel.active) { + setYank(p, yankRows(p, pane, @min(pane.msel.r0, pane.msel.r1), @max(pane.msel.r0, pane.msel.r1))); + } else { + const save = pane.vsel; + pane.vsel = .{ .active = true, .row = pane.cur_row, .col = pane.cur_col, .explicit = false }; + setYank(p, vselText(p, pane)); + pane.vsel = save; + } +} + +pub fn pasteText(p: *Pardes, pane: *Pane, y0: []const u8, before: bool, count: usize) void { + if (y0.len == 0) return; + pushUndo(p, pane); + pane.select = false; + pane.sticky_col = -1; + const arena = p.scratch.allocator(); + var y: []const u8 = y0; + if (count > 1) { + const total = std.math.mul(usize, count, y0.len) catch return; + const buf = arena.alloc(u8, total) catch return; + for (0..count) |i| @memcpy(buf[i * y0.len ..][0..y0.len], y0); + y = buf; + } + const b: Bounds = if (pane.vsel.active) + vselBounds(pane) + else + .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }; + const eb = editText(p, pane, b.lo_row, b.hi_row, -1) orelse return; + const row0 = eb.row0; + if (y[y.len - 1] == '\n') { + const block_text = y[0 .. y.len - 1]; + const n = @max(1, modal.lineCount(block_text)); + var out: []u8 = undefined; + if (before) { + const row: usize = @intCast(@max(0, b.lo_row - row0)); + const block = std.fmt.allocPrint(arena, "{s}\n", .{block_text}) catch return; + out = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = 0 }, block) catch return; + pane.cur_row = @as(i32, @intCast(row + n - 1)) + row0; + } else { + const row: usize = @intCast(@max(0, b.hi_row - row0)); + out = modal.pasteLineBelow(p.gpa, eb.text, row, block_text) catch return; + pane.cur_row = @as(i32, @intCast(row + n)) + row0; + } + setEditText(p, pane, out); + pane.vsel = .{ .active = true, .row = pane.cur_row - @as(i32, @intCast(n - 1)), .col = 0, .explicit = false }; + // cursor ON the last pasted line's '\n' (helix) + const llen = modal.lineSlice(out, @intCast(@max(0, pane.cur_row - row0))).len; + pane.cur_col = @intCast(llen); + } else { + const at: modal.Cursor = if (before) + .{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) } + else blk: { + const hrow: usize = @intCast(@max(0, b.hi_row - row0)); + const hi_col: usize = @intCast(@max(0, b.hi_col)); + const high_line = modal.lineSlice(eb.text, hrow); + if (hi_col >= high_line.len) break :blk .{ .row = hrow + 1, .col = 0 }; + const gcol = modal.nextGrapheme(high_line, hi_col); + break :blk .{ .row = hrow, .col = gcol }; + }; + const out = modal.insertAt(p.gpa, eb.text, at, y) catch return; + setEditText(p, pane, out); + pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(at.row)) + row0, .col = @intCast(at.col), .explicit = false }; + const end = modal.advanceBy(at, y); + if (end.col > 0) { + pane.cur_row = @as(i32, @intCast(end.row)) + row0; + pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(out, end.row), end.col)); + } else { + pane.cur_row = @as(i32, @intCast(end.row -| 1)) + row0; + pane.cur_col = @intCast(modal.lineSlice(out, end.row -| 1).len); + } + } + pane.msel.active = false; + pane.cur_pinned = true; + pane.ensureCursorVisible(); +} + +pub fn normalChange(p: *Pardes, pane: *Pane) void { + pane.select = false; + pane.sticky_col = -1; + if (pane.vsel.active) { + const b = vselBounds(pane); + const eb = editTextEol(p, pane, b) orelse return; + const hi_len = modal.lineSlice(eb.text, @intCast(@max(0, b.hi_row - eb.row0))).len; + if (b.lo_col == 0 and @as(usize, @intCast(@max(0, b.hi_col))) >= hi_len) { + setYank(p, vselText(p, pane)); + pushUndo(p, pane); + const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))) catch return; + setEditText(p, pane, d.content); + p.gpa.free(d.deleted); + const n = modal.lineCount(d.content); + const row: usize = @min(@as(usize, @intCast(@max(0, b.lo_row - eb.row0))), if (n == 0) 0 else n - 1); + const ind = modal.indentText(modal.lineSlice(d.content, row)); + const arena = p.scratch.allocator(); + const block = std.fmt.allocPrint(arena, "{s}\n", .{ind}) catch return; + const new = modal.insertAt(p.gpa, d.content, .{ .row = row, .col = 0 }, block) catch return; + setEditText(p, pane, new); + pane.cur_row = @as(i32, @intCast(row)) + eb.row0; + pane.cur_col = @intCast(ind.len); + pane.vsel.active = false; + pane.msel.active = false; + pane.cur_pinned = true; + pane.mode = .insert; + pane.normal.clear(); + pane.ensureCursorVisible(); + return; + } + setYank(p, vselText(p, pane)); + pushUndo(p, pane); + const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch { + pane.vsel.active = false; + return; + }; + setEditText(p, pane, d.content); + p.gpa.free(d.deleted); + pane.cur_row = b.lo_row; + pane.cur_col = b.lo_col; + pane.clampCursor(d.content, eb.row0); + pane.mode = .insert; + pane.normal.clear(); + return; + } + if (pane.msel.active) { + const r0 = @min(pane.msel.r0, pane.msel.r1); + const r1 = @max(pane.msel.r0, pane.msel.r1); + pushUndo(p, pane); + const eb = editText(p, pane, r0, r1 + 1, -1) orelse return; + const arena = p.scratch.allocator(); + const lo: usize = @intCast(@max(0, r0 - eb.row0)); + const hi: usize = @intCast(@max(0, r1 - eb.row0)); + var total: usize = hi - lo; + for (lo..hi + 1) |r| total += modal.lineSlice(eb.text, r).len; + const buf = arena.alloc(u8, total) catch return; + var at: usize = 0; + for (lo..hi + 1) |r| { + if (r > lo) { + buf[at] = '\n'; + at += 1; + } + const line = modal.lineSlice(eb.text, r); + @memcpy(buf[at..][0..line.len], line); + at += line.len; + } + setYank(p, buf); + var body: []u8 = eb.text; + if (hi > lo) { + const d = modal.deleteLines(p.gpa, body, lo + 1, hi) catch { + pane.msel.active = false; + return; + }; + setEditText(p, pane, d.content); + p.gpa.free(d.deleted); + body = d.content; + } + const cl = modal.clearLine(p.gpa, body, lo) catch { + pane.msel.active = false; + return; + }; + setEditText(p, pane, cl); + pane.cur_row = r0; + pane.cur_col = 0; + pane.msel.active = false; + pane.cur_pinned = true; + pane.mode = .insert; + pane.normal.clear(); + pane.ensureCursorVisible(); + } else { + pushUndo(p, pane); + const eb = editTextEol(p, pane, .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }) orelse return; + const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; + const arena = p.scratch.allocator(); + setYank(p, modal.rangeText(arena, eb.text, c, c) catch return); + const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return; + setEditText(p, pane, d.content); + p.gpa.free(d.deleted); + const llen = modal.lineSlice(d.content, c.row).len; + pane.cur_col = @min(pane.cur_col, @as(i32, @intCast(llen))); + pane.mode = .insert; + pane.normal.clear(); + } +} + +fn selRange(pane: *Pane, content: []const u8, row0: i32) modal.Range { + if (pane.vsel.active) { + const b = vselBounds(pane); + return .{ + .a = .{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) }, + .b = .{ .row = @intCast(@max(0, b.hi_row - row0)), .col = @intCast(@max(0, b.hi_col)) }, + }; + } + if (pane.msel.active) { + const r0: usize = @intCast(@max(0, @min(pane.msel.r0, pane.msel.r1) - row0)); + const r1: usize = @intCast(@max(0, @max(pane.msel.r0, pane.msel.r1) - row0)); + const llen = modal.lineSlice(content, r1).len; + return .{ .a = .{ .row = r0, .col = 0 }, .b = .{ .row = r1, .col = if (llen == 0) 0 else modal.prevGrapheme(modal.lineSlice(content, r1), llen) } }; + } + const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - row0)), .col = @intCast(@max(0, pane.cur_col)) }; + return .{ .a = c, .b = c }; +} + +/// the rows an op's selection spans, absolute (what editText must cover) +fn selRows(pane: *Pane) Bounds { + if (pane.vsel.active) return vselBounds(pane); + if (pane.msel.active) return .{ + .lo_row = @min(pane.msel.r0, pane.msel.r1), + .lo_col = 0, + .hi_row = @max(pane.msel.r0, pane.msel.r1), + .hi_col = 0, + }; + return .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }; +} + +/// `r`: overwrite the selection (or the cursor char) with ch — +/// newlines included (helix), so `xrz` joins the selected lines +pub fn normalReplaceChar(p: *Pardes, pane: *Pane, ch: u21) void { + pane.select = false; + const eb = editTextEol(p, pane, selRows(pane)) orelse return; + const before = pane.primaryRange(eb.text, eb.row0); + const lo = @min(before.anchor, before.head); + const hi = @max(before.anchor, before.head); + var graphemes: usize = 0; + var at = lo; + while (at < hi) : (graphemes += 1) at = modal.nextGrapheme(eb.text, at); + var encoded: [4]u8 = undefined; + const encoded_len = std.unicode.utf8Encode(ch, &encoded) catch return; + const r = selRange(pane, eb.text, eb.row0); + pushUndo(p, pane); + const new = modal.replaceChars(p.gpa, eb.text, r.a, r.b, ch) catch return; + setEditText(p, pane, new); + const end = lo + graphemes * encoded_len; + const mapped: modal.Selection = if (before.head < before.anchor) + .{ .anchor = end, .head = lo } + else + .{ .anchor = lo, .head = end }; + pane.setRange(new, eb.row0, mapped, pane.vsel.explicit); +} + +/// `R`: replace the selection (or the cursor char) with the DEFAULT +/// register. `SPC R` is the same verb over the system clipboard. +pub fn normalReplaceYank(p: *Pardes, pane: *Pane) void { + replaceWithText(p, pane, p.yank orelse return); +} + +/// The pasted text becomes the selection, head on its last char (which for +/// a trailing-newline `y` is the '\n' cell of the last full line). +fn replaceWithText(p: *Pardes, pane: *Pane, y: []const u8) void { + if (y.len == 0) return; + pane.select = false; + const eb = editTextEol(p, pane, selRows(pane)) orelse return; + const r = selRange(pane, eb.text, eb.row0); + pushUndo(p, pane); + const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, y) catch return; + setEditText(p, pane, new); + pane.msel.active = false; + pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; + const end = modal.advanceBy(r.a, y); + if (end.col > 0) { + pane.cur_row = @as(i32, @intCast(end.row)) + eb.row0; + pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(new, end.row), end.col)); + } else { + // the yank ended in '\n': the cursor lands ON that newline + pane.cur_row = @as(i32, @intCast(end.row -| 1)) + eb.row0; + pane.cur_col = @intCast(modal.lineSlice(new, end.row -| 1).len); + } + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); +} + +/// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char), +/// keeping the selection (helix) +pub fn normalCase(p: *Pardes, pane: *Pane, op: modal.CaseOp) void { + pane.select = false; + const eb = editTextEol(p, pane, selRows(pane)) orelse return; + const r = selRange(pane, eb.text, eb.row0); + pushUndo(p, pane); + const new = modal.changeCase(p.gpa, eb.text, r.a, r.b, op) catch return; + setEditText(p, pane, new); +} + +/// a change to apply to file content: delete [from, to), insert `ins` at +/// `from`. Ascending and disjoint. +const TextChange = struct { from: usize, to: usize, ins: []const u8 }; + +fn mapThroughChanges(chs: []const TextChange, pos: usize) usize { + var delta: i64 = 0; + for (chs) |ch| { + if (pos < ch.from) break; + if (ch.from == ch.to) { + delta += @intCast(ch.ins.len); + continue; + } + if (pos == ch.from) break; + if (pos < ch.to) return @intCast(@as(i64, @intCast(ch.from)) + delta); + delta += @as(i64, @intCast(ch.ins.len)) - @as(i64, @intCast(ch.to - ch.from)); + } + return @intCast(@as(i64, @intCast(pos)) + delta); +} + +/// apply a change list. gpa-owned result. +fn applyChanges(p: *Pardes, text: []const u8, chs: []const TextChange) ![]u8 { + var total = text.len; + for (chs) |ch| total = total - (ch.to - ch.from) + ch.ins.len; + const out = try p.gpa.alloc(u8, total); + errdefer p.gpa.free(out); + var copied: usize = 0; + var at: usize = 0; + for (chs) |ch| { + const unchanged = text[copied..ch.from]; + @memcpy(out[at..][0..unchanged.len], unchanged); + at += unchanged.len; + @memcpy(out[at..][0..ch.ins.len], ch.ins); + at += ch.ins.len; + copied = ch.to; + } + @memcpy(out[at..], text[copied..]); + return out; +} + +pub fn normalJoin(p: *Pardes, pane: *Pane) void { + // a join always eats the newline of its last line, so the buffer has + // to reach one row PAST the selection + const sr = selRows(pane); + const eb = editText(p, pane, sr.lo_row, sr.hi_row + 1, -1) orelse return; + const text = eb.text; + const range = pane.primaryRange(text, eb.row0); + const span = Pane.rangeLineSpan(text, range); + const nlines = modal.cursorLineCount(text); + var end = span.end; + if (span.start == end) end = @min(end + 1, nlines - 1); + if (end <= span.start) return; + const arena = p.scratch.allocator(); + const chs = arena.alloc(TextChange, end - span.start) catch return; + var chs_len: usize = 0; + var l = span.start; + while (l < end) : (l += 1) { + const from = modal.lineEndOffset(text, l); + var to = if (l + 1 >= nlines) text.len else modal.lineStartOffset(text, l + 1); + while (to < text.len and (text[to] == ' ' or text[to] == '\t')) to += 1; + const sep: []const u8 = if (to == modal.lineEndOffset(text, @min(l + 1, nlines - 1))) "" else " "; + chs[chs_len] = .{ .from = from, .to = to, .ins = sep }; + chs_len += 1; + } + if (chs_len == 0) return; + pushUndo(p, pane); + const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }); + const anc_off = if (pane.vsel.active) + modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row - eb.row0)), .col = @intCast(@max(0, pane.vsel.col)) }) + else + cur_off; + const new = applyChanges(p, text, chs[0..chs_len]) catch return; + const nc = mapThroughChanges(chs[0..chs_len], cur_off); + const na = mapThroughChanges(chs[0..chs_len], anc_off); + setEditText(p, pane, new); + const cc = modal.positionAt(new, nc); + const ac = modal.positionAt(new, na); + pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; + pane.cur_col = @intCast(cc.col); + if (pane.vsel.active) { + pane.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0; + pane.vsel.col = @intCast(ac.col); + } + pane.msel.active = false; + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); +} + +pub fn normalIndent(p: *Pardes, pane: *Pane, cnt: usize, add: bool) void { + pane.select = false; + const sr = selRows(pane); + const eb = editText(p, pane, sr.lo_row, sr.hi_row, -1) orelse return; + const text = eb.text; + const range = pane.primaryRange(text, eb.row0); + const span = Pane.rangeLineSpan(text, range); + const arena = p.scratch.allocator(); + // one run of spaces, sliced per line: `>` never inserts more than this + const pad = arena.alloc(u8, modal.INDENT_W * cnt) catch return; + @memset(pad, ' '); + const chs = arena.alloc(TextChange, span.end - span.start + 1) catch return; + var chs_len: usize = 0; + var l = span.start; + while (l <= span.end) : (l += 1) { + const ls = modal.lineStartOffset(text, l); + const le = modal.lineEndOffset(text, l); + const line = text[ls..le]; + const nw = modal.firstNonWs(line); + if (nw == line.len) continue; // blank lines stay blank (helix) + if (add) { + const ins = modal.INDENT_W * cnt - (nw % modal.INDENT_W); + chs[chs_len] = .{ .from = ls, .to = ls, .ins = pad[0..ins] }; + chs_len += 1; + } else { + const want = modal.INDENT_W * cnt; + var w: usize = 0; + var pos: usize = 0; + while (pos < line.len) { + if (line[pos] == ' ') { + w += 1; + } else if (line[pos] == '\t') { + w = (w / modal.INDENT_W + 1) * modal.INDENT_W; + } else break; + pos += 1; + if (w >= want) break; + } + if (pos > 0) { + chs[chs_len] = .{ .from = ls, .to = ls + pos, .ins = "" }; + chs_len += 1; + } + } + } + if (chs_len == 0) return; + pushUndo(p, pane); + const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }); + const anc_off = if (pane.vsel.active) + modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row - eb.row0)), .col = @intCast(@max(0, pane.vsel.col)) }) + else + cur_off; + const new = applyChanges(p, text, chs[0..chs_len]) catch return; + const nc = mapThroughChanges(chs[0..chs_len], cur_off); + const na = mapThroughChanges(chs[0..chs_len], anc_off); + setEditText(p, pane, new); + const cc = modal.positionAt(new, nc); + const ac = modal.positionAt(new, na); + pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; + pane.cur_col = @intCast(cc.col); + if (pane.vsel.active) { + pane.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0; + pane.vsel.col = @intCast(ac.col); + } + pane.msel.active = false; + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); +} + +pub fn normalToggleComment(p: *Pardes, pane: *Pane) void { + const expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; + pane.select = false; // helix exit_select_mode + // the buffer must cover every cursor's rows, not just the primary's + var b = selRows(pane); + for (pane.sels[0..pane.nsel]) |s| { + b.lo_row = @min(b.lo_row, @min(s.row, s.arow)); + b.hi_row = @max(b.hi_row, @max(s.row, s.arow)); + } + const surface = flatSurface(p, pane) catch return; + const last_row = @as(i32, @intCast(panes.File.textLineCount(pane, surface))) - 1; + const eb = editText(p, pane, b.lo_row, @min(b.hi_row + 1, last_row), -1) orelse return; + const text = eb.text; + var rs: [Pane.max_selections]modal.Selection = undefined; + const got = pane.ranges(text, eb.row0, &rs); + const nlines = modal.cursorLineCount(text); + const arena = p.scratch.allocator(); + // the lines the ranges cover, each ONE ONCE and in order (helix's + // min_next_line: two cursors on one line comment it once) + const lines = arena.alloc(usize, nlines) catch return; + var lines_len: usize = 0; + var next: usize = 0; + for (rs[0..got.n]) |r| { + const span = Pane.rangeLineSpan(text, r); + var l = @max(span.start, next); + const end = @min(span.end + 1, nlines); + while (l < end) : (l += 1) { + lines[lines_len] = l; + lines_len += 1; + } + next = @max(next, end); + } + const ext = if (pane.file) |f| std.fs.path.extension(f.path) else ""; + var token: []const u8 = config.comment_token_default; + lang: for (config.comment_tokens) |row| { + for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) { + token = row.token; + break :lang; + }; + } + var commented = true; + var indent: usize = std.math.maxInt(usize); + var margin: usize = 1; + var live: usize = 0; + for (lines[0..lines_len]) |l| { + const line = text[modal.lineStartOffset(text, l)..modal.lineEndOffset(text, l)]; + const nw = modal.firstNonWs(line); + if (nw == line.len) continue; + indent = @min(indent, nw); + if (!std.mem.startsWith(u8, line[nw..], token)) commented = false; + if (nw + token.len >= line.len or line[nw + token.len] != ' ') margin = 0; + live += 1; + } + if (live == 0) return; // nothing but blank lines + const ins = std.fmt.allocPrint(arena, "{s} ", .{token}) catch return; + const chs = arena.alloc(TextChange, lines_len) catch return; + var chs_len: usize = 0; + for (lines[0..lines_len]) |l| { + const ls = modal.lineStartOffset(text, l); + const le = modal.lineEndOffset(text, l); + const line = text[ls..le]; + if (modal.firstNonWs(line) == line.len) continue; // blank lines untouched + const at = ls + indent; + // the @min can never bind: margin is 1 only when every line has a + // space after its own token, which is a byte past `at + token.len` + chs[chs_len] = if (commented) + .{ .from = at, .to = @min(at + token.len + margin, le), .ins = "" } + else + .{ .from = at, .to = at, .ins = ins }; + chs_len += 1; + } + pushUndo(p, pane); + // one edit, and the WHOLE selection rides through it (helix maps the + // selection with the transaction) + var cells: [Pane.max_selections]Pane.SelRange = undefined; + const new = applyChanges(p, text, chs[0..chs_len]) catch return; + for (rs[0..got.n], 0..) |r, i| { + const c = Pane.rangeCells(new, .{ + .anchor = mapThroughChanges(chs[0..chs_len], r.anchor), + .head = mapThroughChanges(chs[0..chs_len], r.head), + }); + const cc = modal.positionAt(new, c.cur); + const ac = modal.positionAt(new, c.anc); + cells[i] = .{ + .row = @as(i32, @intCast(cc.row)) + eb.row0, + .col = @intCast(cc.col), + .arow = @as(i32, @intCast(ac.row)) + eb.row0, + .acol = @intCast(ac.col), + }; + } + setEditText(p, pane, new); + const t2 = flatSurface(p, pane) catch return; + for (cells[0..got.n], 0..) |s, i| rs[i] = Pane.cellRange(t2, s.arow, s.acol, s.row, s.col); + pane.setRanges(t2, rs[0..got.n], &.{}, got.pri, expl); +} + +pub fn normalAdjustNumber(p: *Pardes, pane: *Pane, delta: i64) void { + const eb = editTextEol(p, pane, selRows(pane)) orelse return; + const r = selRange(pane, eb.text, eb.row0); + const arena = p.scratch.allocator(); + const frag = modal.rangeText(arena, eb.text, r.a, r.b) catch return; + const rep = (modal.incrementDecimal(arena, frag, delta) catch null) orelse return; + pushUndo(p, pane); + pane.select = false; + const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, rep) catch return; + setEditText(p, pane, new); + const start = modal.lineStartOffset(new, r.a.row) + r.a.col; + const cc = modal.positionAt(new, modal.prevGrapheme(new, start + rep.len)); + pane.vsel = .{ .active = modal.nextGrapheme(rep, 0) < rep.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; + pane.msel.active = false; + pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; + pane.cur_col = @intCast(cc.col); + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); +} + +/// `]Space` / `[Space`: add blank lines below/above, the cursor staying +/// on its text line (the selection rides along) +pub fn addNewline(p: *Pardes, pane: *Pane, below: bool, cnt: usize) void { + const eb = editText(p, pane, pane.cur_row, pane.cur_row, -1) orelse return; + pushUndo(p, pane); + const row: usize = @intCast(@max(0, pane.cur_row - eb.row0)); + const arena = p.scratch.allocator(); + const nl = arena.alloc(u8, cnt) catch return; + @memset(nl, '\n'); + const llen = modal.lineSlice(eb.text, row).len; + const new = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl) catch return; + setEditText(p, pane, new); + if (!below) { + pane.cur_row += @intCast(cnt); // the line moved down; stay on it + if (pane.vsel.active and pane.vsel.row >= @as(i32, @intCast(row))) pane.vsel.row += @intCast(cnt); + } else if (pane.vsel.active and pane.vsel.row > @as(i32, @intCast(row))) { + pane.vsel.row += @intCast(cnt); + } + pane.cur_pinned = true; + pane.ensureCursorVisible(); +} + +/// pair mapping for m-mode: either bracket names the pair; anything else +/// surrounds with itself (quotes) +fn pairFor(ch: u21) ?struct { o: u8, c: u8 } { + return switch (ch) { + '(', ')' => .{ .o = '(', .c = ')' }, + '[', ']' => .{ .o = '[', .c = ']' }, + '{', '}' => .{ .o = '{', .c = '}' }, + '<', '>' => .{ .o = '<', .c = '>' }, + else => if (ch <= 0x7f) .{ .o = @intCast(ch), .c = @intCast(ch) } else null, + }; +} + +pub fn textobjectSelect(p: *Pardes, pane: *Pane, text: []const u8, obj: u21, around: bool) void { + const range = pane.primaryRange(text, 0); + switch (obj) { + 'w', 'W' => { + const r = modal.selectWord(text, range, around, obj == 'W'); + return pane.setRange(text, 0, r, false); + }, + 'p' => { + const r = modal.selectParagraph(text, range, around, 1); + return pane.setRange(text, 0, r, false); + }, + else => {}, + } + const lines = paneCursorLines(p, pane) catch return; + const cur = modal.positionAt(text, modal.selectionCursor(text, range)); + const pair: ?modal.Range = switch (obj) { + '\'', '"', '`' => modal.enclosingQuote(lines, cur, @intCast(obj)), + '(', ')' => modal.enclosingPair(lines, cur, '(', ')'), + '[', ']' => modal.enclosingPair(lines, cur, '[', ']'), + '{', '}' => modal.enclosingPair(lines, cur, '{', '}'), + '<', '>' => modal.enclosingPair(lines, cur, '<', '>'), + else => null, + }; + const pr = pair orelse return; + var a = modal.offsetAt(text, pr.a); + var head = modal.nextGrapheme(text, modal.offsetAt(text, pr.b)); + if (!around) { + // inside: shrink off the delimiters; an EMPTY pair collapses to + // a 1-wide cursor on the closing char (helix) + a = modal.nextGrapheme(text, a); + head = modal.prevGrapheme(text, head); + } + pane.setRange(text, 0, .{ .anchor = a, .head = head }, false); +} + +/// `ms`: wrap the selection (or the cursor char) in a pair; the wrap +/// including the pair becomes the selection +pub fn surroundAdd(p: *Pardes, pane: *Pane, ch: u21) void { + const pr = pairFor(ch) orelse return; + pane.select = false; + const eb = editTextEol(p, pane, selRows(pane)) orelse return; + const r = selRange(pane, eb.text, eb.row0); + pushUndo(p, pane); + const close_col = modal.nextGrapheme(modal.lineSlice(eb.text, r.b.row), r.b.col); + var new = modal.insertAt(p.gpa, eb.text, .{ .row = r.b.row, .col = close_col }, &[1]u8{pr.c}) catch return; + setEditText(p, pane, new); + new = modal.insertAt(p.gpa, new, .{ .row = r.a.row, .col = r.a.col }, &[1]u8{pr.o}) catch return; + setEditText(p, pane, new); + pane.msel.active = false; + pane.vsel = .{ .active = true, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; + pane.cur_row = @as(i32, @intCast(r.b.row)) + eb.row0; + pane.cur_col = @intCast(close_col + @as(usize, if (r.a.row == r.b.row) 1 else 0)); + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); +} + +/// `md`: delete the enclosing pair's chars; the cursor maps through +pub fn surroundDelete(p: *Pardes, pane: *Pane, ch: u21) void { + const pr = pairFor(ch) orelse return; + const lines = paneCursorLines(p, pane) catch return; + const cur = pane.toModalCursor(); + const r = (if (pr.o == pr.c) + modal.enclosingQuote(lines, cur, pr.o) + else + modal.enclosingPair(lines, cur, pr.o, pr.c)) orelse return; + const lo: i32 = @intCast(@min(r.a.row, cur.row)); + const hi: i32 = @intCast(@max(r.b.row, cur.row)); + const eb = editText(p, pane, lo, hi, -1) orelse return; + const text = eb.text; + const drow = -eb.row0; // surface row -> buffer row + const ra: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.a.row)) + drow), .col = r.a.col }; + const rb: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.b.row)) + drow), .col = r.b.col }; + pushUndo(p, pane); + const a_off = modal.offsetAt(text, ra); + const b_off = modal.offsetAt(text, rb); + const cur_off = modal.offsetAt(text, .{ .row = @intCast(@as(i32, @intCast(cur.row)) + drow), .col = cur.col }); + // the close first, so the open's position stays valid + var new = modal.deleteChar(p.gpa, text, rb) catch return; + setEditText(p, pane, new); + new = modal.deleteChar(p.gpa, new, ra) catch return; + setEditText(p, pane, new); + var nc = cur_off; + if (nc > b_off) nc -= 1; + if (nc > a_off) nc -= 1; + const cc = modal.positionAt(new, nc); + pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; + pane.cur_col = @intCast(cc.col); + pane.vsel.active = false; + pane.msel.active = false; + pane.cur_pinned = true; + pane.ensureCursorVisible(); +} + +/// `mr`: swap the enclosing pair's chars for 's +pub fn surroundReplace(p: *Pardes, pane: *Pane, from: u21, to: u21) void { + const fp = pairFor(from) orelse return; + const tp = pairFor(to) orelse return; + const lines = paneCursorLines(p, pane) catch return; + const cur = pane.toModalCursor(); + const r = (if (fp.o == fp.c) + modal.enclosingQuote(lines, cur, fp.o) + else + modal.enclosingPair(lines, cur, fp.o, fp.c)) orelse return; + const eb = editText(p, pane, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1) orelse return; + const drow = -eb.row0; // surface row -> buffer row + const ar: usize = @intCast(@as(i32, @intCast(r.a.row)) + drow); + const br: usize = @intCast(@as(i32, @intCast(r.b.row)) + drow); + pushUndo(p, pane); + const out = p.gpa.dupe(u8, eb.text) catch return; + out[modal.lineStartOffset(out, ar) + r.a.col] = tp.o; + out[modal.lineStartOffset(out, br) + r.b.col] = tp.c; + setEditText(p, pane, out); +} + +pub fn pushUndo(p: *Pardes, pane: *Pane) void { + // one keystroke, one undo step — even when it edited at ten cursors. + if (p.multi_on and !p.multi_first) return; + if (pane.file != null) return panes.File.pushUndo(p, pane); + panes.Terminal.pushUndo(p, pane); +} + +pub fn doUndo(p: *Pardes, pane: *Pane) void { + if (pane.file != null) return panes.File.undo(p, pane); + panes.Terminal.undo(p, pane); +} + +pub fn doRedo(p: *Pardes, pane: *Pane) void { + if (pane.file != null) return panes.File.redo(p, pane); + panes.Terminal.redo(p, pane); +} + +const PointerTextSelection = struct { + sel: Pane.Sel, + on_tag: bool, +}; + +pub fn pointerTextSelection(p: *const Pardes, id: usize, col: u16, row: u16, body_hit: ?Mouse.BodyHit, tag_hit: ?TagHit) ?PointerTextSelection { + if (p.panes[id] == null) return null; + const r = p.rects[id]; + if (col < r.x + config.GUTTER or col >= r.x + r.w or row < r.y or row >= r.y + r.h) return null; + const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; + const body_y = p.bodyTop(r); + const on_tag = row >= tag_y and row < tag_y + BOX_H; + if (on_tag and col < r.x + TAG_TEXT_INSET) return null; + // A notice chip is chrome: it sits OVER the body's top rows, so a + // click inside one belongs to nobody. The rest of those rows is + // ordinary body text and still answers normally. + if (!on_tag and row >= body_y and row - body_y < p.panes[id].?.notices.span() and + p.panes[id].?.notices.covers(row - body_y, col)) return null; + if (!on_tag) if (body_hit) |supplied| { + const mapped_hit = p.bodyHitForPane(id, supplied, false) orelse return null; + const c = @as(i32, mapped_hit.col) - config.GUTTER; + const v = @as(i32, mapped_hit.row) + BOX_H; + return .{ .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, .on_tag = false }; + }; + const tag_col = if (on_tag) p.tagColumn(.pane, id, tag_hit, false) else null; + const c: i32 = (if (tag_col) |value| @as(i32, value) else @as(i32, col) - @as(i32, r.x + (if (on_tag) TAG_TEXT_INSET else config.GUTTER))) + + (if (on_tag) @as(i32, p.panes[id].?.tag_scroll) else 0); + const v: i32 = if (on_tag) 0 else @as(i32, row) - @as(i32, body_y) + @as(i32, BOX_H); + return .{ + .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, + .on_tag = on_tag, + }; +} + +/// 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; + while (p.nextEffect()) |effect| { + if (std.meta.activeTag(effect) == want) seen = true; + } + return seen; +} + +test "insert newline adds one indent level after a closing call" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile(" callback({})\n"); + pane.mode = .insert; + pane.cur_col = 16; + + p.update(.{ .key = .{ .cp = Key.enter } }); + + try std.testing.expectEqualSlices(u8, " callback({})\n \n", pane.file.?.content); + try std.testing.expectEqual(@as(i32, 1), pane.cur_row); + try std.testing.expectEqual(@as(i32, 8), pane.cur_col); +} + +test "insert and normal modes edit complete Unicode graphemes" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("a" ++ "e\u{301}" ++ "👩🏽\u{200d}🚀" ++ "界" ++ "z"); + + pane.mode = .insert; + pane.cur_col = 22; // on z, after the CJK grapheme + insertKey(p, pane, .{ .cp = Key.left }); + try std.testing.expectEqual(@as(i32, 19), pane.cur_col); + insertKey(p, pane, .{ .cp = Key.left }); + try std.testing.expectEqual(@as(i32, 4), pane.cur_col); + insertKey(p, pane, .{ .cp = Key.right }); + try std.testing.expectEqual(@as(i32, 19), pane.cur_col); + insertKey(p, pane, .{ .cp = Key.backspace }); + try std.testing.expectEqualStrings("ae\u{301}界z", pane.file.?.content); + try std.testing.expectEqual(@as(i32, 4), pane.cur_col); + + pane.mode = .normal; + pane.cur_col = 1; + normalDelete(p, pane, false); + try std.testing.expectEqualStrings("a界z", pane.file.?.content); + try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + normalReplaceChar(p, pane, 'λ'); + try std.testing.expectEqualStrings("aλz", pane.file.?.content); + + panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a")); + pane.cur_col = 3; + pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + normalReplaceChar(p, pane, 'λ'); + try std.testing.expectEqualStrings("λλ", pane.file.?.content); + try std.testing.expectEqual(@as(i32, 2), pane.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.vsel.col); + + panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a")); + pane.cur_col = 0; + pane.vsel = .{ .active = true, .row = 0, .col = 3, .explicit = true }; + normalReplaceChar(p, pane, 'λ'); + try std.testing.expectEqualStrings("λλ", pane.file.?.content); + try std.testing.expectEqual(@as(i32, 0), pane.cur_col); + try std.testing.expectEqual(@as(i32, 2), pane.vsel.col); +} + +test "flat text replacement preserves a terminal fragment origin and direction" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 12 }); + defer p.deinit(); + p.update(.{ .output = .{ .pane = 0, .bytes = "first\r\nsecond\r\nthird\r\n界a\r\n" } }); + const pane = p.panes[0].?; + pane.mode = .normal; + pane.cur_pinned = true; + pane.cur_row = 3; + pane.cur_col = 0; + pane.vsel = .{ .active = true, .row = 3, .col = 3, .explicit = true }; + normalReplaceChar(p, pane, 'λ'); + try std.testing.expectEqual(@as(i32, 3), pane.ovl.?.row); + try std.testing.expectEqualStrings("λλ", pane.ovl.?.text); + try std.testing.expectEqual(@as(i32, 3), pane.cur_row); + try std.testing.expectEqual(@as(i32, 0), pane.cur_col); + try std.testing.expectEqual(@as(i32, 3), pane.vsel.row); + try std.testing.expectEqual(@as(i32, 2), pane.vsel.col); + try std.testing.expect(pane.vsel.active and pane.vsel.explicit); + const lines = try paneCursorLines(p, pane); + try std.testing.expectEqualStrings("first", lines[0]); + try std.testing.expectEqualStrings("λλ", lines[3]); + const flat = try flatSurface(p, pane); + try std.testing.expect(std.mem.startsWith(u8, flat, "first\nsecond\nthird\nλλ\n")); +} + +test "only the SPC clipboard commands cross to the system clipboard" { + if (platform == .web) return; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); + const pane = p.panes[0].?; + + _ = drainedEffect(p, .set_clipboard); + p.update(.{ .key = .{ .cp = 'y' } }); + try std.testing.expect(p.yank != null and p.yank.?.len > 0); + try std.testing.expect(!drainedEffect(p, .set_clipboard)); + p.update(.{ .key = .{ .cp = 'd' } }); + try std.testing.expect(!drainedEffect(p, .set_clipboard)); + + // `SPC y` is the one that does, and it puts the SAME text there that `y` + // put in the register — it is the ordinary yank path plus the mirror. + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'y' } }); + const yanked = p.yank orelse return error.MissingYank; + try std.testing.expect(drainedEffect(p, .set_clipboard)); + + const before = pane.file.?.content.len; + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'p' } }); + try std.testing.expect(p.clip_pending != null); + try std.testing.expect(drainedEffect(p, .read_clipboard)); + try std.testing.expectEqual(before, pane.file.?.content.len); // nothing yet + p.update(.{ .paste = "PASTED" }); + try std.testing.expect(p.clip_pending == null); + try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "PASTED") != null); + // ...and it did NOT land in the register on its way past, nor echo back + // out to the clipboard it came from. + try std.testing.expectEqualStrings(yanked, p.yank orelse ""); + try std.testing.expect(!drainedEffect(p, .set_clipboard)); + + // An UNSOLICITED paste — the outer terminal's bracketed paste, a Cmd-V — + // is the same event with no request behind it, and means paste after. + p.update(.{ .paste = "UNASKED" }); + try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "UNASKED") != null); + try std.testing.expectEqualStrings(yanked, p.yank orelse ""); + + // A request the shell never answers dies at the next keystroke rather + // than firing late into whatever pane is focused by then. + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'P' } }); + try std.testing.expect(p.clip_pending != null); + p.update(.{ .key = .{ .cp = 'l' } }); + try std.testing.expect(p.clip_pending == null); +} diff --git a/src/fs.zig b/src/fs.zig index 4d8a5188..04a8ed36 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -40,6 +40,7 @@ const source_files = [_]Source{ .{ .path = "src/colors.zig", .contents = @embedFile("colors.zig") }, .{ .path = "src/Messages.zig", .contents = @embedFile("Messages.zig") }, .{ .path = "src/body_layer.zig", .contents = @embedFile("body_layer.zig") }, + .{ .path = "src/edit.zig", .contents = @embedFile("edit.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/pardes.zig b/src/pardes.zig index fe96a221..55e1dc7a 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const edit = @import("edit.zig"); pub const body_layer = @import("body_layer.zig"); pub const Messages = @import("Messages.zig"); pub const colors = @import("colors.zig"); @@ -432,6 +433,7 @@ pub const Loc = struct { }; test { + _ = @import("edit.zig"); _ = @import("Messages.zig"); _ = @import("selection_pipe.zig"); _ = @import("colors.zig"); @@ -664,22 +666,6 @@ test "the acme chords act once per selection, not once on the primary" { try std.testing.expectEqual(@as(u8, 0), p.panes[0].?.nsel); } -test "insert newline adds one indent level after a closing call" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = try p.setTestFile(" callback({})\n"); - pane.mode = .insert; - pane.cur_col = 16; - - p.update(.{ .key = .{ .cp = Key.enter } }); - - try std.testing.expectEqualSlices(u8, " callback({})\n \n", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); - try std.testing.expectEqual(@as(i32, 8), pane.cur_col); -} - test "startup config runs builtin lines in order and isolates bad lines" { const p = try Pardes.init(std.testing.allocator, .{ .startup_config = @@ -2702,49 +2688,6 @@ test "every line of the board's boot buffer renders whole" { // ---- the boundary types ---- -test "insert and normal modes edit complete Unicode graphemes" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); - defer p.deinit(); - const pane = try p.setTestFile("a" ++ "e\u{301}" ++ "👩🏽\u{200d}🚀" ++ "界" ++ "z"); - - pane.mode = .insert; - pane.cur_col = 22; // on z, after the CJK grapheme - p.insertKey(pane, .{ .cp = Key.left }); - try std.testing.expectEqual(@as(i32, 19), pane.cur_col); - p.insertKey(pane, .{ .cp = Key.left }); - try std.testing.expectEqual(@as(i32, 4), pane.cur_col); - p.insertKey(pane, .{ .cp = Key.right }); - try std.testing.expectEqual(@as(i32, 19), pane.cur_col); - p.insertKey(pane, .{ .cp = Key.backspace }); - try std.testing.expectEqualStrings("ae\u{301}界z", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 4), pane.cur_col); - - pane.mode = .normal; - pane.cur_col = 1; - p.normalDelete(pane, false); - try std.testing.expectEqualStrings("a界z", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - p.normalReplaceChar(pane, 'λ'); - try std.testing.expectEqualStrings("aλz", pane.file.?.content); - - panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a")); - pane.cur_col = 3; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - p.normalReplaceChar(pane, 'λ'); - try std.testing.expectEqualStrings("λλ", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 2), pane.cur_col); - try std.testing.expectEqual(@as(i32, 0), pane.vsel.col); - - panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a")); - pane.cur_col = 0; - pane.vsel = .{ .active = true, .row = 0, .col = 3, .explicit = true }; - p.normalReplaceChar(pane, 'λ'); - try std.testing.expectEqualStrings("λλ", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); - try std.testing.expectEqual(@as(i32, 2), pane.vsel.col); -} - test "flat text movement and selection replay need no scratch rows" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); @@ -2796,31 +2739,6 @@ test "flat text movement and selection replay need no scratch rows" { try std.testing.expectEqual(@as(i32, 8), pane.cur_col); } -test "flat text replacement preserves a terminal fragment origin and direction" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 12 }); - defer p.deinit(); - p.update(.{ .output = .{ .pane = 0, .bytes = "first\r\nsecond\r\nthird\r\n界a\r\n" } }); - const pane = p.panes[0].?; - pane.mode = .normal; - pane.cur_pinned = true; - pane.cur_row = 3; - pane.cur_col = 0; - pane.vsel = .{ .active = true, .row = 3, .col = 3, .explicit = true }; - p.normalReplaceChar(pane, 'λ'); - try std.testing.expectEqual(@as(i32, 3), pane.ovl.?.row); - try std.testing.expectEqualStrings("λλ", pane.ovl.?.text); - try std.testing.expectEqual(@as(i32, 3), pane.cur_row); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); - try std.testing.expectEqual(@as(i32, 3), pane.vsel.row); - try std.testing.expectEqual(@as(i32, 2), pane.vsel.col); - try std.testing.expect(pane.vsel.active and pane.vsel.explicit); - const lines = try p.paneCursorLines(pane); - try std.testing.expectEqualStrings("first", lines[0]); - try std.testing.expectEqualStrings("λλ", lines[3]); - const flat = try p.flatSurface(pane); - try std.testing.expect(std.mem.startsWith(u8, flat, "first\nsecond\nthird\nλλ\n")); -} - test "Unicode display cells map back to body and tag byte cursors" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); @@ -3343,7 +3261,7 @@ pub const Key = struct { pub const delete: u21 = 0xF0009; }; -fn hit(key: Key, binding: []const config.Chord) bool { +pub fn hit(key: Key, binding: []const config.Chord) bool { for (binding) |c| { if (key.cp != c.cp or key.ctrl != c.ctrl or key.alt != c.alt) continue; if (c.shift and !key.shift) continue; @@ -3352,7 +3270,7 @@ fn hit(key: Key, binding: []const config.Chord) bool { return false; } -const sel_slot = @intFromEnum(config.select_button); +pub const sel_slot = @intFromEnum(config.select_button); fn isPrefix(key: Key, cp: u21) bool { return key.cp == cp and !key.ctrl and !key.alt; @@ -4777,7 +4695,7 @@ pub const Pardes = struct { in_len: usize = 0, yank: ?[]u8 = null, - clip_pending: ?ClipRequest = null, + clip_pending: ?edit.ClipRequest = null, /// the last serialized dump (gpa-owned), read by the write_dump effect dump_out: ?[]u8 = null, /// where the shell wrote the last dump (shell reports back after @@ -5031,7 +4949,7 @@ pub const Pardes = struct { } } - fn headerReplace(p: *Pardes, bytes: []const u8) void { + pub fn headerReplace(p: *Pardes, bytes: []const u8) void { const cur = p.topbar_col orelse return; const anchor = p.header_anchor orelse cur; const lo = @min(cur, anchor); @@ -5740,7 +5658,7 @@ pub const Pardes = struct { } } }, - .paste => |bytes| p.applyPaste(bytes), + .paste => |bytes| edit.applyPaste(p, bytes), .command => |line| _ = p.executeBuiltinLine(p.active, line), .pinch => |scale| p.ov_pinch_scale = scale, .touch_scroll => |delta| p.ov_touch_scroll_delta = delta, @@ -5776,97 +5694,6 @@ pub const Pardes = struct { } } - fn setYank(p: *Pardes, text: []const u8) void { - if (p.multi_on and !p.multi_first) { - const old = p.yank orelse ""; - const sep: []const u8 = if (text.len > 0 and text[text.len - 1] == '\n') "" else "\n"; - const joined = std.fmt.allocPrint(p.gpa, "{s}{s}{s}", .{ text, sep, old }) catch return; - if (p.yank) |y| p.gpa.free(y); - p.yank = joined; - return; - } - if (p.yank) |y| p.gpa.free(y); - p.yank = p.gpa.dupe(u8, text) catch null; - } - - fn setClipboard(p: *Pardes, text: []const u8) void { - p.setYank(text); - if (!p.multi_on or p.multi_first) p.emit(.{ .set_clipboard = {} }); - } - - /// Where a `SPC p` / `SPC P` / `SPC R` goes once the shell answers. - pub const ClipRequest = struct { - pane: usize, - serial: u32, - mode: enum { after, before, replace }, - }; - - pub fn clipRequest(p: *Pardes, id: usize, mode: @FieldType(ClipRequest, "mode")) void { - const pane = p.panes[id] orelse return; - p.clip_pending = .{ .pane = id, .serial = pane.serial, .mode = mode }; - p.emit(.read_clipboard); - } - - pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) void { - if (text.len == 0) return; - if (panes.Terminal.bracketedPaste(pane)) { - p.emitWrite(id, "\x1b[200~"); - p.emitWrite(id, text); - p.emitWrite(id, "\x1b[201~"); - return; - } - const cp = p.scratch.allocator().dupe(u8, text) catch return; - for (cp) |*ch| { - if (ch.* == '\n') ch.* = '\r'; - } - p.emitWrite(id, cp); - } - - fn applyPaste(p: *Pardes, bytes: []const u8) void { - if (p.topbar_col != null) { - p.clip_pending = null; - p.headerReplace(bytes); - return; - } - const req = p.clip_pending; - p.clip_pending = null; - if (bytes.len == 0) return; - const id = if (req) |r| r.pane else p.active; - const pane = p.panes[id] orelse return; - if (req) |r| if (pane.serial != r.serial) return; - p.active = id; - if (pane.tag_edit) { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - const range: @TypeOf(tagSelBounds(pane)) = if (pane.tag_sel) tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; - const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; - _ = p.replaceTagText(pane, range.lo, hi, bytes); - if (selRegexArmed(pane)) |a| p.applySelRegex(pane, a.pat, a.split); - return; - } - if (pane.isTerminal() and pane.mode == .tty) return p.typeToTty(id, pane, bytes); - switch (if (req) |r| r.mode else .after) { - .after => p.pasteText(pane, bytes, false, 1), - .before => p.pasteText(pane, bytes, true, 1), - .replace => p.replaceWithText(pane, bytes), - } - } - - pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { - if (comptime pdf_enabled) if (pane.pdf) |pv| { - if (pv.selection_text.len > 0) p.setClipboard(pv.selection_text); - return; - }; - if (pane.nsel > 0 and !main_only) { - p.replaySels(pane, .{ .normal = .{ .edit = .{ .kind = .yank, .count = 1 } } }); - } else { - const others = pane.nsel; - pane.nsel = 0; - p.normalYank(pane); - pane.nsel = others; - } - p.emit(.{ .set_clipboard = {} }); - } - fn multiOnce(p: *Pardes) bool { if (!p.multi_on) return true; p.multi_stop = true; @@ -6004,7 +5831,7 @@ pub const Pardes = struct { pane.nsel_snap = 0; // ...and its s/S preview keeps whatever it previewed } - fn tagSelBounds(pane: *Pane) struct { lo: usize, hi: usize } { + pub fn tagSelBounds(pane: *Pane) struct { lo: usize, hi: usize } { const a: usize = pane.tag_anchor; const c: usize = pane.tag_col; return .{ .lo = @min(a, c), .hi = @max(a, c) }; @@ -6060,7 +5887,7 @@ pub const Pardes = struct { /// Replace one range in the rendered tag. The file name and command tail /// retain separate identities even when a selection crosses their boundary. - fn replaceTagText(p: *Pardes, pane: *Pane, start: usize, finish: usize, input: []const u8) bool { + pub fn replaceTagText(p: *Pardes, pane: *Pane, start: usize, finish: usize, input: []const u8) bool { const prefix_len = (p.tagPrefix(pane) catch return false).len; const end = prefix_len + pane.tag_tail_len; const lo = @min(start, end); @@ -6183,7 +6010,7 @@ pub const Pardes = struct { return; } if (hit(key, config.tag_yank)) { - if (p.tagChordText(pane)) |txt| p.setClipboard(txt); + if (p.tagChordText(pane)) |txt| edit.setClipboard(p, txt); return; } if (hit(key, config.insert) or hit(key, config.append) or @@ -6314,7 +6141,7 @@ pub const Pardes = struct { if (key.ctrl and (key.cp == 'c' or key.cp == 'x')) { const anchor = p.header_anchor orelse @as(u16, @intCast(cur)); if (anchor != cur) { - p.setClipboard(bar[@min(anchor, cur)..@max(anchor, cur)]); + edit.setClipboard(p, bar[@min(anchor, cur)..@max(anchor, cur)]); if (key.cp == 'x') p.headerReplace(""); } return; @@ -6388,140 +6215,6 @@ pub const Pardes = struct { if (col) |c| p.topbar_col = @intCast(@min(c, modal.prevGrapheme(bar, bar.len))); } - /// tag + '\n' + body: the full selectable pane text (row 0 = the tag) - fn paneText(p: *Pardes, pane: *Pane) ![]u8 { - const arena = p.scratch.allocator(); - return std.fmt.allocPrint(arena, "{s}\n{s}", .{ try p.tagText(arena, pane), try body_layer.bodyText(p, arena, pane) }); - } - - pub fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i32) []const u8 { - if (row < 0) return ""; - if (pane.file != null) return panes.File.sourceLine(pane, row); - const index: usize = @intCast(row); - return if (index < terminal_lines.len) terminal_lines[index] else ""; - } - - fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { - var gesture = pane.sel[slot]; - if (pane.hasPdf()) return; - if (gesture.state != .done or @min(gesture.r0, gesture.r1) < BOX_H) return; - if (pane.pointerSelection(gesture) != null) return; - pane.clearPointerSelection(slot); - // Refresh the source map before translating the rendered rectangle. - const raw = pane.isTerminal() and pane.mode == .tty; - const body = try body_layer.bodyText(p, p.scratch.allocator(), pane); - const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{}; - const first = @max(0, @min(gesture.r0, gesture.r1) - BOX_H); - const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; - const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - BOX_H); - if (first > last) return; - const rows = try p.gpa.alloc(Pane.PointerRow, @intCast(last - first + 1)); - errdefer p.gpa.free(rows); - const raw_text = if (raw) try p.gpa.dupe(u8, try p.selectionText(pane, gesture)) else null; - const prefix: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; - const left = @max(0, @min(gesture.c0, gesture.c1)); - const right = @max(0, @max(gesture.c0, gesture.c1)); - for (rows, 0..) |*row, index| { - const visible = first + @as(i32, @intCast(index)); - var source = pane.wrapAt(visible); - if (raw) source = .{ .line = panes.Terminal.gridOffset(pane) + visible, .at = 0 }; - const line = if (raw) modal.lineSlice(body, @intCast(visible)) else pointerSourceLine(pane, terminal_lines, source.line); - var next = pane.wrapAt(visible + 1); - if (raw) next = .{ .line = source.line + 1, .at = 0 }; - const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; - const start: usize = @intCast(@max(0, source.at)); - const lo = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix)))); - const at = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix)))); - row.* = .{ - .row = source.line, - .lo = lo, - .hi = if (right < prefix) lo else @min(end, modal.nextGrapheme(line, at)), - .raw_terminal = raw, - .prompt_bytes = if (raw) panes.Terminal.promptPrefixBytes(pane, source.line, line) else 0, - }; - const rendered = modal.lineSlice(body, @intCast(visible)); - const prefix_end = @min(rendered.len, @as(usize, @intCast(@min(prefix, right + 1)))); - const prefix_start = @min(prefix_end, @as(usize, @intCast(left))); - row.prefix_len = @intCast(prefix_end - prefix_start); - @memcpy(row.prefix[0..row.prefix_len], rendered[prefix_start..prefix_end]); - } - pane.next_pointer_selection += 1; - gesture.source_id = pane.next_pointer_selection; - pane.sel[slot] = gesture; - pane.pointer_selections[slot] = .{ .gesture = gesture, .rows = rows, .raw_text = raw_text }; - } - - /// block-selected text, newline-joined per row; reads the rendered screen - /// so typed text and shell output select identically. Scratch-owned. - fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { - const arena = p.scratch.allocator(); - if (pane.rawPointerText(sl)) |text| return arena.dupe(u8, text); - if (pane.pointerSelection(sl)) |rows| { - const terminal_lines = if (pane.file == null) try panes.Terminal.cursorLines(p, pane) else &.{}; - var total: usize = rows.len -| 1; - for (rows) |row| { - const line = pointerSourceLine(pane, terminal_lines, row.row); - total += row.prefix_len + @min(row.hi, line.len) - @min(row.lo, line.len); - } - const result = try arena.alloc(u8, total); - var at: usize = 0; - for (rows, 0..) |row, index| { - if (index > 0) { - result[at] = '\n'; - at += 1; - } - @memcpy(result[at..][0..row.prefix_len], row.prefix[0..row.prefix_len]); - at += row.prefix_len; - const line = pointerSourceLine(pane, terminal_lines, row.row); - const bytes = line[@min(row.lo, line.len)..@min(row.hi, line.len)]; - @memcpy(result[at..][0..bytes.len], bytes); - at += bytes.len; - } - return result; - } - const r0 = @min(sl.r0, sl.r1); - const r1 = @max(sl.r0, sl.r1); - const c0: usize = @intCast(@max(0, @min(sl.c0, sl.c1))); - const c1: usize = @intCast(@max(0, @max(sl.c0, sl.c1))); - const text = try p.paneText(pane); - var total: usize = 0; - var selected: usize = 0; - var count_it = std.mem.splitAny(u8, text, "\n"); - var count_row: i32 = 0; - while (count_it.next()) |line| : (count_row += 1) { - if (count_row < r0 or count_row > r1) continue; - const b0 = @min(panes.File.renderedLineByteCol(pane, count_row, line, c0), line.len); - const b1 = modal.nextGrapheme(line, @min(panes.File.renderedLineByteCol(pane, count_row, line, c1), line.len)); - total += b1 - b0 + @intFromBool(selected > 0); - selected += 1; - } - const out = try arena.alloc(u8, total); - var at: usize = 0; - var it = std.mem.splitAny(u8, text, "\n"); - var v: i32 = 0; - var first = true; - while (it.next()) |line| : (v += 1) { - if (v < r0 or v > r1) continue; - if (!first) { - out[at] = '\n'; - at += 1; - } - first = false; - const b0 = @min(panes.File.renderedLineByteCol(pane, v, line, c0), line.len); - const b1 = modal.nextGrapheme(line, @min(panes.File.renderedLineByteCol(pane, v, line, c1), line.len)); - @memcpy(out[at..][0 .. b1 - b0], line[b0..b1]); - at += b1 - b0; - } - return out; - } - - fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool { - const fwd = ar < br or (ar == br and ac <= bc); - const sr, const sc = if (fwd) .{ ar, ac } else .{ br, bc }; - const er, const ec = if (fwd) .{ br, bc } else .{ ar, ac }; - return (r > sr or (r == sr and c >= sc)) and (r < er or (r == er and c <= ec)); - } - const ExpandedWord = struct { lo: usize, hi: usize }; fn expandedWord(line: []const u8, col: usize) ?ExpandedWord { @@ -6538,7 +6231,7 @@ pub const Pardes = struct { fn expandedSel(p: *Pardes, pane: *Pane, at: Pane.Sel) ?Pane.Sel { var sl = at; if (sl.c0 != sl.c1 or sl.r0 != sl.r1) return sl; - const text = p.paneText(pane) catch return null; + const text = edit.paneText(p, pane) catch return null; var it = std.mem.splitAny(u8, text, "\n"); var v: i32 = 0; while (it.next()) |line| : (v += 1) { @@ -6561,7 +6254,7 @@ pub const Pardes = struct { const vcol = if (pane.file != null) panes.File.displayOffset(pane, pane.cur_row, w.at, pane.cur_col) + @as(i32, panes.File.gutterWidth(pane)) else blk: { - const lines = p.paneCursorLines(pane) catch break :blk pane.cur_col; + const lines = edit.paneCursorLines(p, pane) catch break :blk pane.cur_col; const local = pane.cur_row; if (local < 0 or @as(usize, @intCast(local)) >= lines.len) break :blk pane.cur_col; break :blk panes.File.lineDisplayOffset(lines[@intCast(local)], @intCast(@max(0, w.at)), @intCast(@max(0, pane.cur_col))); @@ -6569,18 +6262,9 @@ pub const Pardes = struct { return .{ .state = .done, .c0 = vcol, .c1 = vcol, .r0 = vrow, .r1 = vrow }; } - /// the active modal selection as text (v range or x lines), if any - fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 { - if (comptime pdf_enabled) if (p.native_images) if (pane.pdf) |pv| - if (pv.selection != null and pv.selection_text.len > 0) return pv.selection_text; - if (pane.vsel.active) return p.vselText(pane); - if (!pane.msel.active) return null; - return p.yankRows(pane, @min(pane.msel.r0, pane.msel.r1), @max(pane.msel.r0, pane.msel.r1)); - } - fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool { if (pane.nsel == 0) return false; - const text = p.flatSurface(pane) catch return false; + const text = edit.flatSurface(p, pane) catch return false; var ranges: [Pane.max_selections]modal.Selection = undefined; const got = pane.ranges(text, 0, &ranges); if (got.n < 2) return false; @@ -6643,7 +6327,8 @@ pub const Pardes = struct { const col = if (raw) @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) else if (clicked.r0 >= BOX_H) - p.paneByteAtDisplay( + edit.paneByteAtDisplay( + p, pane, wrapped.line, wrapped.at, @@ -6677,22 +6362,22 @@ pub const Pardes = struct { break :inside true; } break :inside false; - } else spanHas(clicked.r0, clicked.c0, kept.r0, kept.c0, kept.r1, kept.c1); + } else edit.spanHas(clicked.r0, clicked.c0, kept.r0, kept.c0, kept.r1, kept.c1); if (kept.state == .done and inside_kept) { - result.text = p.selectionText(pane, kept) catch null; + result.text = edit.selectionText(p, pane, kept) catch null; result.preview = kept; return result; } if (pane.vsel.active and pane.vsel.explicit and - spanHas(row, col, pane.vsel.row, pane.vsel.col, pane.cur_row, pane.cur_col)) + edit.spanHas(row, col, pane.vsel.row, pane.vsel.col, pane.cur_row, pane.cur_col)) { - result.text = p.currentSelText(pane); + result.text = edit.currentSelText(p, pane); return result; } if (pane.msel.active and row >= @min(pane.msel.r0, pane.msel.r1) and row <= @max(pane.msel.r0, pane.msel.r1)) { - result.text = p.currentSelText(pane); + result.text = edit.currentSelText(p, pane); return result; } if (pane.file != null and clicked.r0 >= BOX_H and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1) { @@ -6719,7 +6404,7 @@ pub const Pardes = struct { } const expanded = p.expandedSel(pane, clicked) orelse return result; - result.text = p.selectionText(pane, expanded) catch null; + result.text = edit.selectionText(p, pane, expanded) catch null; if (result.text == null or result.text.?.len == 0) return result; result.preview = expanded; result.expanded = expanded; @@ -6741,9 +6426,9 @@ pub const Pardes = struct { return pv.selection_text; }; if (t.sel[sel_slot].state == .done) { - if (p.selectionText(t, t.sel[sel_slot]) catch null) |tx| return tx; + if (edit.selectionText(p, t, t.sel[sel_slot]) catch null) |tx| return tx; } else if ((t.vsel.active and t.vsel.explicit) or t.msel.active) { - if (p.currentSelText(t)) |tx| return tx; + if (edit.currentSelText(p, t)) |tx| return tx; } } return null; @@ -6770,42 +6455,14 @@ pub const Pardes = struct { pane.mode = .normal; pane.normal.clear(); }, - .normal => p.enterInsert(pane, .at, 1), + .normal => edit.enterInsert(p, pane, .at, 1), .insert => { - p.exitInsert(pane); + edit.exitInsert(p, pane); if (pane.isTerminal()) panes.Terminal.enterTty(p, id); }, } } - fn exitInsert(p: *Pardes, pane: *Pane) void { - pane.mode = .normal; - pane.msel.active = false; - pane.normal.clear(); - if (pane.append_at) |aa| { - pane.append_at = null; - const text = p.flatSurface(pane) catch return; - const gap = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }); - const a_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, aa.row)), .col = @intCast(@max(0, aa.col)) }); - const back = @max(a_off, modal.prevGrapheme(text, gap)); - const bc = modal.positionAt(text, back); - pane.cur_row = @intCast(bc.row); - pane.cur_col = @intCast(bc.col); - pane.vsel = .{ .active = a_off != back, .row = aa.row, .col = aa.col, .explicit = false }; - pane.cur_pinned = true; - pane.ensureCursorVisible(); - for (pane.sels[0..pane.nsel]) |*s| { - const sgap = modal.offsetAt(text, .{ .row = @intCast(@max(0, s.row)), .col = @intCast(@max(0, s.col)) }); - const b2 = if (back == gap) sgap else modal.prevGrapheme(text, sgap); - const bp = modal.positionAt(text, b2); - s.row = @intCast(bp.row); - s.col = @intCast(bp.col); - s.arow = s.row; - s.acol = s.col; - } - } - } - /// One mode transition for the terminal tag command and the Ctrl-B chord. pub fn toggleTty(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; @@ -6851,12 +6508,12 @@ pub const Pardes = struct { // account instead — a coding agent goes there hunting for an image. // A host that folds Shift into the letter says the same thing. if (key.ctrl and !key.alt and (key.cp == 'v' or key.cp == 'V')) { - if (key.shift or key.cp == 'V') return p.clipRequest(p.active, .after); + if (key.shift or key.cp == 'V') return edit.clipRequest(p, p.active, .after); // With something in the register this is a paste. With nothing // in it the chord is the program's -- vim's visual block, // readline's quoted-insert -- and swallowing it would make // Ctrl-V a black hole in every full-screen application. - if (p.yank) |text| return p.typeToTty(p.active, pane, text); + if (p.yank) |text| return edit.typeToTty(p, p.active, pane, text); } return panes.Terminal.forwardKey(p, p.active, key); } @@ -6935,12 +6592,12 @@ pub const Pardes = struct { } if (pane.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd; - p.pinPaneCursor(pane); + edit.pinPaneCursor(p, pane); const explicit = (p.native_images and pane.hasPdfSelection()) or (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; if (explicit) { if (p.chordEachSel(pane, cmd)) return; - if (p.currentSelText(pane)) |txt| { + if (edit.currentSelText(p, pane)) |txt| { pane.vsel.active = false; pane.msel.active = false; pane.select = false; @@ -6949,7 +6606,7 @@ pub const Pardes = struct { } } const sel = p.expandedSel(pane, p.cursorWordSel(pane)) orelse return; - const word = p.selectionText(pane, sel) catch return; + const word = edit.selectionText(p, pane, sel) catch return; p.runBuiltin(cmd, p.active, "", word); return; } @@ -6959,8 +6616,8 @@ pub const Pardes = struct { p.handleNormal(pane, key); }, .insert => { - if (hit(key, config.escape)) return p.exitInsert(pane); - p.handleInsert(pane, key); + if (hit(key, config.escape)) return edit.exitInsert(p, pane); + edit.handleInsert(p, pane, key); }, .tty => panes.Terminal.forwardKey(p, p.active, key), } @@ -6994,51 +6651,8 @@ pub const Pardes = struct { // ---- helix-modal normal mode ---- - pub fn paneCursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { - const arena = p.scratch.allocator(); - if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); - if (pane.hasPdf()) { - if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); - unreachable; - } - return panes.Terminal.cursorLines(p, pane); - } - - fn paneByteAtDisplay(p: *Pardes, pane: *Pane, row: i32, from_raw: i32, display_col: i32) i32 { - if (pane.file != null) - return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col); - const lines = p.paneCursorLines(pane) catch return @max(0, from_raw + display_col); - const local = row; - if (local < 0 or @as(usize, @intCast(local)) >= lines.len) - return @max(0, from_raw + display_col); - return @intCast(panes.File.byteAtDisplayFrom( - lines[@intCast(local)], - @intCast(@max(0, from_raw)), - @intCast(@max(0, display_col)), - )); - } - - /// Freeze the live terminal cursor into the modal coordinate space. The - /// emulator reports screen cells; editing state stores UTF-8 byte offsets. - fn pinPaneCursor(p: *Pardes, pane: *Pane) void { - if (pane.cur_pinned) return; - pane.pinCursor(); - if (pane.file == null and !pane.hasPdf()) - pane.cur_col = p.paneByteAtDisplay(pane, pane.cur_row, 0, pane.cur_col); - } - - fn flatSurface(p: *Pardes, pane: *Pane) ![]const u8 { - if (pane.file) |f| return f.content; - if (pane.hasPdf()) { - if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa); - unreachable; - } - const lines = try panes.Terminal.cursorLines(p, pane); - return panes.Terminal.flatSurface(p, pane, lines); - } - fn startSelRegex(p: *Pardes, pane: *Pane, split: bool) void { - const text = p.flatSurface(pane) catch return; + const text = edit.flatSurface(p, pane) catch return; const got = pane.ranges(text, 0, &pane.sel_snap); pane.nsel_snap = @intCast(got.n); pane.sel_snap_pri = @intCast(got.pri); @@ -7060,8 +6674,8 @@ pub const Pardes = struct { return .{ .pat = armed[slash + 1 ..], .split = split }; } - fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void { - const text = p.flatSurface(pane) catch return; + pub fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void { + const text = edit.flatSurface(p, pane) catch return; const snap = pane.sel_snap[0..pane.nsel_snap]; var out: [Pane.max_selections]modal.Selection = undefined; var m: usize = 0; @@ -7147,7 +6761,7 @@ pub const Pardes = struct { insert: Key, }; - fn replaySels(p: *Pardes, pane: *Pane, what: Replay) void { + pub fn replaySels(p: *Pardes, pane: *Pane, what: Replay) void { const id = p.active; const serial = pane.serial; // the whole selection in pane coordinates, document order. pane.sels @@ -7210,14 +6824,14 @@ pub const Pardes = struct { pane.sticky_col = list[i].sticky; switch (what) { .normal => |normal_action| p.executeNormalAction(pane, normal_action), - .insert => |insert_key| p.insertKey(pane, insert_key), + .insert => |insert_key| edit.insertKey(p, pane, insert_key), } if (p.multi_stop) break; if (i == pri) { after = KeyState.of(pane); after_expl = pane.vsel.explicit; } - const text = p.flatSurface(pane) catch { + const text = edit.flatSurface(p, pane) catch { p.multi_stop = true; break; }; @@ -7236,7 +6850,7 @@ pub const Pardes = struct { if (pn.serial == serial) pn.nsel = 0; return; } - const text = p.flatSurface(pane) catch return; + const text = edit.flatSurface(p, pane) catch return; var rs: [Pane.max_selections]modal.Selection = undefined; var st: [Pane.max_selections]i32 = undefined; for (res[0..n], 0..) |r, k| { @@ -7248,11 +6862,6 @@ pub const Pardes = struct { pane.ensureCursorVisible(); // the view follows the PRIMARY, not the last pass } - fn paneWrapWidth(p: *const Pardes, pane: *const Pane) usize { - if (pane.file == null) return 0; - return panes.File.wrapWidth(pane, p.settings.wrap); - } - fn handleNormal(p: *Pardes, pane: *Pane, key: Key) void { const parsed = modal.Normal.parse(&pane.normal, normalInput(key)); const semantic = switch (parsed) { @@ -7271,9 +6880,9 @@ pub const Pardes = struct { pane.clearPointerSelection(sel_slot); pane.sel[sel_slot].state = .none; }; - if (raw_selection and semantic == .edit and semantic.edit.kind == .yank) return p.normalYank(pane); - p.pinPaneCursor(pane); - const text = p.flatSurface(pane) catch return; + if (raw_selection and semantic == .edit and semantic.edit.kind == .yank) return edit.normalYank(p, pane); + edit.pinPaneCursor(p, pane); + const text = edit.flatSurface(p, pane) catch return; const range = pane.primaryRange(text, 0); const cur = modal.selectionCursor(text, range); @@ -7302,8 +6911,8 @@ pub const Pardes = struct { if (nw == slice.len) return; return pane.pointMove(text, range, ls + nw); }, - .line_down => return pane.visualMove(text, range, true, go.count, p.paneWrapWidth(pane)), - .line_up => return pane.visualMove(text, range, false, go.count, p.paneWrapWidth(pane)), + .line_down => return pane.visualMove(text, range, true, go.count, edit.paneWrapWidth(p, pane)), + .line_up => return pane.visualMove(text, range, false, go.count, edit.paneWrapWidth(p, pane)), .column => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); @@ -7348,21 +6957,21 @@ pub const Pardes = struct { find.count, ); }, - .replace_char => |char| return p.normalReplaceChar(pane, char), + .replace_char => |char| return edit.normalReplaceChar(p, pane, char), .match_bracket => { - const lines = p.paneCursorLines(pane) catch return; + const lines = edit.paneCursorLines(p, pane) catch return; const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; return pane.pointMove(text, range, modal.offsetAt(text, mc)); }, - .textobject => |object| return p.textobjectSelect(pane, text, object.char, object.around), - .surround_add => |char| return p.surroundAdd(pane, char), - .surround_delete => |char| return p.surroundDelete(pane, char), - .surround_replace => |replace| return p.surroundReplace(pane, replace.from, replace.to), + .textobject => |object| return edit.textobjectSelect(p, pane, text, object.char, object.around), + .surround_add => |char| return edit.surroundAdd(p, pane, char), + .surround_delete => |char| return edit.surroundDelete(p, pane, char), + .surround_replace => |replace| return edit.surroundReplace(p, pane, replace.from, replace.to), .paragraph => |paragraph| { const r2 = modal.moveParagraph(text, range, paragraph.count, paragraph.direction == .forward, pane.select); return pane.setRange(text, 0, r2, false); }, - .add_newline => |newline| return p.addNewline(pane, newline.direction == .forward, newline.count), + .add_newline => |newline| return edit.addNewline(p, pane, newline.direction == .forward, newline.count), .diagnostic => |diagnostic| { const fwd = diagnostic.direction == .forward; if (!diagnostic.endpoint) { @@ -7450,7 +7059,7 @@ pub const Pardes = struct { .up => return pane.scrollViewMove(text, range, -@as(i32, pane.rows)), }, .insert => |insert| { - const where: InsertAt = switch (insert.kind) { + const where: edit.InsertAt = switch (insert.kind) { .at => .at, .append => .append, .line_start => .line_start, @@ -7458,7 +7067,7 @@ pub const Pardes = struct { .open_below => .open_below, .open_above => .open_above, }; - return p.enterInsert(pane, where, insert.count); + return edit.enterInsert(p, pane, where, insert.count); }, .select => |select| switch (select.kind) { .mode => { @@ -7494,23 +7103,23 @@ pub const Pardes = struct { return pane.multiSelAction(text, multi.kind, multi.count); }, .select_regex => |split| return p.startSelRegex(pane, split), - .edit => |edit| switch (edit.kind) { - .delete => return p.normalDelete(pane, true), - .delete_noyank => return p.normalDelete(pane, false), - .change => return p.normalChange(pane), - .yank => return p.normalYank(pane), - .replace_with_yank => return p.normalReplaceYank(pane), - .paste_after => return p.pasteText(pane, p.yank orelse return, false, edit.count), - .paste_before => return p.pasteText(pane, p.yank orelse return, true, edit.count), - .switch_case => return p.normalCase(pane, .toggle), - .lowercase => return p.normalCase(pane, .lower), - .uppercase => return p.normalCase(pane, .upper), - .join_lines => return p.normalJoin(pane), - .indent => return p.normalIndent(pane, edit.count, true), - .unindent => return p.normalIndent(pane, edit.count, false), - .comment_toggle => return p.normalToggleComment(pane), - .undo => return p.doUndo(pane), - .redo => return p.doRedo(pane), + .edit => |op| switch (op.kind) { + .delete => return edit.normalDelete(p, pane, true), + .delete_noyank => return edit.normalDelete(p, pane, false), + .change => return edit.normalChange(p, pane), + .yank => return edit.normalYank(p, pane), + .replace_with_yank => return edit.normalReplaceYank(p, pane), + .paste_after => return edit.pasteText(p, pane, p.yank orelse return, false, op.count), + .paste_before => return edit.pasteText(p, pane, p.yank orelse return, true, op.count), + .switch_case => return edit.normalCase(p, pane, .toggle), + .lowercase => return edit.normalCase(p, pane, .lower), + .uppercase => return edit.normalCase(p, pane, .upper), + .join_lines => return edit.normalJoin(p, pane), + .indent => return edit.normalIndent(p, pane, op.count, true), + .unindent => return edit.normalIndent(p, pane, op.count, false), + .comment_toggle => return edit.normalToggleComment(p, pane), + .undo => return edit.doUndo(p, pane), + .redo => return edit.doRedo(p, pane), }, .lsp => |request| return p.lspRequest(p.active, switch (request) { .definition => .definition, @@ -7520,7 +7129,7 @@ pub const Pardes = struct { .references => .references, .format => .format, }, ""), - .adjust_number => |delta| return p.normalAdjustNumber(pane, delta), + .adjust_number => |delta| return edit.normalAdjustNumber(p, pane, delta), .leader => { p.leader_on = true; p.leader_n = 0; @@ -7693,7 +7302,7 @@ pub const Pardes = struct { p.active = rid; p.lookWalk(1); if (p.active != rid) return; // walked out of the list; leave it there - const txt = p.currentSelText(rp) orelse return; + const txt = edit.currentSelText(p, rp) orelse return; // spent, exactly as the look chord spends it (handleKey) rp.vsel.active = false; rp.msel.active = false; @@ -7756,7 +7365,7 @@ pub const Pardes = struct { anchor = found.anchor; } } else { - const lines = try p.paneCursorLines(pane); + const lines = try edit.paneCursorLines(p, pane); // a real file names itself; a terminal or an output buffer has no path const has_path = if (pane.file) |f| f.output == null else false; var idbuf: [16]u8 = undefined; @@ -8012,7 +7621,7 @@ pub const Pardes = struct { } @memcpy(replacement[write_at..], f.content[read_at..]); - p.pushUndo(pane); + edit.pushUndo(p, pane); panes.File.setContent(p, f, replacement); const cursor = modal.positionAt(f.content, mapped_cursor); pane.cur_row = @intCast(cursor.row); @@ -8050,7 +7659,7 @@ pub const Pardes = struct { } if (rows.len == 0) { if (w.kind == .completion and pane.mode == .insert and pane.nsel == 0 and - pane.cur_row == w.row and pane.cur_col == w.col) p.insertTab(pane); + pane.cur_row == w.row and pane.cur_col == w.col) edit.insertTab(p, pane); return; } @@ -8143,7 +7752,7 @@ pub const Pardes = struct { } fn lookSpanIn(p: *Pardes, pane: *Pane, from: LookFrom, delta: i32, budget: *usize) ?Pane.LookSpot { - const lines = p.paneCursorLines(pane) catch return null; + const lines = edit.paneCursorLines(p, pane) catch return null; const nrows: i32 = @intCast(lines.len); if (nrows == 0) return null; const grain: panes.Output.Grain = if (pane.file) |*f| panes.Output.grain(f.output) else .word; @@ -8219,7 +7828,7 @@ pub const Pardes = struct { } fn landLookSpot(p: *Pardes, id: usize, pane: *Pane, spot: Pane.LookSpot) void { - p.pinPaneCursor(pane); // fresh out of tty mode the cursor still tracks the shell + edit.pinPaneCursor(p, pane); // fresh out of tty mode the cursor still tracks the shell pane.vsel = .{ .active = true, .row = spot.row, .col = spot.col1, .explicit = true }; pane.msel.active = false; pane.nsel = 0; @@ -8232,1190 +7841,10 @@ pub const Pardes = struct { pane.ensureCursorVisible(); } - /// Route shared edit operations to a file's content or a terminal overlay. - fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?panes.EditText { - if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; - if (pane.image != null or pane.hasPdf()) return null; - return panes.Terminal.editText(p, pane, lo, hi, col); - } - - fn editTextEol(p: *Pardes, pane: *Pane, b: Bounds) ?panes.EditText { - const eb = p.editText(pane, b.lo_row, b.hi_row, -1) orelse return null; - const r: usize = @intCast(@max(0, b.hi_row - eb.row0)); - if (r + 1 < modal.lineCount(eb.text)) return eb; - if (b.hi_col < @as(i32, @intCast(modal.lineSlice(eb.text, r).len))) return eb; - return p.editText(pane, b.lo_row, b.hi_row + 1, -1); - } - - /// install a rewritten editable text (frees the old one) - fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { - if (pane.file) |*f| return panes.File.setContent(p, f, new); - panes.Terminal.setEditText(p, pane, new); - } - - const InsertAt = enum { at, append, line_start, line_end, open_below, open_above }; - - /// Files insert only inside existing rows and at grapheme boundaries. - /// Terminal overlays can materialize virtual rows/columns, so keep those. - fn clampFileCursor(pane: *Pane) bool { - const file = if (pane.file) |*file| file else return false; - const old_row = pane.cur_row; - const old_col = pane.cur_col; - const last = panes.File.nlines(pane.gpa, file) -| 1; - pane.cur_row = @intCast(@min(last, @as(usize, @intCast(@max(0, pane.cur_row))))); - const line = panes.File.sourceLine(pane, pane.cur_row); - pane.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, pane.cur_col)))))); - return old_row != pane.cur_row or old_col != pane.cur_col; - } - - fn enterInsert(p: *Pardes, pane: *Pane, where: InsertAt, cnt: usize) void { - if (pane.hasPdf()) return; - p.pinPaneCursor(pane); - _ = clampFileCursor(pane); - // snapshot once per insert session (WITH the pre-insert selection) so - // `u` undoes the whole session and restores what was selected - p.pushUndo(pane); - pane.select = false; - pane.append_at = null; - pane.sticky_col = -1; - const text = p.flatSurface(pane) catch { - pane.mode = .insert; - pane.msel.active = false; - pane.vsel.active = false; - pane.normal.clear(); - return; - }; - const cur = pane.toModalCursor(); - const line = panes.File.textLine(pane, text, cur.row); - const b: ?Bounds = if (pane.vsel.active) vselBounds(pane) else null; - switch (where) { - .at => { - if (b) |bb| { - pane.cur_row = bb.lo_row; - pane.cur_col = bb.lo_col; - pane.vsel = .{ .active = true, .row = bb.hi_row, .col = bb.hi_col, .explicit = false }; - pane.cur_pinned = true; - } - }, - .append => { - const lo_row = if (b) |bb| bb.lo_row else pane.cur_row; - const lo_col = if (b) |bb| bb.lo_col else pane.cur_col; - const hi_row = if (b) |bb| bb.hi_row else pane.cur_row; - const hi_col = if (b) |bb| bb.hi_col else pane.cur_col; - pane.append_at = .{ .row = lo_row, .col = lo_col }; - const gap = modal.nextGrapheme(text, modal.offsetAt(text, .{ .row = @intCast(@max(0, hi_row)), .col = @intCast(@max(0, hi_col)) })); - const gc = modal.positionAt(text, gap); - pane.cur_row = @intCast(gc.row); - pane.cur_col = @intCast(gc.col); - pane.vsel = .{ .active = b != null, .row = lo_row, .col = lo_col, .explicit = false }; - pane.cur_pinned = true; - }, - .line_start => { - pane.fromModalCursor(.{ .row = cur.row, .col = modal.firstNonWs(line) }); - pane.vsel.active = false; - }, - .line_end => { - pane.cur_col = @intCast(line.len); - pane.cur_pinned = true; - pane.vsel.active = false; - }, - .open_below, .open_above => { - pane.vsel.active = false; - const below = where == .open_below; - const abs: i32 = if (b) |bb| (if (below) bb.hi_row else bb.lo_row) else pane.cur_row; - const eb = p.editText(pane, abs, abs, -1) orelse return; - const row: usize = @intCast(@max(0, abs - eb.row0)); - const ind = modal.indentText(modal.lineSlice(eb.text, row)); - const arena = p.scratch.allocator(); - const block_len = std.math.mul(usize, cnt, ind.len + 1) catch return; - const block = arena.alloc(u8, block_len) catch return; - var block_at: usize = 0; - for (0..cnt) |_| { - if (below) { - block[block_at] = '\n'; - block_at += 1; - } - @memcpy(block[block_at..][0..ind.len], ind); - block_at += ind.len; - if (!below) { - block[block_at] = '\n'; - block_at += 1; - } - } - const at: modal.Cursor = if (below) - .{ .row = row, .col = modal.lineSlice(eb.text, row).len } - else - .{ .row = row, .col = 0 }; - const new = modal.insertAt(p.gpa, eb.text, at, block) catch return; - p.setEditText(pane, new); - pane.cur_row = @as(i32, @intCast(if (below) row + 1 else row)) + eb.row0; - pane.cur_col = @intCast(ind.len); - pane.cur_pinned = true; - if (cnt > 1 and !p.multi_on) opened: { - const t2 = p.flatSurface(pane) catch break :opened; - var rs: [Pane.max_selections]modal.Selection = undefined; - const m = @min(cnt, Pane.max_selections); - for (0..m) |k| { - const o = modal.offsetAt(t2, .{ .row = @intCast(@max(0, pane.cur_row) + @as(i32, @intCast(k))), .col = ind.len }); - rs[k] = .{ .anchor = o, .head = o }; - } - pane.setRanges(t2, rs[0..m], &.{}, 0, false); - } - }, - } - pane.mode = .insert; - pane.msel.active = false; - pane.normal.clear(); - pane.ensureCursorVisible(); - } - - fn handleInsert(p: *Pardes, pane: *Pane, key: Key) void { - if (pane.nsel == 0) return p.insertKey(pane, key); - p.replaySels(pane, .{ .insert = key }); - } - - fn insertKey(p: *Pardes, pane: *Pane, key: Key) void { - // helix aliases: normalize to the base key and re-dispatch - if (hit(key, config.insert_backspace_alias)) return p.insertKey(pane, .{ .cp = Key.backspace }); - if (hit(key, config.insert_enter_alias)) return p.insertKey(pane, .{ .cp = Key.enter }); - if (hit(key, config.insert_delete_alias)) return p.insertKey(pane, .{ .cp = Key.delete }); - pane.vsel.active = false; - if (!pane.cur_pinned) p.pinPaneCursor(pane); - _ = clampFileCursor(pane); - switch (key.cp) { - Key.left, Key.right, Key.up, Key.down => { - const lines = p.paneCursorLines(pane) catch return; - const cur0 = pane.toModalCursor(); - const nc = switch (key.cp) { - Key.left => modal.charLeft(lines, cur0), - Key.right => modal.charRight(lines, cur0), - Key.up => Pane.insertVerticalCursor(lines, cur0, false), - Key.down => Pane.insertVerticalCursor(lines, cur0, true), - else => cur0, - }; - pane.fromModalCursor(nc); - pane.ensureCursorVisible(); - return; - }, - Key.page_up, Key.page_down => { - // helix binds insert pageup/pagedown to the same view - // scroll + cursor snap as normal mode - const flat = p.flatSurface(pane) catch return; - const range = pane.primaryRange(flat, 0); - const step: i32 = @intCast(@max(1, pane.rows)); - pane.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step); - return; - }, - Key.home => { - pane.cur_col = 0; - pane.cur_pinned = true; - pane.ensureCursorVisible(); - return; - }, - Key.end => { - // helix insert End: past the last char (goto_line_end_newline) - const text = p.flatSurface(pane) catch return; - const cur0 = pane.toModalCursor(); - pane.cur_col = @intCast(panes.File.textLine(pane, text, cur0.row).len); - pane.cur_pinned = true; - pane.ensureCursorVisible(); - return; - }, - else => {}, - } - const eb = p.editText(pane, pane.cur_row, pane.cur_row, pane.cur_col) orelse return; - const text = eb.text; - const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; - if (key.text.len > 0 and !key.ctrl and !key.alt) { - const new = modal.insertAt(p.gpa, text, c, key.text) catch return; - p.setEditText(pane, new); - for (key.text) |ch| { - if (ch == '\n') { - pane.cur_row += 1; - pane.cur_col = 0; - } else pane.cur_col += 1; - } - pane.cur_pinned = true; - pane.ensureCursorVisible(); - return; - } - // helix insert-mode kills (word/line; deleteSpan is exclusive) - if (hit(key, config.delete_word_backward)) { - const e2 = if (c.row == 0 and c.col == 0) - (p.editText(pane, pane.cur_row - 1, pane.cur_row, 0) orelse return) - else - eb; - const c2 = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - e2.row0)), .col = c.col }; - const g = modal.offsetAt(e2.text, c2); - if (g == 0) return; - const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .prev_word_start); - const from = @min(wr.anchor, wr.head); - const fc = modal.positionAt(e2.text, from); - const new = modal.deleteSpan(p.gpa, e2.text, fc, c2) catch return; - p.setEditText(pane, new); - pane.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; - pane.cur_col = @intCast(fc.col); - pane.cur_pinned = true; - pane.ensureCursorVisible(); - return; - } - if (hit(key, config.delete_word_forward)) { - const e2 = if (c.col >= modal.lineSlice(text, c.row).len and c.row + 1 >= modal.lineCount(text)) - (p.editText(pane, pane.cur_row, pane.cur_row + 1, pane.cur_col) orelse return) - else - eb; - const c2 = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - e2.row0)), .col = c.col }; - const g = modal.offsetAt(e2.text, c2); - const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .next_word_end); - const to = @max(wr.anchor, wr.head); - if (to <= g) return; - const new = modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to)) catch return; - p.setEditText(pane, new); - pane.cur_pinned = true; - return; - } - if (hit(key, config.kill_to_line_start)) { - const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c) catch return; - p.setEditText(pane, new); - pane.cur_col = 0; - pane.cur_pinned = true; - pane.ensureCursorVisible(); - return; - } - if (hit(key, config.kill_to_line_end)) { - const llen = modal.lineSlice(text, c.row).len; - const new = modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }) catch return; - p.setEditText(pane, new); - pane.cur_pinned = true; - return; - } - switch (key.cp) { - Key.enter => { - const line = modal.lineSlice(text, c.row); - const indent = modal.newlineIndentWidth(line, c.col); - const arena = p.scratch.allocator(); - const block = arena.alloc(u8, 1 + indent) catch return; - block[0] = '\n'; - @memset(block[1..], ' '); - const new = modal.insertAt(p.gpa, text, c, block) catch return; - p.setEditText(pane, new); - pane.cur_row += 1; - pane.cur_col = @intCast(indent); - pane.cur_pinned = true; - pane.ensureCursorVisible(); - }, - Key.backspace => { - if (pane.cur_col > 0) { - const line = modal.lineSlice(text, c.row); - const prev = modal.prevGrapheme(line, c.col); - const new = modal.deleteChar(p.gpa, text, .{ .row = c.row, .col = prev }) catch return; - p.setEditText(pane, new); - pane.cur_col = @intCast(prev); - pane.cur_pinned = true; - pane.ensureCursorVisible(); - return; - } - // at col 0: eat the newline above (join up) — a terminal grows - // its buffer over the row it is joining with - if (pane.cur_row <= 0) return; - const e2 = p.editText(pane, pane.cur_row - 1, pane.cur_row, 0) orelse return; - const row: usize = @intCast(@max(0, pane.cur_row - e2.row0)); - if (row == 0) return; - const prevlen = modal.lineSlice(e2.text, row - 1).len; - const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }) catch return; - p.setEditText(pane, new); - pane.cur_row -= 1; - pane.cur_col = @intCast(prevlen); - pane.cur_pinned = true; - pane.ensureCursorVisible(); - }, - Key.delete => { - // delete forward; at line end eat the newline (join), which on - // a terminal means the buffer swallowing the row below - const line = modal.lineSlice(text, c.row); - if (c.col < line.len) { - const new = modal.deleteChar(p.gpa, text, c) catch return; - p.setEditText(pane, new); - } else { - const e2 = p.editText(pane, pane.cur_row, pane.cur_row + 1, pane.cur_col) orelse return; - const row: usize = @intCast(@max(0, pane.cur_row - e2.row0)); - if (row + 1 >= modal.lineCount(e2.text)) return; - const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }) catch return; - p.setEditText(pane, new); - } - pane.cur_pinned = true; - }, - Key.tab => { - const ln = modal.lineSlice(text, c.row); - if (!p.multi_on and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: { - const f = pane.file orelse break :dot; - if (f.output != null or !lsp.speaks(f.path)) break :dot; - const seq = p.lsp_seq; - p.lspRequest(p.active, .completion, ""); - if (p.lsp_seq != seq) return; - } - p.insertTab(pane); - }, - else => {}, - } - } - - fn insertTab(p: *Pardes, pane: *Pane) void { - const eb = p.editText(pane, pane.cur_row, pane.cur_row, pane.cur_col) orelse return; - const c: modal.Cursor = .{ - .row = @intCast(@max(0, pane.cur_row - eb.row0)), - .col = @intCast(@max(0, pane.cur_col)), - }; - const pad = modal.INDENT_W - (c.col % modal.INDENT_W); - const new = modal.insertAt(p.gpa, eb.text, c, " "[0..pad]) catch return; - p.setEditText(pane, new); - pane.cur_col += @intCast(pad); - pane.cur_pinned = true; - pane.ensureCursorVisible(); - } - - const Bounds = struct { lo_row: i32, lo_col: i32, hi_row: i32, hi_col: i32 }; - - /// a range's two cells, normalized to document order - pub fn cellBounds(s: Pane.SelRange) Bounds { - if (s.row < s.arow or (s.row == s.arow and s.col < s.acol)) - return .{ .lo_row = s.row, .lo_col = s.col, .hi_row = s.arow, .hi_col = s.acol }; - return .{ .lo_row = s.arow, .lo_col = s.acol, .hi_row = s.row, .hi_col = s.col }; - } - - /// the char selection [anchor, cursor] normalized to document order - fn vselBounds(pane: *Pane) Bounds { - return cellBounds(.{ .row = pane.cur_row, .col = pane.cur_col, .arow = pane.vsel.row, .acol = pane.vsel.col }); - } - fn vselText(p: *Pardes, pane: *Pane) []const u8 { - const arena = p.scratch.allocator(); - const b = vselBounds(pane); - const text = p.flatSurface(pane) catch return ""; - return modal.rangeText(arena, text, .{ .row = @intCast(@max(0, b.lo_row)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row)), .col = @intCast(@max(0, b.hi_col)) }) catch ""; - } - - /// join surface rows [r0, r1] (absolute) with '\n'; scratch-owned - fn yankRows(p: *Pardes, pane: *Pane, r0: i32, r1: i32) []const u8 { - const arena = p.scratch.allocator(); - const lines = p.paneCursorLines(pane) catch return ""; - const rows_count: usize = @intCast(@max(0, r1 - r0 + 1)); - var total: usize = rows_count -| 1; - var i = r0; - while (i <= r1) : (i += 1) { - if (i >= 0 and @as(usize, @intCast(i)) < lines.len) - total += lines[@intCast(i)].len; - } - const out = arena.alloc(u8, total) catch return ""; - var at: usize = 0; - i = r0; - while (i <= r1) : (i += 1) { - if (i > r0) { - out[at] = '\n'; - at += 1; - } - if (i >= 0 and @as(usize, @intCast(i)) < lines.len) { - const line = lines[@intCast(i)]; - @memcpy(out[at..][0..line.len], line); - at += line.len; - } - } - return out; - } - // ---- edit operations (d / c / y / p) ---- - fn normalDelete(p: *Pardes, pane: *Pane, yank: bool) void { - pane.select = false; // helix delete exits select mode - pane.sticky_col = -1; - if (pane.vsel.active) { - const b = vselBounds(pane); - if (yank) p.setYank(p.vselText(pane)); // read the range before the move - p.pushUndo(pane); - const eb = p.editTextEol(pane, b) orelse { - pane.vsel.active = false; - return; - }; - const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch { - pane.vsel.active = false; - return; - }; - p.setEditText(pane, d.content); - p.gpa.free(d.deleted); - pane.cur_row = b.lo_row; - pane.cur_col = b.lo_col; - pane.clampCursor(d.content, eb.row0); - return; - } - if (pane.msel.active) { - const r0 = @min(pane.msel.r0, pane.msel.r1); - const r1 = @max(pane.msel.r0, pane.msel.r1); - p.pushUndo(pane); - // linewise: a line's newline lives on the row below it - const eb = p.editText(pane, r0, r1 + 1, -1) orelse { - pane.msel.active = false; - return; - }; - const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, r0 - eb.row0)), @intCast(@max(0, r1 - eb.row0))) catch { - pane.msel.active = false; - return; - }; - p.setEditText(pane, d.content); - if (yank) p.setYank(d.deleted); - p.gpa.free(d.deleted); - const n = modal.lineCount(d.content); - pane.cur_row = @as(i32, @intCast(@min(@as(usize, @intCast(@max(0, r0 - eb.row0))), if (n == 0) 0 else n - 1))) + eb.row0; - pane.cur_col = 0; - pane.msel.active = false; - pane.cur_pinned = true; - pane.ensureCursorVisible(); - } else { - p.pushUndo(pane); - const eb = p.editTextEol(pane, .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }) orelse return; - const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; - if (yank) { - const arena = p.scratch.allocator(); - p.setYank(modal.rangeText(arena, eb.text, c, c) catch return); - } - // deleteRange (not deleteChar): the cursor may sit ON a '\n' - // cell, where a delete joins the lines (helix 1-wide selection) - const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return; - p.setEditText(pane, d.content); - p.gpa.free(d.deleted); - const llen = modal.lineSlice(d.content, c.row).len; - pane.cur_col = @min(pane.cur_col, @as(i32, @intCast(llen))); - } - } - - fn normalYank(p: *Pardes, pane: *Pane) void { - pane.select = false; - if (pane.rawPointerText(pane.sel[sel_slot])) |text| { - p.setYank(text); - return; - } - if (pane.vsel.active) { - p.setYank(p.vselText(pane)); - return; - } - if (pane.msel.active) { - p.setYank(p.yankRows(pane, @min(pane.msel.r0, pane.msel.r1), @max(pane.msel.r0, pane.msel.r1))); - } else { - const save = pane.vsel; - pane.vsel = .{ .active = true, .row = pane.cur_row, .col = pane.cur_col, .explicit = false }; - p.setYank(p.vselText(pane)); - pane.vsel = save; - } - } - - fn pasteText(p: *Pardes, pane: *Pane, y0: []const u8, before: bool, count: usize) void { - if (y0.len == 0) return; - p.pushUndo(pane); - pane.select = false; - pane.sticky_col = -1; - const arena = p.scratch.allocator(); - var y: []const u8 = y0; - if (count > 1) { - const total = std.math.mul(usize, count, y0.len) catch return; - const buf = arena.alloc(u8, total) catch return; - for (0..count) |i| @memcpy(buf[i * y0.len ..][0..y0.len], y0); - y = buf; - } - const b: Bounds = if (pane.vsel.active) - vselBounds(pane) - else - .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }; - const eb = p.editText(pane, b.lo_row, b.hi_row, -1) orelse return; - const row0 = eb.row0; - if (y[y.len - 1] == '\n') { - const block_text = y[0 .. y.len - 1]; - const n = @max(1, modal.lineCount(block_text)); - var out: []u8 = undefined; - if (before) { - const row: usize = @intCast(@max(0, b.lo_row - row0)); - const block = std.fmt.allocPrint(arena, "{s}\n", .{block_text}) catch return; - out = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = 0 }, block) catch return; - pane.cur_row = @as(i32, @intCast(row + n - 1)) + row0; - } else { - const row: usize = @intCast(@max(0, b.hi_row - row0)); - out = modal.pasteLineBelow(p.gpa, eb.text, row, block_text) catch return; - pane.cur_row = @as(i32, @intCast(row + n)) + row0; - } - p.setEditText(pane, out); - pane.vsel = .{ .active = true, .row = pane.cur_row - @as(i32, @intCast(n - 1)), .col = 0, .explicit = false }; - // cursor ON the last pasted line's '\n' (helix) - const llen = modal.lineSlice(out, @intCast(@max(0, pane.cur_row - row0))).len; - pane.cur_col = @intCast(llen); - } else { - const at: modal.Cursor = if (before) - .{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) } - else blk: { - const hrow: usize = @intCast(@max(0, b.hi_row - row0)); - const hi_col: usize = @intCast(@max(0, b.hi_col)); - const high_line = modal.lineSlice(eb.text, hrow); - if (hi_col >= high_line.len) break :blk .{ .row = hrow + 1, .col = 0 }; - const gcol = modal.nextGrapheme(high_line, hi_col); - break :blk .{ .row = hrow, .col = gcol }; - }; - const out = modal.insertAt(p.gpa, eb.text, at, y) catch return; - p.setEditText(pane, out); - pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(at.row)) + row0, .col = @intCast(at.col), .explicit = false }; - const end = modal.advanceBy(at, y); - if (end.col > 0) { - pane.cur_row = @as(i32, @intCast(end.row)) + row0; - pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(out, end.row), end.col)); - } else { - pane.cur_row = @as(i32, @intCast(end.row -| 1)) + row0; - pane.cur_col = @intCast(modal.lineSlice(out, end.row -| 1).len); - } - } - pane.msel.active = false; - pane.cur_pinned = true; - pane.ensureCursorVisible(); - } - - fn normalChange(p: *Pardes, pane: *Pane) void { - pane.select = false; - pane.sticky_col = -1; - if (pane.vsel.active) { - const b = vselBounds(pane); - const eb = p.editTextEol(pane, b) orelse return; - const hi_len = modal.lineSlice(eb.text, @intCast(@max(0, b.hi_row - eb.row0))).len; - if (b.lo_col == 0 and @as(usize, @intCast(@max(0, b.hi_col))) >= hi_len) { - p.setYank(p.vselText(pane)); - p.pushUndo(pane); - const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))) catch return; - p.setEditText(pane, d.content); - p.gpa.free(d.deleted); - const n = modal.lineCount(d.content); - const row: usize = @min(@as(usize, @intCast(@max(0, b.lo_row - eb.row0))), if (n == 0) 0 else n - 1); - const ind = modal.indentText(modal.lineSlice(d.content, row)); - const arena = p.scratch.allocator(); - const block = std.fmt.allocPrint(arena, "{s}\n", .{ind}) catch return; - const new = modal.insertAt(p.gpa, d.content, .{ .row = row, .col = 0 }, block) catch return; - p.setEditText(pane, new); - pane.cur_row = @as(i32, @intCast(row)) + eb.row0; - pane.cur_col = @intCast(ind.len); - pane.vsel.active = false; - pane.msel.active = false; - pane.cur_pinned = true; - pane.mode = .insert; - pane.normal.clear(); - pane.ensureCursorVisible(); - return; - } - p.setYank(p.vselText(pane)); - p.pushUndo(pane); - const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch { - pane.vsel.active = false; - return; - }; - p.setEditText(pane, d.content); - p.gpa.free(d.deleted); - pane.cur_row = b.lo_row; - pane.cur_col = b.lo_col; - pane.clampCursor(d.content, eb.row0); - pane.mode = .insert; - pane.normal.clear(); - return; - } - if (pane.msel.active) { - const r0 = @min(pane.msel.r0, pane.msel.r1); - const r1 = @max(pane.msel.r0, pane.msel.r1); - p.pushUndo(pane); - const eb = p.editText(pane, r0, r1 + 1, -1) orelse return; - const arena = p.scratch.allocator(); - const lo: usize = @intCast(@max(0, r0 - eb.row0)); - const hi: usize = @intCast(@max(0, r1 - eb.row0)); - var total: usize = hi - lo; - for (lo..hi + 1) |r| total += modal.lineSlice(eb.text, r).len; - const buf = arena.alloc(u8, total) catch return; - var at: usize = 0; - for (lo..hi + 1) |r| { - if (r > lo) { - buf[at] = '\n'; - at += 1; - } - const line = modal.lineSlice(eb.text, r); - @memcpy(buf[at..][0..line.len], line); - at += line.len; - } - p.setYank(buf); - var body: []u8 = eb.text; - if (hi > lo) { - const d = modal.deleteLines(p.gpa, body, lo + 1, hi) catch { - pane.msel.active = false; - return; - }; - p.setEditText(pane, d.content); - p.gpa.free(d.deleted); - body = d.content; - } - const cl = modal.clearLine(p.gpa, body, lo) catch { - pane.msel.active = false; - return; - }; - p.setEditText(pane, cl); - pane.cur_row = r0; - pane.cur_col = 0; - pane.msel.active = false; - pane.cur_pinned = true; - pane.mode = .insert; - pane.normal.clear(); - pane.ensureCursorVisible(); - } else { - p.pushUndo(pane); - const eb = p.editTextEol(pane, .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }) orelse return; - const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; - const arena = p.scratch.allocator(); - p.setYank(modal.rangeText(arena, eb.text, c, c) catch return); - const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return; - p.setEditText(pane, d.content); - p.gpa.free(d.deleted); - const llen = modal.lineSlice(d.content, c.row).len; - pane.cur_col = @min(pane.cur_col, @as(i32, @intCast(llen))); - pane.mode = .insert; - pane.normal.clear(); - } - } - - fn selRange(pane: *Pane, content: []const u8, row0: i32) modal.Range { - if (pane.vsel.active) { - const b = vselBounds(pane); - return .{ - .a = .{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) }, - .b = .{ .row = @intCast(@max(0, b.hi_row - row0)), .col = @intCast(@max(0, b.hi_col)) }, - }; - } - if (pane.msel.active) { - const r0: usize = @intCast(@max(0, @min(pane.msel.r0, pane.msel.r1) - row0)); - const r1: usize = @intCast(@max(0, @max(pane.msel.r0, pane.msel.r1) - row0)); - const llen = modal.lineSlice(content, r1).len; - return .{ .a = .{ .row = r0, .col = 0 }, .b = .{ .row = r1, .col = if (llen == 0) 0 else modal.prevGrapheme(modal.lineSlice(content, r1), llen) } }; - } - const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - row0)), .col = @intCast(@max(0, pane.cur_col)) }; - return .{ .a = c, .b = c }; - } - - /// the rows an op's selection spans, absolute (what editText must cover) - fn selRows(pane: *Pane) Bounds { - if (pane.vsel.active) return vselBounds(pane); - if (pane.msel.active) return .{ - .lo_row = @min(pane.msel.r0, pane.msel.r1), - .lo_col = 0, - .hi_row = @max(pane.msel.r0, pane.msel.r1), - .hi_col = 0, - }; - return .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }; - } - - /// `r`: overwrite the selection (or the cursor char) with ch — - /// newlines included (helix), so `xrz` joins the selected lines - fn normalReplaceChar(p: *Pardes, pane: *Pane, ch: u21) void { - pane.select = false; - const eb = p.editTextEol(pane, selRows(pane)) orelse return; - const before = pane.primaryRange(eb.text, eb.row0); - const lo = @min(before.anchor, before.head); - const hi = @max(before.anchor, before.head); - var graphemes: usize = 0; - var at = lo; - while (at < hi) : (graphemes += 1) at = modal.nextGrapheme(eb.text, at); - var encoded: [4]u8 = undefined; - const encoded_len = std.unicode.utf8Encode(ch, &encoded) catch return; - const r = selRange(pane, eb.text, eb.row0); - p.pushUndo(pane); - const new = modal.replaceChars(p.gpa, eb.text, r.a, r.b, ch) catch return; - p.setEditText(pane, new); - const end = lo + graphemes * encoded_len; - const mapped: modal.Selection = if (before.head < before.anchor) - .{ .anchor = end, .head = lo } - else - .{ .anchor = lo, .head = end }; - pane.setRange(new, eb.row0, mapped, pane.vsel.explicit); - } - - /// `R`: replace the selection (or the cursor char) with the DEFAULT - /// register. `SPC R` is the same verb over the system clipboard. - fn normalReplaceYank(p: *Pardes, pane: *Pane) void { - p.replaceWithText(pane, p.yank orelse return); - } - - /// The pasted text becomes the selection, head on its last char (which for - /// a trailing-newline `y` is the '\n' cell of the last full line). - fn replaceWithText(p: *Pardes, pane: *Pane, y: []const u8) void { - if (y.len == 0) return; - pane.select = false; - const eb = p.editTextEol(pane, selRows(pane)) orelse return; - const r = selRange(pane, eb.text, eb.row0); - p.pushUndo(pane); - const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, y) catch return; - p.setEditText(pane, new); - pane.msel.active = false; - pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; - const end = modal.advanceBy(r.a, y); - if (end.col > 0) { - pane.cur_row = @as(i32, @intCast(end.row)) + eb.row0; - pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(new, end.row), end.col)); - } else { - // the yank ended in '\n': the cursor lands ON that newline - pane.cur_row = @as(i32, @intCast(end.row -| 1)) + eb.row0; - pane.cur_col = @intCast(modal.lineSlice(new, end.row -| 1).len); - } - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); - } - - /// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char), - /// keeping the selection (helix) - fn normalCase(p: *Pardes, pane: *Pane, op: modal.CaseOp) void { - pane.select = false; - const eb = p.editTextEol(pane, selRows(pane)) orelse return; - const r = selRange(pane, eb.text, eb.row0); - p.pushUndo(pane); - const new = modal.changeCase(p.gpa, eb.text, r.a, r.b, op) catch return; - p.setEditText(pane, new); - } - - /// a change to apply to file content: delete [from, to), insert `ins` at - /// `from`. Ascending and disjoint. - const TextChange = struct { from: usize, to: usize, ins: []const u8 }; - - fn mapThroughChanges(chs: []const TextChange, pos: usize) usize { - var delta: i64 = 0; - for (chs) |ch| { - if (pos < ch.from) break; - if (ch.from == ch.to) { - delta += @intCast(ch.ins.len); - continue; - } - if (pos == ch.from) break; - if (pos < ch.to) return @intCast(@as(i64, @intCast(ch.from)) + delta); - delta += @as(i64, @intCast(ch.ins.len)) - @as(i64, @intCast(ch.to - ch.from)); - } - return @intCast(@as(i64, @intCast(pos)) + delta); - } - - /// apply a change list. gpa-owned result. - fn applyChanges(p: *Pardes, text: []const u8, chs: []const TextChange) ![]u8 { - var total = text.len; - for (chs) |ch| total = total - (ch.to - ch.from) + ch.ins.len; - const out = try p.gpa.alloc(u8, total); - errdefer p.gpa.free(out); - var copied: usize = 0; - var at: usize = 0; - for (chs) |ch| { - const unchanged = text[copied..ch.from]; - @memcpy(out[at..][0..unchanged.len], unchanged); - at += unchanged.len; - @memcpy(out[at..][0..ch.ins.len], ch.ins); - at += ch.ins.len; - copied = ch.to; - } - @memcpy(out[at..], text[copied..]); - return out; - } - - fn normalJoin(p: *Pardes, pane: *Pane) void { - // a join always eats the newline of its last line, so the buffer has - // to reach one row PAST the selection - const sr = selRows(pane); - const eb = p.editText(pane, sr.lo_row, sr.hi_row + 1, -1) orelse return; - const text = eb.text; - const range = pane.primaryRange(text, eb.row0); - const span = Pane.rangeLineSpan(text, range); - const nlines = modal.cursorLineCount(text); - var end = span.end; - if (span.start == end) end = @min(end + 1, nlines - 1); - if (end <= span.start) return; - const arena = p.scratch.allocator(); - const chs = arena.alloc(TextChange, end - span.start) catch return; - var chs_len: usize = 0; - var l = span.start; - while (l < end) : (l += 1) { - const from = modal.lineEndOffset(text, l); - var to = if (l + 1 >= nlines) text.len else modal.lineStartOffset(text, l + 1); - while (to < text.len and (text[to] == ' ' or text[to] == '\t')) to += 1; - const sep: []const u8 = if (to == modal.lineEndOffset(text, @min(l + 1, nlines - 1))) "" else " "; - chs[chs_len] = .{ .from = from, .to = to, .ins = sep }; - chs_len += 1; - } - if (chs_len == 0) return; - p.pushUndo(pane); - const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }); - const anc_off = if (pane.vsel.active) - modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row - eb.row0)), .col = @intCast(@max(0, pane.vsel.col)) }) - else - cur_off; - const new = p.applyChanges(text, chs[0..chs_len]) catch return; - const nc = mapThroughChanges(chs[0..chs_len], cur_off); - const na = mapThroughChanges(chs[0..chs_len], anc_off); - p.setEditText(pane, new); - const cc = modal.positionAt(new, nc); - const ac = modal.positionAt(new, na); - pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; - pane.cur_col = @intCast(cc.col); - if (pane.vsel.active) { - pane.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0; - pane.vsel.col = @intCast(ac.col); - } - pane.msel.active = false; - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); - } - - fn normalIndent(p: *Pardes, pane: *Pane, cnt: usize, add: bool) void { - pane.select = false; - const sr = selRows(pane); - const eb = p.editText(pane, sr.lo_row, sr.hi_row, -1) orelse return; - const text = eb.text; - const range = pane.primaryRange(text, eb.row0); - const span = Pane.rangeLineSpan(text, range); - const arena = p.scratch.allocator(); - // one run of spaces, sliced per line: `>` never inserts more than this - const pad = arena.alloc(u8, modal.INDENT_W * cnt) catch return; - @memset(pad, ' '); - const chs = arena.alloc(TextChange, span.end - span.start + 1) catch return; - var chs_len: usize = 0; - var l = span.start; - while (l <= span.end) : (l += 1) { - const ls = modal.lineStartOffset(text, l); - const le = modal.lineEndOffset(text, l); - const line = text[ls..le]; - const nw = modal.firstNonWs(line); - if (nw == line.len) continue; // blank lines stay blank (helix) - if (add) { - const ins = modal.INDENT_W * cnt - (nw % modal.INDENT_W); - chs[chs_len] = .{ .from = ls, .to = ls, .ins = pad[0..ins] }; - chs_len += 1; - } else { - const want = modal.INDENT_W * cnt; - var w: usize = 0; - var pos: usize = 0; - while (pos < line.len) { - if (line[pos] == ' ') { - w += 1; - } else if (line[pos] == '\t') { - w = (w / modal.INDENT_W + 1) * modal.INDENT_W; - } else break; - pos += 1; - if (w >= want) break; - } - if (pos > 0) { - chs[chs_len] = .{ .from = ls, .to = ls + pos, .ins = "" }; - chs_len += 1; - } - } - } - if (chs_len == 0) return; - p.pushUndo(pane); - const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }); - const anc_off = if (pane.vsel.active) - modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row - eb.row0)), .col = @intCast(@max(0, pane.vsel.col)) }) - else - cur_off; - const new = p.applyChanges(text, chs[0..chs_len]) catch return; - const nc = mapThroughChanges(chs[0..chs_len], cur_off); - const na = mapThroughChanges(chs[0..chs_len], anc_off); - p.setEditText(pane, new); - const cc = modal.positionAt(new, nc); - const ac = modal.positionAt(new, na); - pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; - pane.cur_col = @intCast(cc.col); - if (pane.vsel.active) { - pane.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0; - pane.vsel.col = @intCast(ac.col); - } - pane.msel.active = false; - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); - } - - fn normalToggleComment(p: *Pardes, pane: *Pane) void { - const expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; - pane.select = false; // helix exit_select_mode - // the buffer must cover every cursor's rows, not just the primary's - var b = selRows(pane); - for (pane.sels[0..pane.nsel]) |s| { - b.lo_row = @min(b.lo_row, @min(s.row, s.arow)); - b.hi_row = @max(b.hi_row, @max(s.row, s.arow)); - } - const surface = p.flatSurface(pane) catch return; - const last_row = @as(i32, @intCast(panes.File.textLineCount(pane, surface))) - 1; - const eb = p.editText(pane, b.lo_row, @min(b.hi_row + 1, last_row), -1) orelse return; - const text = eb.text; - var rs: [Pane.max_selections]modal.Selection = undefined; - const got = pane.ranges(text, eb.row0, &rs); - const nlines = modal.cursorLineCount(text); - const arena = p.scratch.allocator(); - // the lines the ranges cover, each ONE ONCE and in order (helix's - // min_next_line: two cursors on one line comment it once) - const lines = arena.alloc(usize, nlines) catch return; - var lines_len: usize = 0; - var next: usize = 0; - for (rs[0..got.n]) |r| { - const span = Pane.rangeLineSpan(text, r); - var l = @max(span.start, next); - const end = @min(span.end + 1, nlines); - while (l < end) : (l += 1) { - lines[lines_len] = l; - lines_len += 1; - } - next = @max(next, end); - } - const ext = if (pane.file) |f| std.fs.path.extension(f.path) else ""; - var token: []const u8 = config.comment_token_default; - lang: for (config.comment_tokens) |row| { - for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) { - token = row.token; - break :lang; - }; - } - var commented = true; - var indent: usize = std.math.maxInt(usize); - var margin: usize = 1; - var live: usize = 0; - for (lines[0..lines_len]) |l| { - const line = text[modal.lineStartOffset(text, l)..modal.lineEndOffset(text, l)]; - const nw = modal.firstNonWs(line); - if (nw == line.len) continue; - indent = @min(indent, nw); - if (!std.mem.startsWith(u8, line[nw..], token)) commented = false; - if (nw + token.len >= line.len or line[nw + token.len] != ' ') margin = 0; - live += 1; - } - if (live == 0) return; // nothing but blank lines - const ins = std.fmt.allocPrint(arena, "{s} ", .{token}) catch return; - const chs = arena.alloc(TextChange, lines_len) catch return; - var chs_len: usize = 0; - for (lines[0..lines_len]) |l| { - const ls = modal.lineStartOffset(text, l); - const le = modal.lineEndOffset(text, l); - const line = text[ls..le]; - if (modal.firstNonWs(line) == line.len) continue; // blank lines untouched - const at = ls + indent; - // the @min can never bind: margin is 1 only when every line has a - // space after its own token, which is a byte past `at + token.len` - chs[chs_len] = if (commented) - .{ .from = at, .to = @min(at + token.len + margin, le), .ins = "" } - else - .{ .from = at, .to = at, .ins = ins }; - chs_len += 1; - } - p.pushUndo(pane); - // one edit, and the WHOLE selection rides through it (helix maps the - // selection with the transaction) - var cells: [Pane.max_selections]Pane.SelRange = undefined; - const new = p.applyChanges(text, chs[0..chs_len]) catch return; - for (rs[0..got.n], 0..) |r, i| { - const c = Pane.rangeCells(new, .{ - .anchor = mapThroughChanges(chs[0..chs_len], r.anchor), - .head = mapThroughChanges(chs[0..chs_len], r.head), - }); - const cc = modal.positionAt(new, c.cur); - const ac = modal.positionAt(new, c.anc); - cells[i] = .{ - .row = @as(i32, @intCast(cc.row)) + eb.row0, - .col = @intCast(cc.col), - .arow = @as(i32, @intCast(ac.row)) + eb.row0, - .acol = @intCast(ac.col), - }; - } - p.setEditText(pane, new); - const t2 = p.flatSurface(pane) catch return; - for (cells[0..got.n], 0..) |s, i| rs[i] = Pane.cellRange(t2, s.arow, s.acol, s.row, s.col); - pane.setRanges(t2, rs[0..got.n], &.{}, got.pri, expl); - } - - fn normalAdjustNumber(p: *Pardes, pane: *Pane, delta: i64) void { - const eb = p.editTextEol(pane, selRows(pane)) orelse return; - const r = selRange(pane, eb.text, eb.row0); - const arena = p.scratch.allocator(); - const frag = modal.rangeText(arena, eb.text, r.a, r.b) catch return; - const rep = (modal.incrementDecimal(arena, frag, delta) catch null) orelse return; - p.pushUndo(pane); - pane.select = false; - const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, rep) catch return; - p.setEditText(pane, new); - const start = modal.lineStartOffset(new, r.a.row) + r.a.col; - const cc = modal.positionAt(new, modal.prevGrapheme(new, start + rep.len)); - pane.vsel = .{ .active = modal.nextGrapheme(rep, 0) < rep.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; - pane.msel.active = false; - pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; - pane.cur_col = @intCast(cc.col); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); - } - - /// `]Space` / `[Space`: add blank lines below/above, the cursor staying - /// on its text line (the selection rides along) - fn addNewline(p: *Pardes, pane: *Pane, below: bool, cnt: usize) void { - const eb = p.editText(pane, pane.cur_row, pane.cur_row, -1) orelse return; - p.pushUndo(pane); - const row: usize = @intCast(@max(0, pane.cur_row - eb.row0)); - const arena = p.scratch.allocator(); - const nl = arena.alloc(u8, cnt) catch return; - @memset(nl, '\n'); - const llen = modal.lineSlice(eb.text, row).len; - const new = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl) catch return; - p.setEditText(pane, new); - if (!below) { - pane.cur_row += @intCast(cnt); // the line moved down; stay on it - if (pane.vsel.active and pane.vsel.row >= @as(i32, @intCast(row))) pane.vsel.row += @intCast(cnt); - } else if (pane.vsel.active and pane.vsel.row > @as(i32, @intCast(row))) { - pane.vsel.row += @intCast(cnt); - } - pane.cur_pinned = true; - pane.ensureCursorVisible(); - } - - /// pair mapping for m-mode: either bracket names the pair; anything else - /// surrounds with itself (quotes) - fn pairFor(ch: u21) ?struct { o: u8, c: u8 } { - return switch (ch) { - '(', ')' => .{ .o = '(', .c = ')' }, - '[', ']' => .{ .o = '[', .c = ']' }, - '{', '}' => .{ .o = '{', .c = '}' }, - '<', '>' => .{ .o = '<', .c = '>' }, - else => if (ch <= 0x7f) .{ .o = @intCast(ch), .c = @intCast(ch) } else null, - }; - } - - fn textobjectSelect(p: *Pardes, pane: *Pane, text: []const u8, obj: u21, around: bool) void { - const range = pane.primaryRange(text, 0); - switch (obj) { - 'w', 'W' => { - const r = modal.selectWord(text, range, around, obj == 'W'); - return pane.setRange(text, 0, r, false); - }, - 'p' => { - const r = modal.selectParagraph(text, range, around, 1); - return pane.setRange(text, 0, r, false); - }, - else => {}, - } - const lines = p.paneCursorLines(pane) catch return; - const cur = modal.positionAt(text, modal.selectionCursor(text, range)); - const pair: ?modal.Range = switch (obj) { - '\'', '"', '`' => modal.enclosingQuote(lines, cur, @intCast(obj)), - '(', ')' => modal.enclosingPair(lines, cur, '(', ')'), - '[', ']' => modal.enclosingPair(lines, cur, '[', ']'), - '{', '}' => modal.enclosingPair(lines, cur, '{', '}'), - '<', '>' => modal.enclosingPair(lines, cur, '<', '>'), - else => null, - }; - const pr = pair orelse return; - var a = modal.offsetAt(text, pr.a); - var head = modal.nextGrapheme(text, modal.offsetAt(text, pr.b)); - if (!around) { - // inside: shrink off the delimiters; an EMPTY pair collapses to - // a 1-wide cursor on the closing char (helix) - a = modal.nextGrapheme(text, a); - head = modal.prevGrapheme(text, head); - } - pane.setRange(text, 0, .{ .anchor = a, .head = head }, false); - } - - /// `ms`: wrap the selection (or the cursor char) in a pair; the wrap - /// including the pair becomes the selection - fn surroundAdd(p: *Pardes, pane: *Pane, ch: u21) void { - const pr = pairFor(ch) orelse return; - pane.select = false; - const eb = p.editTextEol(pane, selRows(pane)) orelse return; - const r = selRange(pane, eb.text, eb.row0); - p.pushUndo(pane); - const close_col = modal.nextGrapheme(modal.lineSlice(eb.text, r.b.row), r.b.col); - var new = modal.insertAt(p.gpa, eb.text, .{ .row = r.b.row, .col = close_col }, &[1]u8{pr.c}) catch return; - p.setEditText(pane, new); - new = modal.insertAt(p.gpa, new, .{ .row = r.a.row, .col = r.a.col }, &[1]u8{pr.o}) catch return; - p.setEditText(pane, new); - pane.msel.active = false; - pane.vsel = .{ .active = true, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; - pane.cur_row = @as(i32, @intCast(r.b.row)) + eb.row0; - pane.cur_col = @intCast(close_col + @as(usize, if (r.a.row == r.b.row) 1 else 0)); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); - } - - /// `md`: delete the enclosing pair's chars; the cursor maps through - fn surroundDelete(p: *Pardes, pane: *Pane, ch: u21) void { - const pr = pairFor(ch) orelse return; - const lines = p.paneCursorLines(pane) catch return; - const cur = pane.toModalCursor(); - const r = (if (pr.o == pr.c) - modal.enclosingQuote(lines, cur, pr.o) - else - modal.enclosingPair(lines, cur, pr.o, pr.c)) orelse return; - const lo: i32 = @intCast(@min(r.a.row, cur.row)); - const hi: i32 = @intCast(@max(r.b.row, cur.row)); - const eb = p.editText(pane, lo, hi, -1) orelse return; - const text = eb.text; - const drow = -eb.row0; // surface row -> buffer row - const ra: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.a.row)) + drow), .col = r.a.col }; - const rb: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.b.row)) + drow), .col = r.b.col }; - p.pushUndo(pane); - const a_off = modal.offsetAt(text, ra); - const b_off = modal.offsetAt(text, rb); - const cur_off = modal.offsetAt(text, .{ .row = @intCast(@as(i32, @intCast(cur.row)) + drow), .col = cur.col }); - // the close first, so the open's position stays valid - var new = modal.deleteChar(p.gpa, text, rb) catch return; - p.setEditText(pane, new); - new = modal.deleteChar(p.gpa, new, ra) catch return; - p.setEditText(pane, new); - var nc = cur_off; - if (nc > b_off) nc -= 1; - if (nc > a_off) nc -= 1; - const cc = modal.positionAt(new, nc); - pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; - pane.cur_col = @intCast(cc.col); - pane.vsel.active = false; - pane.msel.active = false; - pane.cur_pinned = true; - pane.ensureCursorVisible(); - } - - /// `mr`: swap the enclosing pair's chars for 's - fn surroundReplace(p: *Pardes, pane: *Pane, from: u21, to: u21) void { - const fp = pairFor(from) orelse return; - const tp = pairFor(to) orelse return; - const lines = p.paneCursorLines(pane) catch return; - const cur = pane.toModalCursor(); - const r = (if (fp.o == fp.c) - modal.enclosingQuote(lines, cur, fp.o) - else - modal.enclosingPair(lines, cur, fp.o, fp.c)) orelse return; - const eb = p.editText(pane, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1) orelse return; - const drow = -eb.row0; // surface row -> buffer row - const ar: usize = @intCast(@as(i32, @intCast(r.a.row)) + drow); - const br: usize = @intCast(@as(i32, @intCast(r.b.row)) + drow); - p.pushUndo(pane); - const out = p.gpa.dupe(u8, eb.text) catch return; - out[modal.lineStartOffset(out, ar) + r.a.col] = tp.o; - out[modal.lineStartOffset(out, br) + r.b.col] = tp.c; - p.setEditText(pane, out); - } - // ---- dumb undo/redo: whole-state snapshots, one per edit op ---- - pub fn pushUndo(p: *Pardes, pane: *Pane) void { - // one keystroke, one undo step — even when it edited at ten cursors. - if (p.multi_on and !p.multi_first) return; - if (pane.file != null) return panes.File.pushUndo(p, pane); - panes.Terminal.pushUndo(p, pane); - } - - fn doUndo(p: *Pardes, pane: *Pane) void { - if (pane.file != null) return panes.File.undo(p, pane); - panes.Terminal.undo(p, pane); - } - - fn doRedo(p: *Pardes, pane: *Pane) void { - if (pane.file != null) return panes.File.redo(p, pane); - panes.Terminal.redo(p, pane); - } - pub const ChromeTarget = struct { col: u16, row: u16 }; pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { @@ -9470,12 +7899,7 @@ pub const Pardes = struct { return null; } - const PointerTextSelection = struct { - sel: Pane.Sel, - on_tag: bool, - }; - - fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clamp: bool) ?Mouse.BodyHit { + pub fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clamp: bool) ?Mouse.BodyHit { const pane = p.panes[id] orelse return null; if (pane.file == null or (!clamp and supplied.serial != pane.serial)) return null; if (!std.math.isFinite(supplied.pixel_x) or !std.math.isFinite(supplied.pixel_y) or @@ -9499,35 +7923,6 @@ pub const Pardes = struct { return p.reprojectBodyHit(mapped_hit); } - fn pointerTextSelection(p: *const Pardes, id: usize, col: u16, row: u16, body_hit: ?Mouse.BodyHit, tag_hit: ?TagHit) ?PointerTextSelection { - if (p.panes[id] == null) return null; - const r = p.rects[id]; - if (col < r.x + config.GUTTER or col >= r.x + r.w or row < r.y or row >= r.y + r.h) return null; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = p.bodyTop(r); - const on_tag = row >= tag_y and row < tag_y + BOX_H; - if (on_tag and col < r.x + TAG_TEXT_INSET) return null; - // A notice chip is chrome: it sits OVER the body's top rows, so a - // click inside one belongs to nobody. The rest of those rows is - // ordinary body text and still answers normally. - if (!on_tag and row >= body_y and row - body_y < p.panes[id].?.notices.span() and - p.panes[id].?.notices.covers(row - body_y, col)) return null; - if (!on_tag) if (body_hit) |supplied| { - const mapped_hit = p.bodyHitForPane(id, supplied, false) orelse return null; - const c = @as(i32, mapped_hit.col) - config.GUTTER; - const v = @as(i32, mapped_hit.row) + BOX_H; - return .{ .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, .on_tag = false }; - }; - const tag_col = if (on_tag) p.tagColumn(.pane, id, tag_hit, false) else null; - const c: i32 = (if (tag_col) |value| @as(i32, value) else @as(i32, col) - @as(i32, r.x + (if (on_tag) TAG_TEXT_INSET else config.GUTTER))) + - (if (on_tag) @as(i32, p.panes[id].?.tag_scroll) else 0); - const v: i32 = if (on_tag) 0 else @as(i32, row) - @as(i32, body_y) + @as(i32, BOX_H); - return .{ - .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, - .on_tag = on_tag, - }; - } - fn cancelLookHover(p: *Pardes) void { if (comptime pdf_enabled) if (p.pdf_hover_preview) |*preview| { if (preview.pane < p.panes.len) if (p.panes[preview.pane]) |pane| { @@ -9554,7 +7949,7 @@ pub const Pardes = struct { return first.kind == second.kind and first.id == second.id and first.serial == second.serial and first.col == second.col; } - fn tagColumn(p: *const Pardes, kind: TagKind, id: usize, supplied: ?TagHit, clamp: bool) ?u16 { + pub fn tagColumn(p: *const Pardes, kind: TagKind, id: usize, supplied: ?TagHit, clamp: bool) ?u16 { var point = supplied orelse return null; if (point.kind != kind or point.id != id) return null; if (clamp) for (p.surface.tagLayers()) |*layer| { @@ -9581,7 +7976,7 @@ pub const Pardes = struct { _ = delay; const id = p.paneAt(col, row) orelse return p.cancelLookHover(); const pane = p.panes[id] orelse return p.cancelLookHover(); - _ = p.pointerTextSelection(id, col, row, body_hit, tag_hit) orelse return p.cancelLookHover(); + _ = edit.pointerTextSelection(p, id, col, row, body_hit, tag_hit) orelse return p.cancelLookHover(); if (comptime pdf_enabled) if (p.pdf_hover_preview) |shown| if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial) return; @@ -9614,7 +8009,7 @@ pub const Pardes = struct { if (waiting.frames < delay) return; const pane = p.panes[waiting.pane] orelse return p.cancelLookHover(); if (pane.serial != waiting.serial) return p.cancelLookHover(); - const pointed = p.pointerTextSelection(waiting.pane, waiting.col, waiting.row, waiting.body_hit, waiting.tag_hit) orelse + const pointed = edit.pointerTextSelection(p, waiting.pane, waiting.col, waiting.row, waiting.body_hit, waiting.tag_hit) orelse return p.cancelLookHover(); if (comptime pdf_enabled) if (!pointed.on_tag and panes.Pdf.paneNativeReady(p, pane)) { const probe = panes.Pdf.probeAt(p, pane, waiting.col, waiting.row) orelse @@ -9921,7 +8316,7 @@ pub const Pardes = struct { } else { p.active = id; if (pane.tag_edit) exitTagEdit(pane); - const pointed = p.pointerTextSelection(id, mcol, mrow, m.body_hit, p.pointer_tag_hit) orelse return; + const pointed = edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit) orelse return; pane.clearPointerSelection(sel_slot); pane.sel[sel_slot] = pointed.sel; p.drag = .{ .select = .{ @@ -9977,7 +8372,7 @@ pub const Pardes = struct { const local = @as(i32, mrow) - @as(i32, body_y); if (m.button == config.look_button) p.active = id; pane.scrollBy(if (m.button == config.look_button) local else -local); - } else if (p.pointerTextSelection(id, mcol, mrow, m.body_hit, p.pointer_tag_hit)) |pointed| { + } else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit)) |pointed| { if (m.button == config.look_button) p.active = id; pane.clearPointerSelection(@intFromEnum(m.button)); pane.sel[@intFromEnum(m.button)] = pointed.sel; @@ -10148,7 +8543,7 @@ pub const Pardes = struct { const top = @min(sel.r0, sel.r1) - @as(i32, BOX_H); if (top < 0) break :lead null; const w = pane.wrapAt(top); - const col = p.paneByteAtDisplay(pane, w.line, w.at, @min(sel.c0, sel.c1) - panes.File.gutterWidth(pane)); + const col = edit.paneByteAtDisplay(p, pane, w.line, w.at, @min(sel.c0, sel.c1) - panes.File.gutterWidth(pane)); break :lead .{ .row = @intCast(@max(0, w.line)), .col = @intCast(@max(0, col)), @@ -10202,7 +8597,7 @@ pub const Pardes = struct { pane.append_at = null; pane.sticky_col = -1; pane.normal.clear(); - p.setYank(text); + edit.setYank(p, text); } fn dragRelease(p: *Pardes, button: Mouse.Button) void { @@ -10277,20 +8672,21 @@ pub const Pardes = struct { const sl = pane.sel[sel_slot]; const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1; if (!dragged) pane.sel[sel_slot].state = .none; - if (dragged) p.capturePointerSelection(pane, sel_slot) catch {}; + if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; if (dragged and pane.mode == .tty) p.mirrorTtySelection(pane); const body_vis = sl.r1 - @as(i32, BOX_H); if (body_vis >= 0 and pane.mode != .tty) { const w = pane.wrapAt(body_vis); pane.cur_row = w.line; - pane.cur_col = p.paneByteAtDisplay( + pane.cur_col = edit.paneByteAtDisplay( + p, pane, w.line, w.at, sl.c1 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), ); pane.cur_pinned = true; - if (clampFileCursor(pane)) pane.ensureCursorVisible(); + if (edit.clampFileCursor(pane)) pane.ensureCursorVisible(); pane.msel.active = false; pane.normal.clear(); pane.vsel.active = false; @@ -10325,7 +8721,7 @@ pub const Pardes = struct { if (s.button == config.look_button and clk.r0 >= BOX_H and pane.mode != .tty) { pane.cur_row = operand.row; pane.cur_col = operand.col; - if (clampFileCursor(pane)) pane.ensureCursorVisible(); + if (edit.clampFileCursor(pane)) pane.ensureCursorVisible(); } const txt = operand.text; const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; @@ -10370,7 +8766,7 @@ pub const Pardes = struct { } // A PDF is immutable: its Cut-side chord is Snarf (copy), while // Paste has no document mutation to perform. - if (cut and pv.selection_text.len > 0) p.setYank(pv.selection_text); + if (cut and pv.selection_text.len > 0) edit.setYank(p, pv.selection_text); return; }; if (pane.mode == .tty) { @@ -10394,7 +8790,7 @@ pub const Pardes = struct { p.emitWrite(s.id, &[_]u8{ 0x1b, '[', 'M', 32, cb, rb, 0x1b, '[', 'M', 35, cb, rb }); } } - p.typeToTty(s.id, pane, y); + edit.typeToTty(p, s.id, pane, y); return; } if (!s.chorded) { @@ -10408,8 +8804,8 @@ pub const Pardes = struct { const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, BOX_H))); const row0 = w0.line; const row1 = w1.line; - const col0 = p.paneByteAtDisplay(pane, w0.line, w0.at, sl.c0 - pfx); - const col1 = p.paneByteAtDisplay(pane, w1.line, w1.at, sl.c1 - pfx); + const col0 = edit.paneByteAtDisplay(p, pane, w0.line, w0.at, sl.c0 - pfx); + const col1 = edit.paneByteAtDisplay(p, pane, w1.line, w1.at, sl.c1 - pfx); pane.cur_row = row1; pane.cur_col = col1; pane.cur_pinned = true; @@ -10420,16 +8816,16 @@ pub const Pardes = struct { pane.nsel = 0; } if (cut) { - if (pane.vsel.active) p.normalDelete(pane, true); + if (pane.vsel.active) edit.normalDelete(p, pane, true); } else if (pane.vsel.active) { - p.normalReplaceYank(pane); + edit.normalReplaceYank(p, pane); } else if (pane.file) |*f| { // bare cursor: splice the register in literally (no linewise // magic) so a paste right after a cut restores the text exactly const y = p.yank orelse return; if (y.len == 0) return; const at = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }; - p.pushUndo(pane); + edit.pushUndo(p, pane); const new = modal.insertAt(p.gpa, f.content, at, y) catch return; panes.File.setContent(p, f, new); pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; @@ -10445,7 +8841,7 @@ pub const Pardes = struct { pane.cur_pinned = true; pane.sticky_col = -1; pane.ensureCursorVisible(); - } else p.pasteText(pane, p.yank orelse return, true, 1); + } else edit.pasteText(p, pane, p.yank orelse return, true, 1); } /// Tty: a shell in the caller's directory, raw from the first frame, @@ -10658,7 +9054,7 @@ pub const Pardes = struct { } fn selectSpan(p: *Pardes, pane: *Pane, at: look.Spot) void { - const text = p.flatSurface(pane) catch return; + const text = edit.flatSurface(p, pane) catch return; // saturating, not `- 1`: `f.zig:0-5` is a legal thing to type and a // 1-based zero is the same nothing an absent number is const acol: i32 = @intCast(at.col -| 1); @@ -13040,66 +11436,6 @@ test "hopping between two panes does not grow the jump stack" { try std.testing.expectEqual(depth, p.njumps); } -/// 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; - while (p.nextEffect()) |effect| { - if (std.meta.activeTag(effect) == want) seen = true; - } - return seen; -} - -test "only the SPC clipboard commands cross to the system clipboard" { - if (platform == .web) return; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); - const pane = p.panes[0].?; - - _ = drainedEffect(p, .set_clipboard); - p.update(.{ .key = .{ .cp = 'y' } }); - try std.testing.expect(p.yank != null and p.yank.?.len > 0); - try std.testing.expect(!drainedEffect(p, .set_clipboard)); - p.update(.{ .key = .{ .cp = 'd' } }); - try std.testing.expect(!drainedEffect(p, .set_clipboard)); - - // `SPC y` is the one that does, and it puts the SAME text there that `y` - // put in the register — it is the ordinary yank path plus the mirror. - p.update(.{ .key = .{ .cp = ' ' } }); - p.update(.{ .key = .{ .cp = 'y' } }); - const yanked = p.yank orelse return error.MissingYank; - try std.testing.expect(drainedEffect(p, .set_clipboard)); - - const before = pane.file.?.content.len; - p.update(.{ .key = .{ .cp = ' ' } }); - p.update(.{ .key = .{ .cp = 'p' } }); - try std.testing.expect(p.clip_pending != null); - try std.testing.expect(drainedEffect(p, .read_clipboard)); - try std.testing.expectEqual(before, pane.file.?.content.len); // nothing yet - p.update(.{ .paste = "PASTED" }); - try std.testing.expect(p.clip_pending == null); - try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "PASTED") != null); - // ...and it did NOT land in the register on its way past, nor echo back - // out to the clipboard it came from. - try std.testing.expectEqualStrings(yanked, p.yank orelse ""); - try std.testing.expect(!drainedEffect(p, .set_clipboard)); - - // An UNSOLICITED paste — the outer terminal's bracketed paste, a Cmd-V — - // is the same event with no request behind it, and means paste after. - p.update(.{ .paste = "UNASKED" }); - try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "UNASKED") != null); - try std.testing.expectEqualStrings(yanked, p.yank orelse ""); - - // A request the shell never answers dies at the next keystroke rather - // than firing late into whatever pane is focused by then. - p.update(.{ .key = .{ .cp = ' ' } }); - p.update(.{ .key = .{ .cp = 'P' } }); - try std.testing.expect(p.clip_pending != null); - p.update(.{ .key = .{ .cp = 'l' } }); - try std.testing.expect(p.clip_pending == null); -} - /// Every `.write` a keystroke produced, joined — what the pane's program would /// actually have read off its pty. fn drainWrites(p: *Pardes, buf: []u8) []const u8 { @@ -13122,7 +11458,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { defer p.deinit(); var buf: [256]u8 = undefined; _ = drainWrites(p, &buf); - p.setYank("register text"); + edit.setYank(p, "register text"); for ('a'..'z' + 1) |letter| { if (letter == p.opts.tty_toggle) continue; // editor/TTY mode shortcut if (letter == 'v') continue; // the window's paste, asserted just below @@ -13507,7 +11843,7 @@ test "jump history clears selections and lands at the recorded cursor" { for ([_]u21{ 'o', 'i' }, 0..) |key, index| { pane.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); pane.sel[0] = .{ .state = .done, .c0 = 2, .c1 = 5, .r0 = 1, .r1 = 1 }; - try p.capturePointerSelection(pane, 0); + try edit.capturePointerSelection(p, pane, 0); pane.select = true; p.update(.{ .key = .{ .cp = key, .ctrl = true } }); try std.testing.expectEqual(index, p.jcur); @@ -13542,10 +11878,10 @@ test "jump history terminal rectangle follows output and clears on reflow" { const pane = p.panes[0].?; p.update(.{ .output = .{ .pane = 0, .bytes = "alpha bravo\r\nsecond line\r\n" } }); pane.sel[0] = .{ .state = .done, .c0 = 0, .c1 = 4, .r0 = BOX_H, .r1 = BOX_H }; - try p.capturePointerSelection(pane, 0); - try std.testing.expectEqualStrings("alpha", try p.selectionText(pane, pane.sel[0])); + try edit.capturePointerSelection(p, pane, 0); + try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); for (0..40) |_| p.update(.{ .output = .{ .pane = 0, .bytes = "more output\r\n" } }); - try std.testing.expectEqualStrings("alpha", try p.selectionText(pane, pane.sel[0])); + try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); panes.Terminal.resizeGrid(pane, p.gpa, pane.cols - 1, pane.rows); try std.testing.expect(pane.pointerSelection(pane.sel[0]) == null); try std.testing.expectEqual(.none, pane.sel[0].state); diff --git a/src/selection_pipe.zig b/src/selection_pipe.zig index ea4a4d5b..90c8e951 100644 --- a/src/selection_pipe.zig +++ b/src/selection_pipe.zig @@ -7,6 +7,7 @@ const std = @import("std"); const filesystem = @import("fs.zig"); const pardes = @import("pardes.zig"); +const edit = @import("edit.zig"); const modal = @import("modal.zig"); const panes = @import("panes.zig"); const config = @import("config.zig"); @@ -662,7 +663,7 @@ pub fn pipeResponse( @memcpy(replacement[write_at..], f.content[read_at..]); // One async request is one history transaction, even at 64 cursors. - p.pushUndo(pane); + edit.pushUndo(p, pane); panes.File.setContent(p, f, replacement); pane.setRanges(f.content, new_ranges[0..n], &.{}, wait.primary, wait.explicit); pane.select = false; diff --git a/test/hxdiff.zig b/test/hxdiff.zig index 22d8067d..e79a6bb6 100644 --- a/test/hxdiff.zig +++ b/test/hxdiff.zig @@ -488,7 +488,7 @@ fn runCase(arena: std.mem.Allocator, case: Case, pane_kind: []const u8) !Result // the cursor's empty row below the output (see Pardes.shellRows), so // its line list is exactly a file content's — join it and you have the // same bytes, trailing newline included, with nothing to patch up. - const lines = try core.paneCursorLines(pane); + const lines = try pardes.edit.paneCursorLines(core, pane); var text_len: usize = if (lines.len == 0) 0 else lines.len - 1; for (lines) |ln| text_len = std.math.add(usize, text_len, ln.len) catch return error.OutOfMemory; const joined = try arena.alloc(u8, text_len); diff --git a/test/lspbench.zig b/test/lspbench.zig index 59cac155..7c4e8753 100644 --- a/test/lspbench.zig +++ b/test/lspbench.zig @@ -22,7 +22,7 @@ const Anchor = struct { }; const anchors = [_]Anchor{ - .{ .file = "src/pardes.zig", .needle = "modal.cursorLineCount(text)", .at = 6, .kind = .definition, .expect = "modal.zig" }, + .{ .file = "src/edit.zig", .needle = "modal.cursorLineCount(text)", .at = 6, .kind = .definition, .expect = "modal.zig" }, .{ .file = "src/lsp/lsp.zig", .needle = "lineCol(source", .at = 0, .kind = .definition, .expect = "lsp.zig" }, .{ .file = "src/lsp/lsp.zig", .needle = "std.mem.count(u8", .at = 8, .kind = .definition, .expect = "mem.zig" }, .{ .file = "src/lsp/lsp.zig", .needle = "lineCol(source", .at = 0, .kind = .hover, .expect = "" }, diff --git a/test/perf.zig b/test/perf.zig index 057725fd..7d3b5e3d 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -527,7 +527,7 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { pump(core); } _ = try frame(core); - const motion_rows = if (op == .key_down) (try core.paneCursorLines(pane)).len else 0; + const motion_rows = if (op == .key_down) (try pardes.edit.paneCursorLines(core, pane)).len else 0; if (op == .key_down and motion_rows < 3) return error.EmptyTerminalFixture; var cols = screen_cols; -- cgit v1.3 From f1025c18a78c02ebf157f0e3a5d9552605c082e8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 22:13:34 -0300 Subject: Move helix normal mode out of pardes.zig into normal.zig Pure move, no behaviour change: the key-to-role matching (isPrefix, roleBindingName, normalInput), multiOnce, the selection regex prompt (startSelRegex, selRegexArmed, applySelRegex), KeyState, Replay and replaySels, handleNormal, executeNormalAction and handlePdfNormal, with two tests, go verbatim to normal.zig. The methods become free functions taking `p: *Pardes`; their 22 call sites (handleKey, the mouse, look walk, lsp, runBuiltin, body drawing and edit.zig) change from `p.handleNormal(..)` to `normal.handleNormal(p, ..)`. test/lspbench.zig's second anchor follows its needle into src/normal.zig. Co-Authored-By: Claude Opus 5.5 --- src/body_layer.zig | 3 +- src/edit.zig | 7 +- src/fs.zig | 1 + src/normal.zig | 720 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/pardes.zig | 727 +---------------------------------------------------- test/lspbench.zig | 2 +- 6 files changed, 741 insertions(+), 719 deletions(-) create mode 100644 src/normal.zig (limited to 'src/fs.zig') diff --git a/src/body_layer.zig b/src/body_layer.zig index 8c345b97..6bac7018 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -5,6 +5,7 @@ //! and cursor. const std = @import("std"); const pardes = @import("pardes.zig"); +const normal = @import("normal.zig"); const edit = @import("edit.zig"); const config = @import("config.zig"); const limits = @import("memory.zig").limits; @@ -386,7 +387,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id } } } - const preview = Pardes.selRegexArmed(pane) != null; + const preview = normal.selRegexArmed(pane) != null; const show_prim = (pane.mode == .normal and pane.vsel.active) or preview or (modal_hover and pane.vsel.active); const show_extra = pane.mode != .tty and pane.nsel > 0; diff --git a/src/edit.zig b/src/edit.zig index e44a3364..f829decc 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -3,6 +3,7 @@ //! operations, replace, case, join, indent, comments, numbers, textobjects //! and surround, undo, yank and paste, and the pointer selections as text. const pardes = @import("pardes.zig"); +const normal = @import("normal.zig"); const std = @import("std"); const modal = @import("modal.zig"); const panes = @import("panes.zig"); @@ -86,7 +87,7 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { const range: @TypeOf(Pardes.tagSelBounds(pane)) = if (pane.tag_sel) Pardes.tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; _ = p.replaceTagText(pane, range.lo, hi, bytes); - if (Pardes.selRegexArmed(pane)) |a| p.applySelRegex(pane, a.pat, a.split); + if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } if (pane.isTerminal() and pane.mode == .tty) return typeToTty(p, id, pane, bytes); @@ -103,7 +104,7 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { return; }; if (pane.nsel > 0 and !main_only) { - p.replaySels(pane, .{ .normal = .{ .edit = .{ .kind = .yank, .count = 1 } } }); + normal.replaySels(p, pane, .{ .normal = .{ .edit = .{ .kind = .yank, .count = 1 } } }); } else { const others = pane.nsel; pane.nsel = 0; @@ -471,7 +472,7 @@ pub fn enterInsert(p: *Pardes, pane: *Pane, where: InsertAt, cnt: usize) void { pub fn handleInsert(p: *Pardes, pane: *Pane, key: Key) void { if (pane.nsel == 0) return insertKey(p, pane, key); - p.replaySels(pane, .{ .insert = key }); + normal.replaySels(p, pane, .{ .insert = key }); } pub fn insertKey(p: *Pardes, pane: *Pane, key: Key) void { diff --git a/src/fs.zig b/src/fs.zig index 04a8ed36..5fbd3cd8 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -41,6 +41,7 @@ const source_files = [_]Source{ .{ .path = "src/Messages.zig", .contents = @embedFile("Messages.zig") }, .{ .path = "src/body_layer.zig", .contents = @embedFile("body_layer.zig") }, .{ .path = "src/edit.zig", .contents = @embedFile("edit.zig") }, + .{ .path = "src/normal.zig", .contents = @embedFile("normal.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/normal.zig b/src/normal.zig new file mode 100644 index 00000000..7a18aae5 --- /dev/null +++ b/src/normal.zig @@ -0,0 +1,720 @@ +//! Helix normal mode: a key read against the configured bindings becomes +//! modal actions, replayed across every selection, and each action is done +//! to the pane; PDF panes get their own normal keys. +const pardes = @import("pardes.zig"); +const std = @import("std"); +const mvzr = @import("mvzr"); +const modal = @import("modal.zig"); +const panes = @import("panes.zig"); +const edit = @import("edit.zig"); +const config = @import("config.zig"); +const pdf_enabled = panes.Pdf.enabled; +const Pane = panes.Pane; +const Key = pardes.Key; +const hit = pardes.hit; +const sel_slot = pardes.sel_slot; +const Pardes = pardes.Pardes; + +fn isPrefix(key: Key, cp: u21) bool { + return key.cp == cp and !key.ctrl and !key.alt; +} + +fn roleBindingName(comptime role: modal.Normal.Role) []const u8 { + return switch (role) { + .prefix_goto => "goto_prefix", + .prefix_view => "view_prefix", + .prefix_match => "match_prefix", + .prefix_find_fwd => "find_char_fwd", + .prefix_find_back => "find_char_back", + .prefix_till_fwd => "till_char_fwd", + .prefix_till_back => "till_char_back", + .prefix_replace => "replace_prefix", + .prefix_next => "next_prefix", + .prefix_prev => "prev_prefix", + else => @tagName(role), + }; +} + +fn normalInput(key: Key) modal.Normal.Input { + var out: modal.Normal.Input = .{ + .cp = key.cp, + .ctrl = key.ctrl, + .alt = key.alt, + }; + inline for (std.enums.values(modal.Normal.Role)) |role| { + const name = comptime roleBindingName(role); + if (!@hasDecl(config, name)) + @compileError("normal input role has no config binding: " ++ name); + const binding = @field(config, name); + const matched = if (@TypeOf(binding) == comptime_int) + isPrefix(key, binding) + else if (@TypeOf(binding) == []const config.Chord) + hit(key, binding) + else + @compileError("normal input binding has unsupported type: " ++ name); + if (matched) out.roles.insert(role); + } + return out; +} + +pub fn multiOnce(p: *Pardes) bool { + if (!p.multi_on) return true; + p.multi_stop = true; + return p.multi_first; +} + +fn startSelRegex(p: *Pardes, pane: *Pane, split: bool) void { + const text = edit.flatSurface(p, pane) catch return; + const got = pane.ranges(text, 0, &pane.sel_snap); + pane.nsel_snap = @intCast(got.n); + pane.sel_snap_pri = @intCast(got.pri); + pane.sel_snap_expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; + p.startPrompt(pane, .{ .search = if (split) config.split_marker else config.select_marker }); +} + +pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } { + const prompt_at = switch (pane.prompt) { + .search => |at| at, + else => return null, + }; + if (pane.nsel_snap == 0) return null; + const tail = pane.tagSlice(); + const armed = tail[@min(prompt_at, tail.len)..]; + const split = std.mem.startsWith(u8, armed, config.split_marker); + if (!split and !std.mem.startsWith(u8, armed, config.select_marker)) return null; + const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return null; + return .{ .pat = armed[slash + 1 ..], .split = split }; +} + +pub fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void { + const text = edit.flatSurface(p, pane) catch return; + const snap = pane.sel_snap[0..pane.nsel_snap]; + var out: [Pane.max_selections]modal.Selection = undefined; + var m: usize = 0; + if (pat.len > 0) if (mvzr.compile(pat)) |re| { + var hay_all = text; + if (for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true) { + const low = p.scratch.allocator().dupe(u8, text) catch return; + for (low) |*c| c.* = std.ascii.toLower(c.*); + hay_all = low; + } + for (snap) |r| { + const from = @min(r.anchor, r.head); + const to = @min(@max(r.anchor, r.head), text.len); + if (from >= to) continue; + const hay = hay_all[from..to]; + var at: usize = 0; + var piece = from; // split: where the next piece begins + while (at < hay.len and m < Pane.max_selections) { + const hit_at = re.matchPos(at, hay) orelse break; + if (split) { + out[m] = .{ .anchor = piece, .head = from + hit_at.start }; + m += 1; + piece = from + hit_at.end; + } else if (from + hit_at.start != to) { + out[m] = .{ .anchor = from + hit_at.start, .head = from + hit_at.end }; + m += 1; + } + // an empty match would otherwise never advance + at = if (hit_at.end > hit_at.start) hit_at.end else hit_at.end + 1; + } + if (split and piece < to and m < Pane.max_selections) { + out[m] = .{ .anchor = piece, .head = to }; + m += 1; + } + } + }; + if (m == 0) { + // the text CAN move under an armed prompt (a tag chord runs a + // builtin), and these are raw offsets into the surface as it was + for (snap) |*r| { + r.anchor = @min(r.anchor, text.len); + r.head = @min(r.head, text.len); + } + return pane.setRanges(text, snap, &.{}, pane.sel_snap_pri, pane.sel_snap_expl); + } + pane.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) +} + +const KeyState = struct { + mode: Pane.Mode, + select: bool, + normal: modal.Normal.State, + find_op: u8, + find_ch: u21, + append_at: @FieldType(Pane, "append_at"), + + fn of(pane: *Pane) KeyState { + return .{ + .mode = pane.mode, + .select = pane.select, + .normal = pane.normal, + .find_op = pane.find_op, + .find_ch = pane.find_ch, + .append_at = pane.append_at, + }; + } + + fn into(s: KeyState, pane: *Pane) void { + pane.mode = s.mode; + pane.select = s.select; + pane.normal = s.normal; + pane.find_op = s.find_op; + pane.find_ch = s.find_ch; + pane.append_at = s.append_at; + } +}; + +/// what a replayed key does at each cursor +const Replay = union(enum) { + normal: modal.Normal.Action, + insert: Key, +}; + +pub fn replaySels(p: *Pardes, pane: *Pane, what: Replay) void { + const id = p.active; + const serial = pane.serial; + // the whole selection in pane coordinates, document order. pane.sels + // is already ordered, so this only slots the primary into place. + var list: [Pane.max_selections]Pane.SelRange = undefined; + var n: usize = 0; + var pri: usize = 0; + const prim: Pane.SelRange = .{ + .row = pane.cur_row, + .col = pane.cur_col, + .arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row, + .acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col, + .sticky = pane.sticky_col, + }; + const pr = Pane.selStart(prim); + var placed = false; + for (pane.sels[0..pane.nsel]) |s| { + const sr = Pane.selStart(s); + if (!placed and (pr.row < sr.row or (pr.row == sr.row and pr.col <= sr.col))) { + pri = n; + list[n] = prim; + n += 1; + placed = true; + } + list[n] = s; + n += 1; + } + if (!placed) { + pri = n; + list[n] = prim; + n += 1; + } + + const saved = KeyState.of(pane); + const explicit = pane.vsel.explicit; + var after = saved; + var after_expl = explicit; + // each pass's result: cursor and anchor cells as distances from the + // end of the surface text, plus the range's own j/k goal column + var res: [Pane.max_selections]struct { cur: usize, anc: usize, sticky: i32 } = undefined; + p.multi_on = true; + p.multi_stop = false; + var passes: usize = 0; + var i: usize = n; + while (i > 0) { + i -= 1; + p.multi_first = passes == 0; + passes += 1; + saved.into(pane); + pane.nsel = 0; // the handler underneath sees ONE selection + pane.cur_row = list[i].row; + pane.cur_col = list[i].col; + pane.vsel = .{ + .active = list[i].arow != list[i].row or list[i].acol != list[i].col or pane.select, + .row = list[i].arow, + .col = list[i].acol, + .explicit = explicit, + }; + pane.msel.active = false; + pane.sticky_col = list[i].sticky; + switch (what) { + .normal => |normal_action| executeNormalAction(p, pane, normal_action), + .insert => |insert_key| edit.insertKey(p, pane, insert_key), + } + if (p.multi_stop) break; + if (i == pri) { + after = KeyState.of(pane); + after_expl = pane.vsel.explicit; + } + const text = edit.flatSurface(p, pane) catch { + p.multi_stop = true; + break; + }; + const co = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }); + const ao = if (pane.vsel.active) + modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row)), .col = @intCast(@max(0, pane.vsel.col)) }) + else + co; + res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = pane.sticky_col }; + } + p.multi_on = false; + p.multi_first = false; + if (p.multi_stop) { + p.multi_stop = false; + const pn = p.panes[id] orelse return; + if (pn.serial == serial) pn.nsel = 0; + return; + } + const text = edit.flatSurface(p, pane) catch return; + var rs: [Pane.max_selections]modal.Selection = undefined; + var st: [Pane.max_selections]i32 = undefined; + for (res[0..n], 0..) |r, k| { + rs[k] = Pane.cellOffRange(text, text.len - @min(r.anc, text.len), text.len - @min(r.cur, text.len)); + st[k] = r.sticky; + } + pane.setRanges(text, rs[0..n], st[0..n], pri, after_expl); + after.into(pane); + pane.ensureCursorVisible(); // the view follows the PRIMARY, not the last pass +} + +pub fn handleNormal(p: *Pardes, pane: *Pane, key: Key) void { + const parsed = modal.Normal.parse(&pane.normal, normalInput(key)); + const semantic = switch (parsed) { + .pending, .ignored, .unbound => return, + .action => |value| value, + }; + if (pane.nsel == 0 or semantic.scope() == .once) + return executeNormalAction(p, pane, semantic); + replaySels(p, pane, .{ .normal = semantic }); +} + +fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) void { + const raw_selection = pane.rawPointerText(pane.sel[sel_slot]) != null; + const before = .{ pane.cur_row, pane.cur_col, pane.vsel, pane.msel, pane.select, pane.nsel, pane.mode }; + defer if (raw_selection and !std.meta.eql(before, .{ pane.cur_row, pane.cur_col, pane.vsel, pane.msel, pane.select, pane.nsel, pane.mode })) { + pane.clearPointerSelection(sel_slot); + pane.sel[sel_slot].state = .none; + }; + if (raw_selection and semantic == .edit and semantic.edit.kind == .yank) return edit.normalYank(p, pane); + edit.pinPaneCursor(p, pane); + const text = edit.flatSurface(p, pane) catch return; + const range = pane.primaryRange(text, 0); + const cur = modal.selectionCursor(text, range); + + switch (semantic) { + .escape => { + pane.select = false; + return p.runBuiltin(.Last, p.active, "", null); + }, + .goto => |go| switch (go.target) { + .file_start => { + const line = if (go.explicit_count) @min(@as(usize, go.count) - 1, Pane.maxLine(text)) else 0; + return pane.pointMove(text, range, modal.lineStartOffset(text, line)); + }, + .last_line => return pane.pointMove(text, range, modal.lineStartOffset(text, Pane.maxLine(text))), + .line_start => return pane.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), + .line_end => { + const line = modal.lineAtOffset(text, cur); + const ls = modal.lineStartOffset(text, line); + return pane.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); + }, + .first_nonws => { + const line = modal.lineAtOffset(text, cur); + const ls = modal.lineStartOffset(text, line); + const slice = text[ls..modal.lineEndOffset(text, line)]; + const nw = modal.firstNonWs(slice); + if (nw == slice.len) return; + return pane.pointMove(text, range, ls + nw); + }, + .line_down => return pane.visualMove(text, range, true, go.count, edit.paneWrapWidth(p, pane)), + .line_up => return pane.visualMove(text, range, false, go.count, edit.paneWrapWidth(p, pane)), + .column => { + const line = modal.lineAtOffset(text, cur); + const ls = modal.lineStartOffset(text, line); + const slice = text[ls..modal.lineEndOffset(text, line)]; + return pane.pointMove(text, range, ls + modal.graphemeAtColumn(slice, @as(usize, go.count) - 1)); + }, + .view_top => return pane.gotoWindow(text, range, .top, go.count), + .view_center => return pane.gotoWindow(text, range, .center, go.count), + .view_bottom => return pane.gotoWindow(text, range, .bottom, go.count), + }, + .view => |view| switch (view) { + .top => { + pane.scrollBy(pane.cur_row - pane.scroll()); + pane.ensureCursorVisible(); + }, + .center => { + pane.scrollBy(pane.cur_row - (pane.scroll() + @divTrunc(@as(i32, pane.rows), 2) - 1)); + pane.ensureCursorVisible(); + }, + .bottom => { + pane.scrollBy(pane.cur_row - (pane.scroll() + @as(i32, pane.rows) - 1)); + pane.ensureCursorVisible(); + }, + .scroll_down => return pane.scrollViewMove(text, range, 1), + .scroll_up => return pane.scrollViewMove(text, range, -1), + }, + .find => |find| { + const op: u8 = switch (find.kind) { + .forward => @intCast(config.find_char_fwd), + .backward => @intCast(config.find_char_back), + .till_forward => @intCast(config.till_char_fwd), + .till_backward => @intCast(config.till_char_back), + }; + pane.find_op = op; + pane.find_ch = find.char; + return pane.findMove( + text, + range, + find.char, + find.kind == .forward or find.kind == .till_forward, + find.kind == .till_forward or find.kind == .till_backward, + find.count, + ); + }, + .replace_char => |char| return edit.normalReplaceChar(p, pane, char), + .match_bracket => { + const lines = edit.paneCursorLines(p, pane) catch return; + const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; + return pane.pointMove(text, range, modal.offsetAt(text, mc)); + }, + .textobject => |object| return edit.textobjectSelect(p, pane, text, object.char, object.around), + .surround_add => |char| return edit.surroundAdd(p, pane, char), + .surround_delete => |char| return edit.surroundDelete(p, pane, char), + .surround_replace => |replace| return edit.surroundReplace(p, pane, replace.from, replace.to), + .paragraph => |paragraph| { + const r2 = modal.moveParagraph(text, range, paragraph.count, paragraph.direction == .forward, pane.select); + return pane.setRange(text, 0, r2, false); + }, + .add_newline => |newline| return edit.addNewline(p, pane, newline.direction == .forward, newline.count), + .diagnostic => |diagnostic| { + const fwd = diagnostic.direction == .forward; + if (!diagnostic.endpoint) { + if (panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics }) and + p.searchStep(p.active, if (fwd) 1 else -1)) return; + return p.lspRequest(p.active, .diagnostics, ""); + } + if (!panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics })) + return p.lspRequest(p.active, .diagnostics, ""); + if (!fwd) { + pane.search_row = null; + _ = p.searchStep(p.active, 1); + return; + } + const rp = p.panes[pane.search_pane orelse return] orelse return; + const rf = rp.file orelse return; + pane.search_row = std.mem.count(u8, rf.content, "\n"); + _ = p.searchStep(p.active, -1); + }, + .move => |move| switch (move.motion) { + .left => { + var target = cur; + for (0..move.count) |_| target = modal.prevGrapheme(text, target); + return pane.pointMove(text, range, target); + }, + .right => { + var target = cur; + for (0..move.count) |_| target = modal.nextGrapheme(text, target); + return pane.pointMove(text, range, target); + }, + .down => return pane.verticalMove(text, range, true, move.count), + .up => return pane.verticalMove(text, range, false, move.count), + .next_word_start => return pane.wordMove(text, range, move.count, .next_word_start), + .prev_word_start => return pane.wordMove(text, range, move.count, .prev_word_start), + .next_word_end => return pane.wordMove(text, range, move.count, .next_word_end), + .next_long_word_start => return pane.wordMove(text, range, move.count, .next_long_word_start), + .prev_long_word_start => return pane.wordMove(text, range, move.count, .prev_long_word_start), + .next_long_word_end => return pane.wordMove(text, range, move.count, .next_long_word_end), + }, + .repeat_find => |count| { + if (pane.find_op == 0) return; + const fwd = pane.find_op == config.find_char_fwd or pane.find_op == config.till_char_fwd; + const till = pane.find_op == config.till_char_fwd or pane.find_op == config.till_char_back; + var repeated = range; + var moved = false; + for (0..count) |_| { + const cc = modal.selectionCursor(text, repeated); + const target = modal.findTarget(text, cc, pane.find_ch, fwd, till, 1) orelse break; + repeated = if (pane.select) + modal.moveSelectionCursor(text, repeated, target, true) + else + modal.moveSelectionCursor(text, .{ .anchor = cc, .head = cc }, target, true); + moved = true; + } + if (!moved) return; + return pane.setRange(text, 0, repeated, false); + }, + .line => |line_kind| switch (line_kind) { + .start => return pane.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), + .end => { + const line = modal.lineAtOffset(text, cur); + const ls = modal.lineStartOffset(text, line); + return pane.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); + }, + .first_nonws => { + const line = modal.lineAtOffset(text, cur); + const ls = modal.lineStartOffset(text, line); + const slice = text[ls..modal.lineEndOffset(text, line)]; + const nw = modal.firstNonWs(slice); + if (nw == slice.len) return; + return pane.pointMove(text, range, ls + nw); + }, + }, + .goto_line => |go| { + if (!go.explicit) return; + const line = @min(@as(usize, go.count) - 1, Pane.maxLine(text)); + return pane.pointMove(text, range, modal.lineStartOffset(text, line)); + }, + .page => |page| switch (page.kind) { + // Counts were parsed historically but these four text view + // actions intentionally move exactly one viewport unit. + .half_down => return pane.halfPageMove(text, range, true), + .half_up => return pane.halfPageMove(text, range, false), + .down => return pane.scrollViewMove(text, range, @as(i32, pane.rows)), + .up => return pane.scrollViewMove(text, range, -@as(i32, pane.rows)), + }, + .insert => |insert| { + const where: edit.InsertAt = switch (insert.kind) { + .at => .at, + .append => .append, + .line_start => .line_start, + .line_end => .line_end, + .open_below => .open_below, + .open_above => .open_above, + }; + return edit.enterInsert(p, pane, where, insert.count); + }, + .select => |select| switch (select.kind) { + .mode => { + if (pane.select) { + pane.select = false; + } else { + pane.select = true; + if (pane.msel.active) { + pane.setRange(text, 0, range, true); + } else if (!pane.vsel.active) { + pane.vsel = .{ .active = true, .row = pane.cur_row, .col = pane.cur_col, .explicit = true }; + } else { + pane.vsel.explicit = true; + } + } + pane.cur_pinned = true; + }, + .line => return pane.lineSelect(text, range, select.count), + .line_bounds => return pane.lineBoundsSelect(text, range), + .shrink_to_line_bounds => return pane.shrinkSelToLineBounds(text, range), + .collapse => return pane.setRange(text, 0, .{ .anchor = cur, .head = cur }, false), + .flip => { + const explicit = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; + return pane.setRange(text, 0, .{ .anchor = range.head, .head = range.anchor }, explicit); + }, + .all => return pane.setRange(text, 0, .{ .anchor = 0, .head = text.len }, false), + }, + .multi => |multi| { + if (multi.kind == .keep_primary) { + pane.nsel = 0; + return; + } + return pane.multiSelAction(text, multi.kind, multi.count); + }, + .select_regex => |split| return startSelRegex(p, pane, split), + .edit => |op| switch (op.kind) { + .delete => return edit.normalDelete(p, pane, true), + .delete_noyank => return edit.normalDelete(p, pane, false), + .change => return edit.normalChange(p, pane), + .yank => return edit.normalYank(p, pane), + .replace_with_yank => return edit.normalReplaceYank(p, pane), + .paste_after => return edit.pasteText(p, pane, p.yank orelse return, false, op.count), + .paste_before => return edit.pasteText(p, pane, p.yank orelse return, true, op.count), + .switch_case => return edit.normalCase(p, pane, .toggle), + .lowercase => return edit.normalCase(p, pane, .lower), + .uppercase => return edit.normalCase(p, pane, .upper), + .join_lines => return edit.normalJoin(p, pane), + .indent => return edit.normalIndent(p, pane, op.count, true), + .unindent => return edit.normalIndent(p, pane, op.count, false), + .comment_toggle => return edit.normalToggleComment(p, pane), + .undo => return edit.doUndo(p, pane), + .redo => return edit.doRedo(p, pane), + }, + .lsp => |request| return p.lspRequest(p.active, switch (request) { + .definition => .definition, + .declaration => .declaration, + .type_definition => .type_definition, + .implementation => .implementation, + .references => .references, + .format => .format, + }, ""), + .adjust_number => |delta| return edit.normalAdjustNumber(p, pane, delta), + .leader => { + p.leader_on = true; + p.leader_n = 0; + }, + .command_line => { + p.enterTagEdit(pane, -1); + if (pane.tag_edit) pane.mode = .normal; + }, + .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), + .search => return p.startPrompt(pane, .{ .search = config.search_marker }), + .search_step => |direction| return p.lookWalk( + if (direction == .forward) @as(i32, 1) else -1, + ), + } +} + +pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { + if (comptime !pdf_enabled) return; + if (pane.pdf == null) return; + if (hit(key, config.leave_pane)) { + pane.normal.clear(); + pane.select = false; + return p.runBuiltin(.Last, p.active, "", null); + } + if (pane.normal.prefix == .none and isPrefix(key, 'f')) { + pane.normal.clear(); + return p.runBuiltin(.PdfSections, p.active, "", null); + } + const parsed = modal.Normal.parse(&pane.normal, normalInput(key)); + switch (parsed) { + .pending, .ignored, .unbound => {}, + .action => |semantic| { + const result = panes.Pdf.applyNormal( + &pane.pdf.?, + p.pdf_gpa, + semantic, + p.native_images, + .{ .w = p.cell_pixels.w, .h = p.cell_pixels.h }, + panes.Pdf.paneViewport(p, pane), + panes.Pdf.paneGeometry(p, pane), + ); + if (result.page_changed) panes.Pdf.resetPageChrome(pane); + switch (result.host) { + .none => {}, + .leader => { + p.leader_on = true; + p.leader_n = 0; + }, + .command_line => { + p.enterTagEdit(pane, -1); + if (pane.tag_edit) pane.mode = .normal; + }, + .search => p.startPrompt(pane, .{ .search = config.search_marker }), + .search_forward => p.lookWalk(1), + .search_backward => p.lookWalk(-1), + } + }, + } +} + +test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const long = "a" ** 400; + const pane = try p.setTestFile(long ++ "\nsecond\n"); + p.settings.wrap = true; + const width = panes.File.wrapWidth(pane, true); + try std.testing.expect(width > 4 and long.len > width * 3); + + // gj holds the column INSIDE the row and lands on the next break; the line + // is one line the whole way down, which is the whole point. + pane.cur_row = 0; + pane.cur_col = 3; + pane.sticky_col = -1; + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'j' } }); + try std.testing.expectEqual(@as(i32, 0), pane.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.cur_col); + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'j' } }); + try std.testing.expectEqual(@as(i32, @intCast(width * 2 + 3)), pane.cur_col); + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'k' } }); + try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.cur_col); + // A count is counted in rows, not lines. + p.update(.{ .key = .{ .cp = '2' } }); + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'j' } }); + try std.testing.expectEqual(@as(i32, 0), pane.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(width * 3 + 3)), pane.cur_col); + + // Plain j/k are untouched: one FILE line each, whatever the body drew. + pane.cur_col = 3; + pane.sticky_col = -1; + p.update(.{ .key = .{ .cp = 'j' } }); + try std.testing.expectEqual(@as(i32, 1), pane.cur_row); + p.update(.{ .key = .{ .cp = 'k' } }); + try std.testing.expectEqual(@as(i32, 0), pane.cur_row); + + // The last row of a line steps into the next line's first row, and the + // first row steps back onto the previous line's LAST row. + pane.cur_row = 0; + pane.cur_col = @intCast(long.len - 1); + pane.sticky_col = -1; + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'j' } }); + try std.testing.expectEqual(@as(i32, 1), pane.cur_row); + pane.cur_col = 0; + pane.sticky_col = -1; + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'k' } }); + try std.testing.expectEqual(@as(i32, 0), pane.cur_row); + try std.testing.expect(pane.cur_col >= @as(i32, @intCast(long.len - long.len % width))); + + // Wrap OFF: a line is one visual row, so gj/gk ARE j/k again. + p.settings.wrap = false; + pane.cur_row = 0; + pane.cur_col = 3; + pane.sticky_col = -1; + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'j' } }); + try std.testing.expectEqual(@as(i32, 1), pane.cur_row); +} + +test "flat text movement and selection replay need no scratch rows" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); + defer p.deinit(); + const row_text = "one (two) λ\r\n"; + const text = try gpa.alloc(u8, 4096 * row_text.len); + defer gpa.free(text); + for (0..4096) |row| @memcpy(text[row * row_text.len ..][0..row_text.len], row_text); + const pane = try p.setTestFile(text); + _ = try panes.File.lineIndex(gpa, &pane.file.?); + var denied = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + p.scratch.deinit(); + p.scratch = .init(denied.allocator()); + + pane.cur_row = 4094; + handleNormal(p, pane, .{ .cp = 'l' }); + try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + handleNormal(p, pane, .{ .cp = 'j' }); + try std.testing.expectEqual(@as(i32, 4095), pane.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + handleNormal(p, pane, .{ .cp = 'h' }); + try std.testing.expectEqual(@as(i32, 0), pane.cur_col); + executeNormalAction(p, pane, .{ .textobject = .{ .char = 'w', .around = false } }); + try std.testing.expectEqual(@as(i32, 2), pane.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.vsel.col); + + pane.vsel.active = false; + pane.cur_row = 1024; + pane.cur_col = 0; + pane.nsel = 1; + pane.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 }; + handleNormal(p, pane, .{ .cp = 'l' }); + handleNormal(p, pane, .{ .cp = 'j' }); + try std.testing.expectEqual(@as(u8, 1), pane.nsel); + try std.testing.expectEqual(@as(i32, 1025), pane.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + try std.testing.expectEqual(@as(i32, 3073), pane.sels[0].row); + try std.testing.expectEqual(@as(i32, 1), pane.sels[0].col); + try std.testing.expect(!denied.has_induced_failure); + try std.testing.expectEqual(@as(usize, 0), p.scratch.queryCapacity()); + + pane.nsel = 0; + pane.cur_col = 4; + executeNormalAction(p, pane, .match_bracket); + try std.testing.expect(denied.has_induced_failure); + try std.testing.expectEqual(@as(i32, 4), pane.cur_col); + denied.fail_index = std.math.maxInt(usize); + executeNormalAction(p, pane, .match_bracket); + try std.testing.expectEqual(@as(i32, 8), pane.cur_col); +} diff --git a/src/pardes.zig b/src/pardes.zig index 55e1dc7a..e001aa41 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); pub const body_layer = @import("body_layer.zig"); pub const Messages = @import("Messages.zig"); @@ -433,6 +434,7 @@ pub const Loc = struct { }; test { + _ = @import("normal.zig"); _ = @import("edit.zig"); _ = @import("Messages.zig"); _ = @import("selection_pipe.zig"); @@ -576,72 +578,6 @@ test "Detach asks the frontend to leave, and says so when there is nothing to le try std.testing.expect(!p.quit); } -test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const long = "a" ** 400; - const pane = try p.setTestFile(long ++ "\nsecond\n"); - p.settings.wrap = true; - const width = panes.File.wrapWidth(pane, true); - try std.testing.expect(width > 4 and long.len > width * 3); - - // gj holds the column INSIDE the row and lands on the next break; the line - // is one line the whole way down, which is the whole point. - pane.cur_row = 0; - pane.cur_col = 3; - pane.sticky_col = -1; - p.update(.{ .key = .{ .cp = 'g' } }); - p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.cur_col); - p.update(.{ .key = .{ .cp = 'g' } }); - p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, @intCast(width * 2 + 3)), pane.cur_col); - p.update(.{ .key = .{ .cp = 'g' } }); - p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.cur_col); - // A count is counted in rows, not lines. - p.update(.{ .key = .{ .cp = '2' } }); - p.update(.{ .key = .{ .cp = 'g' } }); - p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, @intCast(width * 3 + 3)), pane.cur_col); - - // Plain j/k are untouched: one FILE line each, whatever the body drew. - pane.cur_col = 3; - pane.sticky_col = -1; - p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); - p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - - // The last row of a line steps into the next line's first row, and the - // first row steps back onto the previous line's LAST row. - pane.cur_row = 0; - pane.cur_col = @intCast(long.len - 1); - pane.sticky_col = -1; - p.update(.{ .key = .{ .cp = 'g' } }); - p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); - pane.cur_col = 0; - pane.sticky_col = -1; - p.update(.{ .key = .{ .cp = 'g' } }); - p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expect(pane.cur_col >= @as(i32, @intCast(long.len - long.len % width))); - - // Wrap OFF: a line is one visual row, so gj/gk ARE j/k again. - p.settings.wrap = false; - pane.cur_row = 0; - pane.cur_col = 3; - pane.sticky_col = -1; - p.update(.{ .key = .{ .cp = 'g' } }); - p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); -} - 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 }); @@ -2688,57 +2624,6 @@ test "every line of the board's boot buffer renders whole" { // ---- the boundary types ---- -test "flat text movement and selection replay need no scratch rows" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); - defer p.deinit(); - const row_text = "one (two) λ\r\n"; - const text = try gpa.alloc(u8, 4096 * row_text.len); - defer gpa.free(text); - for (0..4096) |row| @memcpy(text[row * row_text.len ..][0..row_text.len], row_text); - const pane = try p.setTestFile(text); - _ = try panes.File.lineIndex(gpa, &pane.file.?); - var denied = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - p.scratch.deinit(); - p.scratch = .init(denied.allocator()); - - pane.cur_row = 4094; - p.handleNormal(pane, .{ .cp = 'l' }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - p.handleNormal(pane, .{ .cp = 'j' }); - try std.testing.expectEqual(@as(i32, 4095), pane.cur_row); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - p.handleNormal(pane, .{ .cp = 'h' }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); - p.executeNormalAction(pane, .{ .textobject = .{ .char = 'w', .around = false } }); - try std.testing.expectEqual(@as(i32, 2), pane.cur_col); - try std.testing.expectEqual(@as(i32, 0), pane.vsel.col); - - pane.vsel.active = false; - pane.cur_row = 1024; - pane.cur_col = 0; - pane.nsel = 1; - pane.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 }; - p.handleNormal(pane, .{ .cp = 'l' }); - p.handleNormal(pane, .{ .cp = 'j' }); - try std.testing.expectEqual(@as(u8, 1), pane.nsel); - try std.testing.expectEqual(@as(i32, 1025), pane.cur_row); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - try std.testing.expectEqual(@as(i32, 3073), pane.sels[0].row); - try std.testing.expectEqual(@as(i32, 1), pane.sels[0].col); - try std.testing.expect(!denied.has_induced_failure); - try std.testing.expectEqual(@as(usize, 0), p.scratch.queryCapacity()); - - pane.nsel = 0; - pane.cur_col = 4; - p.executeNormalAction(pane, .match_bracket); - try std.testing.expect(denied.has_induced_failure); - try std.testing.expectEqual(@as(i32, 4), pane.cur_col); - denied.fail_index = std.math.maxInt(usize); - p.executeNormalAction(pane, .match_bracket); - try std.testing.expectEqual(@as(i32, 8), pane.cur_col); -} - test "Unicode display cells map back to body and tag byte cursors" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); @@ -3272,47 +3157,6 @@ pub fn hit(key: Key, binding: []const config.Chord) bool { pub const sel_slot = @intFromEnum(config.select_button); -fn isPrefix(key: Key, cp: u21) bool { - return key.cp == cp and !key.ctrl and !key.alt; -} -fn roleBindingName(comptime role: modal.Normal.Role) []const u8 { - return switch (role) { - .prefix_goto => "goto_prefix", - .prefix_view => "view_prefix", - .prefix_match => "match_prefix", - .prefix_find_fwd => "find_char_fwd", - .prefix_find_back => "find_char_back", - .prefix_till_fwd => "till_char_fwd", - .prefix_till_back => "till_char_back", - .prefix_replace => "replace_prefix", - .prefix_next => "next_prefix", - .prefix_prev => "prev_prefix", - else => @tagName(role), - }; -} - -fn normalInput(key: Key) modal.Normal.Input { - var out: modal.Normal.Input = .{ - .cp = key.cp, - .ctrl = key.ctrl, - .alt = key.alt, - }; - inline for (std.enums.values(modal.Normal.Role)) |role| { - const name = comptime roleBindingName(role); - if (!@hasDecl(config, name)) - @compileError("normal input role has no config binding: " ++ name); - const binding = @field(config, name); - const matched = if (@TypeOf(binding) == comptime_int) - isPrefix(key, binding) - else if (@TypeOf(binding) == []const config.Chord) - hit(key, binding) - else - @compileError("normal input binding has unsupported type: " ++ name); - if (matched) out.roles.insert(role); - } - return out; -} - /// Pixel dimensions are meaningful only to the native PDF placement path. /// Keep resize events layout-only when that path is not part of the build. pub const CellPixels = if (pdf_enabled) struct { @@ -5694,12 +5538,6 @@ pub const Pardes = struct { } } - fn multiOnce(p: *Pardes) bool { - if (!p.multi_on) return true; - p.multi_stop = true; - return p.multi_first; - } - // ---- tag + selection text (chord sources) ---- pub fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 { @@ -6573,8 +6411,8 @@ pub const Pardes = struct { .search => |at| { if (submit) p.submitSearch(p.active) - else if (selRegexArmed(pane)) |_| - p.applySelRegex(pane, "", false); + else if (normal.selRegexArmed(pane)) |_| + normal.applySelRegex(p, pane, "", false); pane.tag_tail_len = @min(at, pane.tag_tail_len); }, .none, .del_side => unreachable, @@ -6587,7 +6425,7 @@ pub const Pardes = struct { if (pane.tag_edit) { if (pane.mode == .normal) p.tagNormalKey(pane, key) else p.tagInsertKey(pane, key); const pn = p.panes[p.active] orelse return; - if (selRegexArmed(pn)) |a| p.applySelRegex(pn, a.pat, a.split); + if (normal.selRegexArmed(pn)) |a| normal.applySelRegex(p, pn, a.pat, a.split); return; } if (pane.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { @@ -6610,10 +6448,10 @@ pub const Pardes = struct { p.runBuiltin(cmd, p.active, "", word); return; } - if (pane.mode == .normal and pane.hasPdf()) return p.handlePdfNormal(pane, key); + if (pane.mode == .normal and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); switch (pane.mode) { .normal => { - p.handleNormal(pane, key); + normal.handleNormal(p, pane, key); }, .insert => { if (hit(key, config.escape)) return edit.exitInsert(p, pane); @@ -6651,501 +6489,6 @@ pub const Pardes = struct { // ---- helix-modal normal mode ---- - fn startSelRegex(p: *Pardes, pane: *Pane, split: bool) void { - const text = edit.flatSurface(p, pane) catch return; - const got = pane.ranges(text, 0, &pane.sel_snap); - pane.nsel_snap = @intCast(got.n); - pane.sel_snap_pri = @intCast(got.pri); - pane.sel_snap_expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; - p.startPrompt(pane, .{ .search = if (split) config.split_marker else config.select_marker }); - } - - pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } { - const prompt_at = switch (pane.prompt) { - .search => |at| at, - else => return null, - }; - if (pane.nsel_snap == 0) return null; - const tail = pane.tagSlice(); - const armed = tail[@min(prompt_at, tail.len)..]; - const split = std.mem.startsWith(u8, armed, config.split_marker); - if (!split and !std.mem.startsWith(u8, armed, config.select_marker)) return null; - const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return null; - return .{ .pat = armed[slash + 1 ..], .split = split }; - } - - pub fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void { - const text = edit.flatSurface(p, pane) catch return; - const snap = pane.sel_snap[0..pane.nsel_snap]; - var out: [Pane.max_selections]modal.Selection = undefined; - var m: usize = 0; - if (pat.len > 0) if (mvzr.compile(pat)) |re| { - var hay_all = text; - if (for (pat) |c| { - if (std.ascii.isUpper(c)) break false; - } else true) { - const low = p.scratch.allocator().dupe(u8, text) catch return; - for (low) |*c| c.* = std.ascii.toLower(c.*); - hay_all = low; - } - for (snap) |r| { - const from = @min(r.anchor, r.head); - const to = @min(@max(r.anchor, r.head), text.len); - if (from >= to) continue; - const hay = hay_all[from..to]; - var at: usize = 0; - var piece = from; // split: where the next piece begins - while (at < hay.len and m < Pane.max_selections) { - const hit_at = re.matchPos(at, hay) orelse break; - if (split) { - out[m] = .{ .anchor = piece, .head = from + hit_at.start }; - m += 1; - piece = from + hit_at.end; - } else if (from + hit_at.start != to) { - out[m] = .{ .anchor = from + hit_at.start, .head = from + hit_at.end }; - m += 1; - } - // an empty match would otherwise never advance - at = if (hit_at.end > hit_at.start) hit_at.end else hit_at.end + 1; - } - if (split and piece < to and m < Pane.max_selections) { - out[m] = .{ .anchor = piece, .head = to }; - m += 1; - } - } - }; - if (m == 0) { - // the text CAN move under an armed prompt (a tag chord runs a - // builtin), and these are raw offsets into the surface as it was - for (snap) |*r| { - r.anchor = @min(r.anchor, text.len); - r.head = @min(r.head, text.len); - } - return pane.setRanges(text, snap, &.{}, pane.sel_snap_pri, pane.sel_snap_expl); - } - pane.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) - } - - const KeyState = struct { - mode: Pane.Mode, - select: bool, - normal: modal.Normal.State, - find_op: u8, - find_ch: u21, - append_at: @FieldType(Pane, "append_at"), - - fn of(pane: *Pane) KeyState { - return .{ - .mode = pane.mode, - .select = pane.select, - .normal = pane.normal, - .find_op = pane.find_op, - .find_ch = pane.find_ch, - .append_at = pane.append_at, - }; - } - - fn into(s: KeyState, pane: *Pane) void { - pane.mode = s.mode; - pane.select = s.select; - pane.normal = s.normal; - pane.find_op = s.find_op; - pane.find_ch = s.find_ch; - pane.append_at = s.append_at; - } - }; - - /// what a replayed key does at each cursor - const Replay = union(enum) { - normal: modal.Normal.Action, - insert: Key, - }; - - pub fn replaySels(p: *Pardes, pane: *Pane, what: Replay) void { - const id = p.active; - const serial = pane.serial; - // the whole selection in pane coordinates, document order. pane.sels - // is already ordered, so this only slots the primary into place. - var list: [Pane.max_selections]Pane.SelRange = undefined; - var n: usize = 0; - var pri: usize = 0; - const prim: Pane.SelRange = .{ - .row = pane.cur_row, - .col = pane.cur_col, - .arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row, - .acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col, - .sticky = pane.sticky_col, - }; - const pr = Pane.selStart(prim); - var placed = false; - for (pane.sels[0..pane.nsel]) |s| { - const sr = Pane.selStart(s); - if (!placed and (pr.row < sr.row or (pr.row == sr.row and pr.col <= sr.col))) { - pri = n; - list[n] = prim; - n += 1; - placed = true; - } - list[n] = s; - n += 1; - } - if (!placed) { - pri = n; - list[n] = prim; - n += 1; - } - - const saved = KeyState.of(pane); - const explicit = pane.vsel.explicit; - var after = saved; - var after_expl = explicit; - // each pass's result: cursor and anchor cells as distances from the - // end of the surface text, plus the range's own j/k goal column - var res: [Pane.max_selections]struct { cur: usize, anc: usize, sticky: i32 } = undefined; - p.multi_on = true; - p.multi_stop = false; - var passes: usize = 0; - var i: usize = n; - while (i > 0) { - i -= 1; - p.multi_first = passes == 0; - passes += 1; - saved.into(pane); - pane.nsel = 0; // the handler underneath sees ONE selection - pane.cur_row = list[i].row; - pane.cur_col = list[i].col; - pane.vsel = .{ - .active = list[i].arow != list[i].row or list[i].acol != list[i].col or pane.select, - .row = list[i].arow, - .col = list[i].acol, - .explicit = explicit, - }; - pane.msel.active = false; - pane.sticky_col = list[i].sticky; - switch (what) { - .normal => |normal_action| p.executeNormalAction(pane, normal_action), - .insert => |insert_key| edit.insertKey(p, pane, insert_key), - } - if (p.multi_stop) break; - if (i == pri) { - after = KeyState.of(pane); - after_expl = pane.vsel.explicit; - } - const text = edit.flatSurface(p, pane) catch { - p.multi_stop = true; - break; - }; - const co = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }); - const ao = if (pane.vsel.active) - modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row)), .col = @intCast(@max(0, pane.vsel.col)) }) - else - co; - res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = pane.sticky_col }; - } - p.multi_on = false; - p.multi_first = false; - if (p.multi_stop) { - p.multi_stop = false; - const pn = p.panes[id] orelse return; - if (pn.serial == serial) pn.nsel = 0; - return; - } - const text = edit.flatSurface(p, pane) catch return; - var rs: [Pane.max_selections]modal.Selection = undefined; - var st: [Pane.max_selections]i32 = undefined; - for (res[0..n], 0..) |r, k| { - rs[k] = Pane.cellOffRange(text, text.len - @min(r.anc, text.len), text.len - @min(r.cur, text.len)); - st[k] = r.sticky; - } - pane.setRanges(text, rs[0..n], st[0..n], pri, after_expl); - after.into(pane); - pane.ensureCursorVisible(); // the view follows the PRIMARY, not the last pass - } - - fn handleNormal(p: *Pardes, pane: *Pane, key: Key) void { - const parsed = modal.Normal.parse(&pane.normal, normalInput(key)); - const semantic = switch (parsed) { - .pending, .ignored, .unbound => return, - .action => |value| value, - }; - if (pane.nsel == 0 or semantic.scope() == .once) - return p.executeNormalAction(pane, semantic); - p.replaySels(pane, .{ .normal = semantic }); - } - - fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) void { - const raw_selection = pane.rawPointerText(pane.sel[sel_slot]) != null; - const before = .{ pane.cur_row, pane.cur_col, pane.vsel, pane.msel, pane.select, pane.nsel, pane.mode }; - defer if (raw_selection and !std.meta.eql(before, .{ pane.cur_row, pane.cur_col, pane.vsel, pane.msel, pane.select, pane.nsel, pane.mode })) { - pane.clearPointerSelection(sel_slot); - pane.sel[sel_slot].state = .none; - }; - if (raw_selection and semantic == .edit and semantic.edit.kind == .yank) return edit.normalYank(p, pane); - edit.pinPaneCursor(p, pane); - const text = edit.flatSurface(p, pane) catch return; - const range = pane.primaryRange(text, 0); - const cur = modal.selectionCursor(text, range); - - switch (semantic) { - .escape => { - pane.select = false; - return p.runBuiltin(.Last, p.active, "", null); - }, - .goto => |go| switch (go.target) { - .file_start => { - const line = if (go.explicit_count) @min(@as(usize, go.count) - 1, Pane.maxLine(text)) else 0; - return pane.pointMove(text, range, modal.lineStartOffset(text, line)); - }, - .last_line => return pane.pointMove(text, range, modal.lineStartOffset(text, Pane.maxLine(text))), - .line_start => return pane.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), - .line_end => { - const line = modal.lineAtOffset(text, cur); - const ls = modal.lineStartOffset(text, line); - return pane.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); - }, - .first_nonws => { - const line = modal.lineAtOffset(text, cur); - const ls = modal.lineStartOffset(text, line); - const slice = text[ls..modal.lineEndOffset(text, line)]; - const nw = modal.firstNonWs(slice); - if (nw == slice.len) return; - return pane.pointMove(text, range, ls + nw); - }, - .line_down => return pane.visualMove(text, range, true, go.count, edit.paneWrapWidth(p, pane)), - .line_up => return pane.visualMove(text, range, false, go.count, edit.paneWrapWidth(p, pane)), - .column => { - const line = modal.lineAtOffset(text, cur); - const ls = modal.lineStartOffset(text, line); - const slice = text[ls..modal.lineEndOffset(text, line)]; - return pane.pointMove(text, range, ls + modal.graphemeAtColumn(slice, @as(usize, go.count) - 1)); - }, - .view_top => return pane.gotoWindow(text, range, .top, go.count), - .view_center => return pane.gotoWindow(text, range, .center, go.count), - .view_bottom => return pane.gotoWindow(text, range, .bottom, go.count), - }, - .view => |view| switch (view) { - .top => { - pane.scrollBy(pane.cur_row - pane.scroll()); - pane.ensureCursorVisible(); - }, - .center => { - pane.scrollBy(pane.cur_row - (pane.scroll() + @divTrunc(@as(i32, pane.rows), 2) - 1)); - pane.ensureCursorVisible(); - }, - .bottom => { - pane.scrollBy(pane.cur_row - (pane.scroll() + @as(i32, pane.rows) - 1)); - pane.ensureCursorVisible(); - }, - .scroll_down => return pane.scrollViewMove(text, range, 1), - .scroll_up => return pane.scrollViewMove(text, range, -1), - }, - .find => |find| { - const op: u8 = switch (find.kind) { - .forward => @intCast(config.find_char_fwd), - .backward => @intCast(config.find_char_back), - .till_forward => @intCast(config.till_char_fwd), - .till_backward => @intCast(config.till_char_back), - }; - pane.find_op = op; - pane.find_ch = find.char; - return pane.findMove( - text, - range, - find.char, - find.kind == .forward or find.kind == .till_forward, - find.kind == .till_forward or find.kind == .till_backward, - find.count, - ); - }, - .replace_char => |char| return edit.normalReplaceChar(p, pane, char), - .match_bracket => { - const lines = edit.paneCursorLines(p, pane) catch return; - const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; - return pane.pointMove(text, range, modal.offsetAt(text, mc)); - }, - .textobject => |object| return edit.textobjectSelect(p, pane, text, object.char, object.around), - .surround_add => |char| return edit.surroundAdd(p, pane, char), - .surround_delete => |char| return edit.surroundDelete(p, pane, char), - .surround_replace => |replace| return edit.surroundReplace(p, pane, replace.from, replace.to), - .paragraph => |paragraph| { - const r2 = modal.moveParagraph(text, range, paragraph.count, paragraph.direction == .forward, pane.select); - return pane.setRange(text, 0, r2, false); - }, - .add_newline => |newline| return edit.addNewline(p, pane, newline.direction == .forward, newline.count), - .diagnostic => |diagnostic| { - const fwd = diagnostic.direction == .forward; - if (!diagnostic.endpoint) { - if (panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics }) and - p.searchStep(p.active, if (fwd) 1 else -1)) return; - return p.lspRequest(p.active, .diagnostics, ""); - } - if (!panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics })) - return p.lspRequest(p.active, .diagnostics, ""); - if (!fwd) { - pane.search_row = null; - _ = p.searchStep(p.active, 1); - return; - } - const rp = p.panes[pane.search_pane orelse return] orelse return; - const rf = rp.file orelse return; - pane.search_row = std.mem.count(u8, rf.content, "\n"); - _ = p.searchStep(p.active, -1); - }, - .move => |move| switch (move.motion) { - .left => { - var target = cur; - for (0..move.count) |_| target = modal.prevGrapheme(text, target); - return pane.pointMove(text, range, target); - }, - .right => { - var target = cur; - for (0..move.count) |_| target = modal.nextGrapheme(text, target); - return pane.pointMove(text, range, target); - }, - .down => return pane.verticalMove(text, range, true, move.count), - .up => return pane.verticalMove(text, range, false, move.count), - .next_word_start => return pane.wordMove(text, range, move.count, .next_word_start), - .prev_word_start => return pane.wordMove(text, range, move.count, .prev_word_start), - .next_word_end => return pane.wordMove(text, range, move.count, .next_word_end), - .next_long_word_start => return pane.wordMove(text, range, move.count, .next_long_word_start), - .prev_long_word_start => return pane.wordMove(text, range, move.count, .prev_long_word_start), - .next_long_word_end => return pane.wordMove(text, range, move.count, .next_long_word_end), - }, - .repeat_find => |count| { - if (pane.find_op == 0) return; - const fwd = pane.find_op == config.find_char_fwd or pane.find_op == config.till_char_fwd; - const till = pane.find_op == config.till_char_fwd or pane.find_op == config.till_char_back; - var repeated = range; - var moved = false; - for (0..count) |_| { - const cc = modal.selectionCursor(text, repeated); - const target = modal.findTarget(text, cc, pane.find_ch, fwd, till, 1) orelse break; - repeated = if (pane.select) - modal.moveSelectionCursor(text, repeated, target, true) - else - modal.moveSelectionCursor(text, .{ .anchor = cc, .head = cc }, target, true); - moved = true; - } - if (!moved) return; - return pane.setRange(text, 0, repeated, false); - }, - .line => |line_kind| switch (line_kind) { - .start => return pane.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), - .end => { - const line = modal.lineAtOffset(text, cur); - const ls = modal.lineStartOffset(text, line); - return pane.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); - }, - .first_nonws => { - const line = modal.lineAtOffset(text, cur); - const ls = modal.lineStartOffset(text, line); - const slice = text[ls..modal.lineEndOffset(text, line)]; - const nw = modal.firstNonWs(slice); - if (nw == slice.len) return; - return pane.pointMove(text, range, ls + nw); - }, - }, - .goto_line => |go| { - if (!go.explicit) return; - const line = @min(@as(usize, go.count) - 1, Pane.maxLine(text)); - return pane.pointMove(text, range, modal.lineStartOffset(text, line)); - }, - .page => |page| switch (page.kind) { - // Counts were parsed historically but these four text view - // actions intentionally move exactly one viewport unit. - .half_down => return pane.halfPageMove(text, range, true), - .half_up => return pane.halfPageMove(text, range, false), - .down => return pane.scrollViewMove(text, range, @as(i32, pane.rows)), - .up => return pane.scrollViewMove(text, range, -@as(i32, pane.rows)), - }, - .insert => |insert| { - const where: edit.InsertAt = switch (insert.kind) { - .at => .at, - .append => .append, - .line_start => .line_start, - .line_end => .line_end, - .open_below => .open_below, - .open_above => .open_above, - }; - return edit.enterInsert(p, pane, where, insert.count); - }, - .select => |select| switch (select.kind) { - .mode => { - if (pane.select) { - pane.select = false; - } else { - pane.select = true; - if (pane.msel.active) { - pane.setRange(text, 0, range, true); - } else if (!pane.vsel.active) { - pane.vsel = .{ .active = true, .row = pane.cur_row, .col = pane.cur_col, .explicit = true }; - } else { - pane.vsel.explicit = true; - } - } - pane.cur_pinned = true; - }, - .line => return pane.lineSelect(text, range, select.count), - .line_bounds => return pane.lineBoundsSelect(text, range), - .shrink_to_line_bounds => return pane.shrinkSelToLineBounds(text, range), - .collapse => return pane.setRange(text, 0, .{ .anchor = cur, .head = cur }, false), - .flip => { - const explicit = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; - return pane.setRange(text, 0, .{ .anchor = range.head, .head = range.anchor }, explicit); - }, - .all => return pane.setRange(text, 0, .{ .anchor = 0, .head = text.len }, false), - }, - .multi => |multi| { - if (multi.kind == .keep_primary) { - pane.nsel = 0; - return; - } - return pane.multiSelAction(text, multi.kind, multi.count); - }, - .select_regex => |split| return p.startSelRegex(pane, split), - .edit => |op| switch (op.kind) { - .delete => return edit.normalDelete(p, pane, true), - .delete_noyank => return edit.normalDelete(p, pane, false), - .change => return edit.normalChange(p, pane), - .yank => return edit.normalYank(p, pane), - .replace_with_yank => return edit.normalReplaceYank(p, pane), - .paste_after => return edit.pasteText(p, pane, p.yank orelse return, false, op.count), - .paste_before => return edit.pasteText(p, pane, p.yank orelse return, true, op.count), - .switch_case => return edit.normalCase(p, pane, .toggle), - .lowercase => return edit.normalCase(p, pane, .lower), - .uppercase => return edit.normalCase(p, pane, .upper), - .join_lines => return edit.normalJoin(p, pane), - .indent => return edit.normalIndent(p, pane, op.count, true), - .unindent => return edit.normalIndent(p, pane, op.count, false), - .comment_toggle => return edit.normalToggleComment(p, pane), - .undo => return edit.doUndo(p, pane), - .redo => return edit.doRedo(p, pane), - }, - .lsp => |request| return p.lspRequest(p.active, switch (request) { - .definition => .definition, - .declaration => .declaration, - .type_definition => .type_definition, - .implementation => .implementation, - .references => .references, - .format => .format, - }, ""), - .adjust_number => |delta| return edit.normalAdjustNumber(p, pane, delta), - .leader => { - p.leader_on = true; - p.leader_n = 0; - }, - .command_line => { - p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.mode = .normal; - }, - .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), - .search => return p.startPrompt(pane, .{ .search = config.search_marker }), - .search_step => |direction| return p.lookWalk( - if (direction == .forward) @as(i32, 1) else -1, - ), - } - } - // ---- selection pipe (`|`): visible prompt, async shell, atomic edit ---- // ---- search (`/`, Find, n/N): results into an output buffer, look the rows ---- @@ -7279,7 +6622,7 @@ pub const Pardes = struct { fn submitSearch(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; - if (selRegexArmed(pane)) |a| return p.applySelRegex(pane, a.pat, a.split); + if (normal.selRegexArmed(pane)) |a| return normal.applySelRegex(p, pane, a.pat, a.split); const armed = pane.promptText() orelse return; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return; if (std.mem.startsWith(u8, armed, config.rename_marker)) return p.lspRequest(id, .rename, armed[slash + 1 ..]); @@ -7400,7 +6743,7 @@ pub const Pardes = struct { try panes.Output.fillResults(p, id, dir, from, pat, content, anchor); } - fn searchStep(p: *Pardes, id: usize, delta: i32) bool { + pub fn searchStep(p: *Pardes, id: usize, delta: i32) bool { const pane = p.panes[id] orelse return false; const rid = pane.search_pane orelse return false; const rp = p.panes[rid] orelse return false; @@ -7477,7 +6820,7 @@ pub const Pardes = struct { } pub fn lspRequest(p: *Pardes, id: usize, kind: lsp.Kind, arg: []const u8) void { - if (!p.multiOnce()) return; // one question per keystroke, from the primary + if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary if (!lsp.supports.contains(kind)) return; const pane = p.panes[id] orelse return; if (kind != .status) { @@ -7803,7 +7146,7 @@ pub const Pardes = struct { return null; } - fn lookWalk(p: *Pardes, delta: i32) void { + pub fn lookWalk(p: *Pardes, delta: i32) void { var buf: [MAX_PANES]usize = undefined; const order = p.lookWalkPanes(&buf); if (order.len == 0) return; @@ -8976,50 +8319,6 @@ pub const Pardes = struct { return pane; } - fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { - if (comptime !pdf_enabled) return; - if (pane.pdf == null) return; - if (hit(key, config.leave_pane)) { - pane.normal.clear(); - pane.select = false; - return p.runBuiltin(.Last, p.active, "", null); - } - if (pane.normal.prefix == .none and isPrefix(key, 'f')) { - pane.normal.clear(); - return p.runBuiltin(.PdfSections, p.active, "", null); - } - const parsed = modal.Normal.parse(&pane.normal, normalInput(key)); - switch (parsed) { - .pending, .ignored, .unbound => {}, - .action => |semantic| { - const result = panes.Pdf.applyNormal( - &pane.pdf.?, - p.pdf_gpa, - semantic, - p.native_images, - .{ .w = p.cell_pixels.w, .h = p.cell_pixels.h }, - panes.Pdf.paneViewport(p, pane), - panes.Pdf.paneGeometry(p, pane), - ); - if (result.page_changed) panes.Pdf.resetPageChrome(pane); - switch (result.host) { - .none => {}, - .leader => { - p.leader_on = true; - p.leader_n = 0; - }, - .command_line => { - p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.mode = .normal; - }, - .search => p.startPrompt(pane, .{ .search = config.search_marker }), - .search_forward => p.lookWalk(1), - .search_backward => p.lookWalk(-1), - } - }, - } - } - // ---- the ONE dispatcher: look (right/Enter) and execute (middle/Tab) ---- pub fn focusPaneLine(p: *Pardes, id: usize, at: look.Spot, landing: enum { center, keep }) void { @@ -9358,8 +8657,8 @@ pub const Pardes = struct { while (lines.next()) |line| _ = p.executeBuiltinLine(p.active, line); } - fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8) void { - if (!p.multiOnce()) return; // a builtin is per-keystroke, never per-cursor + pub fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8) void { + if (!normal.multiOnce(p)) return; // a builtin is per-keystroke, never per-cursor const pane = p.panes[id] orelse return; // A builtin says its own name before it runs, so a tagline click is // legible even when what it did is invisible. Whatever the builtin diff --git a/test/lspbench.zig b/test/lspbench.zig index 7c4e8753..36969680 100644 --- a/test/lspbench.zig +++ b/test/lspbench.zig @@ -41,7 +41,7 @@ const anchors = [_]Anchor{ .{ .file = "test/lspfixture/broken.zig", .needle = "unused_local", .at = 0, .kind = .workspace_diagnostics, .expect = "broken.zig" }, .{ .file = "src/lsp/lsp.zig", .needle = "std.mem.count(u8", .at = 4, .kind = .completion, .expect = "std.zig" }, .{ .file = "src/lsp/lsp_zls.zig", .needle = ".declaration => try rowForToken", .at = 1, .kind = .completion, .expect = "type_definition" }, - .{ .file = "src/pardes.zig", .needle = ".definition => .definition,", .at = 1, .kind = .completion, .expect = "" }, + .{ .file = "src/normal.zig", .needle = ".definition => .definition,", .at = 1, .kind = .completion, .expect = "" }, // The repeated name proves the result includes the declaration, not just the cursor line. .{ .file = "test/lspfixture/dotcomplete.zig", .needle = "return switch (s) {\n .", .at = 29, .kind = .completion, .expect = "verdigris verdigris," }, // Indentation keeps the fixture header from becoming the first needle match. -- cgit v1.3 From 9660151c94e988620c79b40a0326057b9854c081 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 22:16:35 -0300 Subject: Move the mouse out of pardes.zig into mouse.zig Pure move, no behaviour change: handleMouse with dragUpdate, dragRelease, seamIdxAt, reportGesture, gestureRange, dispatchPointerBuiltin, mirrorTtySelection and chordCutPaste, the pointer hit helpers (bodyHitForPane, sameTagCell, tagColumn, sameBodyCell), chromeTarget with ChromeTarget, paneAt, the Drag state type with clampBorderCol/Row, the seam test fixtures and thirteen pointer and drag tests go verbatim to mouse.zig. The methods become free functions taking `p: *Pardes`; their 36 call sites change from `p.handleMouse(..)` to `mouse.handleMouse(p, ..)`, including web.zig's chromeTarget and macos.zig's paneAt. The Mouse event type stays in pardes.zig with the rest of the event vocabulary. Co-Authored-By: Claude Opus 5.5 --- src/edit.zig | 5 +- src/fs.zig | 1 + src/macos.zig | 3 +- src/mouse.zig | 1428 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/pardes.zig | 1447 +------------------------------------------------------- src/web.zig | 3 +- 6 files changed, 1462 insertions(+), 1425 deletions(-) create mode 100644 src/mouse.zig (limited to 'src/fs.zig') diff --git a/src/edit.zig b/src/edit.zig index f829decc..04416b67 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -3,6 +3,7 @@ //! operations, replace, case, join, indent, comments, numbers, textobjects //! and surround, undo, yank and paste, and the pointer selections as text. const pardes = @import("pardes.zig"); +const mouse = @import("mouse.zig"); const normal = @import("normal.zig"); const std = @import("std"); const modal = @import("modal.zig"); @@ -1533,12 +1534,12 @@ pub fn pointerTextSelection(p: *const Pardes, id: usize, col: u16, row: u16, bod if (!on_tag and row >= body_y and row - body_y < p.panes[id].?.notices.span() and p.panes[id].?.notices.covers(row - body_y, col)) return null; if (!on_tag) if (body_hit) |supplied| { - const mapped_hit = p.bodyHitForPane(id, supplied, false) orelse return null; + const mapped_hit = mouse.bodyHitForPane(p, id, supplied, false) orelse return null; const c = @as(i32, mapped_hit.col) - config.GUTTER; const v = @as(i32, mapped_hit.row) + BOX_H; return .{ .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, .on_tag = false }; }; - const tag_col = if (on_tag) p.tagColumn(.pane, id, tag_hit, false) else null; + const tag_col = if (on_tag) mouse.tagColumn(p, .pane, id, tag_hit, false) else null; const c: i32 = (if (tag_col) |value| @as(i32, value) else @as(i32, col) - @as(i32, r.x + (if (on_tag) TAG_TEXT_INSET else config.GUTTER))) + (if (on_tag) @as(i32, p.panes[id].?.tag_scroll) else 0); const v: i32 = if (on_tag) 0 else @as(i32, row) - @as(i32, body_y) + @as(i32, BOX_H); diff --git a/src/fs.zig b/src/fs.zig index 5fbd3cd8..13fce858 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -42,6 +42,7 @@ const source_files = [_]Source{ .{ .path = "src/body_layer.zig", .contents = @embedFile("body_layer.zig") }, .{ .path = "src/edit.zig", .contents = @embedFile("edit.zig") }, .{ .path = "src/normal.zig", .contents = @embedFile("normal.zig") }, + .{ .path = "src/mouse.zig", .contents = @embedFile("mouse.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/macos.zig b/src/macos.zig index cab8212a..f83fb8b4 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -6,6 +6,7 @@ const builtin = @import("builtin"); const posix = std.posix; const libc = std.c; const pardes = @import("pardes.zig"); +const mouse = @import("mouse.zig"); const colors = @import("colors.zig"); const look = @import("look.zig"); const message = pardes.Messages.Message; @@ -2623,7 +2624,7 @@ const Spent = struct { }; fn spendScroll(st: *State, delta_rows: f32, delta_cols: f32, col: u16, row: u16) Spent { - const pane = if (st.core.paneAt(col, row)) |id| st.core.panes[id] else null; + const pane = if (mouse.paneAt(st.core, col, row)) |id| st.core.panes[id] else null; var out: Spent = .{}; var down_left = takeScrollTicks(&st.scroll_lag, delta_rows); while (down_left != 0) { diff --git a/src/mouse.zig b/src/mouse.zig new file mode 100644 index 00000000..7ce95302 --- /dev/null +++ b/src/mouse.zig @@ -0,0 +1,1428 @@ +//! The mouse: what a pointer is over, the three buttons' presses, drags and +//! releases (acme's chords, border and seam drags, gestures), and the +//! chrome targets a shell asks about. +const pardes = @import("pardes.zig"); +const std = @import("std"); +const layout = @import("layout.zig"); +const modal = @import("modal.zig"); +const ctlfs = @import("ninep/tree.zig"); +const panes = @import("panes.zig"); +const edit = @import("edit.zig"); +const body_layer = @import("body_layer.zig"); +const PanelCellDiff = @import("surface.zig").PanelCellDiff; +const builtins = @import("builtins.zig"); +const config = @import("config.zig"); +const pdf_enabled = panes.Pdf.enabled; +const pdf = panes.Pdf.pdf; +const platform = pardes.platform; +const Pane = panes.Pane; +const MAX_PANES = pardes.MAX_PANES; +const TagHit = @import("tag_layer.zig").Hit; +const TagKind = @import("tag_layer.zig").Kind; +const TOPBAR_H = pardes.TOPBAR_H; +const BOX_H = pardes.BOX_H; +const TAG_GAP = pardes.TAG_GAP; +const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; +const Builtin = pardes.Builtin; +const wordAtCol = pardes.wordAtCol; +const Mouse = pardes.Mouse; +const sel_slot = pardes.sel_slot; +const Pardes = pardes.Pardes; + +pub const Drag = union(enum) { + none, + border_v: struct { left_col: usize, cur_x: u16, corner: ?struct { col: usize, idx: usize } = null, cur_y: u16 = 0 }, + border_h: struct { col: usize, top_idx: usize, cur_y: u16 }, + move: struct { id: usize, cur_x: u16, cur_y: u16 }, + /// `grab`: how far into the grip it was pressed, so the column's left + /// edge lands at `cur_x - grab`. A release still on the grip moves nothing. + column_move: struct { serial: u32, cur_x: u16, grab: u16 = 0 }, + tag: struct { id: usize }, + /// chorded: a 1-2/1-3 cut/paste chord fired during this left drag — + /// the drag's own release is then inert + select: struct { + id: usize, + button: Mouse.Button, + chorded: bool = false, + ctrl: bool = false, + /// This gesture began over a usable native PDF raster. The payload is + /// zero-bit when PDF support is absent. + pdf: panes.Pdf.PointerDrag = .{}, + }, + + fn button(drag: Drag) ?Mouse.Button { + return switch (drag) { + .none => null, + .border_v, .border_h, .move, .column_move, .tag => config.select_button, + .select => |selection| selection.button, + }; + } +}; + +fn clampBorderCol(lx: u16, lw: u16, rw: u16, mcol: u16) u16 { + const lo = lx + config.MINW; + const hi = lx +| lw +| rw -| config.MINW; + return if (lo <= hi) std.math.clamp(mcol, lo, hi) else mcol; +} + +fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16, tag_bottom: bool) u16 { + const d: u16 = if (tag_bottom) 1 else 0; + const lo = ay + BOX_H - 1 + d; + const hi = (ay +| ah +| bh -| (BOX_H + 1)) +| d; + return if (lo <= hi) std.math.clamp(mrow, lo, hi) else mrow; +} + +fn seamRowOf(p: *const Pardes, c: usize, k: usize) u16 { + const r = p.rects[p.col_panes[c][k]]; + return if (p.settings.tag_bottom) r.y +| r.h else 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.active = p.col_panes[1][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.col_x[1] + p.col_w[1] / 2; + const to: u16 = @intCast(@as(i32, from) + delta); + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = inside, .row = from } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = inside, .row = to } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = inside, .row = to } }); + p.sync(); + return seamRowOf(p, 1, 0); +} + +pub const ChromeTarget = struct { col: u16, row: u16 }; + +pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { + if (row < p.topBarHeight() + p.columnBarHeight()) return .{ .col = col, .row = row }; + for (p.panes, 0..) |slot, id| { + if (slot == null) continue; + const rect = p.rects[id]; + const tag = if (p.settings.tag_bottom) rect.y + rect.h -| BOX_H else rect.y; + if (row == tag and col >= rect.x and col < rect.x + rect.w and col < rect.x + config.GUTTER) + return .{ .col = col, .row = tag }; + } + for (0..p.ncol -| 1) |column| { + const handle = p.col_x[column] + p.col_w[column] -| 1; + if (col == handle) return .{ .col = handle, .row = row }; + } + for (0..p.ncol) |column| { + if (col < p.col_x[column] or col >= p.col_x[column] + p.col_w[column]) continue; + for (0..p.col_n[column] -| 1) |index| { + const rect = p.rects[p.col_panes[column][index]]; + const handle = if (p.settings.tag_bottom) rect.y +| rect.h else rect.y + rect.h -| 1; + if (row == handle) return .{ .col = col, .row = handle }; + } + } + for (p.panes, 0..) |slot, id| { + if (slot == null) continue; + const rect = p.rects[id]; + const tag = if (p.settings.tag_bottom) rect.y + rect.h -| BOX_H else rect.y; + if (row == tag and col >= rect.x and col < rect.x + rect.w) + return .{ .col = col, .row = tag }; + } + for (0..p.ncol -| 1) |column| { + const handle = p.col_x[column] + p.col_w[column] -| 1; + if (@max(col, handle) - @min(col, handle) == 1) return .{ .col = handle, .row = row }; + } + for (0..p.ncol) |column| { + if (col < p.col_x[column] or col >= p.col_x[column] + p.col_w[column]) continue; + for (0..p.col_n[column] -| 1) |index| { + const rect = p.rects[p.col_panes[column][index]]; + const handle = if (p.settings.tag_bottom) rect.y +| rect.h else rect.y + rect.h -| 1; + if (@max(row, handle) - @min(row, handle) == 1) return .{ .col = col, .row = handle }; + } + } + return null; +} + +pub fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { + for (p.panes, 0..) |slot, id| { + if (slot == null) continue; + const r = p.rects[id]; + if (col >= r.x and col < r.x + r.w and row >= r.y and row < r.y + r.h) return id; + } + return null; +} + +pub fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clamp: bool) ?Mouse.BodyHit { + const pane = p.panes[id] orelse return null; + if (pane.file == null or (!clamp and supplied.serial != pane.serial)) return null; + if (!std.math.isFinite(supplied.pixel_x) or !std.math.isFinite(supplied.pixel_y) or + supplied.metrics.body_w == 0 or supplied.metrics.body_h == 0 or + supplied.metrics.tagline_w == 0 or supplied.metrics.tagline_h == 0) return null; + var mapped_hit = supplied; + if (clamp) { + mapped_hit.serial = pane.serial; + const layer = for (&p.surface.body_layers) |*layer| { + if (layer.rows > 0 and layer.serial == pane.serial) break layer; + } else return null; + const bw: f32 = @floatFromInt(mapped_hit.metrics.body_w); + const bh: f32 = @floatFromInt(mapped_hit.metrics.body_h); + const x0 = @as(f32, @floatFromInt(layer.viewport.x)) * bw; + const y0 = @as(f32, @floatFromInt(layer.viewport.y)) * bh; + const x1 = x0 + @as(f32, @floatFromInt(layer.viewport.w)) * bw; + const y1 = y0 + @as(f32, @floatFromInt(layer.viewport.h)) * bh; + mapped_hit.pixel_x = std.math.clamp(mapped_hit.pixel_x, x0, @max(x0, x1 - 0.001)); + mapped_hit.pixel_y = std.math.clamp(mapped_hit.pixel_y, y0, @max(y0, y1 - 0.001)); + } + return p.reprojectBodyHit(mapped_hit); +} + +pub fn sameTagCell(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.col == second.col; +} + +pub fn tagColumn(p: *const Pardes, kind: TagKind, id: usize, supplied: ?TagHit, clamp: bool) ?u16 { + var point = supplied orelse return null; + if (point.kind != kind or point.id != id) return null; + if (clamp) for (p.surface.tagLayers()) |*layer| { + if (layer.cols == 0 or layer.kind != kind or layer.id != id or layer.serial != point.serial) continue; + const bw: f32 = @floatFromInt(point.metrics.body_w); + const bh: f32 = @floatFromInt(point.metrics.body_h); + const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; + const right = @as(f32, @floatFromInt(layer.viewport.x + layer.viewport.w)) * bw; + point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); + point.pixel_y = (@as(f32, @floatFromInt(layer.viewport.y)) + 0.5) * bh; + break; + }; + return if (p.reprojectTagHit(point)) |mapped| mapped.col else null; +} + +pub fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { + const first = a orelse return b == null; + const second = b orelse return false; + return first.serial == second.serial and first.row == second.row and first.col == second.col; +} + +pub fn handleMouse(p: *Pardes, m: Mouse) void { + // A click goes somewhere else: the question it leaves unanswered is + // taken back, and the pane stays. A wheel only looks around. + if (m.kind == .press and switch (m.button) { + .left, .middle, .right => true, + else => false, + }) for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.prompt == .del_side) pane.prompt = .none; + }; + if (m.button == .back or m.button == .forward) { + if (m.kind == .press) p.jumpBy(if (m.button == .back) -1 else 1); + return; + } + const raw_col = @min(m.col, p.screen_w -| 1); + const raw_row = @min(m.row, p.screen_h -| 1); + p.pointer_raw_col = raw_col; + p.pointer_raw_row = raw_row; + const previous_hit = p.pointer_body_hit; + p.pointer_body_hit = m.body_hit; + const previous_tag_hit = p.pointer_tag_hit; + p.pointer_tag_hit = if (m.tag_hit) |point| p.reprojectTagHit(point) else null; + if (m.tag_hit != null and p.pointer_tag_hit == null and m.kind == .press) return; + if (m.tag_hit == null and (m.kind == .drag or m.kind == .release) and (p.drag == .tag or p.drag == .select or p.header_drag)) { + if (previous_tag_hit) |previous| { + var continued = previous; + continued.pixel_x = (@as(f32, @floatFromInt(raw_col)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_w)); + continued.pixel_y = (@as(f32, @floatFromInt(raw_row)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_h)); + p.pointer_tag_hit = continued; + } + } + if ((m.kind == .drag or m.kind == .release) and (p.drag == .tag or p.drag == .select or p.header_drag)) { + if (previous_tag_hit) |previous| if (p.pointer_tag_hit) |*current| { + current.kind = previous.kind; + current.id = previous.id; + current.serial = previous.serial; + }; + } + // A drag can leave the compact text viewport. Preserve its metrics so + // the endpoint still clamps to that body's last visible logical row. + if (m.body_hit == null and (m.kind == .drag or m.kind == .release) and p.drag == .select) { + if (previous_hit) |previous| { + var continued = previous; + continued.pixel_x = (@as(f32, @floatFromInt(raw_col)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_w)); + continued.pixel_y = (@as(f32, @floatFromInt(raw_row)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_h)); + p.pointer_body_hit = continued; + } + } + p.pointer_inside = true; + if (m.button == .none and m.kind == .motion) { + p.raw_hover_intent = true; + p.refreshLookHoverFromRaw(); + return; + } + p.raw_hover_intent = false; + const mapped = p.presentation.pointer(p.screen_w, p.screen_h, raw_col, raw_row) orelse { + p.cancelLookHover(); + if (m.kind == .release) dragRelease(p, m.button); + return; + }; + const mcol = mapped.col; + const mrow = mapped.row; + p.hover_col = mcol; + p.hover_row = mrow; + + const hovered = paneAt(p, mcol, mrow); + + // any press that is NOT the execute+select chord abandons a pending + // chord argument + if (m.kind == .press and + !(m.button == config.select_button and p.drag == .select and p.drag.select.button == config.exec_button)) + { + if (p.chord_arg) |a| { + p.gpa.free(a); + p.chord_arg = null; + } + } + if (mrow >= p.topBarHeight() and mrow < p.topBarHeight() + p.columnBarHeight() and m.kind == .press) { + for (0..p.ncol) |column| { + if (mcol < p.col_x[column] or mcol >= p.col_x[column] + @min(config.GUTTER, p.col_w[column])) continue; + if (m.button == config.select_button) { + p.header_drag = false; + p.drag = .{ .column_move = .{ .serial = p.col_serial[column], .cur_x = mcol, .grab = mcol - p.col_x[column] } }; + } + return; + } + } + if (p.header_drag and m.button == config.select_button and (m.kind == .drag or m.kind == .release)) { + const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; + const bar = p.headerText(); + p.topbar_col = @intCast(@min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll))); + if (m.kind == .release) p.header_drag = false; + return; + } + if (mrow < p.topBarHeight() + p.columnBarHeight() and m.kind == .press and + (m.button == config.select_button or m.button == config.exec_button or m.button == config.look_button)) + { + if (m.button == config.select_button) if (p.panes[p.active]) |pane| { + if (pane.tag_edit) Pardes.exitTagEdit(pane); + }; + var column: ?usize = null; + var x: u16 = 0; + if (mrow >= p.topBarHeight()) { + for (0..p.ncol) |c| if (mcol >= p.col_x[c] and mcol < p.col_x[c] + p.col_w[c]) { + column = c; + x = p.col_x[c] + TAG_TEXT_INSET; + if (layout.findPane(p, p.active)) |active_col| { + if (active_col.col != c and p.col_n[c] > 0) p.active = p.col_panes[c][0]; + } + break; + }; + if (column == null or mcol < x) return; + } + if (p.header_column != column) { + p.rememberHeader(); + p.topbar_col = null; + p.header_anchor = null; + p.header_scroll = 0; + } + p.header_column = column; + const bar = p.headerText(); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll)); + if (m.button == config.select_button) { + p.topbar_col = @intCast(at); + p.header_anchor = @intCast(at); + p.header_insert = true; + p.header_drag = true; + } else { + const selected = if (p.topbar_col) |cur| blk: { + const a = p.header_anchor orelse cur; + break :blk if (at >= @min(a, cur) and at < @max(a, cur)) bar[@min(a, cur)..@max(a, cur)] else wordAtCol(bar, at); + } else wordAtCol(bar, at); + const word = p.scratch.allocator().dupe(u8, selected) catch return; + p.exitHeader(); + if (word.len > 0) { + if (m.button == config.exec_button) { + const named = std.meta.stringToEnum(Builtin, word); + const held = if (named) |b| (if (builtins.registry.takesArg(b)) p.heldSelection(p.active) else null) else p.heldSelection(p.active); + _ = p.execute(p.active, p.withArg(word, held)); + } else p.runBuiltin(config.look_cmd, p.active, "", word); + } + } + return; + } + if (m.kind == .press) { + p.exitHeader(); + } + + switch (m.button) { + .none, .back, .forward => {}, // hover and navigation handled above + .wheel_up, .wheel_down => { + if (m.kind != .press) return; + // re-arms the drift guard below; vertical always scrolls, so + // the answer is never in doubt here + _ = config.wheelTick(&p.wheel_guard, true); + const id = hovered orelse return; + const pane = p.panes[id].?; + if (pane.hasPdf()) + panes.Pdf.verticalWheel(p, pane, if (m.button == .wheel_up) -1 else 1) + else + pane.scrollBy(if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows); + }, + .wheel_left, .wheel_right => { + if (m.kind != .press) return; + if (!config.wheelTick(&p.wheel_guard, false)) return; + const id = hovered orelse return; + const pane = p.panes[id].?; + if (pane.hasPdf()) { + panes.Pdf.horizontalWheel(p, pane, if (m.button == .wheel_right) 1 else -1); + // ponytail: no right clamp — overscroll shows blank and the + // next cursor move or left wheel pulls it back + } else if (pane.file != null and !p.settings.wrap) { + // wrapped there is nothing off to the right to reach + const line = panes.File.sourceLine(pane, pane.cur_row); + const visual = panes.File.rawDisplayCol(line, @intCast(@max(0, pane.hscroll))); + const next: usize = if (m.button == .wheel_right) + visual +| @as(usize, @intCast(config.wheel_cols)) + else + visual -| @as(usize, @intCast(config.wheel_cols)); + pane.hscroll = @intCast(panes.File.rawAtDisplay(line, next)); + } + }, + config.select_button => switch (m.kind) { + .press => { + if (p.drag == .select and p.drag.select.button == config.exec_button) { + if (p.heldSelection(p.drag.select.id)) |tx| { + if (p.chord_arg) |old| p.gpa.free(old); + p.chord_arg = p.gpa.dupe(u8, tx) catch null; + } + return; + } + // acme 3-1: a select tap during a LOOK drag cancels the + // look; the rest of the gesture is inert + if (p.drag == .select and p.drag.select.button == config.look_button) { + if (p.panes[p.drag.select.id]) |t| { + t.sel[@intFromEnum(config.look_button)].state = .none; + if (comptime pdf_enabled) + panes.Pdf.pointerCancel(t, p.drag.select.pdf); + } + p.drag = .none; + return; + } + if (hovered) |mid| { + const mr = p.rects[mid]; + const mtag = if (p.settings.tag_bottom) mr.y + mr.h -| BOX_H else mr.y; + if (mcol < mr.x + config.GUTTER and mrow >= mtag and mrow < mtag + BOX_H) { + p.drag = .{ .move = .{ .id = mid, .cur_x = mcol, .cur_y = mrow } }; + return; + } + } + for (0..p.ncol -| 1) |c| { + if (mcol == p.col_x[c] + p.col_w[c] -| 1) { + const corner: @FieldType(@FieldType(Drag, "border_v"), "corner") = if (seamIdxAt(p, c, mrow)) |k| + .{ .col = c, .idx = k } + else if (seamIdxAt(p, c + 1, mrow)) |k| + .{ .col = c + 1, .idx = k } + else + null; + p.drag = .{ .border_v = .{ .left_col = c, .cur_x = mcol, .corner = corner, .cur_y = mrow } }; + return; + } + } + for (0..p.ncol) |cc| { + if (mcol < p.col_x[cc] or mcol >= p.col_x[cc] + p.col_w[cc]) continue; + if (seamIdxAt(p, cc, mrow)) |k| { + p.drag = .{ .border_h = .{ .col = cc, .top_idx = k, .cur_y = mrow } }; + return; + } + } + const id = hovered orelse return; + const r = p.rects[id]; + const pane = p.panes[id] orelse return; + if (id != p.active) if (p.panes[p.active]) |previous| { + if (previous.tag_edit) Pardes.exitTagEdit(previous); + }; + const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; + const body_y = p.bodyTop(r); + if (mcol < r.x + config.GUTTER) { + // gutter scrollbar: a left click scrolls UP to that row + p.active = id; + pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); + } else if (mrow >= tag_y and mrow < tag_y + BOX_H) { + if (mcol < r.x + TAG_TEXT_INSET) return; + p.active = id; + p.enterTagEdit(pane, if (tagColumn(p, .pane, id, p.pointer_tag_hit, false)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, r.x + TAG_TEXT_INSET)); + pane.tag_anchor = pane.tag_col; + p.drag = .{ .tag = .{ .id = id } }; + } else { + p.active = id; + if (pane.tag_edit) Pardes.exitTagEdit(pane); + const pointed = edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit) orelse return; + pane.clearPointerSelection(sel_slot); + pane.sel[sel_slot] = pointed.sel; + p.drag = .{ .select = .{ + .id = id, + .button = config.select_button, + .ctrl = m.ctrl, + .pdf = panes.Pdf.pointerStart( + p, + pane, + config.select_button, + mcol, + mrow, + false, + ), + } }; + } + }, + .drag => dragUpdate(p, mcol, mrow, p.pointer_body_hit), + .release => { + if ((p.pointer_body_hit != null or p.pointer_tag_hit != null or p.drag == .column_move) and p.drag.button() == m.button) dragUpdate(p, mcol, mrow, p.pointer_body_hit); + dragRelease(p, config.select_button); + }, + .motion => {}, + }, + config.exec_button, config.look_button => switch (m.kind) { + .press => { + // acme 1-2 / 1-3: the execute (Cut) or look (Paste) button + // tapped while the select button holds a selection drag + if (p.drag == .select and p.drag.select.button == config.select_button) { + chordCutPaste(p, m.button == config.exec_button); + return; + } + // acme 2-3 / 3-2: tapping the OTHER of execute/look during + // an execute or look drag cancels it (textselect23's mask) + if (p.drag == .select) { + if (p.panes[p.drag.select.id]) |t| { + t.sel[@intFromEnum(p.drag.select.button)].state = .none; + if (comptime pdf_enabled) + panes.Pdf.pointerCancel(t, p.drag.select.pdf); + } + p.drag = .none; + return; + } + const id = hovered orelse return; + const r = p.rects[id]; + const pane = p.panes[id] orelse return; + // the tag row and the body's first, exactly as the select + // arm above derives them + const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; + const body_y = p.bodyTop(r); + const on_tag = mrow >= tag_y and mrow < tag_y + BOX_H; + if (mcol < r.x + config.GUTTER and !on_tag) { + const local = @as(i32, mrow) - @as(i32, body_y); + if (m.button == config.look_button) p.active = id; + pane.scrollBy(if (m.button == config.look_button) local else -local); + } else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit)) |pointed| { + if (m.button == config.look_button) p.active = id; + pane.clearPointerSelection(@intFromEnum(m.button)); + pane.sel[@intFromEnum(m.button)] = pointed.sel; + p.drag = .{ + .select = .{ + .id = id, + .button = m.button, + // A native body gesture stays native even when its + // point later misses a letterbox or selection. + .pdf = panes.Pdf.pointerStart( + p, + pane, + m.button, + mcol, + mrow, + pointed.on_tag, + ), + }, + }; + } + }, + .drag => dragUpdate(p, mcol, mrow, p.pointer_body_hit), + .release => { + if ((p.pointer_body_hit != null or p.pointer_tag_hit != null or p.drag == .column_move) and p.drag.button() == m.button) dragUpdate(p, mcol, mrow, p.pointer_body_hit); + dragRelease(p, m.button); + }, + .motion => {}, + }, + } +} + +/// Index of the pane pair in column `c` whose seam (see seamRowOf) is screen +/// row `mrow`. Out-of-range columns simply have no seam. +pub fn seamIdxAt(p: *const Pardes, c: usize, mrow: u16) ?usize { + if (c >= p.ncol) return null; + for (0..p.col_n[c] -| 1) |k| if (mrow == seamRowOf(p, c, k)) return k; + return null; +} + +pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) void { + switch (p.drag) { + .border_v => |*d| { + const c = d.left_col; + d.cur_x = if (c + 1 < p.ncol) + clampBorderCol(p.col_x[c], p.col_w[c], p.col_w[c + 1], mcol) + else + mcol; + if (d.corner) |k| if (k.idx + 1 < p.col_n[k.col]) { + const a = p.rects[p.col_panes[k.col][k.idx]]; + const b = p.rects[p.col_panes[k.col][k.idx + 1]]; + d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow, p.settings.tag_bottom); + } else { + d.cur_y = mrow; + }; + }, + .border_h => |*d| { + const cc = d.col; + const k = d.top_idx; + if (k + 1 < p.col_n[cc]) { + const a = p.rects[p.col_panes[cc][k]]; + const b = p.rects[p.col_panes[cc][k + 1]]; + d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow, p.settings.tag_bottom); + } else d.cur_y = mrow; + }, + .column_move => |*d| d.cur_x = mcol, + .move => |*d| { + d.cur_x = mcol; + d.cur_y = mrow; + }, + .select => |*s| { + if (p.panes[s.id]) |pane| { + const r = p.rects[s.id]; + const b = @intFromEnum(s.button); + if (pane.body_rows > 0 and pane.sel[b].r0 >= BOX_H) if (body_hit) |supplied| { + const mapped_hit = bodyHitForPane(p, s.id, supplied, true) orelse return; + pane.sel[b].c1 = @as(i32, mapped_hit.col) - config.GUTTER; + pane.sel[b].r1 = @as(i32, mapped_hit.row) + BOX_H; + return; + }; + if (pane.sel[b].r0 < BOX_H) if (tagColumn(p, .pane, s.id, p.pointer_tag_hit, true)) |value| { + pane.sel[b].c1 = @as(i32, value) + pane.tag_scroll; + pane.sel[b].r1 = 0; + return; + }; + pane.sel[b].c1 = @as(i32, mcol) - @as(i32, r.x + config.GUTTER); + // Sel row BOX_H is the body's FIRST row, the same thing + // pointerTextSelection means by it -- so the drag has to + // measure from the body's top, notice bands included, or a + // selection made while a message is up lands rows away + // from the pointer. + const body_y = p.bodyTop(r); + const body_h = r.h -| BOX_H; + pane.sel[b].r1 = if (pane.sel[b].r0 < BOX_H or body_h == 0) + 0 + else + @as(i32, @min(@max(mrow, body_y), body_y + body_h - 1)) - @as(i32, body_y) + @as(i32, BOX_H); + if (pane.sel[b].r1 < BOX_H) pane.sel[b].c1 += @as(i32, pane.tag_scroll) - TAG_GAP; + if (comptime pdf_enabled) + panes.Pdf.pointerUpdate(&s.pdf, p, pane, mcol, mrow); + } + }, + .tag => |d| { + const pane = p.panes[d.id] orelse return; + const c = if (tagColumn(p, .pane, d.id, p.pointer_tag_hit, true)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, p.rects[d.id].x + TAG_TEXT_INSET); + const text = p.tagText(p.scratch.allocator(), pane) catch return; + pane.tag_col = @intCast(@min(text.len, panes.File.rawAtDisplay(text, @as(usize, @intCast(@max(0, c))) + pane.tag_scroll))); + pane.tag_sel = pane.tag_col != pane.tag_anchor; + }, + .none => {}, + } +} + +fn reportGesture( + p: *Pardes, + id: usize, + cmd: Builtin, + text: []const u8, + on_tag: bool, + operand: Pardes.PointerOperand, + chorded: bool, +) bool { + const scripted = p.panes[id] orelse return false; + if (scripted.fs.readers == 0) return false; + const is_look = cmd == config.look_cmd; + const action: ctlfs.events.Action = if (is_look) + (if (on_tag) .tag_look else .body_look) + else + (if (on_tag) .tag_exec else .body_exec); + const named = std.meta.stringToEnum(Builtin, Pardes.commandText(text)) != null; + const range = gestureRange(p, id, text, on_tag, operand); + var flag: u32 = if (named) ctlfs.events.flag_builtin else 0; + if (range.q0 == range.q1 and text.len > 0) flag |= ctlfs.events.flag_expansion; + if (is_look) { + if (!named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= ctlfs.events.flag_filename; + } else if (chorded) flag |= ctlfs.events.flag_chorded; + return ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text); +} + +fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: Pardes.PointerOperand) ctlfs.pane.State.Range { + const pane = p.panes[id] orelse return .{}; + if (on_tag) { + const tag = p.tagText(p.scratch.allocator(), pane) catch return .{}; + const sel = operand.expanded orelse operand.preview orelse return .{}; + const lead = @min(sel.c0, sel.c1); + const at = panes.File.rawAtDisplay(tag, @intCast(@max(0, lead))); + const q0: u32 = @intCast(@min(at, tag.len)); + return .{ .q0 = q0, .q1 = @intCast(@min(q0 + text.len, tag.len)) }; + } + const f = if (pane.file) |*file| file else return .{}; + if (operand.preview) |selection| if (pane.pointerSelection(selection)) |rows| { + if (rows.len == 0) return .{}; + const first = rows[0]; + const last = rows[rows.len - 1]; + const q0 = panes.File.lineStart(p.gpa, f, @intCast(@max(0, first.row))) + + @min(first.lo, panes.File.sourceLine(pane, first.row).len); + const q1 = panes.File.lineStart(p.gpa, f, @intCast(@max(0, last.row))) + + @min(last.hi, panes.File.sourceLine(pane, last.row).len); + // A rectangle may contain disjoint pieces. Such an operand uses + // the event's expansion text instead of inventing a source range. + if (q1 < q0 or !std.mem.eql(u8, f.content[q0..q1], text)) return .{}; + return .{ .q0 = @intCast(q0), .q1 = @intCast(q1) }; + }; + const start: ?modal.Cursor = if (operand.file_word) |w| + .{ .row = @intCast(@max(0, w.row)), .col = @intCast(@max(0, w.lo)) } + else if (operand.expanded orelse operand.preview) |sel| lead: { + // A selection's leading corner in reading order, converted the way + // `pointerOperand` converts the click itself. + const top = @min(sel.r0, sel.r1) - @as(i32, BOX_H); + if (top < 0) break :lead null; + const w = pane.wrapAt(top); + const col = edit.paneByteAtDisplay(p, pane, w.line, w.at, @min(sel.c0, sel.c1) - panes.File.gutterWidth(pane)); + break :lead .{ + .row = @intCast(@max(0, w.line)), + .col = @intCast(@max(0, col)), + }; + } else null; + const cursor = start orelse return .{}; + const q0: u32 = @intCast(@min(modal.offsetAt(f.content, cursor), f.content.len)); + return .{ .q0 = q0, .q1 = @intCast(@min(q0 + text.len, f.content.len)) }; +} + +fn dispatchPointerBuiltin( + p: *Pardes, + id: usize, + cmd: Builtin, + text: ?[]const u8, + gesture: ?struct { on_tag: bool, operand: Pardes.PointerOperand }, +) void { + const arg = p.chord_arg; + p.chord_arg = null; + defer if (arg) |a| p.gpa.free(a); + const operand = text orelse { + if (gesture) |g| _ = reportGesture(p, id, cmd, "", g.on_tag, g.operand, arg != null); + return; + }; + if (gesture) |g| if (reportGesture(p, id, cmd, operand, g.on_tag, g.operand, arg != null)) return; + p.runBuiltin(cmd, id, "", p.withArg(operand, arg)); +} + +fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { + const gesture = pane.sel[sel_slot]; + const rows = pane.pointerSelection(gesture) orelse return; + const text = pane.rawPointerText(gesture) orelse return; + if (rows.len == 0) return; + const endpoint = rows[if (gesture.r1 >= gesture.r0) rows.len - 1 else 0]; + const body = body_layer.bodyText(p, p.scratch.allocator(), pane) catch return; + const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.Terminal.gridOffset(pane)))); + const byte = if (gesture.c1 >= gesture.c0) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; + pane.cur_row = pane.surfRow(endpoint.row); + var shown = std.mem.trimEnd(u8, line[@min(endpoint.prompt_bytes, line.len)..], " \t"); + if (pane.ovl) |overlay| { + const relative = pane.cur_row - overlay.row; + if (relative >= 0 and relative < modal.lineCount(overlay.text)) + shown = modal.lineSlice(overlay.text, @intCast(relative)); + } + pane.cur_col = @intCast(modal.graphemeStart(shown, @min(shown.len, byte -| endpoint.prompt_bytes))); + pane.cur_pinned = true; + pane.msel.active = false; + pane.vsel.active = false; + pane.nsel = 0; + pane.select = false; + pane.append_at = null; + pane.sticky_col = -1; + pane.normal.clear(); + edit.setYank(p, text); +} + +fn dragRelease(p: *Pardes, button: Mouse.Button) void { + // A different button's release belongs to a chord or another host + // stream; only the button which began this gesture may end it. + if (p.drag.button() != button) return; + defer p.drag = .none; + switch (p.drag) { + .border_v => |d| { + const c = d.left_col; + const old_seam = p.col_x[c] + p.col_w[c] -| 1; + // the handle is the left pane's LAST column (inclusive), so + // the new width includes it — a no-drag click changes nothing + if (c + 1 < p.ncol and d.cur_x != old_seam) + layout.setColumnPairWidth(p, c, (d.cur_x + 1) -| p.col_x[c]); + if (d.corner) |k| { + if (d.cur_y != seamRowOf(p, k.col, k.idx)) + layout.applyRowSplit(p, k.col, k.idx, d.cur_y); + } + }, + .border_h => |d| if (d.cur_y != seamRowOf(p, d.col, d.top_idx)) + layout.applyRowSplit(p, d.col, d.top_idx, d.cur_y), + .column_move => |d| if (layout.columnBySerial(p, d.serial)) |column| switch (layout.columnDrop(p, column, d.cur_x, d.grab)) { + .stay => {}, + .reorder => |target| layout.reorderColumn(p, column, target), + .edge => |x| layout.setColumnPairWidth(p, column - 1, x - p.col_x[column - 1]), + }, + .move => |d| { + layout.movePane(p, d.id, d.cur_x, d.cur_y); + if (p.panes[d.id]) |mp| p.stillborn_joiner = mp.serial; + // a file moved into the left column evicts a lone unused shell + if (p.panes[d.id]) |mt| if (mt.file != null) { + if (layout.findPane(p, d.id)) |f| if (f.col == 0) + p.evictLonePristineTty(0, d.id); + }; + }, + .select => |s| { + const pane = p.panes[s.id] orelse return; + if (comptime pdf_enabled) { + if (s.pdf.native) { + var release = panes.Pdf.pointerRelease( + p, + pane, + s.pdf, + s.button, + s.chorded, + ); + defer release.deinit(p.pdf_gpa); + if (release.probe) |*probe| if (probe.link != null) { + p.followPdfLink(s.id, probe); + return; + }; + // A native PDF page has no byte offsets of its own to + // report, so a scripted pane cannot intercept this one. + if (release.action) |action| dispatchPointerBuiltin( + p, + s.id, + if (action == .look) config.look_cmd else config.exec_cmd, + release.text, + null, + ); + return; + } + } + if (s.chorded) { + // a cut/paste chord consumed this drag; the release is inert + pane.sel[@intFromEnum(s.button)].state = .none; + return; + } + const b = @intFromEnum(s.button); + pane.sel[b].state = .done; + if (s.button == config.select_button) { + const sl = pane.sel[sel_slot]; + const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1; + if (!dragged) pane.sel[sel_slot].state = .none; + if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; + if (dragged and pane.mode == .tty) mirrorTtySelection(p, pane); + const body_vis = sl.r1 - @as(i32, BOX_H); + if (body_vis >= 0 and pane.mode != .tty) { + const w = pane.wrapAt(body_vis); + pane.cur_row = w.line; + pane.cur_col = edit.paneByteAtDisplay( + p, + pane, + w.line, + w.at, + sl.c1 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), + ); + pane.cur_pinned = true; + if (edit.clampFileCursor(pane)) pane.ensureCursorVisible(); + pane.msel.active = false; + pane.normal.clear(); + pane.vsel.active = false; + pane.nsel = 0; // a click says WHERE the one cursor is + pane.select = false; + pane.append_at = null; + pane.sticky_col = -1; + if (s.ctrl) p.lspRequest(s.id, .definition, ""); + } + } else { + const clk = pane.sel[b]; + // A right-click on a line NUMBER looks at that line of + // this file -- a sticky context header's number included, + // since the row map holds each header's own source line. + if (s.button == config.look_button and clk.r0 >= BOX_H and clk.r0 == clk.r1 and + clk.c0 == clk.c1 and clk.c0 >= 0 and pane.mode != .tty) + if (pane.file) |f| if (f.output == null and clk.c0 < panes.File.gutterWidth(pane)) { + const line = pane.wrapAt(clk.r0 - BOX_H).line; + if (line >= 0) { + pane.sel[b].state = .none; + var buf: [48]u8 = undefined; + const target = std.fmt.bufPrint(&buf, "@p{d}:{d}", .{ s.id, @as(usize, @intCast(line)) + 1 }) catch return; + p.runBuiltin(config.look_cmd, s.id, "", target); + return; + } + }; + var operand = p.pointerOperand(pane, clk); + if (operand.expanded) |expanded| + pane.sel[b] = expanded + else if (operand.text == null) + pane.sel[b].state = .none; + if (s.button == config.look_button and clk.r0 >= BOX_H and pane.mode != .tty) { + pane.cur_row = operand.row; + pane.cur_col = operand.col; + if (edit.clampFileCursor(pane)) pane.ensureCursorVisible(); + } + const txt = operand.text; + const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; + if (clk.r0 < BOX_H and s.button == config.exec_button and pane.tag_name_len != null) { + const prefix_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); + const on_name = @as(usize, @intCast(@max(0, clk.c0))) < prefix_width; + if (!p.commitTagName(pane)) return; + // Executing a staged filename commits it; executing its + // command tail uses the new identity (especially Save). + if (on_name) return; + const new_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); + const shift = @as(i32, @intCast(new_width)) - @as(i32, @intCast(prefix_width)); + if (operand.expanded) |*sel| { + sel.c0 += shift; + sel.c1 += shift; + } + if (operand.preview) |*sel| { + sel.c0 += shift; + sel.c1 += shift; + } + pane.sel[b].c0 += shift; + pane.sel[b].c1 += shift; + } + dispatchPointerBuiltin(p, s.id, cmd, txt, .{ + .on_tag = clk.r0 < BOX_H, + .operand = operand, + }); + } + }, + .tag => {}, // dragUpdate already left the tag cursor + selection set + .none => {}, + } +} + +fn chordCutPaste(p: *Pardes, cut: bool) void { + const s = &p.drag.select; + const pane = p.panes[s.id] orelse return; + if (comptime pdf_enabled) if (pane.pdf) |pv| { + if (!s.chorded) { + s.chorded = true; + pane.sel[sel_slot].state = .none; + } + // A PDF is immutable: its Cut-side chord is Snarf (copy), while + // Paste has no document mutation to perform. + if (cut and pv.selection_text.len > 0) edit.setYank(p, pv.selection_text); + return; + }; + if (pane.mode == .tty) { + if (!s.chorded) { + s.chorded = true; + pane.sel[sel_slot].state = .none; // drop the sweep highlight + } + if (cut) return; + const y = p.yank orelse return; + if (y.len == 0) return; + if (panes.Terminal.reportsMouse(pane)) { + const col: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].c1 + 1, 1, 9999)); + const row: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].r1 - @as(i32, BOX_H) + 1, 1, 9999)); + var mb: [32]u8 = undefined; + if (panes.Terminal.mouseFormatSgr(pane)) { + p.emitWrite(s.id, std.fmt.bufPrint(&mb, "\x1b[<0;{d};{d}M\x1b[<0;{d};{d}m", .{ col, row, col, row }) catch return); + } else { + // ponytail: legacy X10 bytes; add utf8/urxvt formats if an app ever wants them + const cb: u8 = @intCast(32 + @min(col, 222)); + const rb: u8 = @intCast(32 + @min(row, 222)); + p.emitWrite(s.id, &[_]u8{ 0x1b, '[', 'M', 32, cb, rb, 0x1b, '[', 'M', 35, cb, rb }); + } + } + edit.typeToTty(p, s.id, pane, y); + return; + } + if (!s.chorded) { + s.chorded = true; + const sl = pane.sel[sel_slot]; + pane.sel[sel_slot].state = .none; + const pfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + // both ends of the sweep through the same last-frame map, so a + // chord over wrapped rows cuts the text that was under it + const w0 = pane.wrapAt(@max(0, sl.r0 - @as(i32, BOX_H))); + const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, BOX_H))); + const row0 = w0.line; + const row1 = w1.line; + const col0 = edit.paneByteAtDisplay(p, pane, w0.line, w0.at, sl.c0 - pfx); + const col1 = edit.paneByteAtDisplay(p, pane, w1.line, w1.at, sl.c1 - pfx); + pane.cur_row = row1; + pane.cur_col = col1; + pane.cur_pinned = true; + pane.msel.active = false; + pane.normal.clear(); + if (!pane.isTerminal()) pane.mode = .normal; + pane.vsel = .{ .active = row0 != row1 or col0 != col1, .row = row0, .col = col0, .explicit = false }; + pane.nsel = 0; + } + if (cut) { + if (pane.vsel.active) edit.normalDelete(p, pane, true); + } else if (pane.vsel.active) { + edit.normalReplaceYank(p, pane); + } else if (pane.file) |*f| { + // bare cursor: splice the register in literally (no linewise + // magic) so a paste right after a cut restores the text exactly + const y = p.yank orelse return; + if (y.len == 0) return; + const at = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }; + edit.pushUndo(p, pane); + const new = modal.insertAt(p.gpa, f.content, at, y) catch return; + panes.File.setContent(p, f, new); + pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; + const end = modal.advanceBy(at, y); + if (end.col > 0) { + pane.cur_row = @intCast(end.row); + pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(f.content, end.row), end.col)); + } else { + // the register ended in '\n': the cursor lands ON that newline + pane.cur_row = @intCast(end.row -| 1); + pane.cur_col = @intCast(modal.lineSlice(f.content, end.row -| 1).len); + } + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); + } else edit.pasteText(p, pane, p.yank orelse return, true, 1); +} + +test "plain left click clears explicit modal selection" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 40, .rows = 10 }); + defer p.deinit(); + const pane = try p.setTestFile("abcdef\n"); + pane.cur_row = 0; + pane.cur_col = 5; + pane.vsel = .{ .active = true, .row = 0, .col = 1, .explicit = true }; + pane.msel = .{ .active = true, .r0 = 0, .r1 = 0 }; + + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const rect = p.rects[0]; + const click_x = rect.x + config.GUTTER + config.PREFIX_W + 3; + const body_y = rect.y + BOX_H; + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = click_x, .row = body_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = click_x, .row = body_y } }); + + try std.testing.expectEqual(@as(i32, 3), pane.cur_col); + try std.testing.expect(!pane.vsel.active); + try std.testing.expect(!pane.msel.active); + try std.testing.expectEqual(.none, pane.sel[@intFromEnum(config.select_button)].state); +} + +test "selection drag and queued release do not enter panel pending state" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 50, .rows = 10, .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("alpha beta\n"); + p.acknowledgePanelPresentation(&.{}); + const rect = p.rects[0]; + const x = rect.x + config.GUTTER + config.PREFIX_W + 1; + const y = rect.y + BOX_H; + + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x, .row = y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x + 2, .row = y } }); + try std.testing.expect(!p.presentation.pending); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x + 2, .row = y } }); + try std.testing.expect(p.drag == .none); + try std.testing.expectEqual(.done, pane.sel[sel_slot].state); +} + +test "a corner drag's two axes clamp independently" { + // a 100-wide window split 50/50, and a 30-row column split 15/14 under the + // topbar: the shape windowops.snap drives + const lx: u16 = 0; + const lw: u16 = 50; + const rw: u16 = 50; + const ay: u16 = TOPBAR_H; + const ah: u16 = 15; + const bh: u16 = 14; + const row_lo: u16 = ay + BOX_H - 1; + const row_hi: u16 = ay + ah + bh - (BOX_H + 1); + + // each axis alone, at both walls + try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); + try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); + try std.testing.expectEqual(row_lo, clampBorderRow(ay, ah, bh, 0, false)); + try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999, false)); + + // THE corner property: drag off the right edge while staying mid-height — + // x sits at its wall, y still tracks the mouse row exactly + try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); + try std.testing.expectEqual(@as(u16, 12), clampBorderRow(ay, ah, bh, 12, false)); + // and the mirror: pinned at the bottom, x still free + try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999, false)); + try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); + // both pinned at once is just both walls, not a stuck gesture + try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); + try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999, false)); + + try std.testing.expectEqual(row_lo + 1, clampBorderRow(ay, ah, bh, 0, true)); + try std.testing.expectEqual(row_hi + 1, clampBorderRow(ay, ah, bh, 999, true)); + try std.testing.expectEqual(@as(u16, 12), clampBorderRow(ay, ah, bh, 12, true)); + + // degenerate pairs pass through untouched, each on its own terms: a pane + // pair with no room stays draggable even when the column pair has room + try std.testing.expectEqual(@as(u16, 7), clampBorderCol(0, 5, 5, 7)); + try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); + try std.testing.expectEqual(@as(u16, 9), clampBorderRow(TOPBAR_H, 1, 0, 9, false)); +} + +test "a v-handle press at the RIGHT column's seam drags both boundaries" { + if (platform == .web) return; + const p = try cornerFixture(std.testing.allocator); + defer p.deinit(); + try std.testing.expectEqual(@as(usize, 2), p.col_n[1]); + + const handle = p.col_x[0] + p.col_w[0] - 1; + const right_seam = nudgeRightSeam(p, 3); + try std.testing.expect(right_seam != seamRowOf(p, 0, 0)); + + const w0 = p.col_weight[0]; + const v_left = p.panes[p.col_panes[0][0]].?.vweight; + const v_right = p.panes[p.col_panes[1][0]].?.vweight; + + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); + try std.testing.expect(p.drag == .border_v); + const corner = p.drag.border_v.corner orelse return error.NoCorner; + try std.testing.expectEqual(@as(usize, 1), corner.col); + try std.testing.expectEqual(@as(usize, 0), corner.idx); + + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = right_seam - 4 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = right_seam - 4 } }); + p.sync(); + + // both halves committed: the column pair widened, and the RIGHT column's + // pane pair reweighted — while the left column's panes stayed put + try std.testing.expect(p.col_weight[0] > w0); + try std.testing.expect(p.panes[p.col_panes[1][0]].?.vweight != v_right); + try std.testing.expectEqual(v_left, p.panes[p.col_panes[0][0]].?.vweight); +} + +test "a tie row still moves the LEFT column's pane pair only" { + if (platform == .web) return; + const p = try cornerFixture(std.testing.allocator); + defer p.deinit(); + + // put column 1's seam exactly on column 0's, the row the eye reads as one + // line across the whole window + const left_seam = seamRowOf(p, 0, 0); + _ = nudgeRightSeam(p, @as(i32, left_seam) - @as(i32, seamRowOf(p, 1, 0))); + try std.testing.expectEqual(left_seam, seamRowOf(p, 1, 0)); + + const handle = p.col_x[0] + p.col_w[0] - 1; + const v_left = p.panes[p.col_panes[0][0]].?.vweight; + const v_right = p.panes[p.col_panes[1][0]].?.vweight; + + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = left_seam } }); + const corner = p.drag.border_v.corner orelse return error.NoCorner; + try std.testing.expectEqual(@as(usize, 0), corner.col); + + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = left_seam - 4 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = left_seam - 4 } }); + p.sync(); + try std.testing.expect(p.panes[p.col_panes[0][0]].?.vweight != v_left); + try std.testing.expectEqual(v_right, p.panes[p.col_panes[1][0]].?.vweight); +} + +test "a v-handle press at nobody's seam is still a plain edge drag" { + if (platform == .web) return; + const p = try cornerFixture(std.testing.allocator); + defer p.deinit(); + const right_seam = nudgeRightSeam(p, 3); + const left_seam = seamRowOf(p, 0, 0); + + const handle = p.col_x[0] + p.col_w[0] - 1; + var row: u16 = TOPBAR_H + 1; + while (row == left_seam or row == right_seam) row += 1; + + const w0 = p.col_weight[0]; + const v_left = p.panes[p.col_panes[0][0]].?.vweight; + const v_right = p.panes[p.col_panes[1][0]].?.vweight; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = row } }); + try std.testing.expect(p.drag == .border_v); + try std.testing.expect(p.drag.border_v.corner == null); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = row + 5 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = row + 5 } }); + p.sync(); + // exactly ONE boundary moved + try std.testing.expect(p.col_weight[0] > w0); + try std.testing.expectEqual(v_left, p.panes[p.col_panes[0][0]].?.vweight); + try std.testing.expectEqual(v_right, p.panes[p.col_panes[1][0]].?.vweight); +} + +test "a RIGHT-column corner's two axes clamp independently" { + if (platform == .web) return; + const p = try cornerFixture(std.testing.allocator); + defer p.deinit(); + const right_seam = nudgeRightSeam(p, 3); + const handle = p.col_x[0] + p.col_w[0] - 1; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); + try std.testing.expectEqual(@as(usize, 1), (p.drag.border_v.corner orelse return error.NoCorner).col); + + // off the right edge at mid-height: x parks at its MINW wall, y is the mouse + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 999, .row = right_seam } }); + try std.testing.expectEqual(@as(u16, 100 - config.MINW), p.drag.border_v.cur_x); + try std.testing.expectEqual(right_seam, p.drag.border_v.cur_y); + + // and the mirror: below the bottom at mid-width. y parks, x tracks again + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = 999 } }); + try std.testing.expectEqual(handle, p.drag.border_v.cur_x); + const a = p.rects[p.col_panes[1][0]]; + const b = p.rects[p.col_panes[1][1]]; + try std.testing.expectEqual(clampBorderRow(a.y, a.h, b.h, 999, p.settings.tag_bottom), p.drag.border_v.cur_y); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = 999 } }); +} + +test "pointer coordinates follow presented panel geometry" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); + defer p.deinit(); + const pane = p.panes[0].?; + + const moving: layout.Track = .{ + .serial = pane.serial, + .pane = 0, + .phase = .moving, + .effect = .slide, + .from = .{ .x = 20, .y = 5, .w = 40, .h = 10 }, + .to = .{ .x = 0, .y = 1, .w = 80, .h = 18 }, + }; + p.acknowledgePanelPresentation(&.{moving}); + // One shared physical-to-logical map feeds all pointer gestures. The + // selected sample is 26.25% across and 35% down the presented rectangle. + try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = 21, .row = 7 }, p.presentation.pointer(p.screen_w, p.screen_h, 30, 8).?); + // Canonical cells covered only by the not-yet-arrived target are inert. + try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 2, 2) == null); + // Unrelated screen space remains in the ordinary grid coordinate system. + try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = 100, .row = 10 }, p.presentation.pointer(p.screen_w, p.screen_h, 100, 10).?); + + p.acknowledgePanelPresentation(&.{layout.Track{ + .serial = pane.serial, + .pane = 0, + .phase = .opening, + .effect = .zoom, + .from = .{ .x = 40, .y = 10, .w = 0, .h = 0 }, + .to = .{ .x = 0, .y = 1, .w = 80, .h = 18 }, + }}); + try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 40, 10) == null); + + // Tracks paint in pane-slot order inside a phase. The later slot is the + // top quad and therefore owns an overlap, even though both are moving. + const overlap = [_]layout.Track{ .{ + .serial = pane.serial, + .pane = 0, + .phase = .moving, + .effect = .slide, + .from = .{ .x = 20, .y = 2, .w = 20, .h = 4 }, + .to = .{ .x = 0, .y = 2, .w = 20, .h = 4 }, + }, .{ + .serial = pane.serial + 1, + .pane = 1, + .phase = .moving, + .effect = .slide, + .from = .{ .x = 20, .y = 2, .w = 20, .h = 4 }, + .to = .{ .x = 60, .y = 2, .w = 20, .h = 4 }, + } }; + p.presentation.shown_tracks = @splat(null); + p.presentation.shown_tracks[0] = overlap[0]; + p.presentation.shown_tracks[1] = overlap[1]; + try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = 65, .row = 3 }, p.presentation.pointer(p.screen_w, p.screen_h, 25, 3).?); +} + +test "queued pointer input is inert until a changed layout is presented" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 16, .tty_only = true }); + defer p.deinit(); + // Establish that a real host has presented the boot layout. + p.acknowledgePanelPresentation(&.{}); + p.settings.panel_transition = .slide; + + _ = try p.newShell(1, ""); + try std.testing.expect(layout.splitColumn(p, 0, 1, false)); + p.sync(); + try std.testing.expect(p.presentation.pending); + try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 10, 4) == null); + + var tracks: [MAX_PANES]layout.Track = undefined; + var len: usize = 0; + for (p.presentation.tracks) |maybe| if (maybe) |track| { + tracks[len] = track; + len += 1; + }; + p.acknowledgePanelPresentation(tracks[0..len]); + try std.testing.expect(!p.presentation.pending); + // Whether this particular opening sample exposes the chosen cell is the + // transition's concern; it is no longer rejected merely as speculative. + try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 99, 4) != null); +} + +test "pointer rejects panel content cells which have not materialized" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 12, .tty_only = true }); + defer p.deinit(); + const pane = p.panes[0].?; + const target: layout.Box = .{ .x = 4, .y = 2, .w = 32, .h = 4 }; + p.presentation.diffs = try p.gpa.alloc(PanelCellDiff, @as(usize, p.screen_w) * p.screen_h); + @memset(p.presentation.diffs, .unchanged); + for (2..6) |row| { + for (4..36) |col| { + // Distances on both sides of frame five prove that finished ASCII + // bytes are clickable while bytes still walking are not. + p.presentation.diffs[row * p.screen_w + col] = .{ .ascii = .{ + .from = ' ', + .to = @intCast(' ' + (col - 4) % 12 + 1), + } }; + } + } + p.presentation.diff_state = .ready; + + for ([_]layout.Transition{ .dissolve, .ascii }) |effect| { + const frame: u16 = if (effect == .dissolve) 3 else 5; + const track: layout.Track = .{ + .serial = pane.serial, + .pane = 0, + .phase = .opening, + .effect = effect, + .frame = frame, + .from = target, + .to = target, + }; + p.acknowledgePanelPresentation(&.{track}); + + var saw_visible = false; + var saw_hidden = false; + for (0..4) |relative_row| for (0..32) |relative_col| { + const rcol: u16 = @intCast(relative_col); + const rrow: u16 = @intCast(relative_row); + const col: u16 = @intCast(4 + relative_col); + const row: u16 = @intCast(2 + relative_row); + const visible = switch (effect) { + .dissolve => layout.dissolveRevealed( + pane.serial, + rcol, + rrow, + track.amount(), + ), + .ascii => switch (p.presentation.cellDiff(p.screen_w, p.screen_h, col, row)) { + .ascii => |diff| diff.complete(track.frame), + .unchanged, .visual => true, + }, + else => unreachable, + }; + const mapped = p.presentation.pointer(p.screen_w, p.screen_h, col, row); + try std.testing.expectEqual(visible, mapped != null); + if (mapped) |point| + try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = col, .row = row }, point); + saw_visible = saw_visible or visible; + saw_hidden = saw_hidden or !visible; + }; + try std.testing.expect(saw_visible); + try std.testing.expect(saw_hidden); + } +} + +test "unchanged content cells remain clickable through data effects" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 40, .rows = 10, .tty_only = true }); + defer p.deinit(); + const pane = p.panes[0].?; + p.presentation.diffs = try p.gpa.alloc(PanelCellDiff, @as(usize, p.screen_w) * p.screen_h); + @memset(p.presentation.diffs, .unchanged); + p.presentation.diff_state = .ready; + const box: layout.Box = .{ .x = 2, .y = 2, .w = 20, .h = 4 }; + + for ([_]layout.Transition{ .dissolve, .ascii }) |effect| { + p.acknowledgePanelPresentation(&.{.{ + .serial = pane.serial, + .pane = 0, + .phase = .opening, + .effect = effect, + .from = box, + .to = box, + }}); + try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = 8, .row = 3 }, p.presentation.pointer(p.screen_w, p.screen_h, 8, 3).?); + } +} + +test "held drag follows acknowledged panels and balances an invisible release" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); + defer p.deinit(); + const pane = p.panes[0].?; + const target = layout.panelBox(p.rects[0]); + var track: layout.Track = .{ + .serial = pane.serial, + .pane = 0, + .phase = .moving, + .effect = .slide, + .from = .{ .x = 50, .y = 5, .w = 20, .h = 8 }, + .to = target, + }; + const raw_col: u16 = 55; + const raw_row: u16 = 7; + p.acknowledgePanelPresentation(&.{track}); + p.update(.{ .mouse = .{ + .button = config.select_button, + .kind = .press, + .col = raw_col, + .row = raw_row, + } }); + try std.testing.expect(p.drag == .select); + const first_col = pane.sel[sel_slot].c1; + const first_row = pane.sel[sel_slot].r1; + + // Advancing producer state alone cannot move input. Only the sample the + // host says it actually drew may remap the stationary held endpoint. + track.frame = track.effect.frames() - 1; + p.presentation.tracks[0] = track; + try std.testing.expectEqual(first_col, pane.sel[sel_slot].c1); + try std.testing.expectEqual(first_row, pane.sel[sel_slot].r1); + p.acknowledgePanelPresentation(&.{track}); + try std.testing.expect(first_col != pane.sel[sel_slot].c1 or + first_row != pane.sel[sel_slot].r1); + + const last_col = pane.sel[sel_slot].c1; + const last_row = pane.sel[sel_slot].r1; + track.phase = .opening; + track.effect = .zoom; + track.frame = 0; + track.from = .{ + .x = target.x + target.w * 0.5, + .y = target.y + target.h * 0.5, + }; + p.acknowledgePanelPresentation(&.{track}); + try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, raw_col, raw_row) == null); + try std.testing.expectEqual(last_col, pane.sel[sel_slot].c1); + try std.testing.expectEqual(last_row, pane.sel[sel_slot].r1); + + // An unrelated release cannot consume the left drag. Its own release is + // nevertheless balanced at the retained endpoint while the cell is dark. + p.update(.{ .mouse = .{ + .button = config.exec_button, + .kind = .release, + .col = raw_col, + .row = raw_row, + } }); + try std.testing.expect(p.drag == .select); + p.update(.{ .mouse = .{ + .button = config.select_button, + .kind = .release, + .col = raw_col, + .row = raw_row, + } }); + try std.testing.expect(p.drag == .none); + try std.testing.expectEqual(.done, pane.sel[sel_slot].state); +} + +test "mouse thumb buttons navigate once and clear selection gestures" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha beta\ngamma delta\nepsilon zeta\n"); + pane.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); + p.njumps = 3; + p.jcur = 2; + for (0..3) |i| p.jumps[i] = .{ .pane = 0, .serial = pane.serial, .line = @intCast(i + 1), .col = 1 }; + p.drag = .{ .select = .{ .id = 0, .button = config.select_button } }; + p.update(.{ .mouse = .{ .button = .back, .kind = .press, .col = 0, .row = 0 } }); + try std.testing.expectEqual(@as(usize, 1), p.jcur); + for ([_]Mouse.Kind{ .drag, .release, .motion }) |kind| + p.update(.{ .mouse = .{ .button = .back, .kind = kind, .col = 0, .row = 0 } }); + try std.testing.expectEqual(@as(usize, 1), p.jcur); + p.update(.{ .mouse = .{ .button = .forward, .kind = .press, .col = 0, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .forward, .kind = .release, .col = 0, .row = 0 } }); + try std.testing.expectEqual(@as(usize, 2), p.jcur); + try std.testing.expect(!pane.vsel.active); + try std.testing.expectEqual(.none, p.drag); +} diff --git a/src/pardes.zig b/src/pardes.zig index e001aa41..7a451b3a 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const mouse = @import("mouse.zig"); pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); pub const body_layer = @import("body_layer.zig"); @@ -434,6 +435,7 @@ pub const Loc = struct { }; test { + _ = @import("mouse.zig"); _ = @import("normal.zig"); _ = @import("edit.zig"); _ = @import("Messages.zig"); @@ -479,7 +481,7 @@ const pre_close_last_file_pane_tail = " Save Tty Del Collapse"; const pre_close_last_pdf_pane_tail = " Tty Del PdfSections PdfTint Collapse"; const pre_close_last_terminal_pane_tail = " Tty Save Del Mode Filter Collapse"; -const Builtin = builtins.registry.Builtin(); +pub const Builtin = builtins.registry.Builtin(); pub const test_api = if (@import("builtin").is_test) struct { pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { @@ -2566,7 +2568,7 @@ fn wordBoundsAtCol(str: []const u8, col: usize) ?WordBounds { } /// the whitespace-delimited word covering `col` in `str` (topbar dispatch) -fn wordAtCol(str: []const u8, col: usize) []const u8 { +pub fn wordAtCol(str: []const u8, col: usize) []const u8 { const bounds = wordBoundsAtCol(str, col) orelse return ""; return str[bounds.lo..bounds.hi]; } @@ -2857,48 +2859,6 @@ test "cwd changes cancel only the affected pane's Look hover" { try std.testing.expect(p.look_hover_preview == null); } -test "plain left click clears explicit modal selection" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 40, .rows = 10 }); - defer p.deinit(); - const pane = try p.setTestFile("abcdef\n"); - pane.cur_row = 0; - pane.cur_col = 5; - pane.vsel = .{ .active = true, .row = 0, .col = 1, .explicit = true }; - pane.msel = .{ .active = true, .r0 = 0, .r1 = 0 }; - - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - _ = try p.render(frame.allocator()); - const rect = p.rects[0]; - const click_x = rect.x + config.GUTTER + config.PREFIX_W + 3; - const body_y = rect.y + BOX_H; - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = click_x, .row = body_y } }); - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = click_x, .row = body_y } }); - - try std.testing.expectEqual(@as(i32, 3), pane.cur_col); - try std.testing.expect(!pane.vsel.active); - try std.testing.expect(!pane.msel.active); - try std.testing.expectEqual(.none, pane.sel[@intFromEnum(config.select_button)].state); -} - -test "selection drag and queued release do not enter panel pending state" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 50, .rows = 10, .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("alpha beta\n"); - p.acknowledgePanelPresentation(&.{}); - const rect = p.rects[0]; - const x = rect.x + config.GUTTER + config.PREFIX_W + 1; - const y = rect.y + BOX_H; - - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x, .row = y } }); - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x + 2, .row = y } }); - try std.testing.expect(!p.presentation.pending); - p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x + 2, .row = y } }); - try std.testing.expect(p.drag == .none); - try std.testing.expectEqual(.done, pane.sel[sel_slot].state); -} - test "editable workspace and column tags replace selections and persist" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true }); defer p.deinit(); @@ -3294,220 +3254,6 @@ const PdfWordPreview = if (pdf_enabled) struct { } } else void; -const Drag = union(enum) { - none, - border_v: struct { left_col: usize, cur_x: u16, corner: ?struct { col: usize, idx: usize } = null, cur_y: u16 = 0 }, - border_h: struct { col: usize, top_idx: usize, cur_y: u16 }, - move: struct { id: usize, cur_x: u16, cur_y: u16 }, - /// `grab`: how far into the grip it was pressed, so the column's left - /// edge lands at `cur_x - grab`. A release still on the grip moves nothing. - column_move: struct { serial: u32, cur_x: u16, grab: u16 = 0 }, - tag: struct { id: usize }, - /// chorded: a 1-2/1-3 cut/paste chord fired during this left drag — - /// the drag's own release is then inert - select: struct { - id: usize, - button: Mouse.Button, - chorded: bool = false, - ctrl: bool = false, - /// This gesture began over a usable native PDF raster. The payload is - /// zero-bit when PDF support is absent. - pdf: panes.Pdf.PointerDrag = .{}, - }, - - fn button(drag: Drag) ?Mouse.Button { - return switch (drag) { - .none => null, - .border_v, .border_h, .move, .column_move, .tag => config.select_button, - .select => |selection| selection.button, - }; - } -}; - -fn clampBorderCol(lx: u16, lw: u16, rw: u16, mcol: u16) u16 { - const lo = lx + config.MINW; - const hi = lx +| lw +| rw -| config.MINW; - return if (lo <= hi) std.math.clamp(mcol, lo, hi) else mcol; -} - -fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16, tag_bottom: bool) u16 { - const d: u16 = if (tag_bottom) 1 else 0; - const lo = ay + BOX_H - 1 + d; - const hi = (ay +| ah +| bh -| (BOX_H + 1)) +| d; - return if (lo <= hi) std.math.clamp(mrow, lo, hi) else mrow; -} - -test "a corner drag's two axes clamp independently" { - // a 100-wide window split 50/50, and a 30-row column split 15/14 under the - // topbar: the shape windowops.snap drives - const lx: u16 = 0; - const lw: u16 = 50; - const rw: u16 = 50; - const ay: u16 = TOPBAR_H; - const ah: u16 = 15; - const bh: u16 = 14; - const row_lo: u16 = ay + BOX_H - 1; - const row_hi: u16 = ay + ah + bh - (BOX_H + 1); - - // each axis alone, at both walls - try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); - try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); - try std.testing.expectEqual(row_lo, clampBorderRow(ay, ah, bh, 0, false)); - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999, false)); - - // THE corner property: drag off the right edge while staying mid-height — - // x sits at its wall, y still tracks the mouse row exactly - try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); - try std.testing.expectEqual(@as(u16, 12), clampBorderRow(ay, ah, bh, 12, false)); - // and the mirror: pinned at the bottom, x still free - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999, false)); - try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); - // both pinned at once is just both walls, not a stuck gesture - try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999, false)); - - try std.testing.expectEqual(row_lo + 1, clampBorderRow(ay, ah, bh, 0, true)); - try std.testing.expectEqual(row_hi + 1, clampBorderRow(ay, ah, bh, 999, true)); - try std.testing.expectEqual(@as(u16, 12), clampBorderRow(ay, ah, bh, 12, true)); - - // degenerate pairs pass through untouched, each on its own terms: a pane - // pair with no room stays draggable even when the column pair has room - try std.testing.expectEqual(@as(u16, 7), clampBorderCol(0, 5, 5, 7)); - try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); - try std.testing.expectEqual(@as(u16, 9), clampBorderRow(TOPBAR_H, 1, 0, 9, false)); -} - -fn seamRowOf(p: *const Pardes, c: usize, k: usize) u16 { - const r = p.rects[p.col_panes[c][k]]; - return if (p.settings.tag_bottom) r.y +| r.h else 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.active = p.col_panes[1][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.col_x[1] + p.col_w[1] / 2; - const to: u16 = @intCast(@as(i32, from) + delta); - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = inside, .row = from } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = inside, .row = to } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = inside, .row = to } }); - p.sync(); - return seamRowOf(p, 1, 0); -} - -test "a v-handle press at the RIGHT column's seam drags both boundaries" { - if (platform == .web) return; - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - try std.testing.expectEqual(@as(usize, 2), p.col_n[1]); - - const handle = p.col_x[0] + p.col_w[0] - 1; - const right_seam = nudgeRightSeam(p, 3); - try std.testing.expect(right_seam != seamRowOf(p, 0, 0)); - - const w0 = p.col_weight[0]; - const v_left = p.panes[p.col_panes[0][0]].?.vweight; - const v_right = p.panes[p.col_panes[1][0]].?.vweight; - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); - try std.testing.expect(p.drag == .border_v); - const corner = p.drag.border_v.corner orelse return error.NoCorner; - try std.testing.expectEqual(@as(usize, 1), corner.col); - try std.testing.expectEqual(@as(usize, 0), corner.idx); - - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = right_seam - 4 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = right_seam - 4 } }); - p.sync(); - - // both halves committed: the column pair widened, and the RIGHT column's - // pane pair reweighted — while the left column's panes stayed put - try std.testing.expect(p.col_weight[0] > w0); - try std.testing.expect(p.panes[p.col_panes[1][0]].?.vweight != v_right); - try std.testing.expectEqual(v_left, p.panes[p.col_panes[0][0]].?.vweight); -} - -test "a tie row still moves the LEFT column's pane pair only" { - if (platform == .web) return; - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - - // put column 1's seam exactly on column 0's, the row the eye reads as one - // line across the whole window - const left_seam = seamRowOf(p, 0, 0); - _ = nudgeRightSeam(p, @as(i32, left_seam) - @as(i32, seamRowOf(p, 1, 0))); - try std.testing.expectEqual(left_seam, seamRowOf(p, 1, 0)); - - const handle = p.col_x[0] + p.col_w[0] - 1; - const v_left = p.panes[p.col_panes[0][0]].?.vweight; - const v_right = p.panes[p.col_panes[1][0]].?.vweight; - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = left_seam } }); - const corner = p.drag.border_v.corner orelse return error.NoCorner; - try std.testing.expectEqual(@as(usize, 0), corner.col); - - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = left_seam - 4 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = left_seam - 4 } }); - p.sync(); - try std.testing.expect(p.panes[p.col_panes[0][0]].?.vweight != v_left); - try std.testing.expectEqual(v_right, p.panes[p.col_panes[1][0]].?.vweight); -} - -test "a v-handle press at nobody's seam is still a plain edge drag" { - if (platform == .web) return; - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const right_seam = nudgeRightSeam(p, 3); - const left_seam = seamRowOf(p, 0, 0); - - const handle = p.col_x[0] + p.col_w[0] - 1; - var row: u16 = TOPBAR_H + 1; - while (row == left_seam or row == right_seam) row += 1; - - const w0 = p.col_weight[0]; - const v_left = p.panes[p.col_panes[0][0]].?.vweight; - const v_right = p.panes[p.col_panes[1][0]].?.vweight; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = row } }); - try std.testing.expect(p.drag == .border_v); - try std.testing.expect(p.drag.border_v.corner == null); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = row + 5 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = row + 5 } }); - p.sync(); - // exactly ONE boundary moved - try std.testing.expect(p.col_weight[0] > w0); - try std.testing.expectEqual(v_left, p.panes[p.col_panes[0][0]].?.vweight); - try std.testing.expectEqual(v_right, p.panes[p.col_panes[1][0]].?.vweight); -} - -test "a RIGHT-column corner's two axes clamp independently" { - if (platform == .web) return; - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const right_seam = nudgeRightSeam(p, 3); - const handle = p.col_x[0] + p.col_w[0] - 1; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); - try std.testing.expectEqual(@as(usize, 1), (p.drag.border_v.corner orelse return error.NoCorner).col); - - // off the right edge at mid-height: x parks at its MINW wall, y is the mouse - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 999, .row = right_seam } }); - try std.testing.expectEqual(@as(u16, 100 - config.MINW), p.drag.border_v.cur_x); - try std.testing.expectEqual(right_seam, p.drag.border_v.cur_y); - - // and the mirror: below the bottom at mid-width. y parks, x tracks again - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = 999 } }); - try std.testing.expectEqual(handle, p.drag.border_v.cur_x); - const a = p.rects[p.col_panes[1][0]]; - const b = p.rects[p.col_panes[1][1]]; - try std.testing.expectEqual(clampBorderRow(a.y, a.h, b.h, 999, p.settings.tag_bottom), p.drag.border_v.cur_y); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = 999 } }); -} - test "a new column takes width only from the column that created it" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 124, .rows = 24 }); @@ -3820,87 +3566,6 @@ test "canonical fallback and transition toggle retire unpresented tracks" { for (p.presentation.tracks) |track| try std.testing.expect(track == null); } -test "pointer coordinates follow presented panel geometry" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - - const moving: layout.Track = .{ - .serial = pane.serial, - .pane = 0, - .phase = .moving, - .effect = .slide, - .from = .{ .x = 20, .y = 5, .w = 40, .h = 10 }, - .to = .{ .x = 0, .y = 1, .w = 80, .h = 18 }, - }; - p.acknowledgePanelPresentation(&.{moving}); - // One shared physical-to-logical map feeds all pointer gestures. The - // selected sample is 26.25% across and 35% down the presented rectangle. - try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = 21, .row = 7 }, p.presentation.pointer(p.screen_w, p.screen_h, 30, 8).?); - // Canonical cells covered only by the not-yet-arrived target are inert. - try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 2, 2) == null); - // Unrelated screen space remains in the ordinary grid coordinate system. - try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = 100, .row = 10 }, p.presentation.pointer(p.screen_w, p.screen_h, 100, 10).?); - - p.acknowledgePanelPresentation(&.{layout.Track{ - .serial = pane.serial, - .pane = 0, - .phase = .opening, - .effect = .zoom, - .from = .{ .x = 40, .y = 10, .w = 0, .h = 0 }, - .to = .{ .x = 0, .y = 1, .w = 80, .h = 18 }, - }}); - try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 40, 10) == null); - - // Tracks paint in pane-slot order inside a phase. The later slot is the - // top quad and therefore owns an overlap, even though both are moving. - const overlap = [_]layout.Track{ .{ - .serial = pane.serial, - .pane = 0, - .phase = .moving, - .effect = .slide, - .from = .{ .x = 20, .y = 2, .w = 20, .h = 4 }, - .to = .{ .x = 0, .y = 2, .w = 20, .h = 4 }, - }, .{ - .serial = pane.serial + 1, - .pane = 1, - .phase = .moving, - .effect = .slide, - .from = .{ .x = 20, .y = 2, .w = 20, .h = 4 }, - .to = .{ .x = 60, .y = 2, .w = 20, .h = 4 }, - } }; - p.presentation.shown_tracks = @splat(null); - p.presentation.shown_tracks[0] = overlap[0]; - p.presentation.shown_tracks[1] = overlap[1]; - try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = 65, .row = 3 }, p.presentation.pointer(p.screen_w, p.screen_h, 25, 3).?); -} - -test "queued pointer input is inert until a changed layout is presented" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 16, .tty_only = true }); - defer p.deinit(); - // Establish that a real host has presented the boot layout. - p.acknowledgePanelPresentation(&.{}); - p.settings.panel_transition = .slide; - - _ = try p.newShell(1, ""); - try std.testing.expect(layout.splitColumn(p, 0, 1, false)); - p.sync(); - try std.testing.expect(p.presentation.pending); - try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 10, 4) == null); - - var tracks: [MAX_PANES]layout.Track = undefined; - var len: usize = 0; - for (p.presentation.tracks) |maybe| if (maybe) |track| { - tracks[len] = track; - len += 1; - }; - p.acknowledgePanelPresentation(tracks[0..len]); - try std.testing.expect(!p.presentation.pending); - // Whether this particular opening sample exposes the chosen cell is the - // transition's concern; it is no longer rejected merely as speculative. - try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 99, 4) != null); -} - test "back-to-back layout commits retarget from the last presented boxes" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); defer p.deinit(); @@ -4047,92 +3712,6 @@ test "core composes character motion out of the new grid, not a fade" { try std.testing.expect(try p.composeAsciiTransitions(arena.allocator(), &surface) == &surface); } -test "pointer rejects panel content cells which have not materialized" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 12, .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - const target: layout.Box = .{ .x = 4, .y = 2, .w = 32, .h = 4 }; - p.presentation.diffs = try p.gpa.alloc(PanelCellDiff, @as(usize, p.screen_w) * p.screen_h); - @memset(p.presentation.diffs, .unchanged); - for (2..6) |row| { - for (4..36) |col| { - // Distances on both sides of frame five prove that finished ASCII - // bytes are clickable while bytes still walking are not. - p.presentation.diffs[row * p.screen_w + col] = .{ .ascii = .{ - .from = ' ', - .to = @intCast(' ' + (col - 4) % 12 + 1), - } }; - } - } - p.presentation.diff_state = .ready; - - for ([_]layout.Transition{ .dissolve, .ascii }) |effect| { - const frame: u16 = if (effect == .dissolve) 3 else 5; - const track: layout.Track = .{ - .serial = pane.serial, - .pane = 0, - .phase = .opening, - .effect = effect, - .frame = frame, - .from = target, - .to = target, - }; - p.acknowledgePanelPresentation(&.{track}); - - var saw_visible = false; - var saw_hidden = false; - for (0..4) |relative_row| for (0..32) |relative_col| { - const rcol: u16 = @intCast(relative_col); - const rrow: u16 = @intCast(relative_row); - const col: u16 = @intCast(4 + relative_col); - const row: u16 = @intCast(2 + relative_row); - const visible = switch (effect) { - .dissolve => layout.dissolveRevealed( - pane.serial, - rcol, - rrow, - track.amount(), - ), - .ascii => switch (p.presentation.cellDiff(p.screen_w, p.screen_h, col, row)) { - .ascii => |diff| diff.complete(track.frame), - .unchanged, .visual => true, - }, - else => unreachable, - }; - const mapped = p.presentation.pointer(p.screen_w, p.screen_h, col, row); - try std.testing.expectEqual(visible, mapped != null); - if (mapped) |point| - try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = col, .row = row }, point); - saw_visible = saw_visible or visible; - saw_hidden = saw_hidden or !visible; - }; - try std.testing.expect(saw_visible); - try std.testing.expect(saw_hidden); - } -} - -test "unchanged content cells remain clickable through data effects" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 40, .rows = 10, .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - p.presentation.diffs = try p.gpa.alloc(PanelCellDiff, @as(usize, p.screen_w) * p.screen_h); - @memset(p.presentation.diffs, .unchanged); - p.presentation.diff_state = .ready; - const box: layout.Box = .{ .x = 2, .y = 2, .w = 20, .h = 4 }; - - for ([_]layout.Transition{ .dissolve, .ascii }) |effect| { - p.acknowledgePanelPresentation(&.{.{ - .serial = pane.serial, - .pane = 0, - .phase = .opening, - .effect = effect, - .from = box, - .to = box, - }}); - try std.testing.expectEqual(layout.Presentation.CellPosition{ .col = 8, .row = 3 }, p.presentation.pointer(p.screen_w, p.screen_h, 8, 3).?); - } -} - test "stationary Look hover follows only acknowledged panel samples" { _ = config.look_preview_delay_frames orelse return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); @@ -4195,75 +3774,6 @@ test "stationary Look hover follows only acknowledged panel samples" { try std.testing.expect(p.look_hover_wait != null); } -test "held drag follows acknowledged panels and balances an invisible release" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - const target = layout.panelBox(p.rects[0]); - var track: layout.Track = .{ - .serial = pane.serial, - .pane = 0, - .phase = .moving, - .effect = .slide, - .from = .{ .x = 50, .y = 5, .w = 20, .h = 8 }, - .to = target, - }; - const raw_col: u16 = 55; - const raw_row: u16 = 7; - p.acknowledgePanelPresentation(&.{track}); - p.update(.{ .mouse = .{ - .button = config.select_button, - .kind = .press, - .col = raw_col, - .row = raw_row, - } }); - try std.testing.expect(p.drag == .select); - const first_col = pane.sel[sel_slot].c1; - const first_row = pane.sel[sel_slot].r1; - - // Advancing producer state alone cannot move input. Only the sample the - // host says it actually drew may remap the stationary held endpoint. - track.frame = track.effect.frames() - 1; - p.presentation.tracks[0] = track; - try std.testing.expectEqual(first_col, pane.sel[sel_slot].c1); - try std.testing.expectEqual(first_row, pane.sel[sel_slot].r1); - p.acknowledgePanelPresentation(&.{track}); - try std.testing.expect(first_col != pane.sel[sel_slot].c1 or - first_row != pane.sel[sel_slot].r1); - - const last_col = pane.sel[sel_slot].c1; - const last_row = pane.sel[sel_slot].r1; - track.phase = .opening; - track.effect = .zoom; - track.frame = 0; - track.from = .{ - .x = target.x + target.w * 0.5, - .y = target.y + target.h * 0.5, - }; - p.acknowledgePanelPresentation(&.{track}); - try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, raw_col, raw_row) == null); - try std.testing.expectEqual(last_col, pane.sel[sel_slot].c1); - try std.testing.expectEqual(last_row, pane.sel[sel_slot].r1); - - // An unrelated release cannot consume the left drag. Its own release is - // nevertheless balanced at the retained endpoint while the cell is dark. - p.update(.{ .mouse = .{ - .button = config.exec_button, - .kind = .release, - .col = raw_col, - .row = raw_row, - } }); - try std.testing.expect(p.drag == .select); - p.update(.{ .mouse = .{ - .button = config.select_button, - .kind = .release, - .col = raw_col, - .row = raw_row, - } }); - try std.testing.expect(p.drag == .none); - try std.testing.expectEqual(.done, pane.sel[sel_slot].state); -} - test "repeated non-dyadic column splits preserve every unrelated boundary" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 979, .rows = 20 }); @@ -4445,7 +3955,7 @@ pub const Pardes = struct { native_image_patches: bool = false, quit: bool = false, haptic: HapticSlot = if (platform == .macos) .none else {}, - drag: Drag = .none, + drag: mouse.Drag = .none, hover_col: u16 = 0, hover_row: u16 = 0, pointer_raw_col: u16 = 0, @@ -4769,7 +4279,7 @@ pub const Pardes = struct { return p.col_tags[c].slice("New Tty Find Grep Joincol Delcol"); } - fn headerText(p: *Pardes) []const u8 { + pub fn headerText(p: *Pardes) []const u8 { if (p.header_column) |c| return if (c < p.ncol) p.columnTag(c) else ""; var buf: [1200]u8 = undefined; return p.scratch.allocator().dupe(u8, p.topbar(&buf)) catch ""; @@ -5490,7 +5000,7 @@ pub const Pardes = struct { .border_v, .border_h, .move, .column_move => p.presentation.snap_once = true, else => {}, }; - p.handleMouse(m); + mouse.handleMouse(p, m); }, .pdf_scroll => |scroll| { if (comptime pdf_enabled) { @@ -5656,7 +5166,7 @@ pub const Pardes = struct { } } - fn exitTagEdit(pane: *Pane) void { + pub fn exitTagEdit(pane: *Pane) void { if (pane.tag_edit and pane.prompt == .none) pane.tag_saved_col = pane.tag_col; if (pane.isTerminal()) { if (pane.tag_edit) pane.mode = pane.tag_mode; @@ -5923,7 +5433,7 @@ pub const Pardes = struct { return modal.moveWord(text, .{ .anchor = cur, .head = modal.nextGrapheme(text, cur) }, 1, t); } - fn rememberHeader(p: *Pardes) void { + pub fn rememberHeader(p: *Pardes) void { const col = p.topbar_col orelse return; const line = if (p.header_column) |c| &p.col_tags[c] else &p.global_tag; line.saved_col = col; @@ -6140,7 +5650,7 @@ pub const Pardes = struct { return true; } - const PointerOperand = struct { + pub const PointerOperand = struct { /// Absolute body position corresponding to the pointed screen cell. row: i32, col: i32, @@ -6156,7 +5666,7 @@ pub const Pardes = struct { expanded: ?Pane.Sel = null, }; - fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand { + pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand { const visible = clicked.r0 - @as(i32, BOX_H); const wrapped = pane.wrapAt(visible); const raw = pane.isTerminal() and pane.mode == .tty and clicked.r0 >= BOX_H; @@ -6249,7 +5759,7 @@ pub const Pardes = struct { return result; } - fn heldSelection(p: *Pardes, first: usize) ?[]const u8 { + pub fn heldSelection(p: *Pardes, first: usize) ?[]const u8 { var k: usize = 0; while (k < p.panes.len + 2) : (k += 1) { const i = switch (k) { @@ -6272,7 +5782,7 @@ pub const Pardes = struct { return null; } - fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 { + pub fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 { const a = std.mem.trim(u8, arg orelse return txt, " \t\r\n"); if (a.len == 0) return txt; const t = std.mem.trim(u8, txt, " \t\r\n"); @@ -7188,85 +6698,7 @@ pub const Pardes = struct { // ---- dumb undo/redo: whole-state snapshots, one per edit op ---- - pub const ChromeTarget = struct { col: u16, row: u16 }; - - pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { - if (row < p.topBarHeight() + p.columnBarHeight()) return .{ .col = col, .row = row }; - for (p.panes, 0..) |slot, id| { - if (slot == null) continue; - const rect = p.rects[id]; - const tag = if (p.settings.tag_bottom) rect.y + rect.h -| BOX_H else rect.y; - if (row == tag and col >= rect.x and col < rect.x + rect.w and col < rect.x + config.GUTTER) - return .{ .col = col, .row = tag }; - } - for (0..p.ncol -| 1) |column| { - const handle = p.col_x[column] + p.col_w[column] -| 1; - if (col == handle) return .{ .col = handle, .row = row }; - } - for (0..p.ncol) |column| { - if (col < p.col_x[column] or col >= p.col_x[column] + p.col_w[column]) continue; - for (0..p.col_n[column] -| 1) |index| { - const rect = p.rects[p.col_panes[column][index]]; - const handle = if (p.settings.tag_bottom) rect.y +| rect.h else rect.y + rect.h -| 1; - if (row == handle) return .{ .col = col, .row = handle }; - } - } - for (p.panes, 0..) |slot, id| { - if (slot == null) continue; - const rect = p.rects[id]; - const tag = if (p.settings.tag_bottom) rect.y + rect.h -| BOX_H else rect.y; - if (row == tag and col >= rect.x and col < rect.x + rect.w) - return .{ .col = col, .row = tag }; - } - for (0..p.ncol -| 1) |column| { - const handle = p.col_x[column] + p.col_w[column] -| 1; - if (@max(col, handle) - @min(col, handle) == 1) return .{ .col = handle, .row = row }; - } - for (0..p.ncol) |column| { - if (col < p.col_x[column] or col >= p.col_x[column] + p.col_w[column]) continue; - for (0..p.col_n[column] -| 1) |index| { - const rect = p.rects[p.col_panes[column][index]]; - const handle = if (p.settings.tag_bottom) rect.y +| rect.h else rect.y + rect.h -| 1; - if (@max(row, handle) - @min(row, handle) == 1) return .{ .col = col, .row = handle }; - } - } - return null; - } - - pub fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { - for (p.panes, 0..) |slot, id| { - if (slot == null) continue; - const r = p.rects[id]; - if (col >= r.x and col < r.x + r.w and row >= r.y and row < r.y + r.h) return id; - } - return null; - } - - pub fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clamp: bool) ?Mouse.BodyHit { - const pane = p.panes[id] orelse return null; - if (pane.file == null or (!clamp and supplied.serial != pane.serial)) return null; - if (!std.math.isFinite(supplied.pixel_x) or !std.math.isFinite(supplied.pixel_y) or - supplied.metrics.body_w == 0 or supplied.metrics.body_h == 0 or - supplied.metrics.tagline_w == 0 or supplied.metrics.tagline_h == 0) return null; - var mapped_hit = supplied; - if (clamp) { - mapped_hit.serial = pane.serial; - const layer = for (&p.surface.body_layers) |*layer| { - if (layer.rows > 0 and layer.serial == pane.serial) break layer; - } else return null; - const bw: f32 = @floatFromInt(mapped_hit.metrics.body_w); - const bh: f32 = @floatFromInt(mapped_hit.metrics.body_h); - const x0 = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const y0 = @as(f32, @floatFromInt(layer.viewport.y)) * bh; - const x1 = x0 + @as(f32, @floatFromInt(layer.viewport.w)) * bw; - const y1 = y0 + @as(f32, @floatFromInt(layer.viewport.h)) * bh; - mapped_hit.pixel_x = std.math.clamp(mapped_hit.pixel_x, x0, @max(x0, x1 - 0.001)); - mapped_hit.pixel_y = std.math.clamp(mapped_hit.pixel_y, y0, @max(y0, y1 - 0.001)); - } - return p.reprojectBodyHit(mapped_hit); - } - - fn cancelLookHover(p: *Pardes) void { + pub fn cancelLookHover(p: *Pardes) void { if (comptime pdf_enabled) if (p.pdf_hover_preview) |*preview| { if (preview.pane < p.panes.len) if (p.panes[preview.pane]) |pane| { if (pane.serial == preview.serial) if (pane.pdf) |*pv| @@ -7286,60 +6718,32 @@ pub const Pardes = struct { return null; } - fn sameTagCell(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.col == second.col; - } - - pub fn tagColumn(p: *const Pardes, kind: TagKind, id: usize, supplied: ?TagHit, clamp: bool) ?u16 { - var point = supplied orelse return null; - if (point.kind != kind or point.id != id) return null; - if (clamp) for (p.surface.tagLayers()) |*layer| { - if (layer.cols == 0 or layer.kind != kind or layer.id != id or layer.serial != point.serial) continue; - const bw: f32 = @floatFromInt(point.metrics.body_w); - const bh: f32 = @floatFromInt(point.metrics.body_h); - const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const right = @as(f32, @floatFromInt(layer.viewport.x + layer.viewport.w)) * bw; - point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); - point.pixel_y = (@as(f32, @floatFromInt(layer.viewport.y)) + 0.5) * bh; - break; - }; - return if (p.reprojectTagHit(point)) |mapped| mapped.col else null; - } - - fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { - const first = a orelse return b == null; - const second = b orelse return false; - return first.serial == second.serial and first.row == second.row and first.col == second.col; - } - fn noteLookHover(p: *Pardes, col: u16, row: u16, body_hit: ?Mouse.BodyHit, tag_hit: ?TagHit) void { const delay = config.look_preview_delay_frames orelse return; _ = delay; - const id = p.paneAt(col, row) orelse return p.cancelLookHover(); + const id = mouse.paneAt(p, col, row) orelse return p.cancelLookHover(); const pane = p.panes[id] orelse return p.cancelLookHover(); _ = edit.pointerTextSelection(p, id, col, row, body_hit, tag_hit) orelse return p.cancelLookHover(); if (comptime pdf_enabled) if (p.pdf_hover_preview) |shown| if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial) return; if (p.look_hover_preview) |shown| - if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial and sameBodyCell(shown.body_hit, body_hit) and sameTagCell(shown.tag_hit, tag_hit)) return; + if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial and mouse.sameBodyCell(shown.body_hit, body_hit) and mouse.sameTagCell(shown.tag_hit, tag_hit)) return; if (p.look_hover_wait) |waiting| - if (waiting.col == col and waiting.row == row and waiting.pane == id and waiting.serial == pane.serial and sameBodyCell(waiting.body_hit, body_hit) and sameTagCell(waiting.tag_hit, tag_hit)) return; + if (waiting.col == col and waiting.row == row and waiting.pane == id and waiting.serial == pane.serial and mouse.sameBodyCell(waiting.body_hit, body_hit) and mouse.sameTagCell(waiting.tag_hit, tag_hit)) return; p.cancelLookHover(); p.look_hover_wait = .{ .col = col, .row = row, .pane = id, .serial = pane.serial, .body_hit = body_hit, .tag_hit = tag_hit }; } - fn refreshLookHoverFromRaw(p: *Pardes) void { + pub fn refreshLookHoverFromRaw(p: *Pardes) void { if (!p.pointer_inside or !p.raw_hover_intent) return; const mapped = p.presentation.pointer(p.screen_w, p.screen_h, p.pointer_raw_col, p.pointer_raw_row) orelse return p.cancelLookHover(); p.hover_col = mapped.col; p.hover_row = mapped.row; const body_hit: ?Mouse.BodyHit = if (p.pointer_body_hit) |mapped_hit| - p.bodyHitForPane(p.paneAt(mapped.col, mapped.row) orelse return p.cancelLookHover(), mapped_hit, false) orelse return p.cancelLookHover() + mouse.bodyHitForPane(p, mouse.paneAt(p, mapped.col, mapped.row) orelse return p.cancelLookHover(), mapped_hit, false) orelse return p.cancelLookHover() else null; p.noteLookHover(mapped.col, mapped.row, body_hit, p.pointer_tag_hit); @@ -7392,7 +6796,7 @@ pub const Pardes = struct { if (p.presentation.pointer(p.screen_w, p.screen_h, p.pointer_raw_col, p.pointer_raw_row)) |mapped| { p.hover_col = mapped.col; p.hover_row = mapped.row; - p.dragUpdate(mapped.col, mapped.row, p.pointer_body_hit); + mouse.dragUpdate(p, mapped.col, mapped.row, p.pointer_body_hit); } } p.refreshLookHoverFromRaw(); @@ -7409,784 +6813,6 @@ pub const Pardes = struct { p.settings.scene_effects = .{}; } - fn handleMouse(p: *Pardes, m: Mouse) void { - // A click goes somewhere else: the question it leaves unanswered is - // taken back, and the pane stays. A wheel only looks around. - if (m.kind == .press and switch (m.button) { - .left, .middle, .right => true, - else => false, - }) for (p.panes) |slot| { - const pane = slot orelse continue; - if (pane.prompt == .del_side) pane.prompt = .none; - }; - if (m.button == .back or m.button == .forward) { - if (m.kind == .press) p.jumpBy(if (m.button == .back) -1 else 1); - return; - } - const raw_col = @min(m.col, p.screen_w -| 1); - const raw_row = @min(m.row, p.screen_h -| 1); - p.pointer_raw_col = raw_col; - p.pointer_raw_row = raw_row; - const previous_hit = p.pointer_body_hit; - p.pointer_body_hit = m.body_hit; - const previous_tag_hit = p.pointer_tag_hit; - p.pointer_tag_hit = if (m.tag_hit) |point| p.reprojectTagHit(point) else null; - if (m.tag_hit != null and p.pointer_tag_hit == null and m.kind == .press) return; - if (m.tag_hit == null and (m.kind == .drag or m.kind == .release) and (p.drag == .tag or p.drag == .select or p.header_drag)) { - if (previous_tag_hit) |previous| { - var continued = previous; - continued.pixel_x = (@as(f32, @floatFromInt(raw_col)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_w)); - continued.pixel_y = (@as(f32, @floatFromInt(raw_row)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_h)); - p.pointer_tag_hit = continued; - } - } - if ((m.kind == .drag or m.kind == .release) and (p.drag == .tag or p.drag == .select or p.header_drag)) { - if (previous_tag_hit) |previous| if (p.pointer_tag_hit) |*current| { - current.kind = previous.kind; - current.id = previous.id; - current.serial = previous.serial; - }; - } - // A drag can leave the compact text viewport. Preserve its metrics so - // the endpoint still clamps to that body's last visible logical row. - if (m.body_hit == null and (m.kind == .drag or m.kind == .release) and p.drag == .select) { - if (previous_hit) |previous| { - var continued = previous; - continued.pixel_x = (@as(f32, @floatFromInt(raw_col)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_w)); - continued.pixel_y = (@as(f32, @floatFromInt(raw_row)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_h)); - p.pointer_body_hit = continued; - } - } - p.pointer_inside = true; - if (m.button == .none and m.kind == .motion) { - p.raw_hover_intent = true; - p.refreshLookHoverFromRaw(); - return; - } - p.raw_hover_intent = false; - const mapped = p.presentation.pointer(p.screen_w, p.screen_h, raw_col, raw_row) orelse { - p.cancelLookHover(); - if (m.kind == .release) p.dragRelease(m.button); - return; - }; - const mcol = mapped.col; - const mrow = mapped.row; - p.hover_col = mcol; - p.hover_row = mrow; - - const hovered = p.paneAt(mcol, mrow); - - // any press that is NOT the execute+select chord abandons a pending - // chord argument - if (m.kind == .press and - !(m.button == config.select_button and p.drag == .select and p.drag.select.button == config.exec_button)) - { - if (p.chord_arg) |a| { - p.gpa.free(a); - p.chord_arg = null; - } - } - if (mrow >= p.topBarHeight() and mrow < p.topBarHeight() + p.columnBarHeight() and m.kind == .press) { - for (0..p.ncol) |column| { - if (mcol < p.col_x[column] or mcol >= p.col_x[column] + @min(config.GUTTER, p.col_w[column])) continue; - if (m.button == config.select_button) { - p.header_drag = false; - p.drag = .{ .column_move = .{ .serial = p.col_serial[column], .cur_x = mcol, .grab = mcol - p.col_x[column] } }; - } - return; - } - } - if (p.header_drag and m.button == config.select_button and (m.kind == .drag or m.kind == .release)) { - const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; - const bar = p.headerText(); - p.topbar_col = @intCast(@min(bar.len, panes.File.rawAtDisplay(bar, (p.tagColumn(if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll))); - if (m.kind == .release) p.header_drag = false; - return; - } - if (mrow < p.topBarHeight() + p.columnBarHeight() and m.kind == .press and - (m.button == config.select_button or m.button == config.exec_button or m.button == config.look_button)) - { - if (m.button == config.select_button) if (p.panes[p.active]) |pane| { - if (pane.tag_edit) exitTagEdit(pane); - }; - var column: ?usize = null; - var x: u16 = 0; - if (mrow >= p.topBarHeight()) { - for (0..p.ncol) |c| if (mcol >= p.col_x[c] and mcol < p.col_x[c] + p.col_w[c]) { - column = c; - x = p.col_x[c] + TAG_TEXT_INSET; - if (layout.findPane(p, p.active)) |active_col| { - if (active_col.col != c and p.col_n[c] > 0) p.active = p.col_panes[c][0]; - } - break; - }; - if (column == null or mcol < x) return; - } - if (p.header_column != column) { - p.rememberHeader(); - p.topbar_col = null; - p.header_anchor = null; - p.header_scroll = 0; - } - p.header_column = column; - const bar = p.headerText(); - const at = @min(bar.len, panes.File.rawAtDisplay(bar, (p.tagColumn(if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll)); - if (m.button == config.select_button) { - p.topbar_col = @intCast(at); - p.header_anchor = @intCast(at); - p.header_insert = true; - p.header_drag = true; - } else { - const selected = if (p.topbar_col) |cur| blk: { - const a = p.header_anchor orelse cur; - break :blk if (at >= @min(a, cur) and at < @max(a, cur)) bar[@min(a, cur)..@max(a, cur)] else wordAtCol(bar, at); - } else wordAtCol(bar, at); - const word = p.scratch.allocator().dupe(u8, selected) catch return; - p.exitHeader(); - if (word.len > 0) { - if (m.button == config.exec_button) { - const named = std.meta.stringToEnum(Builtin, word); - const held = if (named) |b| (if (builtins.registry.takesArg(b)) p.heldSelection(p.active) else null) else p.heldSelection(p.active); - _ = p.execute(p.active, p.withArg(word, held)); - } else p.runBuiltin(config.look_cmd, p.active, "", word); - } - } - return; - } - if (m.kind == .press) { - p.exitHeader(); - } - - switch (m.button) { - .none, .back, .forward => {}, // hover and navigation handled above - .wheel_up, .wheel_down => { - if (m.kind != .press) return; - // re-arms the drift guard below; vertical always scrolls, so - // the answer is never in doubt here - _ = config.wheelTick(&p.wheel_guard, true); - const id = hovered orelse return; - const pane = p.panes[id].?; - if (pane.hasPdf()) - panes.Pdf.verticalWheel(p, pane, if (m.button == .wheel_up) -1 else 1) - else - pane.scrollBy(if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows); - }, - .wheel_left, .wheel_right => { - if (m.kind != .press) return; - if (!config.wheelTick(&p.wheel_guard, false)) return; - const id = hovered orelse return; - const pane = p.panes[id].?; - if (pane.hasPdf()) { - panes.Pdf.horizontalWheel(p, pane, if (m.button == .wheel_right) 1 else -1); - // ponytail: no right clamp — overscroll shows blank and the - // next cursor move or left wheel pulls it back - } else if (pane.file != null and !p.settings.wrap) { - // wrapped there is nothing off to the right to reach - const line = panes.File.sourceLine(pane, pane.cur_row); - const visual = panes.File.rawDisplayCol(line, @intCast(@max(0, pane.hscroll))); - const next: usize = if (m.button == .wheel_right) - visual +| @as(usize, @intCast(config.wheel_cols)) - else - visual -| @as(usize, @intCast(config.wheel_cols)); - pane.hscroll = @intCast(panes.File.rawAtDisplay(line, next)); - } - }, - config.select_button => switch (m.kind) { - .press => { - if (p.drag == .select and p.drag.select.button == config.exec_button) { - if (p.heldSelection(p.drag.select.id)) |tx| { - if (p.chord_arg) |old| p.gpa.free(old); - p.chord_arg = p.gpa.dupe(u8, tx) catch null; - } - return; - } - // acme 3-1: a select tap during a LOOK drag cancels the - // look; the rest of the gesture is inert - if (p.drag == .select and p.drag.select.button == config.look_button) { - if (p.panes[p.drag.select.id]) |t| { - t.sel[@intFromEnum(config.look_button)].state = .none; - if (comptime pdf_enabled) - panes.Pdf.pointerCancel(t, p.drag.select.pdf); - } - p.drag = .none; - return; - } - if (hovered) |mid| { - const mr = p.rects[mid]; - const mtag = if (p.settings.tag_bottom) mr.y + mr.h -| BOX_H else mr.y; - if (mcol < mr.x + config.GUTTER and mrow >= mtag and mrow < mtag + BOX_H) { - p.drag = .{ .move = .{ .id = mid, .cur_x = mcol, .cur_y = mrow } }; - return; - } - } - for (0..p.ncol -| 1) |c| { - if (mcol == p.col_x[c] + p.col_w[c] -| 1) { - const corner: @FieldType(@FieldType(Drag, "border_v"), "corner") = if (p.seamIdxAt(c, mrow)) |k| - .{ .col = c, .idx = k } - else if (p.seamIdxAt(c + 1, mrow)) |k| - .{ .col = c + 1, .idx = k } - else - null; - p.drag = .{ .border_v = .{ .left_col = c, .cur_x = mcol, .corner = corner, .cur_y = mrow } }; - return; - } - } - for (0..p.ncol) |cc| { - if (mcol < p.col_x[cc] or mcol >= p.col_x[cc] + p.col_w[cc]) continue; - if (p.seamIdxAt(cc, mrow)) |k| { - p.drag = .{ .border_h = .{ .col = cc, .top_idx = k, .cur_y = mrow } }; - return; - } - } - const id = hovered orelse return; - const r = p.rects[id]; - const pane = p.panes[id] orelse return; - if (id != p.active) if (p.panes[p.active]) |previous| { - if (previous.tag_edit) exitTagEdit(previous); - }; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = p.bodyTop(r); - if (mcol < r.x + config.GUTTER) { - // gutter scrollbar: a left click scrolls UP to that row - p.active = id; - pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); - } else if (mrow >= tag_y and mrow < tag_y + BOX_H) { - if (mcol < r.x + TAG_TEXT_INSET) return; - p.active = id; - p.enterTagEdit(pane, if (p.tagColumn(.pane, id, p.pointer_tag_hit, false)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, r.x + TAG_TEXT_INSET)); - pane.tag_anchor = pane.tag_col; - p.drag = .{ .tag = .{ .id = id } }; - } else { - p.active = id; - if (pane.tag_edit) exitTagEdit(pane); - const pointed = edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit) orelse return; - pane.clearPointerSelection(sel_slot); - pane.sel[sel_slot] = pointed.sel; - p.drag = .{ .select = .{ - .id = id, - .button = config.select_button, - .ctrl = m.ctrl, - .pdf = panes.Pdf.pointerStart( - p, - pane, - config.select_button, - mcol, - mrow, - false, - ), - } }; - } - }, - .drag => p.dragUpdate(mcol, mrow, p.pointer_body_hit), - .release => { - if ((p.pointer_body_hit != null or p.pointer_tag_hit != null or p.drag == .column_move) and p.drag.button() == m.button) p.dragUpdate(mcol, mrow, p.pointer_body_hit); - p.dragRelease(config.select_button); - }, - .motion => {}, - }, - config.exec_button, config.look_button => switch (m.kind) { - .press => { - // acme 1-2 / 1-3: the execute (Cut) or look (Paste) button - // tapped while the select button holds a selection drag - if (p.drag == .select and p.drag.select.button == config.select_button) { - p.chordCutPaste(m.button == config.exec_button); - return; - } - // acme 2-3 / 3-2: tapping the OTHER of execute/look during - // an execute or look drag cancels it (textselect23's mask) - if (p.drag == .select) { - if (p.panes[p.drag.select.id]) |t| { - t.sel[@intFromEnum(p.drag.select.button)].state = .none; - if (comptime pdf_enabled) - panes.Pdf.pointerCancel(t, p.drag.select.pdf); - } - p.drag = .none; - return; - } - const id = hovered orelse return; - const r = p.rects[id]; - const pane = p.panes[id] orelse return; - // the tag row and the body's first, exactly as the select - // arm above derives them - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = p.bodyTop(r); - const on_tag = mrow >= tag_y and mrow < tag_y + BOX_H; - if (mcol < r.x + config.GUTTER and !on_tag) { - const local = @as(i32, mrow) - @as(i32, body_y); - if (m.button == config.look_button) p.active = id; - pane.scrollBy(if (m.button == config.look_button) local else -local); - } else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit)) |pointed| { - if (m.button == config.look_button) p.active = id; - pane.clearPointerSelection(@intFromEnum(m.button)); - pane.sel[@intFromEnum(m.button)] = pointed.sel; - p.drag = .{ - .select = .{ - .id = id, - .button = m.button, - // A native body gesture stays native even when its - // point later misses a letterbox or selection. - .pdf = panes.Pdf.pointerStart( - p, - pane, - m.button, - mcol, - mrow, - pointed.on_tag, - ), - }, - }; - } - }, - .drag => p.dragUpdate(mcol, mrow, p.pointer_body_hit), - .release => { - if ((p.pointer_body_hit != null or p.pointer_tag_hit != null or p.drag == .column_move) and p.drag.button() == m.button) p.dragUpdate(mcol, mrow, p.pointer_body_hit); - p.dragRelease(m.button); - }, - .motion => {}, - }, - } - } - - /// Index of the pane pair in column `c` whose seam (see seamRowOf) is screen - /// row `mrow`. Out-of-range columns simply have no seam. - fn seamIdxAt(p: *const Pardes, c: usize, mrow: u16) ?usize { - if (c >= p.ncol) return null; - for (0..p.col_n[c] -| 1) |k| if (mrow == seamRowOf(p, c, k)) return k; - return null; - } - - fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) void { - switch (p.drag) { - .border_v => |*d| { - const c = d.left_col; - d.cur_x = if (c + 1 < p.ncol) - clampBorderCol(p.col_x[c], p.col_w[c], p.col_w[c + 1], mcol) - else - mcol; - if (d.corner) |k| if (k.idx + 1 < p.col_n[k.col]) { - const a = p.rects[p.col_panes[k.col][k.idx]]; - const b = p.rects[p.col_panes[k.col][k.idx + 1]]; - d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow, p.settings.tag_bottom); - } else { - d.cur_y = mrow; - }; - }, - .border_h => |*d| { - const cc = d.col; - const k = d.top_idx; - if (k + 1 < p.col_n[cc]) { - const a = p.rects[p.col_panes[cc][k]]; - const b = p.rects[p.col_panes[cc][k + 1]]; - d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow, p.settings.tag_bottom); - } else d.cur_y = mrow; - }, - .column_move => |*d| d.cur_x = mcol, - .move => |*d| { - d.cur_x = mcol; - d.cur_y = mrow; - }, - .select => |*s| { - if (p.panes[s.id]) |pane| { - const r = p.rects[s.id]; - const b = @intFromEnum(s.button); - if (pane.body_rows > 0 and pane.sel[b].r0 >= BOX_H) if (body_hit) |supplied| { - const mapped_hit = p.bodyHitForPane(s.id, supplied, true) orelse return; - pane.sel[b].c1 = @as(i32, mapped_hit.col) - config.GUTTER; - pane.sel[b].r1 = @as(i32, mapped_hit.row) + BOX_H; - return; - }; - if (pane.sel[b].r0 < BOX_H) if (p.tagColumn(.pane, s.id, p.pointer_tag_hit, true)) |value| { - pane.sel[b].c1 = @as(i32, value) + pane.tag_scroll; - pane.sel[b].r1 = 0; - return; - }; - pane.sel[b].c1 = @as(i32, mcol) - @as(i32, r.x + config.GUTTER); - // Sel row BOX_H is the body's FIRST row, the same thing - // pointerTextSelection means by it -- so the drag has to - // measure from the body's top, notice bands included, or a - // selection made while a message is up lands rows away - // from the pointer. - const body_y = p.bodyTop(r); - const body_h = r.h -| BOX_H; - pane.sel[b].r1 = if (pane.sel[b].r0 < BOX_H or body_h == 0) - 0 - else - @as(i32, @min(@max(mrow, body_y), body_y + body_h - 1)) - @as(i32, body_y) + @as(i32, BOX_H); - if (pane.sel[b].r1 < BOX_H) pane.sel[b].c1 += @as(i32, pane.tag_scroll) - TAG_GAP; - if (comptime pdf_enabled) - panes.Pdf.pointerUpdate(&s.pdf, p, pane, mcol, mrow); - } - }, - .tag => |d| { - const pane = p.panes[d.id] orelse return; - const c = if (p.tagColumn(.pane, d.id, p.pointer_tag_hit, true)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, p.rects[d.id].x + TAG_TEXT_INSET); - const text = p.tagText(p.scratch.allocator(), pane) catch return; - pane.tag_col = @intCast(@min(text.len, panes.File.rawAtDisplay(text, @as(usize, @intCast(@max(0, c))) + pane.tag_scroll))); - pane.tag_sel = pane.tag_col != pane.tag_anchor; - }, - .none => {}, - } - } - - fn reportGesture( - p: *Pardes, - id: usize, - cmd: Builtin, - text: []const u8, - on_tag: bool, - operand: PointerOperand, - chorded: bool, - ) bool { - const scripted = p.panes[id] orelse return false; - if (scripted.fs.readers == 0) return false; - const is_look = cmd == config.look_cmd; - const action: ctlfs.events.Action = if (is_look) - (if (on_tag) .tag_look else .body_look) - else - (if (on_tag) .tag_exec else .body_exec); - const named = std.meta.stringToEnum(Builtin, commandText(text)) != null; - const range = p.gestureRange(id, text, on_tag, operand); - var flag: u32 = if (named) ctlfs.events.flag_builtin else 0; - if (range.q0 == range.q1 and text.len > 0) flag |= ctlfs.events.flag_expansion; - if (is_look) { - if (!named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= ctlfs.events.flag_filename; - } else if (chorded) flag |= ctlfs.events.flag_chorded; - return ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text); - } - - fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: PointerOperand) ctlfs.pane.State.Range { - const pane = p.panes[id] orelse return .{}; - if (on_tag) { - const tag = p.tagText(p.scratch.allocator(), pane) catch return .{}; - const sel = operand.expanded orelse operand.preview orelse return .{}; - const lead = @min(sel.c0, sel.c1); - const at = panes.File.rawAtDisplay(tag, @intCast(@max(0, lead))); - const q0: u32 = @intCast(@min(at, tag.len)); - return .{ .q0 = q0, .q1 = @intCast(@min(q0 + text.len, tag.len)) }; - } - const f = if (pane.file) |*file| file else return .{}; - if (operand.preview) |selection| if (pane.pointerSelection(selection)) |rows| { - if (rows.len == 0) return .{}; - const first = rows[0]; - const last = rows[rows.len - 1]; - const q0 = panes.File.lineStart(p.gpa, f, @intCast(@max(0, first.row))) + - @min(first.lo, panes.File.sourceLine(pane, first.row).len); - const q1 = panes.File.lineStart(p.gpa, f, @intCast(@max(0, last.row))) + - @min(last.hi, panes.File.sourceLine(pane, last.row).len); - // A rectangle may contain disjoint pieces. Such an operand uses - // the event's expansion text instead of inventing a source range. - if (q1 < q0 or !std.mem.eql(u8, f.content[q0..q1], text)) return .{}; - return .{ .q0 = @intCast(q0), .q1 = @intCast(q1) }; - }; - const start: ?modal.Cursor = if (operand.file_word) |w| - .{ .row = @intCast(@max(0, w.row)), .col = @intCast(@max(0, w.lo)) } - else if (operand.expanded orelse operand.preview) |sel| lead: { - // A selection's leading corner in reading order, converted the way - // `pointerOperand` converts the click itself. - const top = @min(sel.r0, sel.r1) - @as(i32, BOX_H); - if (top < 0) break :lead null; - const w = pane.wrapAt(top); - const col = edit.paneByteAtDisplay(p, pane, w.line, w.at, @min(sel.c0, sel.c1) - panes.File.gutterWidth(pane)); - break :lead .{ - .row = @intCast(@max(0, w.line)), - .col = @intCast(@max(0, col)), - }; - } else null; - const cursor = start orelse return .{}; - const q0: u32 = @intCast(@min(modal.offsetAt(f.content, cursor), f.content.len)); - return .{ .q0 = q0, .q1 = @intCast(@min(q0 + text.len, f.content.len)) }; - } - - fn dispatchPointerBuiltin( - p: *Pardes, - id: usize, - cmd: Builtin, - text: ?[]const u8, - gesture: ?struct { on_tag: bool, operand: PointerOperand }, - ) void { - const arg = p.chord_arg; - p.chord_arg = null; - defer if (arg) |a| p.gpa.free(a); - const operand = text orelse { - if (gesture) |g| _ = p.reportGesture(id, cmd, "", g.on_tag, g.operand, arg != null); - return; - }; - if (gesture) |g| if (p.reportGesture(id, cmd, operand, g.on_tag, g.operand, arg != null)) return; - p.runBuiltin(cmd, id, "", p.withArg(operand, arg)); - } - - fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { - const gesture = pane.sel[sel_slot]; - const rows = pane.pointerSelection(gesture) orelse return; - const text = pane.rawPointerText(gesture) orelse return; - if (rows.len == 0) return; - const endpoint = rows[if (gesture.r1 >= gesture.r0) rows.len - 1 else 0]; - const body = body_layer.bodyText(p, p.scratch.allocator(), pane) catch return; - const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.Terminal.gridOffset(pane)))); - const byte = if (gesture.c1 >= gesture.c0) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; - pane.cur_row = pane.surfRow(endpoint.row); - var shown = std.mem.trimEnd(u8, line[@min(endpoint.prompt_bytes, line.len)..], " \t"); - if (pane.ovl) |overlay| { - const relative = pane.cur_row - overlay.row; - if (relative >= 0 and relative < modal.lineCount(overlay.text)) - shown = modal.lineSlice(overlay.text, @intCast(relative)); - } - pane.cur_col = @intCast(modal.graphemeStart(shown, @min(shown.len, byte -| endpoint.prompt_bytes))); - pane.cur_pinned = true; - pane.msel.active = false; - pane.vsel.active = false; - pane.nsel = 0; - pane.select = false; - pane.append_at = null; - pane.sticky_col = -1; - pane.normal.clear(); - edit.setYank(p, text); - } - - fn dragRelease(p: *Pardes, button: Mouse.Button) void { - // A different button's release belongs to a chord or another host - // stream; only the button which began this gesture may end it. - if (p.drag.button() != button) return; - defer p.drag = .none; - switch (p.drag) { - .border_v => |d| { - const c = d.left_col; - const old_seam = p.col_x[c] + p.col_w[c] -| 1; - // the handle is the left pane's LAST column (inclusive), so - // the new width includes it — a no-drag click changes nothing - if (c + 1 < p.ncol and d.cur_x != old_seam) - layout.setColumnPairWidth(p, c, (d.cur_x + 1) -| p.col_x[c]); - if (d.corner) |k| { - if (d.cur_y != seamRowOf(p, k.col, k.idx)) - layout.applyRowSplit(p, k.col, k.idx, d.cur_y); - } - }, - .border_h => |d| if (d.cur_y != seamRowOf(p, d.col, d.top_idx)) - layout.applyRowSplit(p, d.col, d.top_idx, d.cur_y), - .column_move => |d| if (layout.columnBySerial(p, d.serial)) |column| switch (layout.columnDrop(p, column, d.cur_x, d.grab)) { - .stay => {}, - .reorder => |target| layout.reorderColumn(p, column, target), - .edge => |x| layout.setColumnPairWidth(p, column - 1, x - p.col_x[column - 1]), - }, - .move => |d| { - layout.movePane(p, d.id, d.cur_x, d.cur_y); - if (p.panes[d.id]) |mp| p.stillborn_joiner = mp.serial; - // a file moved into the left column evicts a lone unused shell - if (p.panes[d.id]) |mt| if (mt.file != null) { - if (layout.findPane(p, d.id)) |f| if (f.col == 0) - p.evictLonePristineTty(0, d.id); - }; - }, - .select => |s| { - const pane = p.panes[s.id] orelse return; - if (comptime pdf_enabled) { - if (s.pdf.native) { - var release = panes.Pdf.pointerRelease( - p, - pane, - s.pdf, - s.button, - s.chorded, - ); - defer release.deinit(p.pdf_gpa); - if (release.probe) |*probe| if (probe.link != null) { - p.followPdfLink(s.id, probe); - return; - }; - // A native PDF page has no byte offsets of its own to - // report, so a scripted pane cannot intercept this one. - if (release.action) |action| p.dispatchPointerBuiltin( - s.id, - if (action == .look) config.look_cmd else config.exec_cmd, - release.text, - null, - ); - return; - } - } - if (s.chorded) { - // a cut/paste chord consumed this drag; the release is inert - pane.sel[@intFromEnum(s.button)].state = .none; - return; - } - const b = @intFromEnum(s.button); - pane.sel[b].state = .done; - if (s.button == config.select_button) { - const sl = pane.sel[sel_slot]; - const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1; - if (!dragged) pane.sel[sel_slot].state = .none; - if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; - if (dragged and pane.mode == .tty) p.mirrorTtySelection(pane); - const body_vis = sl.r1 - @as(i32, BOX_H); - if (body_vis >= 0 and pane.mode != .tty) { - const w = pane.wrapAt(body_vis); - pane.cur_row = w.line; - pane.cur_col = edit.paneByteAtDisplay( - p, - pane, - w.line, - w.at, - sl.c1 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), - ); - pane.cur_pinned = true; - if (edit.clampFileCursor(pane)) pane.ensureCursorVisible(); - pane.msel.active = false; - pane.normal.clear(); - pane.vsel.active = false; - pane.nsel = 0; // a click says WHERE the one cursor is - pane.select = false; - pane.append_at = null; - pane.sticky_col = -1; - if (s.ctrl) p.lspRequest(s.id, .definition, ""); - } - } else { - const clk = pane.sel[b]; - // A right-click on a line NUMBER looks at that line of - // this file -- a sticky context header's number included, - // since the row map holds each header's own source line. - if (s.button == config.look_button and clk.r0 >= BOX_H and clk.r0 == clk.r1 and - clk.c0 == clk.c1 and clk.c0 >= 0 and pane.mode != .tty) - if (pane.file) |f| if (f.output == null and clk.c0 < panes.File.gutterWidth(pane)) { - const line = pane.wrapAt(clk.r0 - BOX_H).line; - if (line >= 0) { - pane.sel[b].state = .none; - var buf: [48]u8 = undefined; - const target = std.fmt.bufPrint(&buf, "@p{d}:{d}", .{ s.id, @as(usize, @intCast(line)) + 1 }) catch return; - p.runBuiltin(config.look_cmd, s.id, "", target); - return; - } - }; - var operand = p.pointerOperand(pane, clk); - if (operand.expanded) |expanded| - pane.sel[b] = expanded - else if (operand.text == null) - pane.sel[b].state = .none; - if (s.button == config.look_button and clk.r0 >= BOX_H and pane.mode != .tty) { - pane.cur_row = operand.row; - pane.cur_col = operand.col; - if (edit.clampFileCursor(pane)) pane.ensureCursorVisible(); - } - const txt = operand.text; - const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; - if (clk.r0 < BOX_H and s.button == config.exec_button and pane.tag_name_len != null) { - const prefix_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); - const on_name = @as(usize, @intCast(@max(0, clk.c0))) < prefix_width; - if (!p.commitTagName(pane)) return; - // Executing a staged filename commits it; executing its - // command tail uses the new identity (especially Save). - if (on_name) return; - const new_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); - const shift = @as(i32, @intCast(new_width)) - @as(i32, @intCast(prefix_width)); - if (operand.expanded) |*sel| { - sel.c0 += shift; - sel.c1 += shift; - } - if (operand.preview) |*sel| { - sel.c0 += shift; - sel.c1 += shift; - } - pane.sel[b].c0 += shift; - pane.sel[b].c1 += shift; - } - p.dispatchPointerBuiltin(s.id, cmd, txt, .{ - .on_tag = clk.r0 < BOX_H, - .operand = operand, - }); - } - }, - .tag => {}, // dragUpdate already left the tag cursor + selection set - .none => {}, - } - } - - fn chordCutPaste(p: *Pardes, cut: bool) void { - const s = &p.drag.select; - const pane = p.panes[s.id] orelse return; - if (comptime pdf_enabled) if (pane.pdf) |pv| { - if (!s.chorded) { - s.chorded = true; - pane.sel[sel_slot].state = .none; - } - // A PDF is immutable: its Cut-side chord is Snarf (copy), while - // Paste has no document mutation to perform. - if (cut and pv.selection_text.len > 0) edit.setYank(p, pv.selection_text); - return; - }; - if (pane.mode == .tty) { - if (!s.chorded) { - s.chorded = true; - pane.sel[sel_slot].state = .none; // drop the sweep highlight - } - if (cut) return; - const y = p.yank orelse return; - if (y.len == 0) return; - if (panes.Terminal.reportsMouse(pane)) { - const col: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].c1 + 1, 1, 9999)); - const row: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].r1 - @as(i32, BOX_H) + 1, 1, 9999)); - var mb: [32]u8 = undefined; - if (panes.Terminal.mouseFormatSgr(pane)) { - p.emitWrite(s.id, std.fmt.bufPrint(&mb, "\x1b[<0;{d};{d}M\x1b[<0;{d};{d}m", .{ col, row, col, row }) catch return); - } else { - // ponytail: legacy X10 bytes; add utf8/urxvt formats if an app ever wants them - const cb: u8 = @intCast(32 + @min(col, 222)); - const rb: u8 = @intCast(32 + @min(row, 222)); - p.emitWrite(s.id, &[_]u8{ 0x1b, '[', 'M', 32, cb, rb, 0x1b, '[', 'M', 35, cb, rb }); - } - } - edit.typeToTty(p, s.id, pane, y); - return; - } - if (!s.chorded) { - s.chorded = true; - const sl = pane.sel[sel_slot]; - pane.sel[sel_slot].state = .none; - const pfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; - // both ends of the sweep through the same last-frame map, so a - // chord over wrapped rows cuts the text that was under it - const w0 = pane.wrapAt(@max(0, sl.r0 - @as(i32, BOX_H))); - const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, BOX_H))); - const row0 = w0.line; - const row1 = w1.line; - const col0 = edit.paneByteAtDisplay(p, pane, w0.line, w0.at, sl.c0 - pfx); - const col1 = edit.paneByteAtDisplay(p, pane, w1.line, w1.at, sl.c1 - pfx); - pane.cur_row = row1; - pane.cur_col = col1; - pane.cur_pinned = true; - pane.msel.active = false; - pane.normal.clear(); - if (!pane.isTerminal()) pane.mode = .normal; - pane.vsel = .{ .active = row0 != row1 or col0 != col1, .row = row0, .col = col0, .explicit = false }; - pane.nsel = 0; - } - if (cut) { - if (pane.vsel.active) edit.normalDelete(p, pane, true); - } else if (pane.vsel.active) { - edit.normalReplaceYank(p, pane); - } else if (pane.file) |*f| { - // bare cursor: splice the register in literally (no linewise - // magic) so a paste right after a cut restores the text exactly - const y = p.yank orelse return; - if (y.len == 0) return; - const at = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }; - edit.pushUndo(p, pane); - const new = modal.insertAt(p.gpa, f.content, at, y) catch return; - panes.File.setContent(p, f, new); - pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; - const end = modal.advanceBy(at, y); - if (end.col > 0) { - pane.cur_row = @intCast(end.row); - pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(f.content, end.row), end.col)); - } else { - // the register ended in '\n': the cursor lands ON that newline - pane.cur_row = @intCast(end.row -| 1); - pane.cur_col = @intCast(modal.lineSlice(f.content, end.row -| 1).len); - } - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); - } else edit.pasteText(p, pane, p.yank orelse return, true, 1); - } - /// Tty: a shell in the caller's directory, raw from the first frame, /// stacked below the caller like Alt-n's new shell. pub fn spawnTty(p: *Pardes, from: usize) void { @@ -8218,7 +6844,7 @@ pub const Pardes = struct { /// when a doc lands in `col`, a lone pristine shell there is clutter — drop /// it; absorbVWeight hands its space to the doc - fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void { + pub fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void { var n_tty: usize = 0; var tty_id: usize = 0; for (0..p.col_n[col]) |k| { @@ -8485,7 +7111,7 @@ pub const Pardes = struct { }; } - fn followPdfLink(p: *Pardes, id: usize, probe: *const panes.Pdf.WordProbe) void { + pub fn followPdfLink(p: *Pardes, id: usize, probe: *const panes.Pdf.WordProbe) void { if (comptime !pdf_enabled) return; const pane = p.panes[id] orelse return; const link = probe.link orelse return; @@ -8628,7 +7254,7 @@ pub const Pardes = struct { /// Trim and unwrap clickable command-word notation once for every command /// consumer, so startup lines and interactive Exec speak the same syntax. - fn commandText(txt: []const u8) []const u8 { + pub fn commandText(txt: []const u8) []const u8 { var cmd = std.mem.trim(u8, txt, " \t\r\n"); while (config.commandWord(cmd)) |inner| cmd = std.mem.trim(u8, inner, " \t\r\n"); return cmd; @@ -9630,15 +8256,15 @@ pub const Pardes = struct { for (0..p.ncol) |cc| { if (p.hover_col < p.col_x[cc] or p.hover_col >= p.col_x[cc] + p.col_w[cc]) continue; // the same seam the h-handle hit test picks (see there) - if (p.seamIdxAt(cc, p.hover_row) != null) { + if (mouse.seamIdxAt(p, cc, p.hover_row) != null) { var col = p.col_x[cc]; while (col < p.col_x[cc] + p.col_w[cc]) : (col += 1) s.overlayDash(col, p.hover_row, "╌"); } } for (0..p.ncol -| 1) |cn| { if (p.hover_col != p.col_x[cn] + p.col_w[cn] -| 1) continue; - if (p.seamIdxAt(cn, p.hover_row) != null) continue; - if (p.seamIdxAt(cn + 1, p.hover_row) == null) continue; + if (mouse.seamIdxAt(p, cn, p.hover_row) != null) continue; + if (mouse.seamIdxAt(p, cn + 1, p.hover_row) == null) continue; var col = p.col_x[cn + 1]; while (col < p.col_x[cn + 1] + p.col_w[cn + 1]) : (col += 1) s.overlayDash(col, p.hover_row, "╌"); } @@ -11185,24 +9811,3 @@ test "jump history terminal rectangle follows output and clears on reflow" { try std.testing.expect(pane.pointerSelection(pane.sel[0]) == null); try std.testing.expectEqual(.none, pane.sel[0].state); } - -test "mouse thumb buttons navigate once and clear selection gestures" { - const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); - defer p.deinit(); - const pane = try p.setTestFile("alpha beta\ngamma delta\nepsilon zeta\n"); - pane.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); - p.njumps = 3; - p.jcur = 2; - for (0..3) |i| p.jumps[i] = .{ .pane = 0, .serial = pane.serial, .line = @intCast(i + 1), .col = 1 }; - p.drag = .{ .select = .{ .id = 0, .button = config.select_button } }; - p.update(.{ .mouse = .{ .button = .back, .kind = .press, .col = 0, .row = 0 } }); - try std.testing.expectEqual(@as(usize, 1), p.jcur); - for ([_]Mouse.Kind{ .drag, .release, .motion }) |kind| - p.update(.{ .mouse = .{ .button = .back, .kind = kind, .col = 0, .row = 0 } }); - try std.testing.expectEqual(@as(usize, 1), p.jcur); - p.update(.{ .mouse = .{ .button = .forward, .kind = .press, .col = 0, .row = 0 } }); - p.update(.{ .mouse = .{ .button = .forward, .kind = .release, .col = 0, .row = 0 } }); - try std.testing.expectEqual(@as(usize, 2), p.jcur); - try std.testing.expect(!pane.vsel.active); - try std.testing.expectEqual(.none, p.drag); -} diff --git a/src/web.zig b/src/web.zig index b5a992ae..4c2a9db8 100644 --- a/src/web.zig +++ b/src/web.zig @@ -10,6 +10,7 @@ const std = @import("std"); const pardes = @import("pardes.zig"); +const mouse = @import("mouse.zig"); const gpa = std.heap.wasm_allocator; const embedded_dump = @embedFile("embedded.dump.zon"); @@ -441,7 +442,7 @@ export fn pardes_chrome_target(col_arg: u32, row_arg: u32) u32 { const s = &(state orelse return std.math.maxInt(u32)); const col: u16 = @intCast(@min(col_arg, std.math.maxInt(u16))); const row: u16 = @intCast(@min(row_arg, std.math.maxInt(u16))); - const target = s.core.chromeTarget(col, row) orelse return std.math.maxInt(u32); + const target = mouse.chromeTarget(s.core, col, row) orelse return std.math.maxInt(u32); return (@as(u32, target.row) << 16) | target.col; } -- cgit v1.3 From 52049344c1992850ea712e029eb5c4a88a7dfe19 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 22:30:58 -0300 Subject: Move exec out of pardes.zig into exec.zig Pure move, no behaviour change (acme keeps this in exec.c): execute, commandText, max_exec_depth, executeBuiltinLine, applyStartupConfig, runBuiltin and applySettingBuiltin; the getarg-style operand code (withArg, PointerOperand, pointerOperand, heldSelection, chordEachSel); takesCommandLine and the terminals commands run in (spawnTty, spawnV9fsTty, spawnTtyWithMount, evictLonePristineTty, replaceStillborn, ttyForDir); placeDoc; and the save path (submitSave, saveFile, saveTo, askWrite), with the acme-chords test, go verbatim to exec.zig. The methods become free functions taking `p: *Pardes`. executeBuiltinLine is called from ~170 places as `p.executeBuiltinLine(..)`, so Pardes keeps one declaration alias for it and those call sites stay; the other 104 calls change from `p.execute(..)` to `exec.execute(p, ..)`. ninep/ctl.zig has a local named exec, so it writes `pardes.exec.execute` instead of importing the file. Co-Authored-By: Claude Opus 5.5 --- src/Mini.zig | 3 +- src/Output.zig | 7 +- src/builtins.zig | 15 +- src/exec.zig | 571 ++++++++++++++++++++++++++++++++++++++++++++ src/fs.zig | 1 + src/look.zig | 17 +- src/mouse.zig | 25 +- src/ninep/ctl.zig | 2 +- src/ninep/events.zig | 3 +- src/ninep/pane.zig | 3 +- src/normal.zig | 7 +- src/pardes.zig | 653 +++++---------------------------------------------- src/pdf_view.zig | 3 +- test/panes.zig | 6 +- test/pdf.zig | 2 +- 15 files changed, 681 insertions(+), 637 deletions(-) create mode 100644 src/exec.zig (limited to 'src/fs.zig') diff --git a/src/Mini.zig b/src/Mini.zig index bc93f678..52e26a37 100644 --- a/src/Mini.zig +++ b/src/Mini.zig @@ -2,6 +2,7 @@ const panes = @import("panes.zig"); const std = @import("std"); const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); const config = @import("config.zig"); const Pardes = pardes.Pardes; const modal = @import("modal.zig"); @@ -187,7 +188,7 @@ pub fn open(p: *Pardes, id: usize, argument: []const u8) !void { .syntax_dirty = false, }; pane.cur_pinned = true; - p.placeDoc(id, free, pane); + exec.placeDoc(p, id, free, pane); p.active = free; } diff --git a/src/Output.zig b/src/Output.zig index 674fcbc8..b216c0cf 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -3,6 +3,7 @@ const panes = @import("panes.zig"); const std = @import("std"); const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); const Messages = @import("Messages.zig"); const config = @import("config.zig"); const Pardes = pardes.Pardes; @@ -479,7 +480,7 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] const free = p.freeSlot() orelse return error.NoPaneSlots; const np = try open(p, free, dir, from, arg, result_content); np.file.?.location_rows = result_rows; - p.placeDoc(id, free, np); + exec.placeDoc(p, id, free, np); p.active = id; if (traits(from).steps) { pane.search_pane = free; @@ -559,7 +560,7 @@ fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void { const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); const free = p.freeSlot() orelse return error.NoPaneSlots; const np = try open(p, free, dir, from, "", content); - p.placeDoc(id, free, np); + exec.placeDoc(p, id, free, np); p.active = id; pane.search_pane = free; pane.search_row = null; @@ -778,6 +779,6 @@ fn openRead(p: *Pardes, id: usize, from: Origin, arg: []const u8, content: []u8) const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); const free = p.freeSlot() orelse return error.NoPaneSlots; const np = try open(p, free, dir, from, arg, content); - p.placeDoc(id, free, np); + exec.placeDoc(p, id, free, np); p.active = free; } diff --git a/src/builtins.zig b/src/builtins.zig index 21dd4fa9..19be62e2 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1,6 +1,7 @@ //! Command structs and runtime settings form the builtin registry; bindings live in config.zig. const std = @import("std"); const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); const look = @import("look.zig"); const edit = @import("edit.zig"); const colors = @import("colors.zig"); @@ -155,7 +156,7 @@ pub const registry = struct { inline for (manualBuiltinList(), 0..) |T, i| if (@intFromEnum(b) == i) return T.run(c); inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return c.p.applySettingBuiltin(setting, c.arg); + if (@intFromEnum(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } }; @@ -223,7 +224,7 @@ pub const Exec = struct { pub fn run(c: Ctx) void { // the destination pane is Look's business (it focuses what answered); // an execute deliberately leaves you where you were - _ = c.p.execute(c.id, c.arg orelse return); + _ = exec.execute(c.p, c.id, c.arg orelse return); } }; @@ -478,8 +479,8 @@ pub const Save = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { const path = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (path.len > 0) return c.p.saveTo(c.id, path); - if (c.pane.file) |file| if (file.output == null) return c.p.saveFile(c.id); + if (path.len > 0) return exec.saveTo(c.p, c.id, path); + if (c.pane.file) |file| if (file.output == null) return exec.saveFile(c.p, c.id); if (c.pane.file != null or c.pane.isTerminal()) c.p.startPrompt(c.pane, .save); } }; @@ -585,7 +586,7 @@ pub const DelBelow = struct { /// pane's tagline: the fast path from wherever you are to a prompt there. pub const Tty = struct { pub fn run(c: Ctx) void { - c.p.spawnTty(c.id); + exec.spawnTty(c.p, c.id); } }; @@ -593,7 +594,7 @@ pub const Tty = struct { pub const Tty9p = struct { pub const enabled = pardes.hosted and @import("builtin").os.tag == .linux; pub fn run(c: Ctx) void { - c.p.spawnV9fsTty(c.id); + exec.spawnV9fsTty(c.p, c.id); } }; @@ -609,7 +610,7 @@ pub const Tutor = struct { pub fn run(c: Ctx) void { const free = c.p.freeSlot() orelse return; const nt = c.p.openTutorView(free) catch return; - c.p.placeDoc(c.id, free, nt); // a doc like any other + exec.placeDoc(c.p, c.id, free, nt); // a doc like any other } }; diff --git a/src/exec.zig b/src/exec.zig new file mode 100644 index 00000000..75d07441 --- /dev/null +++ b/src/exec.zig @@ -0,0 +1,571 @@ +//! Executing a word (acme's exec.c): a builtin line or a command typed into +//! a terminal, the builtin dispatch and settings, the operand a click or +//! chord hands over, the terminals commands run in, placing a document, and +//! saving a pane. +const pardes = @import("pardes.zig"); +const std = @import("std"); +const layout = @import("layout.zig"); +const modal = @import("modal.zig"); +const look = @import("look.zig"); +const panes = @import("panes.zig"); +const normal = @import("normal.zig"); +const edit = @import("edit.zig"); +const body_layer = @import("body_layer.zig"); +const colors = @import("colors.zig"); +const themes = colors.themes; +const builtins = @import("builtins.zig"); +const config = @import("config.zig"); +const pdf_enabled = panes.Pdf.enabled; +const font_picker = pardes.font_picker; +const hosted = pardes.hosted; +const fonts = pardes.fonts; +const Pane = panes.Pane; +const MAX_COLS = pardes.MAX_COLS; +const BOX_H = pardes.BOX_H; +const Builtin = pardes.Builtin; +const Key = pardes.Key; +const sel_slot = pardes.sel_slot; +const Pardes = pardes.Pardes; + +pub fn takesCommandLine(p: *const Pardes, id: usize) bool { + const pane = p.panes[id] orelse return false; + if (!pane.isTerminal()) return false; + // A mounted shell sits behind sudo's process supervisor. Its OSC 133 + // prompt marks identify input readiness; the launcher's executable is + // not the shell executable used by the ordinary process heuristic. + if (pane.v9fs_on_spawn) return panes.Terminal.promptInputReady(pane); + return !p.hostTtyTaken(id); +} + +pub fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool { + if (pane.nsel == 0) return false; + const text = edit.flatSurface(p, pane) catch return false; + var ranges: [Pane.max_selections]modal.Selection = undefined; + const got = pane.ranges(text, 0, &ranges); + if (got.n < 2) return false; + + var texts: [Pane.max_selections][]u8 = undefined; + var made: usize = 0; + defer for (texts[0..made]) |t| p.gpa.free(t); + for (ranges[0..got.n]) |range| { + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + if (hi > text.len) break; + texts[made] = p.gpa.dupe(u8, text[lo..hi]) catch break; + made += 1; + } + // All or nothing, like the pipe: half a chord is not a chord. + if (made != got.n) return false; + + const id = p.active; + const serial = pane.serial; + pane.vsel.active = false; + pane.msel.active = false; + pane.select = false; + pane.nsel = 0; // the chord consumed them, exactly as it consumes one + + var primary_active: ?usize = null; + for (texts[0..made], 0..) |txt, i| { + runBuiltin(p, cmd, id, "", txt); + if (i == got.pri) primary_active = p.active; + const still = p.panes[id] orelse break; + if (still.serial != serial) break; + } + if (primary_active) |a| if (p.panes[a] != null) { + p.active = a; + }; + return true; +} + +pub const PointerOperand = struct { + /// Absolute body position corresponding to the pointed screen cell. + row: i32, + col: i32, + /// Exactly what a no-drag middle/right click will dispatch. + text: ?[]const u8 = null, + /// What hover paints. Null names the pane's live modal selection. + preview: ?Pane.Sel = null, + /// File words stay logical so a soft-wrapped operand is not cut into + /// unrelated rendered fragments. Null for tags and non-file panes. + file_word: ?look.FileWordSpan = null, + /// A newly expanded word is installed in the gesture's button slot; + /// an existing selection is only borrowed and must not replace it. + expanded: ?Pane.Sel = null, +}; + +pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand { + const visible = clicked.r0 - @as(i32, BOX_H); + const wrapped = pane.wrapAt(visible); + const raw = pane.isTerminal() and pane.mode == .tty and clicked.r0 >= BOX_H; + const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line; + const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; + const col = if (raw) + @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) + else if (clicked.r0 >= BOX_H) + edit.paneByteAtDisplay( + p, + pane, + wrapped.line, + wrapped.at, + clicked.c0 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), + ) + else + clicked.c0; + var result: PointerOperand = .{ .row = row, .col = col }; + + const kept = pane.sel[sel_slot]; + const inside_kept = if (pane.pointerSelection(kept)) |rows| inside: { + if (clicked.r0 < BOX_H) break :inside false; + if (pane.file != null and clicked.c0 < panes.File.gutterWidth(pane)) break :inside false; + const source_col: usize = @intCast(@max(0, col)); + for (rows) |span| { + const target = if (span.raw_terminal) + (if (raw) span.row else pane.surfRow(span.row)) + else + (if (raw) pane.gridRow(span.row) else span.row); + var lo = span.lo; + var hi = span.hi; + if (span.raw_terminal and !raw) { + lo -|= span.prompt_bytes; + hi -|= span.prompt_bytes; + } else if (!span.raw_terminal and raw) { + const prefix = panes.Terminal.promptPrefixBytes(pane, row, raw_line); + lo += prefix; + hi += prefix; + } + if (target == row and source_col >= lo and source_col < hi) + break :inside true; + } + break :inside false; + } else edit.spanHas(clicked.r0, clicked.c0, kept.r0, kept.c0, kept.r1, kept.c1); + if (kept.state == .done and inside_kept) { + result.text = edit.selectionText(p, pane, kept) catch null; + result.preview = kept; + return result; + } + if (pane.vsel.active and pane.vsel.explicit and + edit.spanHas(row, col, pane.vsel.row, pane.vsel.col, pane.cur_row, pane.cur_col)) + { + result.text = edit.currentSelText(p, pane); + return result; + } + if (pane.msel.active and row >= @min(pane.msel.r0, pane.msel.r1) and + row <= @max(pane.msel.r0, pane.msel.r1)) + { + result.text = edit.currentSelText(p, pane); + return result; + } + if (pane.file != null and clicked.r0 >= BOX_H and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1) { + const line = panes.File.sourceLine(pane, row); + const source_col: usize = @intCast(@max(0, col)); + const b = look.expandedWord(line, source_col) orelse return result; + const lo = std.math.cast(i32, b.lo) orelse return result; + const hi = std.math.cast(i32, b.hi) orelse return result; + result.text = line[b.lo..b.hi]; + result.file_word = .{ .row = row, .lo = lo, .hi = hi }; + + var expanded = clicked; + const first = pane.wrapRow(row, lo); + const last = pane.wrapRow(row, hi - 1); + if (first.row >= 0 and last.row >= 0) { + expanded.r0 = first.row + @as(i32, BOX_H); + expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, first.at, lo); + expanded.r1 = last.row + @as(i32, BOX_H); + expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayEndOffset(pane, row, last.at, hi - 1); + } + result.preview = expanded; + result.expanded = expanded; + return result; + } + + const expanded = look.expandedSel(p, pane, clicked) orelse return result; + result.text = edit.selectionText(p, pane, expanded) catch null; + if (result.text == null or result.text.?.len == 0) return result; + result.preview = expanded; + result.expanded = expanded; + return result; +} + +pub fn heldSelection(p: *Pardes, first: usize) ?[]const u8 { + var k: usize = 0; + while (k < p.panes.len + 2) : (k += 1) { + const i = switch (k) { + 0 => first, + 1 => p.active, + else => k - 2, + }; + if (k > 0 and (i == first or (k > 1 and i == p.active))) continue; + const t = p.panes[i] orelse continue; + if (comptime pdf_enabled) if (p.native_images) if (t.pdf) |pv| { + if (pv.selection != null and pv.selection_text.len > 0) + return pv.selection_text; + }; + if (t.sel[sel_slot].state == .done) { + if (edit.selectionText(p, t, t.sel[sel_slot]) catch null) |tx| return tx; + } else if ((t.vsel.active and t.vsel.explicit) or t.msel.active) { + if (edit.currentSelText(p, t)) |tx| return tx; + } + } + return null; +} + +pub fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 { + const a = std.mem.trim(u8, arg orelse return txt, " \t\r\n"); + if (a.len == 0) return txt; + const t = std.mem.trim(u8, txt, " \t\r\n"); + return std.fmt.allocPrint(p.scratch.allocator(), "{s} {s}", .{ t, a }) catch txt; +} + +/// Enter on a save input: the path is everything past the marker. +pub fn submitSave(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const at = switch (pane.prompt) { + .save => |a| a, + else => return, + }; + const armed = pane.tag_tail[at..pane.tag_tail_len]; + pane.tag_tail_len = at; // drop the prompt back to the seeded tail + if (!std.mem.startsWith(u8, armed, config.save_marker)) return; + const path = std.mem.trim(u8, armed[config.save_marker.len..], " \t\r\n"); + if (path.len == 0) return; + saveTo(p, id, path); +} + +/// Write the file this pane already has: acme's Put, and the one Save that +/// needs no argument because the path was never a question. +pub fn saveFile(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const f = if (pane.file) |*file| file else return; + if (f.output != null) return; // nothing behind it yet: saveTo, with a path + p.emit(.{ .save_file = .{ .pane = @intCast(id) } }); +} + +pub fn saveTo(p: *Pardes, id: usize, path: []const u8) void { + const pane = p.panes[id] orelse return; + if (path.len == 0 or path[path.len - 1] == '/' or + std.mem.indexOfScalar(u8, path, '\n') != null) + return p.reportError(id, "save", error.NoFilename); + const full = std.fs.path.resolvePosix( + p.scratch.allocator(), + &.{ Pardes.paneDir(pane), path }, + ) catch return; + if (!std.fs.path.isAbsolute(full)) return p.reportError(id, "save", error.NoDirectory); + if (full.len > Pardes.SavePath.cap) return p.reportError(id, "save", error.PathTooLong); + const f = if (pane.file) |*file| file else { + // a terminal writes its scrollback; an image and a PDF have nothing + // of their own that is unwritten, so they have nothing to write + if (pane.isTerminal()) askWrite(p, id, pane.serial, full); + return; + }; + if (f.output != null and panes.Output.fileTraits(f.output).saves) { + const owned = p.gpa.dupe(u8, full) catch return; + p.gpa.free(f.path); + f.path = owned; + f.output = null; // an ordinary file pane from here on + f.watch_after_save = true; + pane.clearCwd(); + pane.tag_init = false; // re-derive the tag as a plain file + pane.tag_tail_len = 0; + p.emit(.{ .save_file = .{ .pane = @intCast(id) } }); + return; + } + // its own path, spelled out: the in-place write, so the pane comes clean + if (f.output == null and std.mem.eql(u8, f.path, full)) return saveFile(p, id); + askWrite(p, id, pane.serial, full); +} + +fn askWrite(p: *Pardes, id: usize, serial: u32, path: []const u8) void { + p.emit(.{ .save_text = .{ + .pane = @intCast(id), + .serial = serial, + .path = Pardes.SavePath.from(path), + } }); +} + +/// Tty: a shell in the caller's directory, raw from the first frame, +/// stacked below the caller like Alt-n's new shell. +pub fn spawnTty(p: *Pardes, from: usize) void { + spawnTtyWithMount(p, from, false); +} + +pub fn spawnV9fsTty(p: *Pardes, from: usize) void { + if (comptime !hosted or @import("builtin").os.tag != .linux) + return p.reportError(from, "Tty9p", error.LinuxRequired); + if (p.fs.socket_path.len == 0) + return p.reportError(from, "Tty9p", error.SessionSocketRequired); + spawnTtyWithMount(p, from, true); +} + +fn spawnTtyWithMount(p: *Pardes, from: usize, v9fs: bool) void { + const src = p.panes[from] orelse return; + const free = p.freeSlot() orelse return; + const nt = p.newShell(free, Pardes.paneDir(src)) catch return; + nt.greet = !v9fs; + nt.v9fs_on_spawn = v9fs; + nt.mode = .tty; + const parent = layout.splitParent(p, from); + const f = layout.findPane(p, parent).?; + layout.insert(p, f.col, f.idx + 1, free); + layout.splitBelow(p, parent, nt); + p.active = free; + p.stillborn_joiner = nt.serial; +} + +/// when a doc lands in `col`, a lone pristine shell there is clutter — drop +/// it; absorbVWeight hands its space to the doc +pub fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void { + var n_tty: usize = 0; + var tty_id: usize = 0; + for (0..p.col_n[col]) |k| { + const cid = p.col_panes[col][k]; + if (p.panes[cid]) |ct| if (ct.isTerminal()) { + n_tty += 1; + tty_id = cid; + }; + } + if (n_tty != 1) return; + const tt = p.panes[tty_id] orelse return; + // No typing, cursor on the first prompt line, no scrollback: this is + // the throwaway boot placeholder a document may replace. + if (tt.ovl != null or panes.Terminal.gridCursor(tt).y != 0 or + panes.Terminal.scrollbar(tt).total > tt.rows) return; + p.deinitPane(tt) catch |err| return p.reportError(tty_id, "close", err); + layout.compute(p); // a just-stacked doc has no rect yet; absorb snaps to rows + layout.absorbVWeight(p, tty_id, null); + layout.removePane(p, tty_id); + p.panes[tty_id] = null; + if (p.active == tty_id) p.active = keep_id; +} + +/// A pane that just joined a column whose only other pane is stillborn — +/// an empty scratch nobody typed into, body or tag (what Newcol makes and +/// what a closed column's last pane leaves behind) — takes the column +/// whole: the placeholder was only holding the space for it. Run at the +/// end of a step: the pane that asked for the joiner is often the +/// placeholder itself, and its caller is still holding it. +pub fn replaceStillborn(p: *Pardes) void { + const serial = p.stillborn_joiner orelse return; + p.stillborn_joiner = null; + const new_id = p.paneBySerial(serial) orelse return; + const f = layout.findPane(p, new_id) orelse return; + if (p.col_n[f.col] != 2) return; + const old_id = p.col_panes[f.col][1 - f.idx]; + const old = p.panes[old_id] orelse return; + const file = old.file orelse return; + const out = file.output orelse return; + if (out.from != .cmd or out.from.cmd != .New) return; + if (file.revision != 0 or file.content.len != 0) return; + if (old.tag_init and !std.mem.eql(u8, old.tagSlice(), Pardes.defaultTail(old))) return; + const was_active = p.active == old_id; + layout.compute(p); // the joiner may have no rect yet; absorb snaps to rows + p.removePane(old_id, new_id) catch |err| return p.reportError(old_id, "close", err); + if (was_active) p.active = new_id; +} + +fn ttyForDir(p: *Pardes, dir: []const u8) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |tt| { + if (!std.mem.eql(u8, tt.cwdSlice(), dir)) continue; + if (takesCommandLine(p, i)) return i; + }; + const free = p.freeSlot() orelse return null; + const nt = p.newShell(free, dir) catch return null; + nt.greet = false; + const rc = if (p.ncol > 0) p.ncol - 1 else 0; + if (p.col_n[rc] > 0) { + const src = layout.splitParent(p, p.col_panes[rc][p.col_n[rc] - 1]); + const f = layout.findPane(p, src).?; + layout.splitBelow(p, src, nt); + layout.insert(p, f.col, f.idx + 1, free); + } else layout.insert(p, rc, p.col_n[rc], free); + return free; +} + +const max_exec_depth = 8; + +pub fn execute(p: *Pardes, id: usize, txt: []const u8) ?usize { + const pane = p.panes[id] orelse return null; + const cmd = commandText(txt); + if (cmd.len == 0) return null; + if (p.exec_depth == 0) p.noteHaptic(.exec); + if (executeBuiltinLine(p, id, cmd)) return null; + if (p.exec_depth >= max_exec_depth) return null; + p.exec_depth += 1; + defer p.exec_depth -= 1; + const dst = (if (takesCommandLine(p, id)) id else ttyForDir(p, Pardes.paneDir(pane))) orelse return null; + panes.Terminal.padOutputBelowEdits(p, dst); + if (panes.Terminal.queuePendingCommand(p.panes[dst].?, cmd) catch |err| { + p.reportError(id, "queue command", err); + return dst; + }) return dst; + p.emitWrite(dst, cmd); + p.emitWrite(dst, "\r"); + return dst; +} + +/// Trim and unwrap clickable command-word notation once for every command +/// consumer, so startup lines and interactive Exec speak the same syntax. +pub fn commandText(txt: []const u8) []const u8 { + var cmd = std.mem.trim(u8, txt, " \t\r\n"); + while (config.commandWord(cmd)) |inner| cmd = std.mem.trim(u8, inner, " \t\r\n"); + return cmd; +} + +pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { + const cmd = commandText(txt); + if (cmd.len == 0 or p.exec_depth >= max_exec_depth) return false; + const sp = std.mem.indexOfAny(u8, cmd, " \t"); + const bi: ?Builtin = std.meta.stringToEnum(Builtin, cmd) orelse blk: { + const head = std.meta.stringToEnum(Builtin, cmd[0 .. sp orelse break :blk null]) orelse break :blk null; + break :blk if (builtins.registry.takesArg(head)) head else null; + }; + const b = bi orelse return false; + p.exec_depth += 1; + defer p.exec_depth -= 1; + const typed = if (sp) |s| std.mem.trim(u8, cmd[s + 1 ..], " \t") else ""; + runBuiltin(p, b, id, cmd, if (typed.len > 0) typed else null); + return true; +} + +pub fn applyStartupConfig(p: *Pardes) void { + p.announce = false; + defer p.announce = true; + var lines = std.mem.splitScalar(u8, p.opts.startup_config orelse return, '\n'); + while (lines.next()) |line| _ = executeBuiltinLine(p, p.active, line); +} + +pub fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8) void { + if (!normal.multiOnce(p)) return; // a builtin is per-keystroke, never per-cursor + const pane = p.panes[id] orelse return; + // A builtin says its own name before it runs, so a tagline click is + // legible even when what it did is invisible. Whatever the builtin + // then says for itself replaces the announcement. + if (p.announce and p.settings.verbose and builtins.registry.announces(b)) { + p.setMessage(id, @tagName(b)); + pane.msg_announcement = true; + } + const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg }; + builtins.registry.dispatch(b, c); +} + +pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[]const u8) void { + const previous_colors = p.settings.colors; + const previous_context_style = p.settings.tree_context_tag_style; + const previous_transition = p.settings.panel_transition; + const previous_tagline_percent = p.settings.font.tagline_percent; + const previous_column_tags = p.settings.column_tags; + switch (setting.action) { + .theme => { + const want = std.mem.trim(u8, arg orelse return, " \t\r\n"); + for (themes, 0..) |t, i| if (std.mem.eql(u8, t.name, want)) { + colors.setThemeIndex(p, i); + return; + }; + }, + .font => { + if (comptime !font_picker) return; + const spec = config.Runtime.FontSpec.parse(arg orelse return) orelse return; + const matches = fonts.list(p.scratch.allocator(), spec.name); + if (matches.len == 0) return; + if (!p.settings.requestFont(matches[0].path, matches[0].name, spec.size_hundredths)) return; + p.font_request_taken = false; + }, + else => _ = p.settings.apply(setting, arg), + } + if (p.settings.colors != previous_colors) { + for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.file) |*file| file.syntax_dirty = true; + } + } + if (p.settings.tree_context_tag_style != previous_context_style) { + for (p.panes, 0..) |slot, id| { + p.surface.body_layers[id].rows = 0; + const pane = slot orelse continue; + pane.body_rows = 0; + pane.body_visible_rows = 0; + pane.context_row_limit = null; + pane.wrap_n = 0; + } + p.abandonPanelAnimations(); + } + const transition_changed = setting.action == .transition and + p.settings.panel_transition != previous_transition; + const tagline_metrics_changed = setting.action == .tagline_size and + p.settings.font.tagline_percent != previous_tagline_percent; + if (p.settings.column_tags != previous_column_tags) { + if (p.header_column != null) p.exitHeader(); + } + if (transition_changed or tagline_metrics_changed or p.settings.column_tags != previous_column_tags) { + p.abandonPanelAnimations(); + } +} + +pub fn placeDoc(p: *Pardes, from_id: usize, free: usize, nt: *Pane) void { + p.stillborn_joiner = nt.serial; + const doc = if (nt.file) |f| panes.Output.fileTraits(f.output).doc else true; // an image is a doc + var src_id: ?usize = null; + if (p.panes[from_id]) |src| if (if (src.file) |f| panes.Output.fileTraits(f.output).doc else src.image != null or src.hasPdf()) { + src_id = from_id; + }; + if (doc and src_id == null) { + var n = p.njumps; + while (n > 0) : (n -= 1) { + const j = p.jumps[n - 1]; + const pp = p.panes[j.pane] orelse continue; + if (pp.serial != j.serial) continue; + if (if (pp.file) |f| panes.Output.fileTraits(f.output).doc else pp.image != null or pp.hasPdf()) { + src_id = j.pane; + break; + } + } + } + if (doc and src_id == null) for (p.panes, 0..) |sl, i| { + if (sl) |pp| if (i != free and (if (pp.file) |f| panes.Output.fileTraits(f.output).doc else pp.image != null or pp.hasPdf())) { + src_id = i; + break; + }; + }; + if (!doc) if (layout.findPane(p, from_id)) |sf| { + layout.insert(p, sf.col, sf.idx + 1, free); + layout.splitBelow(p, from_id, nt); // NOT splitParent: no bystander pays + p.active = free; + return; + }; + if (src_id == null and doc and p.ncol < MAX_COLS and + layout.columnFitsHalves(p, from_id, 100) and layout.splitColumn(p, from_id, free, true)) + { + p.active = free; + return; + } + // Without room for a first-document column, split the Look origin + // just like Tty. Never displace (or evict) a top-left bystander. + const src = layout.splitParent(p, src_id orelse from_id); + const sf = layout.findPane(p, src).?; + layout.insert(p, sf.col, sf.idx + 1, free); + layout.splitBelow(p, src, nt); + p.active = free; +} + +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.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); + try std.testing.expectEqual(@as(u8, 1), pane.nsel); + + const before = p.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.ncol); + // ...and the chord consumed the selection exactly as it does with one. + try std.testing.expectEqual(@as(u8, 0), p.panes[0].?.nsel); +} diff --git a/src/fs.zig b/src/fs.zig index 13fce858..825e63bb 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -43,6 +43,7 @@ const source_files = [_]Source{ .{ .path = "src/edit.zig", .contents = @embedFile("edit.zig") }, .{ .path = "src/normal.zig", .contents = @embedFile("normal.zig") }, .{ .path = "src/mouse.zig", .contents = @embedFile("mouse.zig") }, + .{ .path = "src/exec.zig", .contents = @embedFile("exec.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/look.zig b/src/look.zig index af0905a4..1534d332 100644 --- a/src/look.zig +++ b/src/look.zig @@ -2,6 +2,7 @@ const std = @import("std"); const builtin = @import("builtin"); const libc = std.c; const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); const config = @import("config.zig"); const pdf_enabled = @import("pardes_config").mupdf; const fs = @import("fs.zig"); @@ -528,7 +529,7 @@ fn lookFirstHit(p: *Pardes, id: usize) void { rp.vsel.active = false; rp.msel.active = false; rp.select = false; - p.runBuiltin(config.look_cmd, rid, "", txt); + exec.runBuiltin(p, config.look_cmd, rid, "", txt); } pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart) !void { @@ -686,7 +687,7 @@ pub fn jumpResult(p: *Pardes, id: usize, row: usize) bool { rp.look_at = null; } if (tr.commands) { - p.runBuiltin(config.exec_cmd, rid, "", std.mem.trim(u8, ln, " \t\r")); + exec.runBuiltin(p, config.exec_cmd, rid, "", std.mem.trim(u8, ln, " \t\r")); } else if (span) |selected| { lookAt(p, rid, ln[selected.start..selected.end]); // This is the newly visited result, not a selection carried into @@ -922,7 +923,7 @@ pub fn advanceLookHover(p: *Pardes) void { pane.pdf.?.invalidateRaster(probe.page); return; }; - const operand = p.pointerOperand(pane, pointed.sel); + const operand = exec.pointerOperand(p, pane, pointed.sel); if (operand.text == null or operand.text.?.len == 0) return cancelLookHover(p); var preview = operand.preview; if (preview) |*sel| sel.state = .done; @@ -1136,7 +1137,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { noteLookSource(p, id); const command = std.mem.trim(u8, operand, " \t\r\n"); if (config.commandWord(command)) |cmd| { - if (p.execute(id, cmd)) |dst| p.active = dst; + if (exec.execute(p, id, cmd)) |dst| p.active = dst; return; } // The operand may borrow selected terminal/PDF text released below. @@ -1171,7 +1172,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { .url => |u| if (u.len <= 256) p.emit(.{ .open_link = .from(u) }), .dir => |dir| { for (p.panes, 0..) |slot, i| { - if (slot) |tt| if (std.mem.eql(u8, tt.cwdSlice(), dir) and p.takesCommandLine(i)) { + if (slot) |tt| if (std.mem.eql(u8, tt.cwdSlice(), dir) and exec.takesCommandLine(p, i)) { clearNavigationSelection(p, tt); p.active = i; p.emitWrite(i, "ls\r"); @@ -1194,7 +1195,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots); const nt = panes.Pdf.openPane(p, free, target.path, target.at.line) catch |err| return p.reportError(id, "look", err); - p.placeDoc(id, free, nt); + exec.placeDoc(p, id, free, nt); return; }; // focus an existing pane on this path (rescrolled), else open @@ -1203,7 +1204,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return p.reportError(id, "look", err); if (target.at.col > 0) nt.cur_col = @intCast(target.at.col - 1); - p.placeDoc(id, free, nt); + exec.placeDoc(p, id, free, nt); layout.compute(p); nt.file.?.scroll -|= @max(1, p.rects[free].h -| BOX_H) / 2; if (target.at.end_line != 0) { @@ -1217,7 +1218,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots); const nt = panes.Image.create(p, free, target.path, &.{}) catch |err| return p.reportError(id, "look", err); - p.placeDoc(id, free, nt); + exec.placeDoc(p, id, free, nt); }, } } diff --git a/src/mouse.zig b/src/mouse.zig index 27d5dd9c..2a00bded 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -2,6 +2,7 @@ //! releases (acme's chords, border and seam drags, gestures), and the //! chrome targets a shell asks about. const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); const layout = @import("layout.zig"); @@ -341,9 +342,9 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { if (word.len > 0) { if (m.button == config.exec_button) { const named = std.meta.stringToEnum(Builtin, word); - const held = if (named) |b| (if (builtins.registry.takesArg(b)) p.heldSelection(p.active) else null) else p.heldSelection(p.active); - _ = p.execute(p.active, p.withArg(word, held)); - } else p.runBuiltin(config.look_cmd, p.active, "", word); + const held = if (named) |b| (if (builtins.registry.takesArg(b)) exec.heldSelection(p, p.active) else null) else exec.heldSelection(p, p.active); + _ = exec.execute(p, p.active, exec.withArg(p, word, held)); + } else exec.runBuiltin(p, config.look_cmd, p.active, "", word); } } return; @@ -389,7 +390,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { config.select_button => switch (m.kind) { .press => { if (p.drag == .select and p.drag.select.button == config.exec_button) { - if (p.heldSelection(p.drag.select.id)) |tx| { + if (exec.heldSelection(p, p.drag.select.id)) |tx| { if (p.chord_arg) |old| p.gpa.free(old); p.chord_arg = p.gpa.dupe(u8, tx) catch null; } @@ -629,7 +630,7 @@ fn reportGesture( cmd: Builtin, text: []const u8, on_tag: bool, - operand: Pardes.PointerOperand, + operand: exec.PointerOperand, chorded: bool, ) bool { const scripted = p.panes[id] orelse return false; @@ -639,7 +640,7 @@ fn reportGesture( (if (on_tag) .tag_look else .body_look) else (if (on_tag) .tag_exec else .body_exec); - const named = std.meta.stringToEnum(Builtin, Pardes.commandText(text)) != null; + const named = std.meta.stringToEnum(Builtin, exec.commandText(text)) != null; const range = gestureRange(p, id, text, on_tag, operand); var flag: u32 = if (named) ctlfs.events.flag_builtin else 0; if (range.q0 == range.q1 and text.len > 0) flag |= ctlfs.events.flag_expansion; @@ -649,7 +650,7 @@ fn reportGesture( return ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text); } -fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: Pardes.PointerOperand) ctlfs.pane.State.Range { +fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: exec.PointerOperand) ctlfs.pane.State.Range { const pane = p.panes[id] orelse return .{}; if (on_tag) { const tag = p.tagText(p.scratch.allocator(), pane) catch return .{}; @@ -697,7 +698,7 @@ fn dispatchPointerBuiltin( id: usize, cmd: Builtin, text: ?[]const u8, - gesture: ?struct { on_tag: bool, operand: Pardes.PointerOperand }, + gesture: ?struct { on_tag: bool, operand: exec.PointerOperand }, ) void { const arg = p.chord_arg; p.chord_arg = null; @@ -707,7 +708,7 @@ fn dispatchPointerBuiltin( return; }; if (gesture) |g| if (reportGesture(p, id, cmd, operand, g.on_tag, g.operand, arg != null)) return; - p.runBuiltin(cmd, id, "", p.withArg(operand, arg)); + exec.runBuiltin(p, cmd, id, "", exec.withArg(p, operand, arg)); } fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { @@ -769,7 +770,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { // a file moved into the left column evicts a lone unused shell if (p.panes[d.id]) |mt| if (mt.file != null) { if (layout.findPane(p, d.id)) |f| if (f.col == 0) - p.evictLonePristineTty(0, d.id); + exec.evictLonePristineTty(p, 0, d.id); }; }, .select => |s| { @@ -848,11 +849,11 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[b].state = .none; var buf: [48]u8 = undefined; const target = std.fmt.bufPrint(&buf, "@p{d}:{d}", .{ s.id, @as(usize, @intCast(line)) + 1 }) catch return; - p.runBuiltin(config.look_cmd, s.id, "", target); + exec.runBuiltin(p, config.look_cmd, s.id, "", target); return; } }; - var operand = p.pointerOperand(pane, clk); + var operand = exec.pointerOperand(p, pane, clk); if (operand.expanded) |expanded| pane.sel[b] = expanded else if (operand.text == null) diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 25fe4037..645b1c33 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -59,7 +59,7 @@ fn activeSerial(p: *Pardes) ?u32 { fn run(p: *Pardes, id: usize, exec: bool, text: []const u8) void { const context = p.panes[id].?.serial; const before = Serials.snapshot(p); - if (exec) _ = p.execute(id, text) else look.lookAt(p, id, text); + if (exec) _ = pardes.exec.execute(p, id, text) else look.lookAt(p, id, text); const after = Serials.snapshot(p); var created = false; for (after.list[0..after.len]) |serial| if (!before.has(serial)) { diff --git a/src/ninep/events.zig b/src/ninep/events.zig index d4d7fcad..49e852b3 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -2,6 +2,7 @@ //! bounded queues that park a read until something happens. const std = @import("std"); const pardes = @import("../pardes.zig"); +const exec = @import("../exec.zig"); const look = @import("../look.zig"); const tree = @import("tree.zig"); const pane_files = @import("pane.zig"); @@ -461,7 +462,7 @@ pub fn writeEvent(p: *Pardes, req: Req, id: usize) Reply { const hi = @max(lo, @min(@as(usize, r.q1), whole.len)); const text = p.scratch.allocator().dupe(u8, whole[lo..hi]) catch continue; switch (r.action) { - .body_exec, .tag_exec => _ = p.execute(live, text), + .body_exec, .tag_exec => _ = exec.execute(p, live, text), .body_look, .tag_look => look.lookAt(p, live, text), else => unreachable, } diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 4110380a..76854dbc 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -3,6 +3,7 @@ //! mark and scroll, errors, event, look and exec. Terminals add pty/ (pty.zig). const std = @import("std"); const pardes = @import("../pardes.zig"); +const exec = @import("../exec.zig"); const look = @import("../look.zig"); const panes = @import("../panes.zig"); const modal = @import("../modal.zig"); @@ -589,7 +590,7 @@ pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { p.gpa.free(content); return null; }; - p.placeDoc(id, free, np); + exec.placeDoc(p, id, free, np); return text.len; } diff --git a/src/normal.zig b/src/normal.zig index e273f7f1..6647dcca 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -2,6 +2,7 @@ //! modal actions, replayed across every selection, and each action is done //! to the pane; PDF panes get their own normal keys. const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); const mvzr = @import("mvzr"); @@ -302,7 +303,7 @@ fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) v switch (semantic) { .escape => { pane.select = false; - return p.runBuiltin(.Last, p.active, "", null); + return exec.runBuiltin(p, .Last, p.active, "", null); }, .goto => |go| switch (go.target) { .file_start => { @@ -566,11 +567,11 @@ pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { if (hit(key, config.leave_pane)) { pane.normal.clear(); pane.select = false; - return p.runBuiltin(.Last, p.active, "", null); + return exec.runBuiltin(p, .Last, p.active, "", null); } if (pane.normal.prefix == .none and isPrefix(key, 'f')) { pane.normal.clear(); - return p.runBuiltin(.PdfSections, p.active, "", null); + return exec.runBuiltin(p, .PdfSections, p.active, "", null); } const parsed = modal.Normal.parse(&pane.normal, normalInput(key)); switch (parsed) { diff --git a/src/pardes.zig b/src/pardes.zig index bdde1455..75766827 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const exec = @import("exec.zig"); pub const mouse = @import("mouse.zig"); pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); @@ -435,6 +436,7 @@ pub const Loc = struct { }; test { + _ = @import("exec.zig"); _ = @import("look.zig"); _ = @import("mouse.zig"); _ = @import("normal.zig"); @@ -497,7 +499,7 @@ pub const test_api = if (@import("builtin").is_test) struct { arg: ?[]const u8, ) bool { const command = std.meta.stringToEnum(Builtin, name) orelse return false; - p.runBuiltin(command, id, txt, arg); + exec.runBuiltin(p, command, id, txt, arg); return true; } @@ -510,7 +512,7 @@ pub const test_api = if (@import("builtin").is_test) struct { } pub fn heldSelection(p: *Pardes, first: usize) ?[]const u8 { - return p.heldSelection(first); + return exec.heldSelection(p, first); } } else struct {}; @@ -581,30 +583,6 @@ test "Detach asks the frontend to leave, and says so when there is nothing to le try std.testing.expect(!p.quit); } -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.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); - try std.testing.expectEqual(@as(u8, 1), pane.nsel); - - const before = p.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.ncol); - // ...and the chord consumed the selection exactly as it does with one. - try std.testing.expectEqual(@as(u8, 0), p.panes[0].?.nsel); -} - test "startup config runs builtin lines in order and isolates bad lines" { const p = try Pardes.init(std.testing.allocator, .{ .startup_config = @@ -1188,11 +1166,11 @@ test "Tty9p marks only the new Linux terminal for a mounted shell" { try std.testing.expect(pane.isTerminal() and pane.mode == .tty); try std.testing.expect(pane.v9fs_on_spawn); try std.testing.expect(!pane.greet); - try std.testing.expect(!p.takesCommandLine(p.active)); + try std.testing.expect(!exec.takesCommandLine(p, p.active)); panes.Terminal.feedOutput(p, pane, "\x1b]133;A\x07$ \x1b]133;B\x07"); - try std.testing.expect(p.takesCommandLine(p.active)); + try std.testing.expect(exec.takesCommandLine(p, p.active)); panes.Terminal.feedOutput(p, pane, "\x1b]133;C\x07"); - try std.testing.expect(!p.takesCommandLine(p.active)); + try std.testing.expect(!exec.takesCommandLine(p, p.active)); } test "first document fallback splits like Tty from the originating pane" { @@ -1215,8 +1193,8 @@ test "first document fallback splits like Tty from the originating pane" { p.active = (from + 1) % 3; const free = p.freeSlot().?; const doc = try p.openTutorView(free); - p.placeDoc(from, free, doc); - tty.spawnTty(from); + exec.placeDoc(p, from, free, doc); + exec.spawnTty(tty, from); p.sync(); tty.sync(); try std.testing.expectEqual(@as(usize, 2), p.ncol); @@ -1240,7 +1218,7 @@ test "first document keeps its originating shell and only opens a column when it defer p.deinit(); const shell = p.panes[0].?; const doc = try p.openTutorView(1); - p.placeDoc(0, 1, doc); + exec.placeDoc(p, 0, 1, doc); p.sync(); try std.testing.expectEqual(shell, p.panes[0].?); try std.testing.expectEqual(@as(usize, 1), p.active); @@ -1318,7 +1296,7 @@ test "unknown Exec from an image writes to a terminal in the image directory" { const image_doc = try p.newDocPane(1); image_doc.image = .{ .path = try gpa.dupe(u8, "/tmp/pardes-image-dir/pic.ppm") }; try std.testing.expectEqualStrings("/tmp/pardes-image-dir", Pardes.paneDir(image_doc)); - try std.testing.expectEqual(@as(?usize, 0), p.execute(1, "echo image-fallback")); + try std.testing.expectEqual(@as(?usize, 0), exec.execute(p, 1, "echo image-fallback")); var sent: [256]u8 = undefined; var sent_len: usize = 0; @@ -1364,7 +1342,7 @@ test "Exec in a terminal whose tty is taken spawns a shell instead of typing at var host: FakeTtyQuery = .{}; host.install(p); host.taken[0] = true; - const dst = p.execute(0, "echo taken-fallback") orelse return error.ExecFoundNowhereToRun; + const dst = exec.execute(p, 0, "echo taken-fallback") orelse return error.ExecFoundNowhereToRun; // somewhere ELSE — and still without moving focus, which is execute's // contract and the whole difference between it and a look try std.testing.expect(dst != 0); @@ -1466,7 +1444,7 @@ test "Exec from a document pane skips an occupied terminal in its directory and host.install(p); host.taken[0] = true; - const dst = p.execute(1, "echo image-fallback") orelse return error.ExecFoundNowhereToRun; + const dst = exec.execute(p, 1, "echo image-fallback") orelse return error.ExecFoundNowhereToRun; try std.testing.expect(dst != 0 and dst != 1); var spawned: ?Effect = null; @@ -1551,13 +1529,13 @@ test "a terminal its program gave back takes command lines again" { var host: FakeTtyQuery = .{}; host.install(p); host.taken[0] = true; - try std.testing.expect(p.execute(0, "echo while-taken") != 0); + try std.testing.expect(exec.execute(p, 0, "echo while-taken") != 0); while (p.nextEffect()) |_| {} // the program exited, so the host's answer changes — and the core asks // again, because it never cached the old one host.taken[0] = false; - try std.testing.expectEqual(@as(?usize, 0), p.execute(0, "echo after")); + try std.testing.expectEqual(@as(?usize, 0), exec.execute(p, 0, "echo after")); var sent: [64]u8 = undefined; var sent_len: usize = 0; while (p.nextEffect()) |effect| switch (effect) { @@ -1595,13 +1573,13 @@ test "the host is asked about a tty only where a command line is about to go" { try std.testing.expectEqual(@as(usize, 0), host.asked); // The pane an Exec is typed into is one question, asked once... - _ = p.execute(0, "echo lazy"); + _ = exec.execute(p, 0, "echo lazy"); while (p.nextEffect()) |_| {} try std.testing.expectEqual(@as(usize, 1), host.asked); host.taken[0] = true; host.asked = 0; - _ = p.execute(0, "echo lazy-again"); + _ = exec.execute(p, 0, "echo lazy-again"); while (p.nextEffect()) |_| {} try std.testing.expectEqual(@as(usize, 2), host.asked); } @@ -1654,7 +1632,7 @@ test "owned cwd preserves long paths aliases and failed updates" { const free = p.freeSlot().?; try std.testing.expectError(error.PathTooLong, p.newShell(free, path[0 .. effect_path_cap + 1])); try std.testing.expect(p.panes[free] == null); - p.saveTo(0, "file.txt"); + exec.saveTo(p, 0, "file.txt"); try std.testing.expectEqual(effects, p.effects_len); try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "PathTooLong") != null); @@ -1820,7 +1798,7 @@ test "owned cwd Save promotion releases the former directory" { const id = p.active; const pane = p.panes[id].?; try pane.setOwnedCwd("/old/directory"); - p.saveTo(id, "saved.txt"); + exec.saveTo(p, id, "saved.txt"); try std.testing.expect(pane.cwd == .none); try std.testing.expect(pane.file.?.output == null); try std.testing.expectEqualStrings("/old/directory/saved.txt", pane.file.?.path); @@ -1847,7 +1825,7 @@ test "Save on a scratch asks for a path in its inherited dir and makes it a file // typing the filename and submitting converts it into an ordinary file try std.testing.expect(np.appendTag("note.txt")); - p.submitSave(id); + exec.submitSave(p, id); try std.testing.expect(np.file.?.output == null); try std.testing.expectEqualStrings("/tmp/pardes-save-dir/note.txt", np.file.?.path); var saved = false; @@ -1872,7 +1850,7 @@ test "Save on a terminal writes its plaintext scrollback and stays a terminal" { try std.testing.expect(p.executeBuiltinLine(0, "Save")); try std.testing.expect(pane.prompt == .save); try std.testing.expect(pane.appendTag("log.txt")); - p.submitSave(0); + exec.submitSave(p, 0); // the pane is untouched: still a terminal, no file behind it try std.testing.expect(pane.isTerminal()); @@ -1921,7 +1899,7 @@ test "Save on an output buffer writes its rows out and leaves the buffer alone" try std.testing.expect(p.executeBuiltinLine(id, "Save")); try std.testing.expect(out.prompt == .save); try std.testing.expect(out.appendTag("help.txt")); - p.submitSave(id); + exec.submitSave(p, id); // the buffer itself is untouched: same origin, same name, still refillable // and still walked by n/N, because a saved copy of a list is only a copy @@ -2156,7 +2134,7 @@ test "a save path that names no file is refused before anything is rewritten" { try std.testing.expect(p.executeBuiltinLine(id, "Save")); try std.testing.expect(scratch.prompt == .save); - p.submitSave(id); + exec.submitSave(p, id); var buf: [256]u8 = undefined; try std.testing.expect(drainForSavePath(p, &buf) == null); try std.testing.expect(scratch.file.?.output != null); @@ -2213,7 +2191,7 @@ test "a builtin that needs a pane reports capacity failure when every slot is fu _ = try p.newDocPane(id); }; const help = std.meta.stringToEnum(Builtin, "Help") orelse return error.MissingHelpBuiltin; - p.runBuiltin(help, 0, "", null); + exec.runBuiltin(p, help, 0, "", null); try std.testing.expect(std.mem.indexOf(u8, p.panes[0].?.msg[0..p.panes[0].?.msg_len], "help: NoPaneSlots") != null); } @@ -2760,7 +2738,7 @@ test "column tags follow their column through split and close" { defer p.deinit(); _ = try p.setTestFile("left\n"); try std.testing.expect(p.col_tags[0].set("Left Find")); - _ = p.execute(0, "Newcol"); + _ = exec.execute(p, 0, "Newcol"); try std.testing.expectEqual(@as(usize, 2), p.ncol); try std.testing.expectEqualStrings("Left Find", p.columnTag(0)); try std.testing.expect(p.col_tags[1].set("Right Grep")); @@ -3362,7 +3340,7 @@ test "canonical fallback and transition toggle retire unpresented tracks" { const moving = try p.render(frame.allocator()); p.acknowledgePanelPresentation(moving.panelTracks()); try std.testing.expect(moving.panelTracks().len > 0); - p.applySettingBuiltin(config.Runtime.find("PanelZoom").?, null); + exec.applySettingBuiltin(p, config.Runtime.find("PanelZoom").?, null); try std.testing.expectEqual(layout.Transition.zoom, p.settings.panel_transition); try std.testing.expect(p.presentation.pending); try std.testing.expect(p.presentation.pointer(p.screen_w, p.screen_h, 10, 4) == null); @@ -3379,11 +3357,11 @@ test "canonical fallback and transition toggle retire unpresented tracks" { const old_tagline_percent = p.settings.font.tagline_percent; var percent_buf: [3]u8 = undefined; const same_percent = try std.fmt.bufPrint(&percent_buf, "{d}", .{old_tagline_percent}); - p.applySettingBuiltin(config.Runtime.find("TaglineSize").?, same_percent); + exec.applySettingBuiltin(p, config.Runtime.find("TaglineSize").?, same_percent); try std.testing.expect(p.animationActive()); const changed_percent: u8 = if (old_tagline_percent == 73) 74 else 73; const changed_text = try std.fmt.bufPrint(&percent_buf, "{d}", .{changed_percent}); - p.applySettingBuiltin(config.Runtime.find("TaglineSize").?, changed_text); + exec.applySettingBuiltin(p, config.Runtime.find("TaglineSize").?, changed_text); try std.testing.expectEqual(changed_percent, p.settings.font.tagline_percent); try std.testing.expect(p.presentation.pending); for (p.presentation.tracks) |track| try std.testing.expect(track == null); @@ -3839,6 +3817,10 @@ pub const Pardes = struct { pub const setMessage = Messages.setMessage; pub const reportError = Messages.reportError; + /// Running a builtin line, called from everywhere as + /// `p.executeBuiltinLine(...)`; it lives with the rest of exec in exec.zig. + pub const executeBuiltinLine = exec.executeBuiltinLine; + pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes { const image_gpa = opts.image_allocator orelse gpa; const pdf_gpa = opts.pdf_allocator orelse gpa; @@ -3936,7 +3918,7 @@ pub const Pardes = struct { }, } p.sync(); - p.applyStartupConfig(); + exec.applyStartupConfig(p); colors.finishThemeInitialization(p); p.sync(); p.presentation.enabled = true; @@ -4272,16 +4254,6 @@ pub const Pardes = struct { if (look.lookHoverPane(p) == id) look.cancelLookHover(p); } - pub fn takesCommandLine(p: *const Pardes, id: usize) bool { - const pane = p.panes[id] orelse return false; - if (!pane.isTerminal()) return false; - // A mounted shell sits behind sudo's process supervisor. Its OSC 133 - // prompt marks identify input readiness; the launcher's executable is - // not the shell executable used by the ordinary process heuristic. - if (pane.v9fs_on_spawn) return panes.Terminal.promptInputReady(pane); - return !p.hostTtyTaken(id); - } - pub fn shellBin(p: *const Pardes) []const u8 { const selected = p.settings.shell.requested.get(); return if (selected.len == 0) config.default_shell else selected; @@ -4631,7 +4603,7 @@ pub const Pardes = struct { } pub fn update(p: *Pardes, ev: Event) void { - defer p.replaceStillborn(); + defer exec.replaceStillborn(p); // A tick with nothing animating is the one event that cannot change // the screen. p.needs_frame = p.needs_frame or ev != .tick; @@ -4805,7 +4777,7 @@ pub const Pardes = struct { return defaultTail(pane); } - fn defaultTail(pane: *const Pane) []const u8 { + pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; if (pane.file) |file| if (file.output) |out| if (panes.Output.usesLocationsConfig(out.from)) return locations_pane_tail; @@ -5029,7 +5001,7 @@ pub const Pardes = struct { } if (p.tagChordText(pane)) |txt| { pane.tag_sel = false; - p.runBuiltin(if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", txt); + exec.runBuiltin(p, if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", txt); } return; } @@ -5086,7 +5058,7 @@ pub const Pardes = struct { const body_mode = pane.tag_mode; exitTagEdit(pane); // leave the tag FIRST: Del frees the pane pane.mode = body_mode; - p.runBuiltin(cmd, id, "", txt); + exec.runBuiltin(p, cmd, id, "", txt); return; } if (hit(key, config.tag_yank)) { @@ -5116,7 +5088,7 @@ pub const Pardes = struct { } else null; if (dir) |d| { const from = p.active; - p.runBuiltin(d, from, "", null); + exec.runBuiltin(p, d, from, "", null); if (p.active == from) { if (d == .Up) { exitTagEdit(pane); @@ -5208,8 +5180,8 @@ pub const Pardes = struct { if (word.len > 0) { if (!p.header_insert) { // Preserve the workspace tag's keyboard command semantics. - _ = p.execute(p.active, word); - } else p.runBuiltin(if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", word); + _ = exec.execute(p, p.active, word); + } else exec.runBuiltin(p, if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", word); } return; } @@ -5295,185 +5267,6 @@ pub const Pardes = struct { if (col) |c| p.topbar_col = @intCast(@min(c, modal.prevGrapheme(bar, bar.len))); } - fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool { - if (pane.nsel == 0) return false; - const text = edit.flatSurface(p, pane) catch return false; - var ranges: [Pane.max_selections]modal.Selection = undefined; - const got = pane.ranges(text, 0, &ranges); - if (got.n < 2) return false; - - var texts: [Pane.max_selections][]u8 = undefined; - var made: usize = 0; - defer for (texts[0..made]) |t| p.gpa.free(t); - for (ranges[0..got.n]) |range| { - const lo = @min(range.anchor, range.head); - const hi = @max(range.anchor, range.head); - if (hi > text.len) break; - texts[made] = p.gpa.dupe(u8, text[lo..hi]) catch break; - made += 1; - } - // All or nothing, like the pipe: half a chord is not a chord. - if (made != got.n) return false; - - const id = p.active; - const serial = pane.serial; - pane.vsel.active = false; - pane.msel.active = false; - pane.select = false; - pane.nsel = 0; // the chord consumed them, exactly as it consumes one - - var primary_active: ?usize = null; - for (texts[0..made], 0..) |txt, i| { - p.runBuiltin(cmd, id, "", txt); - if (i == got.pri) primary_active = p.active; - const still = p.panes[id] orelse break; - if (still.serial != serial) break; - } - if (primary_active) |a| if (p.panes[a] != null) { - p.active = a; - }; - return true; - } - - pub const PointerOperand = struct { - /// Absolute body position corresponding to the pointed screen cell. - row: i32, - col: i32, - /// Exactly what a no-drag middle/right click will dispatch. - text: ?[]const u8 = null, - /// What hover paints. Null names the pane's live modal selection. - preview: ?Pane.Sel = null, - /// File words stay logical so a soft-wrapped operand is not cut into - /// unrelated rendered fragments. Null for tags and non-file panes. - file_word: ?look.FileWordSpan = null, - /// A newly expanded word is installed in the gesture's button slot; - /// an existing selection is only borrowed and must not replace it. - expanded: ?Pane.Sel = null, - }; - - pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand { - const visible = clicked.r0 - @as(i32, BOX_H); - const wrapped = pane.wrapAt(visible); - const raw = pane.isTerminal() and pane.mode == .tty and clicked.r0 >= BOX_H; - const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line; - const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; - const col = if (raw) - @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) - else if (clicked.r0 >= BOX_H) - edit.paneByteAtDisplay( - p, - pane, - wrapped.line, - wrapped.at, - clicked.c0 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), - ) - else - clicked.c0; - var result: PointerOperand = .{ .row = row, .col = col }; - - const kept = pane.sel[sel_slot]; - const inside_kept = if (pane.pointerSelection(kept)) |rows| inside: { - if (clicked.r0 < BOX_H) break :inside false; - if (pane.file != null and clicked.c0 < panes.File.gutterWidth(pane)) break :inside false; - const source_col: usize = @intCast(@max(0, col)); - for (rows) |span| { - const target = if (span.raw_terminal) - (if (raw) span.row else pane.surfRow(span.row)) - else - (if (raw) pane.gridRow(span.row) else span.row); - var lo = span.lo; - var hi = span.hi; - if (span.raw_terminal and !raw) { - lo -|= span.prompt_bytes; - hi -|= span.prompt_bytes; - } else if (!span.raw_terminal and raw) { - const prefix = panes.Terminal.promptPrefixBytes(pane, row, raw_line); - lo += prefix; - hi += prefix; - } - if (target == row and source_col >= lo and source_col < hi) - break :inside true; - } - break :inside false; - } else edit.spanHas(clicked.r0, clicked.c0, kept.r0, kept.c0, kept.r1, kept.c1); - if (kept.state == .done and inside_kept) { - result.text = edit.selectionText(p, pane, kept) catch null; - result.preview = kept; - return result; - } - if (pane.vsel.active and pane.vsel.explicit and - edit.spanHas(row, col, pane.vsel.row, pane.vsel.col, pane.cur_row, pane.cur_col)) - { - result.text = edit.currentSelText(p, pane); - return result; - } - if (pane.msel.active and row >= @min(pane.msel.r0, pane.msel.r1) and - row <= @max(pane.msel.r0, pane.msel.r1)) - { - result.text = edit.currentSelText(p, pane); - return result; - } - if (pane.file != null and clicked.r0 >= BOX_H and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1) { - const line = panes.File.sourceLine(pane, row); - const source_col: usize = @intCast(@max(0, col)); - const b = look.expandedWord(line, source_col) orelse return result; - const lo = std.math.cast(i32, b.lo) orelse return result; - const hi = std.math.cast(i32, b.hi) orelse return result; - result.text = line[b.lo..b.hi]; - result.file_word = .{ .row = row, .lo = lo, .hi = hi }; - - var expanded = clicked; - const first = pane.wrapRow(row, lo); - const last = pane.wrapRow(row, hi - 1); - if (first.row >= 0 and last.row >= 0) { - expanded.r0 = first.row + @as(i32, BOX_H); - expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, first.at, lo); - expanded.r1 = last.row + @as(i32, BOX_H); - expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayEndOffset(pane, row, last.at, hi - 1); - } - result.preview = expanded; - result.expanded = expanded; - return result; - } - - const expanded = look.expandedSel(p, pane, clicked) orelse return result; - result.text = edit.selectionText(p, pane, expanded) catch null; - if (result.text == null or result.text.?.len == 0) return result; - result.preview = expanded; - result.expanded = expanded; - return result; - } - - pub fn heldSelection(p: *Pardes, first: usize) ?[]const u8 { - var k: usize = 0; - while (k < p.panes.len + 2) : (k += 1) { - const i = switch (k) { - 0 => first, - 1 => p.active, - else => k - 2, - }; - if (k > 0 and (i == first or (k > 1 and i == p.active))) continue; - const t = p.panes[i] orelse continue; - if (comptime pdf_enabled) if (p.native_images) if (t.pdf) |pv| { - if (pv.selection != null and pv.selection_text.len > 0) - return pv.selection_text; - }; - if (t.sel[sel_slot].state == .done) { - if (edit.selectionText(p, t, t.sel[sel_slot]) catch null) |tx| return tx; - } else if ((t.vsel.active and t.vsel.explicit) or t.msel.active) { - if (edit.currentSelText(p, t)) |tx| return tx; - } - } - return null; - } - - pub fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 { - const a = std.mem.trim(u8, arg orelse return txt, " \t\r\n"); - if (a.len == 0) return txt; - const t = std.mem.trim(u8, txt, " \t\r\n"); - return std.fmt.allocPrint(p.scratch.allocator(), "{s} {s}", .{ t, a }) catch txt; - } - /// Cycle only the body modes supported by this pane. pub fn cycleMode(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; @@ -5516,8 +5309,8 @@ pub const Pardes = struct { const asked = slot orelse continue; if (asked.prompt != .del_side) continue; asked.prompt = .none; - if (hit(key, config.del_above)) p.runBuiltin(.Del, id, "", "k"); - if (hit(key, config.del_below)) p.runBuiltin(.Del, id, "", "j"); + if (hit(key, config.del_above)) exec.runBuiltin(p, .Del, id, "", "k"); + if (hit(key, config.del_below)) exec.runBuiltin(p, .Del, id, "", "j"); return; } if (p.topbar_col != null) return p.topbarKey(key); @@ -5530,9 +5323,9 @@ pub const Pardes = struct { // Shift-Escape is the unconditional way out, even mid-application; // bare Escape only leaves at a shell prompt. if (hit(key, config.tty_toggle_alt)) - return p.runBuiltin(.Last, p.active, "", null); - if (key.cp == Key.escape and !key.ctrl and !key.alt and !key.shift and p.takesCommandLine(p.active)) - return p.runBuiltin(.Last, p.active, "", null); + return exec.runBuiltin(p, .Last, p.active, "", null); + if (key.cp == Key.escape and !key.ctrl and !key.alt and !key.shift and exec.takesCommandLine(p, p.active)) + return exec.runBuiltin(p, .Last, p.active, "", null); panes.Terminal.followOutput(pane); // typing snaps back to live output // Paste stays the window's, the one exception to forwarding a raw // tty's keys: Ctrl-V types the register at the program and @@ -5554,7 +5347,7 @@ pub const Pardes = struct { if (p.ctrl_w_pending) { p.ctrl_w_pending = false; for (config.window_keys) |wk| { - if (hit(key, &.{ wk.letter, wk.arrow })) return p.runBuiltin(wk.cmd, p.active, "", null); + if (hit(key, &.{ wk.letter, wk.arrow })) return exec.runBuiltin(p, wk.cmd, p.active, "", null); } return; } @@ -5579,7 +5372,7 @@ pub const Pardes = struct { return; } for (config.jump_keys) |jk| { - if (hit(key, &.{jk.chord})) return p.runBuiltin(jk.cmd, p.active, "", null); + if (hit(key, &.{jk.chord})) return exec.runBuiltin(p, jk.cmd, p.active, "", null); } if (hit(key, config.pane_to_new_column)) { const f = layout.findPane(p, p.active).?; @@ -5601,7 +5394,7 @@ pub const Pardes = struct { pane.tag_tail_len = @min(pipe.at, pane.tag_tail_len); }, .save => |at| { - if (submit) p.submitSave(p.active) else pane.tag_tail_len = @min(at, pane.tag_tail_len); + if (submit) exec.submitSave(p, p.active) else pane.tag_tail_len = @min(at, pane.tag_tail_len); }, .search => |at| { if (submit) @@ -5629,18 +5422,18 @@ pub const Pardes = struct { const explicit = (p.native_images and pane.hasPdfSelection()) or (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; if (explicit) { - if (p.chordEachSel(pane, cmd)) return; + if (exec.chordEachSel(p, pane, cmd)) return; if (edit.currentSelText(p, pane)) |txt| { pane.vsel.active = false; pane.msel.active = false; pane.select = false; - p.runBuiltin(cmd, p.active, "", txt); + exec.runBuiltin(p, cmd, p.active, "", txt); return; } } const sel = look.expandedSel(p, pane, look.cursorWordSel(p, pane)) orelse return; const word = edit.selectionText(p, pane, sel) catch return; - p.runBuiltin(cmd, p.active, "", word); + exec.runBuiltin(p, cmd, p.active, "", word); return; } if (pane.mode == .normal and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); @@ -5672,7 +5465,7 @@ pub const Pardes = struct { // a path-less builtin is a row here too (it is the same index Help // reads), and SPC cannot reach one — so both scans skip it for (builtin_rows) |row| { - if (std.mem.eql(u8, row.path orelse continue, pfx)) return p.runBuiltin(row.cmd, p.active, "", null); + if (std.mem.eql(u8, row.path orelse continue, pfx)) return exec.runBuiltin(p, row.cmd, p.active, "", null); } for (builtin_rows) |row| { if (std.mem.startsWith(u8, row.path orelse continue, pfx)) { @@ -5744,73 +5537,7 @@ pub const Pardes = struct { pane.tag_col = @intCast(prefix_len + pane.tag_tail_len); } - /// Enter on a save input: the path is everything past the marker. - fn submitSave(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const at = switch (pane.prompt) { - .save => |a| a, - else => return, - }; - const armed = pane.tag_tail[at..pane.tag_tail_len]; - pane.tag_tail_len = at; // drop the prompt back to the seeded tail - if (!std.mem.startsWith(u8, armed, config.save_marker)) return; - const path = std.mem.trim(u8, armed[config.save_marker.len..], " \t\r\n"); - if (path.len == 0) return; - p.saveTo(id, path); - } - - /// Write the file this pane already has: acme's Put, and the one Save that - /// needs no argument because the path was never a question. - pub fn saveFile(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const f = if (pane.file) |*file| file else return; - if (f.output != null) return; // nothing behind it yet: saveTo, with a path - p.emit(.{ .save_file = .{ .pane = @intCast(id) } }); - } - - pub fn saveTo(p: *Pardes, id: usize, path: []const u8) void { - const pane = p.panes[id] orelse return; - if (path.len == 0 or path[path.len - 1] == '/' or - std.mem.indexOfScalar(u8, path, '\n') != null) - return p.reportError(id, "save", error.NoFilename); - const full = std.fs.path.resolvePosix( - p.scratch.allocator(), - &.{ paneDir(pane), path }, - ) catch return; - if (!std.fs.path.isAbsolute(full)) return p.reportError(id, "save", error.NoDirectory); - if (full.len > SavePath.cap) return p.reportError(id, "save", error.PathTooLong); - const f = if (pane.file) |*file| file else { - // a terminal writes its scrollback; an image and a PDF have nothing - // of their own that is unwritten, so they have nothing to write - if (pane.isTerminal()) p.askWrite(id, pane.serial, full); - return; - }; - if (f.output != null and panes.Output.fileTraits(f.output).saves) { - const owned = p.gpa.dupe(u8, full) catch return; - p.gpa.free(f.path); - f.path = owned; - f.output = null; // an ordinary file pane from here on - f.watch_after_save = true; - pane.clearCwd(); - pane.tag_init = false; // re-derive the tag as a plain file - pane.tag_tail_len = 0; - p.emit(.{ .save_file = .{ .pane = @intCast(id) } }); - return; - } - // its own path, spelled out: the in-place write, so the pane comes clean - if (f.output == null and std.mem.eql(u8, f.path, full)) return p.saveFile(id); - p.askWrite(id, pane.serial, full); - } - - const SavePath = Effect.Buf(effect_path_cap); - - fn askWrite(p: *Pardes, id: usize, serial: u32, path: []const u8) void { - p.emit(.{ .save_text = .{ - .pane = @intCast(id), - .serial = serial, - .path = SavePath.from(path), - } }); - } + pub const SavePath = Effect.Buf(effect_path_cap); pub fn lspRequest(p: *Pardes, id: usize, kind: lsp.Kind, arg: []const u8) void { if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary @@ -6054,104 +5781,6 @@ pub const Pardes = struct { p.settings.scene_effects = .{}; } - /// Tty: a shell in the caller's directory, raw from the first frame, - /// stacked below the caller like Alt-n's new shell. - pub fn spawnTty(p: *Pardes, from: usize) void { - p.spawnTtyWithMount(from, false); - } - - pub fn spawnV9fsTty(p: *Pardes, from: usize) void { - if (comptime !hosted or @import("builtin").os.tag != .linux) - return p.reportError(from, "Tty9p", error.LinuxRequired); - if (p.fs.socket_path.len == 0) - return p.reportError(from, "Tty9p", error.SessionSocketRequired); - p.spawnTtyWithMount(from, true); - } - - fn spawnTtyWithMount(p: *Pardes, from: usize, v9fs: bool) void { - const src = p.panes[from] orelse return; - const free = p.freeSlot() orelse return; - const nt = p.newShell(free, paneDir(src)) catch return; - nt.greet = !v9fs; - nt.v9fs_on_spawn = v9fs; - nt.mode = .tty; - const parent = layout.splitParent(p, from); - const f = layout.findPane(p, parent).?; - layout.insert(p, f.col, f.idx + 1, free); - layout.splitBelow(p, parent, nt); - p.active = free; - p.stillborn_joiner = nt.serial; - } - - /// when a doc lands in `col`, a lone pristine shell there is clutter — drop - /// it; absorbVWeight hands its space to the doc - pub fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void { - var n_tty: usize = 0; - var tty_id: usize = 0; - for (0..p.col_n[col]) |k| { - const cid = p.col_panes[col][k]; - if (p.panes[cid]) |ct| if (ct.isTerminal()) { - n_tty += 1; - tty_id = cid; - }; - } - if (n_tty != 1) return; - const tt = p.panes[tty_id] orelse return; - // No typing, cursor on the first prompt line, no scrollback: this is - // the throwaway boot placeholder a document may replace. - if (tt.ovl != null or panes.Terminal.gridCursor(tt).y != 0 or - panes.Terminal.scrollbar(tt).total > tt.rows) return; - p.deinitPane(tt) catch |err| return p.reportError(tty_id, "close", err); - layout.compute(p); // a just-stacked doc has no rect yet; absorb snaps to rows - layout.absorbVWeight(p, tty_id, null); - layout.removePane(p, tty_id); - p.panes[tty_id] = null; - if (p.active == tty_id) p.active = keep_id; - } - - /// A pane that just joined a column whose only other pane is stillborn — - /// an empty scratch nobody typed into, body or tag (what Newcol makes and - /// what a closed column's last pane leaves behind) — takes the column - /// whole: the placeholder was only holding the space for it. Run at the - /// end of a step: the pane that asked for the joiner is often the - /// placeholder itself, and its caller is still holding it. - fn replaceStillborn(p: *Pardes) void { - const serial = p.stillborn_joiner orelse return; - p.stillborn_joiner = null; - const new_id = p.paneBySerial(serial) orelse return; - const f = layout.findPane(p, new_id) orelse return; - if (p.col_n[f.col] != 2) return; - const old_id = p.col_panes[f.col][1 - f.idx]; - const old = p.panes[old_id] orelse return; - const file = old.file orelse return; - const out = file.output orelse return; - if (out.from != .cmd or out.from.cmd != .New) return; - if (file.revision != 0 or file.content.len != 0) return; - if (old.tag_init and !std.mem.eql(u8, old.tagSlice(), defaultTail(old))) return; - const was_active = p.active == old_id; - layout.compute(p); // the joiner may have no rect yet; absorb snaps to rows - p.removePane(old_id, new_id) catch |err| return p.reportError(old_id, "close", err); - if (was_active) p.active = new_id; - } - - fn ttyForDir(p: *Pardes, dir: []const u8) ?usize { - for (p.panes, 0..) |slot, i| if (slot) |tt| { - if (!std.mem.eql(u8, tt.cwdSlice(), dir)) continue; - if (p.takesCommandLine(i)) return i; - }; - const free = p.freeSlot() orelse return null; - const nt = p.newShell(free, dir) catch return null; - nt.greet = false; - const rc = if (p.ncol > 0) p.ncol - 1 else 0; - if (p.col_n[rc] > 0) { - const src = layout.splitParent(p, p.col_panes[rc][p.col_n[rc] - 1]); - const f = layout.findPane(p, src).?; - layout.splitBelow(p, src, nt); - layout.insert(p, f.col, f.idx + 1, free); - } else layout.insert(p, rc, p.col_n[rc], free); - return free; - } - // ---- doc panes ---- pub fn openTutorView(p: *Pardes, id: usize) !*Pane { @@ -6188,172 +5817,6 @@ pub const Pardes = struct { // ---- the ONE dispatcher: look (right/Enter) and execute (middle/Tab) ---- - const max_exec_depth = 8; - - pub fn execute(p: *Pardes, id: usize, txt: []const u8) ?usize { - const pane = p.panes[id] orelse return null; - const cmd = commandText(txt); - if (cmd.len == 0) return null; - if (p.exec_depth == 0) p.noteHaptic(.exec); - if (p.executeBuiltinLine(id, cmd)) return null; - if (p.exec_depth >= max_exec_depth) return null; - p.exec_depth += 1; - defer p.exec_depth -= 1; - const dst = (if (p.takesCommandLine(id)) id else p.ttyForDir(paneDir(pane))) orelse return null; - panes.Terminal.padOutputBelowEdits(p, dst); - if (panes.Terminal.queuePendingCommand(p.panes[dst].?, cmd) catch |err| { - p.reportError(id, "queue command", err); - return dst; - }) return dst; - p.emitWrite(dst, cmd); - p.emitWrite(dst, "\r"); - return dst; - } - - /// Trim and unwrap clickable command-word notation once for every command - /// consumer, so startup lines and interactive Exec speak the same syntax. - pub fn commandText(txt: []const u8) []const u8 { - var cmd = std.mem.trim(u8, txt, " \t\r\n"); - while (config.commandWord(cmd)) |inner| cmd = std.mem.trim(u8, inner, " \t\r\n"); - return cmd; - } - - pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { - const cmd = commandText(txt); - if (cmd.len == 0 or p.exec_depth >= max_exec_depth) return false; - const sp = std.mem.indexOfAny(u8, cmd, " \t"); - const bi: ?Builtin = std.meta.stringToEnum(Builtin, cmd) orelse blk: { - const head = std.meta.stringToEnum(Builtin, cmd[0 .. sp orelse break :blk null]) orelse break :blk null; - break :blk if (builtins.registry.takesArg(head)) head else null; - }; - const b = bi orelse return false; - p.exec_depth += 1; - defer p.exec_depth -= 1; - const typed = if (sp) |s| std.mem.trim(u8, cmd[s + 1 ..], " \t") else ""; - p.runBuiltin(b, id, cmd, if (typed.len > 0) typed else null); - return true; - } - - fn applyStartupConfig(p: *Pardes) void { - p.announce = false; - defer p.announce = true; - var lines = std.mem.splitScalar(u8, p.opts.startup_config orelse return, '\n'); - while (lines.next()) |line| _ = p.executeBuiltinLine(p.active, line); - } - - pub fn runBuiltin(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ?[]const u8) void { - if (!normal.multiOnce(p)) return; // a builtin is per-keystroke, never per-cursor - const pane = p.panes[id] orelse return; - // A builtin says its own name before it runs, so a tagline click is - // legible even when what it did is invisible. Whatever the builtin - // then says for itself replaces the announcement. - if (p.announce and p.settings.verbose and builtins.registry.announces(b)) { - p.setMessage(id, @tagName(b)); - pane.msg_announcement = true; - } - const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg }; - builtins.registry.dispatch(b, c); - } - - pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[]const u8) void { - const previous_colors = p.settings.colors; - const previous_context_style = p.settings.tree_context_tag_style; - const previous_transition = p.settings.panel_transition; - const previous_tagline_percent = p.settings.font.tagline_percent; - const previous_column_tags = p.settings.column_tags; - switch (setting.action) { - .theme => { - const want = std.mem.trim(u8, arg orelse return, " \t\r\n"); - for (themes, 0..) |t, i| if (std.mem.eql(u8, t.name, want)) { - colors.setThemeIndex(p, i); - return; - }; - }, - .font => { - if (comptime !font_picker) return; - const spec = config.Runtime.FontSpec.parse(arg orelse return) orelse return; - const matches = fonts.list(p.scratch.allocator(), spec.name); - if (matches.len == 0) return; - if (!p.settings.requestFont(matches[0].path, matches[0].name, spec.size_hundredths)) return; - p.font_request_taken = false; - }, - else => _ = p.settings.apply(setting, arg), - } - if (p.settings.colors != previous_colors) { - for (p.panes) |slot| { - const pane = slot orelse continue; - if (pane.file) |*file| file.syntax_dirty = true; - } - } - if (p.settings.tree_context_tag_style != previous_context_style) { - for (p.panes, 0..) |slot, id| { - p.surface.body_layers[id].rows = 0; - const pane = slot orelse continue; - pane.body_rows = 0; - pane.body_visible_rows = 0; - pane.context_row_limit = null; - pane.wrap_n = 0; - } - p.abandonPanelAnimations(); - } - const transition_changed = setting.action == .transition and - p.settings.panel_transition != previous_transition; - const tagline_metrics_changed = setting.action == .tagline_size and - p.settings.font.tagline_percent != previous_tagline_percent; - if (p.settings.column_tags != previous_column_tags) { - if (p.header_column != null) p.exitHeader(); - } - if (transition_changed or tagline_metrics_changed or p.settings.column_tags != previous_column_tags) { - p.abandonPanelAnimations(); - } - } - - pub fn placeDoc(p: *Pardes, from_id: usize, free: usize, nt: *Pane) void { - p.stillborn_joiner = nt.serial; - const doc = if (nt.file) |f| panes.Output.fileTraits(f.output).doc else true; // an image is a doc - var src_id: ?usize = null; - if (p.panes[from_id]) |src| if (if (src.file) |f| panes.Output.fileTraits(f.output).doc else src.image != null or src.hasPdf()) { - src_id = from_id; - }; - if (doc and src_id == null) { - var n = p.njumps; - while (n > 0) : (n -= 1) { - const j = p.jumps[n - 1]; - const pp = p.panes[j.pane] orelse continue; - if (pp.serial != j.serial) continue; - if (if (pp.file) |f| panes.Output.fileTraits(f.output).doc else pp.image != null or pp.hasPdf()) { - src_id = j.pane; - break; - } - } - } - if (doc and src_id == null) for (p.panes, 0..) |sl, i| { - if (sl) |pp| if (i != free and (if (pp.file) |f| panes.Output.fileTraits(f.output).doc else pp.image != null or pp.hasPdf())) { - src_id = i; - break; - }; - }; - if (!doc) if (layout.findPane(p, from_id)) |sf| { - layout.insert(p, sf.col, sf.idx + 1, free); - layout.splitBelow(p, from_id, nt); // NOT splitParent: no bystander pays - p.active = free; - return; - }; - if (src_id == null and doc and p.ncol < MAX_COLS and - layout.columnFitsHalves(p, from_id, 100) and layout.splitColumn(p, from_id, free, true)) - { - p.active = free; - return; - } - // Without room for a first-document column, split the Look origin - // just like Tty. Never displace (or evict) a top-left bystander. - const src = layout.splitParent(p, src_id orelse from_id); - const sf = layout.findPane(p, src).?; - layout.insert(p, sf.col, sf.idx + 1, free); - layout.splitBelow(p, src, nt); - p.active = free; - } - // ---- dump / load (acme-style: `pardes -l state.zon` restores a session) ---- pub fn dumpState(p: *Pardes) !void { @@ -6562,7 +6025,7 @@ pub const Pardes = struct { } p.active = @min(st.active, MAX_PANES - 1); p.sync(); - p.applyStartupConfig(); + exec.applyStartupConfig(p); colors.finishThemeInitialization(p); p.sync(); p.presentation.enabled = true; @@ -7725,7 +7188,7 @@ test "Esc alternates between two panes of the SAME kind" { defer p.deinit(); p.update(.{ .resize = .{ .cols = 80, .rows = 40 } }); const a = p.active; - p.runBuiltin(.Look, a, "", "build.zig"); + exec.runBuiltin(p, .Look, a, "", "build.zig"); p.sync(); const b = p.active; try std.testing.expect(b != a); @@ -8229,7 +7692,7 @@ test "raw tty Escape only leaves at a shell prompt" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); - p.spawnTty(0); + exec.spawnTty(p, 0); const shell = p.active; const pane = p.panes[shell].?; var buf: [256]u8 = undefined; @@ -8260,7 +7723,7 @@ test "raw tty Ctrl-B switches to editor mode without sending child input" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .file = "mise.toml" }); defer p.deinit(); - p.spawnTty(0); + exec.spawnTty(p, 0); const shell = p.active; p.sync(); var buf: [256]u8 = undefined; @@ -8313,7 +7776,7 @@ test "hopping between two panes does not grow the jump stack" { try std.testing.expectEqual(depth, p.njumps); const before = p.active; - p.runBuiltin(.Back, p.active, "", null); + exec.runBuiltin(p, .Back, p.active, "", null); p.sync(); try std.testing.expect(p.active != before); try std.testing.expectEqual(depth, p.njumps); diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 9b623183..721dac5a 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -3,6 +3,7 @@ const panes = @import("panes.zig"); const std = @import("std"); const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); const layout = @import("layout.zig"); const config = @import("config.zig"); const modal = @import("modal.zig"); @@ -2044,7 +2045,7 @@ pub fn openSections(core: *pardes.Pardes, id: usize) void { .serial = result.serial, .revision = result.file.?.revision, }; - core.placeDoc(id, free, result); + exec.placeDoc(core, id, free, result); layout.compute(core); core.active = id; pane.search_pane = free; diff --git a/test/panes.zig b/test/panes.zig index f45d42b2..f99f9d56 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -721,7 +721,7 @@ const TtySelectionTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 24 }); defer p.deinit(); p.presentation.enabled = false; - p.spawnTty(0); + pardes.exec.spawnTty(p, 0); for (p.panes[0..2]) |slot| { slot.?.mode = .tty; slot.?.tty_filter = false; @@ -3111,8 +3111,8 @@ const TerminalTests = struct { defer p.deinit(); while (p.nextEffect()) |_| {} // the host has not acknowledged spawn yet - try std.testing.expectEqual(@as(?usize, 0), p.execute(0, "echo first")); - try std.testing.expectEqual(@as(?usize, 0), p.execute(0, "echo second")); + try std.testing.expectEqual(@as(?usize, 0), pardes.exec.execute(p, 0, "echo first")); + try std.testing.expectEqual(@as(?usize, 0), pardes.exec.execute(p, 0, "echo second")); while (p.nextEffect()) |effect| switch (effect) { .write => return error.CommandEscapedBeforeFork, else => {}, diff --git a/test/pdf.zig b/test/pdf.zig index 69a82123..dde58df8 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -342,7 +342,7 @@ test "PdfSections Look follows the exact owning PDF, not an equal path" { const duplicate_id = p.freeSlot() orelse return error.NoDuplicatePdfSlot; const duplicate = try panes.Pdf.openPane(p, duplicate_id, path, 0); - p.placeDoc(0, duplicate_id, duplicate); + pardes.exec.placeDoc(p, 0, duplicate_id, duplicate); layout.compute(p); panes.Pdf.openSections(p, duplicate_id); const duplicate_output_id = duplicate.search_pane orelse return error.MissingDuplicatePdfSections; -- cgit v1.3 From d126715cd20a39dbc10870318968546f5e371b97 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 22:42:54 -0300 Subject: Split the pipe's editor side out of selection_pipe.zig into Pipe.zig Pure move, no behaviour change: the editor half of `|` that the earlier change put at the end of selection_pipe.zig (PendingPipe, pipeMarker, submitPipe, pipeRequest, pipeFailed, pipeCut, pipeOutput, pipeResponse, and the eight pipe tests with nextPipeEffect) now lives in its own Pipe.zig, so the pipe's editor state can become Pipe's own fields next. selection_pipe.zig goes back to exactly what it was before this series: the native runner and the boundary values the shells hand to their workers. The moved code names the runner's types as `selection_pipe.X` again, as it did in pardes.zig; callers change from `selection_pipe.submitPipe(p, ..)` to `Pipe.submitPipe(p, ..)` (pardes.zig and the four shells). Co-Authored-By: Claude Opus 5.5 --- src/Pipe.zig | 534 +++++++++++++++++++++++++++++++++++++++++++++++ src/detached/server.zig | 3 +- src/fs.zig | 1 + src/gui/gui.zig | 3 +- src/macos.zig | 3 +- src/pardes.zig | 10 +- src/selection_pipe.zig | 542 +----------------------------------------------- src/tty/tty.zig | 3 +- 8 files changed, 554 insertions(+), 545 deletions(-) create mode 100644 src/Pipe.zig (limited to 'src/fs.zig') diff --git a/src/Pipe.zig b/src/Pipe.zig new file mode 100644 index 00000000..0fde654a --- /dev/null +++ b/src/Pipe.zig @@ -0,0 +1,534 @@ +//! The pipe inside the editor (`|`): the prompt, the request the core emits +//! for the shell to run through selection_pipe.zig, and the atomic edit its +//! answer makes. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const modal = @import("modal.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const selection_pipe = @import("selection_pipe.zig"); +const edit = @import("edit.zig"); +const Pane = panes.Pane; +const Key = pardes.Key; +const Pardes = pardes.Pardes; + +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 { + return switch (how) { + .replace => config.pipe_marker, + .ignore => config.pipe_marker_to, + .insert => config.pipe_marker_insert, + .append => config.pipe_marker_append, + }; +} + +pub const PendingPipe = struct { + id: u32, + pane: usize, + serial: u32, + revision: u32, + command: []u8, + cwd: []u8, + inputs: []selection_pipe.Input, + ranges: [Pane.max_selections]modal.Selection, + primary: u8, + explicit: bool, + how: modal.Normal.PipeBehavior, + nranges: u8, + + pub fn deinit(wait: *PendingPipe, gpa: std.mem.Allocator) void { + gpa.free(wait.command); + gpa.free(wait.cwd); + for (wait.inputs) |input| gpa.free(@constCast(input.bytes)); + gpa.free(wait.inputs); + wait.* = undefined; + } + + fn request(wait: *const PendingPipe) selection_pipe.Request { + return .{ + .id = wait.id, + .command = wait.command, + .cwd = wait.cwd, + .inputs = wait.inputs, + }; + } +}; + +pub fn submitPipe(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const f = pane.file orelse return; + if (!panes.Output.fileTraits(f.output).saves) return; + const prompt = switch (pane.prompt) { + .pipe => |pipe| pipe, + else => return, + }; + const tail = pane.tagSlice(); + const armed = tail[@min(prompt.at, tail.len)..]; + const marker = pipeMarker(prompt.how); + if (!std.mem.startsWith(u8, armed, marker)) return; + const command = armed[marker.len..]; + if (command.len == 0) return; + + var ranges: [Pane.max_selections]modal.Selection = undefined; + const got = pane.ranges(f.content, 0, &ranges); + // `!`/`A-!` take no stdin and run ONCE — see `PendingPipe.nranges`. + const ninputs = if (prompt.how.pipes()) got.n else 1; + const inputs = p.gpa.alloc(selection_pipe.Input, ninputs) catch return; + var made: usize = 0; + for (ranges[0..ninputs], 0..) |range, i| { + const bytes = if (prompt.how.pipes()) bytes: { + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + if (hi > f.content.len) break; + break :bytes f.content[lo..hi]; + } else ""; + const copy = p.gpa.dupe(u8, bytes) catch break; + inputs[i] = .{ .bytes = copy }; + made += 1; + } + if (made != ninputs) { + for (inputs[0..made]) |input| p.gpa.free(@constCast(input.bytes)); + p.gpa.free(inputs); + return; + } + const command_copy = p.gpa.dupe(u8, command) catch { + for (inputs) |input| p.gpa.free(@constCast(input.bytes)); + p.gpa.free(inputs); + return; + }; + const cwd_copy = p.gpa.dupe(u8, Pardes.paneDir(pane)) catch { + p.gpa.free(command_copy); + for (inputs) |input| p.gpa.free(@constCast(input.bytes)); + p.gpa.free(inputs); + return; + }; + + p.pipe_seq +%= 1; + if (p.pipe_wait) |*old| old.deinit(p.gpa); + p.pipe_wait = .{ + .id = p.pipe_seq, + .pane = id, + .serial = pane.serial, + .revision = f.revision, + .command = command_copy, + .cwd = cwd_copy, + .inputs = inputs, + .ranges = ranges, + .primary = @intCast(got.pri), + .explicit = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active, + .how = prompt.how, + .nranges = @intCast(got.n), + }; + p.emit(.{ .pipe = .{ .id = p.pipe_seq } }); +} + +/// Frontends call this while draining a .pipe effect, then immediately +/// copy the borrowed view into a worker-owned selection_pipe.Job. +pub fn pipeRequest(p: *const Pardes, id: u32) ?selection_pipe.Request { + if (p.pipe_wait) |*wait| { + if (wait.id == id) return wait.request(); + } + return null; +} + +fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?selection_pipe.Failure) void { + var out: std.Io.Writer.Allocating = .init(p.gpa); + defer out.deinit(); + const w = &out.writer; + w.print("| {s}\n\n", .{wait.command}) catch return; + if (failure) |fail| { + if (wait.inputs.len > 1) + w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch return; + switch (fail.kind) { + .exit => w.print("exit status {d}\n", .{fail.code}) catch return, + .signal => w.writeAll("killed by a signal\n") catch return, + .timeout => w.print( + "still running after {d} seconds, and stopped\n", + .{selection_pipe.command_timeout_seconds}, + ) catch return, + .too_large => w.writeAll("produced more output than a filter may return\n") catch return, + .spawn => w.writeAll("could not be started\n") catch return, + .io => w.writeAll("could not be read\n") catch return, + } + if (fail.stderr.len > 0) w.print("\n{s}", .{fail.stderr}) catch return; + } else { + // No diagnosis at all: nobody ran it. The detached daemon, the + // browser and the board all leave `pipe` null on purpose. + w.writeAll("this session cannot run filters\n") catch return; + } + const content = out.toOwnedSlice() catch return; + const was = p.active; + panes.Output.openErrors(p, wait.pane, content) catch |err| { + p.gpa.free(content); + // Nowhere to put the report is itself worth one line. + p.reportError(wait.pane, "pipe", err); + return; + }; + if (p.panes[was] != null) p.active = was; +} + +fn pipeCut(wait: *const PendingPipe, content: []const u8, i: usize) ?struct { lo: usize, hi: usize } { + const range = wait.ranges[i]; + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + if (hi > content.len) return null; + return switch (wait.how) { + .replace, .ignore => .{ .lo = lo, .hi = hi }, + .insert => .{ .lo = lo, .hi = lo }, + .append => .{ .lo = hi, .hi = hi }, + }; +} + +fn pipeOutput( + wait: *const PendingPipe, + outputs: []const []const u8, + content: []const u8, + i: usize, +) []const u8 { + var out = if (wait.how.pipes()) outputs[i] else outputs[0]; + const range = wait.ranges[i]; + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + const selected = if (hi <= content.len) content[lo..hi] else ""; + if (!std.mem.endsWith(u8, selected, "\n") and std.mem.endsWith(u8, out, "\n")) { + out = out[0 .. out.len - 1]; + if (std.mem.endsWith(u8, out, "\r")) out = out[0 .. out.len - 1]; + } + return out; +} + +pub fn pipeResponse( + p: *Pardes, + id: u32, + success: bool, + outputs: []const []const u8, + failure: ?selection_pipe.Failure, +) void { + // A SUPERSEDED OR UNKNOWN id is the one silence worth keeping: it is + // the answer to a question nobody is still asking. + if (p.pipe_wait == null or p.pipe_wait.?.id != id) return; + var wait = p.pipe_wait.?; + p.pipe_wait = null; + defer wait.deinit(p.gpa); + + if (!success or outputs.len != wait.inputs.len) return pipeFailed(p, &wait, failure); + + const pane = p.panes[wait.pane] orelse return; + if (pane.serial != wait.serial) return; + const f = if (pane.file) |*file| file else return; + if (!panes.Output.fileTraits(f.output).saves) return; + if (f.revision != wait.revision) + return p.reportError(wait.pane, "pipe", error.FileChangedWhileFiltering); + + if (wait.how == .ignore) return; + + const n = wait.nranges; + var total_output: usize = 0; + var removed: usize = 0; + var previous_end: usize = 0; + for (0..n) |i| { + const cut = pipeCut(&wait, f.content, i) orelse return; + const output = pipeOutput(&wait, outputs, f.content, i); + if (output.len > selection_pipe.max_stdout_bytes) return; + total_output = std.math.add(usize, total_output, output.len) catch return; + if (total_output > selection_pipe.max_total_stdout_bytes) return; + if (cut.lo < previous_end) return; + removed = std.math.add(usize, removed, cut.hi - cut.lo) catch return; + previous_end = cut.hi; + } + const kept = f.content.len - removed; + const final_len = std.math.add(usize, kept, total_output) catch return; + const replacement = p.gpa.alloc(u8, final_len) catch return; + + var new_ranges: [Pane.max_selections]modal.Selection = undefined; + var read_at: usize = 0; + var write_at: usize = 0; + for (0..n) |i| { + const range = wait.ranges[i]; + const cut = pipeCut(&wait, f.content, i).?; + const output = pipeOutput(&wait, outputs, f.content, i); + @memcpy(replacement[write_at .. write_at + (cut.lo - read_at)], f.content[read_at..cut.lo]); + write_at += cut.lo - read_at; + const out_start = write_at; + @memcpy(replacement[write_at .. write_at + output.len], output); + write_at += output.len; + const out_end = write_at; + new_ranges[i] = if (range.anchor > range.head) + .{ .anchor = out_end, .head = out_start } + else + .{ .anchor = out_start, .head = out_end }; + read_at = cut.hi; + } + @memcpy(replacement[write_at..], f.content[read_at..]); + + // One async request is one history transaction, even at 64 cursors. + edit.pushUndo(p, pane); + panes.File.setContent(p, f, replacement); + pane.setRanges(f.content, new_ranges[0..n], &.{}, wait.primary, wait.explicit); + pane.select = false; + pane.ensureCursorVisible(); +} + +test "selection pipe prompt submits exact request and Escape cancels" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("one\ntwo\n"); + pane.cur_row = 0; + pane.cur_col = 2; + pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + + p.update(.{ .key = .{ .cp = '|' } }); + try std.testing.expect(pane.tag_edit and pane.prompt == .pipe); + try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), config.pipe_marker)); + try std.testing.expect(nextPipeEffect(p) == null); + p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); + const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; + try std.testing.expectEqualStrings("tr a-z A-Z", request.command); + try std.testing.expectEqualStrings("/", request.cwd); + try std.testing.expectEqual(@as(usize, 1), request.inputs.len); + try std.testing.expectEqualSlices(u8, "one", request.inputs[0].bytes); + + const before = pane.file.?.content; + p.update(.{ .key = .{ .cp = '|' } }); + p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); + try std.testing.expectEqualSlices(u8, before, pane.file.?.content); + try std.testing.expect(nextPipeEffect(p) == null); +} + +test "selection pipe replaces all ranges atomically and undo restores them" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("aa bb cc\n"); + const ranges = [_]modal.Selection{ + .{ .anchor = 0, .head = 2 }, + .{ .anchor = 6, .head = 8 }, + }; + pane.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); + + p.update(.{ .key = .{ .cp = '|' } }); + p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; + try std.testing.expectEqual(@as(usize, 2), request.inputs.len); + try std.testing.expectEqualSlices(u8, "aa", request.inputs[0].bytes); + try std.testing.expectEqualSlices(u8, "cc", request.inputs[1].bytes); + + var denied = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + p.scratch.deinit(); + p.scratch = .init(denied.allocator()); + const outputs: []const []const u8 = &.{ "AA\n", "" }; + p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } }); + try std.testing.expectEqualSlices(u8, "AA bb \n", pane.file.?.content); + try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); + try std.testing.expectEqual(@as(u8, 1), pane.nsel); + try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + try std.testing.expectEqual(@as(i32, 6), pane.sels[0].col); + try std.testing.expect(!denied.has_induced_failure); + + p.update(.{ .key = .{ .cp = 'u' } }); + try std.testing.expectEqualSlices(u8, "aa bb cc\n", pane.file.?.content); +} + +test "the four shell behaviours put their output where helix puts it" { + const gpa = std.testing.allocator; + const Case = struct { + key: Key, + outputs: []const []const u8, + want: []const u8, + want_effect: bool = true, + }; + // One selection, `bb`, in `aa bb cc\n` — bytes 3..5. + for ([_]Case{ + // `|` replaces the selection with what the command wrote. + .{ .key = .{ .cp = '|' }, .outputs = &.{"XX"}, .want = "aa XX cc\n" }, + // `!` inserts BEFORE it, and the selection survives to its right. + .{ .key = .{ .cp = '!' }, .outputs = &.{"XX"}, .want = "aa XXbb cc\n" }, + // `A-!` appends AFTER it. + .{ .key = .{ .cp = '!', .alt = true }, .outputs = &.{"XX"}, .want = "aa bbXX cc\n" }, + // `A-|` runs the command and leaves the text completely alone: the + // point is the side effect, not the output. + .{ .key = .{ .cp = '|', .alt = true }, .outputs = &.{"XX"}, .want = "aa bb cc\n" }, + }) |case| { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("aa bb cc\n"); + pane.setRanges(pane.file.?.content, &.{.{ .anchor = 3, .head = 5 }}, &.{}, 0, true); + + p.update(.{ .key = case.key }); + for ("cmd") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = case.outputs } }); + try std.testing.expectEqualSlices(u8, case.want, pane.file.?.content); + } +} + +test "a command with no stdin runs once and every cursor gets that one answer" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("aa bb cc\n"); + const ranges = [_]modal.Selection{ + .{ .anchor = 0, .head = 2 }, + .{ .anchor = 6, .head = 8 }, + }; + pane.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); + + p.update(.{ .key = .{ .cp = '!' } }); // insert-output: no stdin + for ("date") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; + + try std.testing.expectEqual(@as(usize, 1), request.inputs.len); + try std.testing.expectEqualSlices(u8, "", request.inputs[0].bytes); + + p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = &.{"T"} } }); + try std.testing.expectEqualSlices(u8, "Taa bb Tcc\n", pane.file.?.content); + try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); +} + +test "selection pipe failure and stale completion never mutate the file" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("abc\n"); + pane.cur_col = 2; + pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + + p.update(.{ .key = .{ .cp = '|' } }); + p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const failed_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + p.update(.{ .pipe_resp = .{ .id = failed_id, .success = false, .outputs = &.{} } }); + try std.testing.expectEqualSlices(u8, "abc\n", pane.file.?.content); + try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); + + p.update(.{ .key = .{ .cp = '|' } }); + p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const stale_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "changed\n")); + p.update(.{ .pipe_resp = .{ .id = stale_id, .success = true, .outputs = &.{"ABC"} } }); + try std.testing.expectEqualSlices(u8, "changed\n", pane.file.?.content); + try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); +} + +test "a failed filter opens an errors buffer carrying the command's own words" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("abc\n"); + pane.cur_col = 2; + pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + + p.update(.{ .key = .{ .cp = '|' } }); + for ("trr") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + + // The shape a real runner brings home for `| trr`: nonzero exit, and the + // shell's own sentence about it. + var stderr = "sh: line 1: trr: command not found\n".*; + p.update(.{ .pipe_resp = .{ + .id = id, + .success = false, + .outputs = &.{}, + .failure = .{ .kind = .exit, .code = 127, .stderr = &stderr }, + } }); + + // The text is untouched — a failed filter is not an edit... + try std.testing.expectEqualSlices(u8, "abc\n", pane.file.?.content); + try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); + // ...and the cursor did not go anywhere, so `|` again edits the same file. + try std.testing.expectEqual(@as(usize, 0), p.active); + + var found: ?[]const u8 = null; + for (p.panes) |slot| { + const q = slot orelse continue; + const qf = q.file orelse continue; + const o = qf.output orelse continue; + if (std.meta.activeTag(o.from) == .errors) found = qf.content; + } + const report = found orelse return error.NoErrorsBuffer; + try std.testing.expect(std.mem.indexOf(u8, report, "| trr") != null); + try std.testing.expect(std.mem.indexOf(u8, report, "exit status 127") != null); + try std.testing.expect(std.mem.indexOf(u8, report, "command not found") != null); +} + +test "selection pipe rejects a reused pane slot and a superseded request" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + var pane = try p.setTestFile("old\n"); + pane.cur_col = 2; + pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + + p.update(.{ .key = .{ .cp = '|' } }); + p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const replaced_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + pane = try p.setTestFile("new\n"); // same slot, different serial + p.update(.{ .pipe_resp = .{ .id = replaced_id, .success = true, .outputs = &.{"OLD"} } }); + try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content); + try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); + + pane.cur_col = 2; + pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + p.update(.{ .key = .{ .cp = '|' } }); + p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const first_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + p.update(.{ .key = .{ .cp = '|' } }); + p.update(.{ .key = .{ .cp = 'c', .text = "tr a-z A-Z" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + const latest_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; + try std.testing.expect(first_id != latest_id); + + p.update(.{ .pipe_resp = .{ .id = first_id, .success = true, .outputs = &.{"BAD"} } }); + try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content); + p.update(.{ .pipe_resp = .{ .id = latest_id, .success = true, .outputs = &.{"NEW"} } }); + try std.testing.expectEqualSlices(u8, "NEW\n", pane.file.?.content); + try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); +} + +test "selection pipe binding is file-normal-only" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("x"); + + pane.file.?.output = .{ .from = .search }; + p.update(.{ .key = .{ .cp = '|' } }); + try std.testing.expect(pane.prompt != .pipe); + pane.file.?.output = null; + pane.mode = .insert; + p.update(.{ .key = .{ .cp = '|', .text = "|" } }); + try std.testing.expect(pane.prompt != .pipe); + try std.testing.expectEqualSlices(u8, "|x", pane.file.?.content); +} diff --git a/src/detached/server.zig b/src/detached/server.zig index b75fa5ad..9b23f8d6 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -9,6 +9,7 @@ const wire = @import("wire.zig"); const host_io = @import("../host_io.zig"); const selection_pipe = @import("../selection_pipe.zig"); +const Pipe = @import("../Pipe.zig"); const file_watch = @import("../file_watch.zig"); @@ -411,7 +412,7 @@ pub const Session = struct { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return; } - const request = selection_pipe.pipeRequest(s.core, id) orelse return; + const request = Pipe.pipeRequest(s.core, id) orelse return; const job = selection_pipe.Job.copy(s.worker_gpa, request) catch |err| { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return s.core.reportError(s.core.active, "pipe", err); diff --git a/src/fs.zig b/src/fs.zig index 825e63bb..5374c843 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -44,6 +44,7 @@ const source_files = [_]Source{ .{ .path = "src/normal.zig", .contents = @embedFile("normal.zig") }, .{ .path = "src/mouse.zig", .contents = @embedFile("mouse.zig") }, .{ .path = "src/exec.zig", .contents = @embedFile("exec.zig") }, + .{ .path = "src/Pipe.zig", .contents = @embedFile("Pipe.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index f044ca17..ef94d5b3 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -16,6 +16,7 @@ const crt = @import("crt.zig"); const pet = @import("pet.zig"); const fonts = @import("../fonts.zig"); // the Font builtin's half of the seam const selection_pipe = @import("../selection_pipe.zig"); +const Pipe = @import("../Pipe.zig"); const c_heap = @import("c_heap"); const ninep_io = @import("../9p_io.zig"); @@ -1703,7 +1704,7 @@ fn spawnPipe( core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return; } - const view = selection_pipe.pipeRequest(core, id) orelse return; + const view = Pipe.pipeRequest(core, id) orelse return; const job = selection_pipe.Job.copy(gpa, view) catch |err| { core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return core.reportError(core.active, "pipe", err); diff --git a/src/macos.zig b/src/macos.zig index 78356810..dc5b79d0 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -18,6 +18,7 @@ const host_io = @import("host_io.zig"); const fonts = @import("fonts.zig"); // the shared fallback preference order const tracy = @import("tracy.zig"); // no-op unless -Dtracy names a checkout const selection_pipe = @import("selection_pipe.zig"); // Job, runJob and Tasks +const Pipe = @import("Pipe.zig"); const crash = @import("crash.zig"); pub const panic = std.debug.FullPanic(struct { @@ -2351,7 +2352,7 @@ fn pipeRequest(ctx: ?*anyopaque, id: u32) void { st.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return; } - const view = selection_pipe.pipeRequest(st.core, id) orelse return; + const view = Pipe.pipeRequest(st.core, id) orelse return; const job = selection_pipe.Job.copy(st.gpa, view) catch |err| { st.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return st.core.reportError(st.core.active, "pipe", err); diff --git a/src/pardes.zig b/src/pardes.zig index d2ac5868..00439a36 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -17,6 +17,7 @@ pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); pub const body_layer = @import("body_layer.zig"); pub const Messages = @import("Messages.zig"); +pub const Pipe = @import("Pipe.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; pub const themes = colors.themes; @@ -443,6 +444,7 @@ test { _ = @import("edit.zig"); _ = @import("Messages.zig"); _ = @import("selection_pipe.zig"); + _ = @import("Pipe.zig"); _ = @import("colors.zig"); _ = @import("surface.zig"); _ = @import("body_layer.zig"); @@ -3745,7 +3747,7 @@ pub const Pardes = struct { } = null, pipe_seq: u32 = 0, - pipe_wait: ?selection_pipe.PendingPipe = null, + pipe_wait: ?Pipe.PendingPipe = null, fs: filesystem.Namespace = .{}, boot: Boot = .shell, @@ -4688,7 +4690,7 @@ pub const Pardes = struct { p.reportError(e.pane, "terminal exited; Del retries close", err); }, .lsp_resp => |r| p.lspResponse(r.id, r.rows), - .pipe_resp => |r| selection_pipe.pipeResponse(p, r.id, r.success, r.outputs, r.failure), + .pipe_resp => |r| Pipe.pipeResponse(p, r.id, r.success, r.outputs, r.failure), .file_changed => |fc| _ = p.applyWatchedFileChanged(fc.pane, fc.bytes), .key => |key| { p.can_ask = true; @@ -5386,7 +5388,7 @@ pub const Pardes = struct { const submit = hit(key, config.search_submit); switch (pane.prompt) { .pipe => |pipe| { - if (submit) selection_pipe.submitPipe(p, p.active); + if (submit) Pipe.submitPipe(p, p.active); pane.tag_tail_len = @min(pipe.at, pane.tag_tail_len); }, .save => |at| { @@ -5501,7 +5503,7 @@ pub const Pardes = struct { .pipe => |how| pipe: { const file = pane.file orelse return; if (!panes.Output.fileTraits(file.output).saves) return; - break :pipe selection_pipe.pipeMarker(how); + break :pipe Pipe.pipeMarker(how); }, }; p.seedTail(pane); diff --git a/src/selection_pipe.zig b/src/selection_pipe.zig index 90c8e951..e1a42962 100644 --- a/src/selection_pipe.zig +++ b/src/selection_pipe.zig @@ -1,19 +1,10 @@ -//! `|`: pipe every editor selection through one shell command. First the -//! native runner and its boundary-owned values: native shells call `Job.copy` -//! before starting a worker, then `runOne` on that worker, so no subprocess or -//! borrowed core memory reaches the editor/event-loop thread. Then the editor -//! side: the prompt, the request the core emits, and the atomic edit its -//! answer makes. +//! Native runner and boundary-owned values for `|`: pipe every editor +//! selection through one shell command. The core imports only the plain value +//! types below; native shells call `Job.copy` before starting a worker, then +//! `runOne` on that worker. No subprocess or borrowed core memory reaches the +//! editor/event-loop thread. const std = @import("std"); const filesystem = @import("fs.zig"); -const pardes = @import("pardes.zig"); -const edit = @import("edit.zig"); -const modal = @import("modal.zig"); -const panes = @import("panes.zig"); -const config = @import("config.zig"); -const Pane = panes.Pane; -const Key = pardes.Key; -const Pardes = pardes.Pardes; /// A deliberately finite answer. One selection cannot retain more than 1 MiB /// and a multi-selection command cannot retain more than 4 MiB in total. @@ -401,526 +392,3 @@ test "native pipe runner preserves stdin/stdout bytes and reports how it failed" .failed => return error.EarlyStdinCloseShouldNotFail, } } - -// ---- the pipe inside the editor: the prompt, the request, the atomic edit ---- - -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 { - return switch (how) { - .replace => config.pipe_marker, - .ignore => config.pipe_marker_to, - .insert => config.pipe_marker_insert, - .append => config.pipe_marker_append, - }; -} - -pub const PendingPipe = struct { - id: u32, - pane: usize, - serial: u32, - revision: u32, - command: []u8, - cwd: []u8, - inputs: []Input, - ranges: [Pane.max_selections]modal.Selection, - primary: u8, - explicit: bool, - how: modal.Normal.PipeBehavior, - nranges: u8, - - pub fn deinit(wait: *PendingPipe, gpa: std.mem.Allocator) void { - gpa.free(wait.command); - gpa.free(wait.cwd); - for (wait.inputs) |input| gpa.free(@constCast(input.bytes)); - gpa.free(wait.inputs); - wait.* = undefined; - } - - fn request(wait: *const PendingPipe) Request { - return .{ - .id = wait.id, - .command = wait.command, - .cwd = wait.cwd, - .inputs = wait.inputs, - }; - } -}; - -pub fn submitPipe(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const f = pane.file orelse return; - if (!panes.Output.fileTraits(f.output).saves) return; - const prompt = switch (pane.prompt) { - .pipe => |pipe| pipe, - else => return, - }; - const tail = pane.tagSlice(); - const armed = tail[@min(prompt.at, tail.len)..]; - const marker = pipeMarker(prompt.how); - if (!std.mem.startsWith(u8, armed, marker)) return; - const command = armed[marker.len..]; - if (command.len == 0) return; - - var ranges: [Pane.max_selections]modal.Selection = undefined; - const got = pane.ranges(f.content, 0, &ranges); - // `!`/`A-!` take no stdin and run ONCE — see `PendingPipe.nranges`. - const ninputs = if (prompt.how.pipes()) got.n else 1; - const inputs = p.gpa.alloc(Input, ninputs) catch return; - var made: usize = 0; - for (ranges[0..ninputs], 0..) |range, i| { - const bytes = if (prompt.how.pipes()) bytes: { - const lo = @min(range.anchor, range.head); - const hi = @max(range.anchor, range.head); - if (hi > f.content.len) break; - break :bytes f.content[lo..hi]; - } else ""; - const copy = p.gpa.dupe(u8, bytes) catch break; - inputs[i] = .{ .bytes = copy }; - made += 1; - } - if (made != ninputs) { - for (inputs[0..made]) |input| p.gpa.free(@constCast(input.bytes)); - p.gpa.free(inputs); - return; - } - const command_copy = p.gpa.dupe(u8, command) catch { - for (inputs) |input| p.gpa.free(@constCast(input.bytes)); - p.gpa.free(inputs); - return; - }; - const cwd_copy = p.gpa.dupe(u8, Pardes.paneDir(pane)) catch { - p.gpa.free(command_copy); - for (inputs) |input| p.gpa.free(@constCast(input.bytes)); - p.gpa.free(inputs); - return; - }; - - p.pipe_seq +%= 1; - if (p.pipe_wait) |*old| old.deinit(p.gpa); - p.pipe_wait = .{ - .id = p.pipe_seq, - .pane = id, - .serial = pane.serial, - .revision = f.revision, - .command = command_copy, - .cwd = cwd_copy, - .inputs = inputs, - .ranges = ranges, - .primary = @intCast(got.pri), - .explicit = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active, - .how = prompt.how, - .nranges = @intCast(got.n), - }; - p.emit(.{ .pipe = .{ .id = p.pipe_seq } }); -} - -/// Frontends call this while draining a .pipe effect, then immediately -/// copy the borrowed view into a worker-owned selection_pipe.Job. -pub fn pipeRequest(p: *const Pardes, id: u32) ?Request { - if (p.pipe_wait) |*wait| { - if (wait.id == id) return wait.request(); - } - return null; -} - -fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?Failure) void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - defer out.deinit(); - const w = &out.writer; - w.print("| {s}\n\n", .{wait.command}) catch return; - if (failure) |fail| { - if (wait.inputs.len > 1) - w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch return; - switch (fail.kind) { - .exit => w.print("exit status {d}\n", .{fail.code}) catch return, - .signal => w.writeAll("killed by a signal\n") catch return, - .timeout => w.print( - "still running after {d} seconds, and stopped\n", - .{command_timeout_seconds}, - ) catch return, - .too_large => w.writeAll("produced more output than a filter may return\n") catch return, - .spawn => w.writeAll("could not be started\n") catch return, - .io => w.writeAll("could not be read\n") catch return, - } - if (fail.stderr.len > 0) w.print("\n{s}", .{fail.stderr}) catch return; - } else { - // No diagnosis at all: nobody ran it. The detached daemon, the - // browser and the board all leave `pipe` null on purpose. - w.writeAll("this session cannot run filters\n") catch return; - } - const content = out.toOwnedSlice() catch return; - const was = p.active; - panes.Output.openErrors(p, wait.pane, content) catch |err| { - p.gpa.free(content); - // Nowhere to put the report is itself worth one line. - p.reportError(wait.pane, "pipe", err); - return; - }; - if (p.panes[was] != null) p.active = was; -} - -fn pipeCut(wait: *const PendingPipe, content: []const u8, i: usize) ?struct { lo: usize, hi: usize } { - const range = wait.ranges[i]; - const lo = @min(range.anchor, range.head); - const hi = @max(range.anchor, range.head); - if (hi > content.len) return null; - return switch (wait.how) { - .replace, .ignore => .{ .lo = lo, .hi = hi }, - .insert => .{ .lo = lo, .hi = lo }, - .append => .{ .lo = hi, .hi = hi }, - }; -} - -fn pipeOutput( - wait: *const PendingPipe, - outputs: []const []const u8, - content: []const u8, - i: usize, -) []const u8 { - var out = if (wait.how.pipes()) outputs[i] else outputs[0]; - const range = wait.ranges[i]; - const lo = @min(range.anchor, range.head); - const hi = @max(range.anchor, range.head); - const selected = if (hi <= content.len) content[lo..hi] else ""; - if (!std.mem.endsWith(u8, selected, "\n") and std.mem.endsWith(u8, out, "\n")) { - out = out[0 .. out.len - 1]; - if (std.mem.endsWith(u8, out, "\r")) out = out[0 .. out.len - 1]; - } - return out; -} - -pub fn pipeResponse( - p: *Pardes, - id: u32, - success: bool, - outputs: []const []const u8, - failure: ?Failure, -) void { - // A SUPERSEDED OR UNKNOWN id is the one silence worth keeping: it is - // the answer to a question nobody is still asking. - if (p.pipe_wait == null or p.pipe_wait.?.id != id) return; - var wait = p.pipe_wait.?; - p.pipe_wait = null; - defer wait.deinit(p.gpa); - - if (!success or outputs.len != wait.inputs.len) return pipeFailed(p, &wait, failure); - - const pane = p.panes[wait.pane] orelse return; - if (pane.serial != wait.serial) return; - const f = if (pane.file) |*file| file else return; - if (!panes.Output.fileTraits(f.output).saves) return; - if (f.revision != wait.revision) - return p.reportError(wait.pane, "pipe", error.FileChangedWhileFiltering); - - if (wait.how == .ignore) return; - - const n = wait.nranges; - var total_output: usize = 0; - var removed: usize = 0; - var previous_end: usize = 0; - for (0..n) |i| { - const cut = pipeCut(&wait, f.content, i) orelse return; - const output = pipeOutput(&wait, outputs, f.content, i); - if (output.len > max_stdout_bytes) return; - total_output = std.math.add(usize, total_output, output.len) catch return; - if (total_output > max_total_stdout_bytes) return; - if (cut.lo < previous_end) return; - removed = std.math.add(usize, removed, cut.hi - cut.lo) catch return; - previous_end = cut.hi; - } - const kept = f.content.len - removed; - const final_len = std.math.add(usize, kept, total_output) catch return; - const replacement = p.gpa.alloc(u8, final_len) catch return; - - var new_ranges: [Pane.max_selections]modal.Selection = undefined; - var read_at: usize = 0; - var write_at: usize = 0; - for (0..n) |i| { - const range = wait.ranges[i]; - const cut = pipeCut(&wait, f.content, i).?; - const output = pipeOutput(&wait, outputs, f.content, i); - @memcpy(replacement[write_at .. write_at + (cut.lo - read_at)], f.content[read_at..cut.lo]); - write_at += cut.lo - read_at; - const out_start = write_at; - @memcpy(replacement[write_at .. write_at + output.len], output); - write_at += output.len; - const out_end = write_at; - new_ranges[i] = if (range.anchor > range.head) - .{ .anchor = out_end, .head = out_start } - else - .{ .anchor = out_start, .head = out_end }; - read_at = cut.hi; - } - @memcpy(replacement[write_at..], f.content[read_at..]); - - // One async request is one history transaction, even at 64 cursors. - edit.pushUndo(p, pane); - panes.File.setContent(p, f, replacement); - pane.setRanges(f.content, new_ranges[0..n], &.{}, wait.primary, wait.explicit); - pane.select = false; - pane.ensureCursorVisible(); -} - -test "selection pipe prompt submits exact request and Escape cancels" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = try p.setTestFile("one\ntwo\n"); - pane.cur_row = 0; - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - - p.update(.{ .key = .{ .cp = '|' } }); - try std.testing.expect(pane.tag_edit and pane.prompt == .pipe); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), config.pipe_marker)); - try std.testing.expect(nextPipeEffect(p) == null); - p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); - const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; - try std.testing.expectEqualStrings("tr a-z A-Z", request.command); - try std.testing.expectEqualStrings("/", request.cwd); - try std.testing.expectEqual(@as(usize, 1), request.inputs.len); - try std.testing.expectEqualSlices(u8, "one", request.inputs[0].bytes); - - const before = pane.file.?.content; - p.update(.{ .key = .{ .cp = '|' } }); - p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); - p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); - try std.testing.expectEqualSlices(u8, before, pane.file.?.content); - try std.testing.expect(nextPipeEffect(p) == null); -} - -test "selection pipe replaces all ranges atomically and undo restores them" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = try p.setTestFile("aa bb cc\n"); - const ranges = [_]modal.Selection{ - .{ .anchor = 0, .head = 2 }, - .{ .anchor = 6, .head = 8 }, - }; - pane.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); - - p.update(.{ .key = .{ .cp = '|' } }); - p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; - try std.testing.expectEqual(@as(usize, 2), request.inputs.len); - try std.testing.expectEqualSlices(u8, "aa", request.inputs[0].bytes); - try std.testing.expectEqualSlices(u8, "cc", request.inputs[1].bytes); - - var denied = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - p.scratch.deinit(); - p.scratch = .init(denied.allocator()); - const outputs: []const []const u8 = &.{ "AA\n", "" }; - p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } }); - try std.testing.expectEqualSlices(u8, "AA bb \n", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); - try std.testing.expectEqual(@as(u8, 1), pane.nsel); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - try std.testing.expectEqual(@as(i32, 6), pane.sels[0].col); - try std.testing.expect(!denied.has_induced_failure); - - p.update(.{ .key = .{ .cp = 'u' } }); - try std.testing.expectEqualSlices(u8, "aa bb cc\n", pane.file.?.content); -} - -test "the four shell behaviours put their output where helix puts it" { - const gpa = std.testing.allocator; - const Case = struct { - key: Key, - outputs: []const []const u8, - want: []const u8, - want_effect: bool = true, - }; - // One selection, `bb`, in `aa bb cc\n` — bytes 3..5. - for ([_]Case{ - // `|` replaces the selection with what the command wrote. - .{ .key = .{ .cp = '|' }, .outputs = &.{"XX"}, .want = "aa XX cc\n" }, - // `!` inserts BEFORE it, and the selection survives to its right. - .{ .key = .{ .cp = '!' }, .outputs = &.{"XX"}, .want = "aa XXbb cc\n" }, - // `A-!` appends AFTER it. - .{ .key = .{ .cp = '!', .alt = true }, .outputs = &.{"XX"}, .want = "aa bbXX cc\n" }, - // `A-|` runs the command and leaves the text completely alone: the - // point is the side effect, not the output. - .{ .key = .{ .cp = '|', .alt = true }, .outputs = &.{"XX"}, .want = "aa bb cc\n" }, - }) |case| { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = try p.setTestFile("aa bb cc\n"); - pane.setRanges(pane.file.?.content, &.{.{ .anchor = 3, .head = 5 }}, &.{}, 0, true); - - p.update(.{ .key = case.key }); - for ("cmd") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = case.outputs } }); - try std.testing.expectEqualSlices(u8, case.want, pane.file.?.content); - } -} - -test "a command with no stdin runs once and every cursor gets that one answer" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = try p.setTestFile("aa bb cc\n"); - const ranges = [_]modal.Selection{ - .{ .anchor = 0, .head = 2 }, - .{ .anchor = 6, .head = 8 }, - }; - pane.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); - - p.update(.{ .key = .{ .cp = '!' } }); // insert-output: no stdin - for ("date") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; - - try std.testing.expectEqual(@as(usize, 1), request.inputs.len); - try std.testing.expectEqualSlices(u8, "", request.inputs[0].bytes); - - p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = &.{"T"} } }); - try std.testing.expectEqualSlices(u8, "Taa bb Tcc\n", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); -} - -test "selection pipe failure and stale completion never mutate the file" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = try p.setTestFile("abc\n"); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - - p.update(.{ .key = .{ .cp = '|' } }); - p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const failed_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - p.update(.{ .pipe_resp = .{ .id = failed_id, .success = false, .outputs = &.{} } }); - try std.testing.expectEqualSlices(u8, "abc\n", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); - - p.update(.{ .key = .{ .cp = '|' } }); - p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const stale_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "changed\n")); - p.update(.{ .pipe_resp = .{ .id = stale_id, .success = true, .outputs = &.{"ABC"} } }); - try std.testing.expectEqualSlices(u8, "changed\n", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); -} - -test "a failed filter opens an errors buffer carrying the command's own words" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = try p.setTestFile("abc\n"); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - - p.update(.{ .key = .{ .cp = '|' } }); - for ("trr") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - - // The shape a real runner brings home for `| trr`: nonzero exit, and the - // shell's own sentence about it. - var stderr = "sh: line 1: trr: command not found\n".*; - p.update(.{ .pipe_resp = .{ - .id = id, - .success = false, - .outputs = &.{}, - .failure = .{ .kind = .exit, .code = 127, .stderr = &stderr }, - } }); - - // The text is untouched — a failed filter is not an edit... - try std.testing.expectEqualSlices(u8, "abc\n", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); - // ...and the cursor did not go anywhere, so `|` again edits the same file. - try std.testing.expectEqual(@as(usize, 0), p.active); - - var found: ?[]const u8 = null; - for (p.panes) |slot| { - const q = slot orelse continue; - const qf = q.file orelse continue; - const o = qf.output orelse continue; - if (std.meta.activeTag(o.from) == .errors) found = qf.content; - } - const report = found orelse return error.NoErrorsBuffer; - try std.testing.expect(std.mem.indexOf(u8, report, "| trr") != null); - try std.testing.expect(std.mem.indexOf(u8, report, "exit status 127") != null); - try std.testing.expect(std.mem.indexOf(u8, report, "command not found") != null); -} - -test "selection pipe rejects a reused pane slot and a superseded request" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - var pane = try p.setTestFile("old\n"); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - - p.update(.{ .key = .{ .cp = '|' } }); - p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const replaced_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - pane = try p.setTestFile("new\n"); // same slot, different serial - p.update(.{ .pipe_resp = .{ .id = replaced_id, .success = true, .outputs = &.{"OLD"} } }); - try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); - - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - p.update(.{ .key = .{ .cp = '|' } }); - p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const first_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - p.update(.{ .key = .{ .cp = '|' } }); - p.update(.{ .key = .{ .cp = 'c', .text = "tr a-z A-Z" } }); - p.update(.{ .key = .{ .cp = Key.enter } }); - const latest_id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - try std.testing.expect(first_id != latest_id); - - p.update(.{ .pipe_resp = .{ .id = first_id, .success = true, .outputs = &.{"BAD"} } }); - try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content); - p.update(.{ .pipe_resp = .{ .id = latest_id, .success = true, .outputs = &.{"NEW"} } }); - try std.testing.expectEqualSlices(u8, "NEW\n", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); -} - -test "selection pipe binding is file-normal-only" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = try p.setTestFile("x"); - - pane.file.?.output = .{ .from = .search }; - p.update(.{ .key = .{ .cp = '|' } }); - try std.testing.expect(pane.prompt != .pipe); - pane.file.?.output = null; - pane.mode = .insert; - p.update(.{ .key = .{ .cp = '|', .text = "|" } }); - try std.testing.expect(pane.prompt != .pipe); - try std.testing.expectEqualSlices(u8, "|x", pane.file.?.content); -} diff --git a/src/tty/tty.zig b/src/tty/tty.zig index fe968650..24403ba8 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -11,6 +11,7 @@ const look = @import("../look.zig"); const message = pardes.Messages.Message; const file_watch = @import("../file_watch.zig"); const selection_pipe = @import("../selection_pipe.zig"); +const Pipe = @import("../Pipe.zig"); const ninep_io = @import("../9p_io.zig"); const panel_compositor = @import("panel_compositor.zig"); const detached_client = @import("../detached/client.zig"); @@ -1325,7 +1326,7 @@ const Shell = struct { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return; } - const view = selection_pipe.pipeRequest(s.core, id) orelse return; + const view = Pipe.pipeRequest(s.core, id) orelse return; const job = selection_pipe.Job.copy(s.gpa, view) catch |err| { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return s.core.reportError(s.core.active, "pipe", err); -- cgit v1.3 From 425d9beb9c977df364ed83743cb2efdef9429478 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 00:42:04 -0300 Subject: File the tag code into tagline.zig and draw tags beside bodies With tags reduced to Texts, what is left of them is the computed prefix, the default and saved tails, entering and leaving a tag and the headers: that goes to tagline.zig, as acme keeps the tag half of a window in wind.c. Tag and header drawing moves next to body drawing in body_layer.zig, and the tag hit helpers go to tag_layer.zig with the Hit they read, where sameCell now also tells the lines of a taller tag apart. The docs describe the tag as a Text. Co-Authored-By: Claude Opus 5.5 --- docs/design.typ | 50 +-- docs/fs.md | 7 +- docs/helix-keys.md | 8 +- docs/tags.md | 64 ++-- src/body_layer.zig | 457 +++++++++++++++++++++- src/builtins.zig | 15 +- src/colors.zig | 3 +- src/dump.zig | 5 +- src/edit.zig | 14 +- src/exec.zig | 5 +- src/fs-help.txt | 2 +- src/fs.zig | 2 + src/gui/gui.zig | 2 +- src/layout.zig | 9 +- src/look.zig | 7 +- src/mouse.zig | 62 +-- src/ninep/pane.zig | 11 +- src/normal.zig | 7 +- src/panes.zig | 2 +- src/pardes.zig | 1025 ++++++-------------------------------------------- src/tag_layer.zig | 25 ++ src/tagline.zig | 360 ++++++++++++++++++ test/column_drag.zig | 18 +- test/fs_bench.zig | 2 +- test/mode.zig | 6 +- test/panes.zig | 50 +-- test/pdf.zig | 10 +- 27 files changed, 1153 insertions(+), 1075 deletions(-) create mode 100644 src/tagline.zig (limited to 'src/fs.zig') diff --git a/docs/design.typ b/docs/design.typ index 82bafb49..8e5f7e6e 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -530,9 +530,9 @@ Each pane kind keeps its storage and operations together in its own file image pane in `image.zig`), reached through `panes.zig` beside `Pane`. `layout.zig` owns placement and presentation state. `pardes.zig` handles input and cross-pane state directly, without a pane vtable; the rest of the editor -is split by thing as acme is: `edit.zig`, `normal.zig`, `look.zig`, `exec.zig`, -`mouse.zig`, `Messages.zig`, `Pipe.zig`, `colors.zig`, `surface.zig`, -`body_layer.zig` and `dump.zig`. Integration fixtures live +is split by thing as acme is: `Text.zig`, `edit.zig`, `normal.zig`, `tagline.zig`, +`look.zig`, `exec.zig`, `mouse.zig`, `Messages.zig`, `Pipe.zig`, `colors.zig`, +`surface.zig`, `body_layer.zig`, `tag_layer.zig` and `dump.zig`. Integration fixtures live in `test/panes.zig`, `test/output.zig`, and `test/pdf.zig`. = State @@ -770,33 +770,35 @@ pair per theme, and the three per-button tints and the dimmed extra cursors are mixed off it, so what stays fixed is the distinction between buttons and not the colours. -`Drag` is a `union(enum)` with six arms (`pardes.Drag`): `none`, -`border_v`, `border_h`, `move`, `tag`, `select`. `border_v` carries an optional +`Drag` is a `union(enum)` with six arms (`mouse.Drag`): `none`, +`border_v`, `border_h`, `move`, `column_move`, `select`. `border_v` carries an optional `corner`: when the press lands on a cell that is both a column's vertical border and one of the two adjoining columns' own horizontal borders, the one drag moves *both* boundaries — never three, and when both columns happen to be split at the grabbed row the left one wins, so the gesture that existed before is bit-for-bit unchanged. -== The tag is a command line - -A tag is one line: a live prefix (mode indicator, cwd or path) plus an editable -tail, and the tail gets the full modal editor. The coordinate space is UTF-8 byte -offsets into the *whole* rendered tag, prefix ++ tail, always on grapheme -boundaries (`Pane.tag_col`). The prefix is live chrome, so it is -selectable, yankable and executable but READ-ONLY: every edit op measures from -`edit0` — the first editable byte — and does nothing left of it. - -`tag_tail` is a fixed `[max_tag_tail]u8`, and the bound IS the storage -(`limits.max_tag_tail`): every writer — `appendTag`, `tagInsert`, -`restoreDumpTail`, the 9P `tag` file — refuses input that does not fit -rather than truncating it. The schema limit and the buffer therefore can never -disagree, which is what lets a dump reader reject data before copying it into a -pane. - -A tag edit is always insert mode, so it hijacks the body's mode; `tag_mode` -remembers what it hijacked and terminals restore it on exit, which is why -clicking a tag never changes a pane's mode. +== The tag is a text + +A tag is a `Text` (`Text.zig`), as a body is: acme's `Text`, one per +`what` — the body, the pane's tag, the prompt line, a column's tag and the +workspace tag. Each holds its own cursor, selections, mode and undo, so tags +are edited by the same `edit.zig` and `normal.zig` code as bodies, and the one +key they do not share is `:`, which moves between a pane's body and its tag. +A tag holds any number of lines; a pane's tag takes a row per line up to +`MAX_TAG_ROWS`, each drawn as a tag layer of its own. + +A pane's tag shows a live prefix (path, dirty marker, PDF page) before the text +it owns, and that prefix is computed at every read, never stored +(`tagline.tagPrefix`). The Text's coordinates are offsets into its own text +alone, so a rename or a save never moves its cursor. The one translation +point is the whole line as shown: render, the mouse, Look, Exec and the 9P +`tag` file see prefix ++ text, while keyboard motions and edits see only the +text. Editing the path is a separate draft (`Pane.prompt = .name`) committed +by Enter, since a buffer's name is not text it owns. + +The tag's text is bounded by `limits.max_tag_tail`: the 9P `tag` file and a +dump reader refuse input that does not fit rather than truncating it. = Diffing and presenting a frame diff --git a/docs/fs.md b/docs/fs.md index da4f4e68..c43034f6 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -180,7 +180,12 @@ back evaluates it, which is what acme(4) promises of its own `addr`. The three flag files `dirty`, `mark` and `scroll` read `0` or `1` and take `0` or `1`: whether the buffer differs from its file, whether a write pushes an undo point (writing `1` pushes one now), and whether a write scrolls the -pane. Truncating `tag` clears the part of the tag you may edit. +pane. + +`tag` reads the whole tag as the pane shows it: the computed path, dirty +marker or PDF page, then the text you may edit. A write appends to that text, +newlines included, and a tag with more than one line takes a row per line on +screen; truncating `tag` clears it, as acme's `cleartag` does. Stats report real lengths for `index`, `status`, `look`, `exec`, `listeners`, `name`, `body`, `tag`, `sel`, `ctl`, the range files and the flag files, and diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 0813c193..64fa2e24 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -117,15 +117,15 @@ language-backend queries, and the shell pipe. | `Esc` (insert) | back to normal mode, cursor right after the insertion (no vim left-step) | | helix-verified | | `Enter` (normal) | acme **look** chord: EXPLICIT selection, else file-ish word under cursor | pardes-specific, keep (helix normal-mode Enter unbound). Covers helix `gf`. Implicit motion residue falls back to the cursor word | pardes-specific | | `Tab` (normal) | acme **execute** chord | pardes-specific, keep; explicit-selection rule as Enter | pardes-specific | -| `:` (normal, body) | focuses the pane's tag in normal mode at its remembered cursor position (first entry starts at the commands). `h`/`l`, arrows, word motions and `0`/`$`/`^` move within the tag; `k` stays on its single line; `j` or `Esc` returns to the body. Uppercase `H`/`J`/`K`/`L` run `Left`/`Down`/`Up`/`Right` and enter the neighboring pane's tag. `K` beyond the top pane reaches the headers below. `y` yanks; Enter/Tab Look/Exec; `i`/`a`/`I`/`A` enter insert mode, where letters type normally. Explicit mouse clicks choose a new cursor position. | Each tag keeps its own cursor position during the session. Positions are UTF-8 byte offsets in the rendered prefix plus editable tail; file-name changes are staged as described in [editable tags](tags.md). | pardes-specific | -| `K` (tag normal, topmost tagline) | focuses the column tag, then another `K` reaches the workspace tag. With `ColumnTags` disabled it goes directly to the workspace. `J` walks back down. Header arrows and `h`/`l` move by grapheme; word motions and `0`/`$`/`^` work too. `j`/`Esc` returns to the panel; lowercase `k` stays put. Enter/Tab executes in normal mode; `i`/`a`/`I`/`A` enter editing, where Enter is Look and Tab is Exec. | Column commands target that column's active pane, or its first pane when coming from elsewhere. Workspace and column text are independently editable and persist in dumps. See [editable tags](tags.md). | pardes-specific | -| `Ctrl-w` + `h/j/k/l`/arrows | directional pane focus prefix — editor normal mode only | pardes' own window handling (helix window mode skipped, section C). Runs the SAME `Left`/`Down`/`Up`/`Right` builtins `SPC w h/j/k/l` runs; Raw **tty** mode forwards Ctrl-w to the child. Insert mode owns `Ctrl-w` = delete-word-back, so a tag being TYPED into swallows it; from a tag in normal mode (`:`) it moves focus to the neighbour's BODY, while the bare letters `h/j/k/l` there move to its TAGLINE (next row) | pardes-specific | +| `:` (normal, body or tag) | in the body, focuses the pane's tag in normal mode at its remembered cursor (the first time, on `Save`); in the tag, goes back to the body; in a column or workspace tag, back to the active pane. The tag's normal and insert modes ARE the body's: every motion, selection, edit and undo works there, `0` meaning the start of the editable text. Enter/Tab Look/Exec the word under the cursor or the selection, and executing hands the keyboard back to the body first. Clicks choose a new cursor position and type into the tag. | Each tag keeps its own cursor during the session. Cursor, selections and undo are offsets in the tag's own text; the computed path/marker/page before it is seen by the mouse, Look and Exec but not by keyboard motions. File-name changes are staged as described in [editable tags](tags.md). | pardes-specific | +| `Ctrl-w k` / `SPC w k` (pane with nothing above) | focuses its column's tag, then the workspace tag; with `ColumnTags` disabled it goes directly to the workspace. `Ctrl-w j` walks back to the panes, `Ctrl-w h`/`l` walk the column tags. Headers edit exactly as a pane tag does. | Column commands target that column's active pane, or its first pane when coming from elsewhere. Workspace and column text are independently editable and persist in dumps. See [editable tags](tags.md). | pardes-specific | +| `Ctrl-w` + `h/j/k/l`/arrows | directional pane focus prefix — editor normal mode only | pardes' own window handling (helix window mode skipped, section C). Runs the SAME `Left`/`Down`/`Up`/`Right` builtins `SPC w h/j/k/l` runs; Raw **tty** mode forwards Ctrl-w to the child. Insert mode owns `Ctrl-w` = delete-word-back, so a tag being TYPED into swallows it; from a tag in normal mode it moves focus to the neighbour's BODY, as from a body, and from the top pane `Up` reaches the column and workspace tags | pardes-specific | | `Alt-n` | new terminal below (outside raw tty) | shadows helix `Alt-n` TS sibling-select — skipped anyway (tree-sitter) | pardes-specific | | `Alt-c` | move active terminal to a fresh column (outside raw tty) | helix `Alt-c` is change-noyank; the pardes window op wins (do-not-touch contract). `Alt-d` + `i` covers the behavior | waived (`alt-c-window-op`) | | `Space` (normal, body) | starts the pardes LEADER: a key path runs the same builtin words used by tags and the topbar. The main groups are `f` files, `h` docs, `c` columns, `t` toggles/effects, `a` panel animations, `s` session, `j` jumps, `l` language, and `w` directional focus; `SPC ?` lists every path and ` ?` lists one group in `+Help`. The pending path appears on the active pane's transient body/message row. Esc or an unmapped key abandons it. Paths, Help rows, and dispatch are all generated from the builtin registry at comptime; the leader applies only to a BODY in normal mode because tags and tty programs own their input | pardes-specific; helix spends Space on pickers/LSP (section C), while pardes uses acme-style executable words | | `SPC y` `SPC Y` `SPC p` `SPC P` `SPC R` | helix's clipboard menu on helix's own letters: yank the selection to the system clipboard (`ClipYank`) or the PRIMARY selection alone (`ClipYankMain`), paste the system clipboard after (`ClipPaste`) / before (`ClipPasteBefore`) the selection, replace the selection with it (`ClipReplace`) | the ONLY five words in pardes that touch the desktop's clipboard — `y`/`d`/`c`/`p`/`P`/`R` and the acme cut/paste chords are the internal register alone. Builtins rather than bare chords because a leader path names a builtin: they land in Help's index and are executable words like every other verb. One divergence: pardes keeps a single register VALUE where helix keeps one per range, so `SPC y` at N cursors joins them with newlines (`Pardes.setYank`, the divergence `msel-yank-paste` already waives). On a tty the write is OSC 52 out and the READ is OSC 52 back, which many terminals refuse or gate — so `SPC y` works there and `SPC p` can be a no-op | out of corpus | | a paste from the OUTER terminal | one `Event.paste`, spliced in at the cursor | the tty shell enables bracketed paste and coalesces `paste_start`..`paste_end` into a single event; before that the bytes arrived as individual key presses and normal mode RAN them, which is how a pasted `d` deleted a line. The bytes deliberately never enter the yank register — clipboard and default register are separate stores in both directions | pardes-specific | -| `/` (any pane) | pardes' own plain-substring search into a `+Search` output buffer: the tag takes the pattern, Enter fills the buffer, and its rows are ordinary look targets. Enter also GOES to the first row — the buffer is focused and then the step `n` is and the look Enter is run in it (`Pardes.lookFirstHit`), so `/foo` lands on the first hit with the matched span selected. A pattern that matched nothing opens its empty buffer and moves nothing | KEEP, do not touch; not in the corpus (helix `/` is regex search). Find and Grep answer with OTHER files and deliberately do NOT jump. The stepping half is the next row | pardes-specific | +| `/` (any pane) | pardes' own plain-substring search into a `+Search` output buffer: the pattern is typed on a line of its own on the pane's notice band, Enter fills the buffer, and its rows are ordinary look targets. Enter also GOES to the first row — the buffer is focused and then the step `n` is and the look Enter is run in it (`Pardes.lookFirstHit`), so `/foo` lands on the first hit with the matched span selected. A pattern that matched nothing opens its empty buffer and moves nothing | KEEP, do not touch; not in the corpus (helix `/` is regex search). Find and Grep answer with OTHER files and deliberately do NOT jump. The stepping half is the next row | pardes-specific | | `n` / `N` (any pane) | MOTION, not a jump: move the SELECTION to the next / previous look-able text and open NOTHING. Enter — the look chord — on what it leaves selected is what opens it | KEEP, do not touch; not in the corpus (helix's `n`/`N` walk regex search hits). What a step selects is the pane's GRAIN (`output_pane.Grain`, read in `Pardes.lookSpanIn`): in FREE TEXT — a terminal, a file, a PDF, a prose answer buffer — the largest whitespace-delimited run `look.resolve` can act on (`look.lookableSpan`, wrapper punctuation peeled off both ends), several to a line; in a RESULTS BUFFER one stop per ROW, the largest run its head resolves as (`look.lookableLineSpan`), because a row there IS one location and the words after it are the match rather than a second place to go; in a COMMAND list the whole line. The walk is a RING across PANES: every pane that has performed a Look, most recent first (`Pardes.look_src`), then the output buffers that have not, newest first, and only when both are empty the active pane. Exhausting a pane enters the next at its first (forward) / last (backward) span and the end wraps to the start, so `N` is the exact inverse of `n`. What it lands on becomes an EXPLICIT `vsel` with the cursor on its FIRST column, in the pane the walk focuses. ONE motion in every pane kind and every buffer kind — a PDF steps the `+Search` buffer its own search filled, `n` to select the row and Enter to jump. The single thing a buffer may change is that grain, and it changes it by BEING a kind of buffer rather than by a branch: `output_pane.Traits.steps` (a list of locations) makes a step take one row at a time, and `Traits.commands` makes it take the WHOLE LINE, because a command list (`ThemeSel`/`FontSel`) holds words to run and there is no path inside `Theme gruvbox` to pick out. Tab on what `n` selected wears the theme, which is the same middle click on the row is. `]d`/`[d` are helix's diagnostic motions, a different binding, and they do still jump to each diagnostic (`docs/lsp.md`) | pardes-specific | | insert: printable text | file: real edit; terminal: typed run splice | | helix-verified (file) | | insert: `Enter` | newline; keeps the current full indent levels and adds one 4-space logical tab when the text before the cursor ends in `(`, `[`, `{`, or `)` (including `})`) | plain lines match `insert_newline`; delimiter heuristic is pardes-specific | helix-verified (plain) / pardes-specific (delimiter) | diff --git a/docs/tags.md b/docs/tags.md index f299c859..ecca046a 100644 --- a/docs/tags.md +++ b/docs/tags.md @@ -44,34 +44,54 @@ asks; there bare `Del` gives the rows to the nearest document above, as it always has. A collapsed pane is never asked about, and collapsed neighbors are passed over: they only keep a weight for later. -Left-click a tag to place its caret; drag to select text, then type to -replace it. Arrow keys, Home, End, Backspace and Delete edit the line. -Tags reveal the caret horizontally when text is wider than their column. -Escape returns to the body, keeping command-text edits. The existing Exec -and Look gestures still apply; the workspace tag is no longer an inert -left-click target. Pasted text goes to the focused tag, not to the file or -embedded shell beneath it. - -Keyboard entry returns to the tag's last cursor position. The first entry into -a pane tag starts at its commands; clicking always chooses a new position. -Each pane, column and workspace tag remembers its own position during the -session. Shortened text clamps the saved cursor to a valid character boundary. - -In normal mode, `h` and `l` move within the tag, `k` stays on the single line, -and `j` returns to the panel like Escape. Uppercase `HJKL` move between pane -tags. From the top pane's `:` tag, `K` reaches the column and another `K` reaches -the workspace; `J` walks back down. Enter or Tab on a header command in -normal mode executes it, as before. `i`/`a`/`I`/`A` switch to editing the -header. In insert mode, letters type normally, Enter is Look and Tab is Exec, -as in pane tags. +A tag is a text like a pane's body: pane tags, column tags and the +workspace tag all edit with the body's own normal and insert modes, undo +included, and may hold more than one line. A tag with a newline in it takes +a row per line, up to eight: a pane's tag leaves its body at least one row +and a collapsed pane shows only the first line; the column and workspace +tags take no more than a third of the screen, and the panes below move down +to make room. The path, the dirty marker and a PDF's page at the start of a +pane tag are computed, never stored: the tag's cursor, selections and undo +live in the text after them, so a rename or a save never moves the cursor. +The mouse still sees the whole line -- a sweep selects across the path and +the commands, and Look and Exec work on either -- but the keyboard moves only +in the tag's own text: `0` goes to its start, not the path's. + +Left-click a tag or a header to type into it at the click, in insert mode; +tags reveal the caret horizontally when text is wider than their column. +Esc is normal mode, where everything a body's normal mode does works, and +Enter looks up and Tab executes the word under the cursor (or an explicit +selection), in either mode. Executing gives the keyboard back to the body +first, so `Del`, `Kill` and `Restore` never return into a tag that is gone. +Pasted text goes to the focused tag, not to the file or embedded shell +beneath it. + +`:` is the one key a tag and a body do not share: in the body's normal mode +it focuses the pane's tag in normal mode, and in the tag's normal mode it +goes back to the body; in a column or workspace tag it goes back to the +active pane. Each pane, column and workspace tag remembers its own cursor +during the session; the first `:` into a pane tag starts on its `Save`. A +tag's text changing under it (a 9P write, a shorter tag) pulls the cursor +back inside it. + +Moving between tags is the window keys' job, as it is between bodies +(`Ctrl-w` or `SPC w` with `h/j/k/l`): they move to the neighbouring pane's +body. Up from a pane with nothing above it reaches its column's tag, then +the workspace's; Down comes back the same way, and Left and Right walk the +column tags. + +Search (`/`), pipe (`|`) and Save's path prompt are not typed into the tag: +each gets a line of its own on the pane's notice band, with the body's +insert-mode keys, and leaves the tag as it was. Pane filenames and commands now have a single separator space rather than generated right-alignment padding. Intentionally customized spacing is kept. ## File names -Editing a file pane's name creates a draft. Enter confirms the new buffer -name; Escape or leaving the tag cancels the draft. Confirmation changes the +Clicking a file pane's name starts a draft of it, typed into at the click. +Enter or Tab confirms the new buffer name; Escape or leaving the pane +cancels the draft. Confirmation changes the buffer's save target and marks it unsaved. It does **not** rename, create or overwrite a disk file. A subsequent explicit `Save` writes the buffer to its committed name. Executing a pane-tag command confirms a valid name draft diff --git a/src/body_layer.zig b/src/body_layer.zig index 2b2c8a74..ab000795 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -2,7 +2,8 @@ //! outnumber its physical grid rows: hosts place the compact declaration rows //! first and clip the remaining body rows. After the layer types come the //! functions that draw a body into the surface: its text, colours, selections -//! and cursor. +//! and cursor; then the tags drawn beside it, a pane's and the column and +//! workspace ones, each line a tag layer of its own. const std = @import("std"); const pardes = @import("pardes.zig"); const normal = @import("normal.zig"); @@ -24,6 +25,20 @@ const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const Rect = layout.Rect; const Pardes = pardes.Pardes; +const tagline = @import("tagline.zig"); +const Messages = @import("Messages.zig"); +const Text = panes.Text; +const MAX_PANES = pardes.MAX_PANES; +const TagKind = @import("tag_layer.zig").Kind; +const MAX_TAG_ROWS = pardes.MAX_TAG_ROWS; +const NOTICE_LAYER_BASE = pardes.NOTICE_LAYER_BASE; +const TAG_LINE_LAYER_BASE = pardes.TAG_LINE_LAYER_BASE; +const HEADER_LINE_LAYER_BASE = pardes.HEADER_LINE_LAYER_BASE; +const MAX_COLS = pardes.MAX_COLS; +const TOPBAR_H = pardes.TOPBAR_H; +const COLBAR_H = pardes.COLBAR_H; +const TAG_GAP = pardes.TAG_GAP; +const wordBoundsAtCol = pardes.wordBoundsAtCol; pub const Metrics = struct { body_w: u16 = 1, @@ -540,3 +555,443 @@ pub fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { if (pane.file) |*f| return panes.File.bodyText(arena, pane, f, p.settings.wrap); return panes.Terminal.bodyText(arena, pane); } + +/// The workspace and column tags as the grid shows them: their text, the +/// word under the pointer and, in the one being edited, its selection and +/// caret. Their tag layers are drawn by renderTagLayers. +pub fn paintHeaders(p: *Pardes) !void { + const s = &p.surface; + const chrome = p.chromeTheme(); + const th = p.theme(); + // global tagbar: full width, top rows — unless a native shell has + // taken its commands over, in which case the rows are not ours to draw + tagline.revealHeader(p); + const global = tagline.topbar(p); + const global_rows = p.topBarHeight(); + const global_scroll = if (p.header_focus and p.header_column == null) p.header_scroll else 0; + if (p.settings.workspace_tag) { + s.fill(0, 0, s.cols, global_rows, .{ + .bg = .{ .rgb = chrome.tag_bg }, + .font_role = .tagline, + }); + for (0..global_rows) |row| { + const line = modal.lineSlice(global, row); + _ = s.print(0, @intCast(row), s.cols, line[panes.File.rawAtDisplay(line, global_scroll)..], .{ + .fg = .{ .rgb = chrome.tag_fg }, + .bg = .{ .rgb = chrome.tag_bg }, + .font_role = .tagline, + }); + } + } + if (p.pointer_inside and p.hover_row < global_rows) { + const bar = modal.lineSlice(global, p.hover_row); + if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col + global_scroll))) |bounds| { + var col = panes.File.rawDisplayCol(bar, bounds.lo) -| global_scroll; + const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| global_scroll; + while (col < hi and col < s.cols) : (col += 1) { + const cell = s.at(@intCast(col), p.hover_row); + cell.default = false; + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + } + } + } + const column_rows = p.columnBarHeight(); + if (column_rows > 0) for (0..p.ncol) |c| { + const grip = @min(config.GUTTER, p.col_w[c]); + const inset = @min(TAG_TEXT_INSET, p.col_w[c]); + const x = p.col_x[c] + inset; + const w = p.col_w[c] - inset; + const y0 = global_rows; + if (p.col_w[c] == 0 or p.col_x[c] >= s.cols) continue; + const active_col = if (layout.findPane(p, p.active)) |f| f.col == c else false; + const bg = if (active_col and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; + const fg = if (active_col and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg; + // A grip is muted until it is grabbed; then it lights, as a pane's + // box does for the active pane, so the drag shows what it holds. + const grabbed = p.drag == .column_move and layout.columnBySerial(p, p.drag.column_move.serial) == c; + const grip_bg = if (grabbed) chrome.column_box else chrome.column_box_dim; + const lum = (@as(u16, grip_bg[0]) * 3 + @as(u16, grip_bg[1]) * 6 + @as(u16, grip_bg[2])) / 10; + const ink: [3]u8 = if (lum > 140) .{ 0, 0, 0 } else .{ 255, 255, 255 }; + const grip_style: CellStyle = .{ .bg = .{ .rgb = grip_bg }, .fg = .{ .rgb = ink }, .font_role = .tagline }; + s.fill(p.col_x[c], y0, grip, column_rows, grip_style); + s.fill(p.col_x[c] + grip, y0, inset - grip, column_rows, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + + s.fill(x, y0, w, column_rows, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + const bar_scroll = if (p.header_focus and p.header_column == c) p.header_scroll else 0; + const tag = tagline.columnTag(p, c); + for (0..column_rows) |row| { + const line = modal.lineSlice(tag, row); + _ = s.print(x, y0 + @as(u16, @intCast(row)), w, line[panes.File.rawAtDisplay(line, bar_scroll)..], .{ + .fg = .{ .rgb = fg }, + .bg = .{ .rgb = bg }, + .font_role = .tagline, + }); + } + // A carried column's pointer is aiming at a place, not a word. + if (p.pointer_inside and p.drag != .column_move and p.hover_row >= y0 and p.hover_row < y0 + column_rows and p.hover_col >= x and p.hover_col < x + w) { + const bar = modal.lineSlice(tag, p.hover_row - y0); + if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col - x + bar_scroll))) |bounds| { + var col = panes.File.rawDisplayCol(bar, bounds.lo) -| bar_scroll; + const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| bar_scroll; + while (col < hi and col < w) : (col += 1) { + const cell = s.at(x + @as(u16, @intCast(col)), p.hover_row); + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + } + } + } + }; + if (tagline.focusedHeader(p)) |t| { + const text = try edit.flatSurface(p, t); + const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; + const w = if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else s.cols; + const y: u16 = if (p.header_column != null) global_rows else 0; + const rows = if (p.header_column != null) column_rows else global_rows; + for (0..rows) |row| { + const bar = modal.lineSlice(text, row); + const span = tagline.headerSelection(t, text, row) orelse continue; + var col = panes.File.rawDisplayCol(bar, span.lo) -| p.header_scroll; + const hi = panes.File.rawDisplayCol(bar, span.hi) -| p.header_scroll; + while (col < hi and col < w) : (col += 1) { + const cell = s.at(x + @as(u16, @intCast(col)), y + @as(u16, @intCast(row))); + cell.style.fg = .{ .rgb = th.sel_fg }; + cell.style.bg = .{ .rgb = th.sel_bg }; + } + } + if (t.cur_row >= 0 and t.cur_row < rows) { + const bar = modal.lineSlice(text, @intCast(t.cur_row)); + const caret = panes.File.rawDisplayCol(bar, @min(@as(usize, @intCast(@max(0, t.cur_col))), bar.len)) -| p.header_scroll; + if (caret < w) s.cursor = .{ .x = x + @as(u16, @intCast(caret)), .y = y + @as(u16, @intCast(t.cur_row)), .bar = t.mode == .insert }; + } + } +} + +fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { lo: usize, hi: usize } { + if (pane.isTerminal()) { + var words = std.mem.tokenizeAny(u8, tag[prefix_len..], " \t\r\n"); + while (words.next()) |word| { + if (!std.mem.eql(u8, word, "Tty")) continue; + const lo = @intFromPtr(word.ptr) - @intFromPtr(tag.ptr); + return .{ .lo = lo, .hi = lo + word.len }; + } + return null; + } + var start: usize = 0; + const name = if (pane.file) |file| + if (pane.prompt == .name) pane.input.own orelse file.path else file.path + else if (pane.image) |state| blk: { + // Image tags put renderer controls before the path. + start = prefix_len -| state.path.len; + break :blk state.path; + } else if (comptime pdf_enabled) blk: { + break :blk if (pane.pdf) |state| state.path else return null; + } else return null; + const basename = if (std.mem.lastIndexOfScalar(u8, name, '/')) |slash| slash + 1 else 0; + if (basename == name.len) return null; + return .{ .lo = start + basename, .hi = start + name.len }; +} + +pub fn renderTagLayers(p: *Pardes, arena: std.mem.Allocator) !void { + const chrome = p.chromeTheme(); + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const r = p.rects[id]; + if (r.w <= TAG_TEXT_INSET or r.h == 0) continue; + const tag = try tagline.tagText(p, arena, pane); + const rows = pane.tag_rows; + // As wide as the widest line it shows, and never narrower than + // its viewport. + var widest: usize = 0; + var split = std.mem.splitScalar(u8, tag, '\n'); + for (0..rows) |_| widest = @max(widest, panes.File.displayWidth(split.next() orelse "")); + const columns: u16 = @intCast(@min(std.math.maxInt(u16) - TAG_TEXT_INSET, @max(p.tagCapacity(r.w - TAG_TEXT_INSET), widest + 1))); + const pitch = @as(usize, columns) + TAG_TEXT_INSET; + const storage = try arena.alloc(Cell, pitch * rows); + @memset(storage, .{}); + var temporary: Surface = .{ .cols = columns + TAG_TEXT_INSET, .rows = rows, .cells = storage }; + std.mem.swap(Surface, &p.surface, &temporary); + paintPaneTag(p, arena, pane, .{ .x = 0, .y = 0, .w = columns + TAG_TEXT_INSET, .h = rows }, id, id == p.active, p.tagCapacity(r.w - TAG_TEXT_INSET)) catch |err| { + std.mem.swap(Surface, &p.surface, &temporary); + return err; + }; + std.mem.swap(Surface, &p.surface, &temporary); + // A layer to a line: the first in the pane's own slot, the rest + // in the slots kept for the lines of taller tags. + for (0..rows) |line| { + const layer = &p.surface.tag_layers[if (line == 0) id else TAG_LINE_LAYER_BASE + id * (MAX_TAG_ROWS - 1) + line - 1]; + if (layer.cells.len != columns) layer.cells = try p.gpa.realloc(layer.cells, columns); + @memcpy(layer.cells, storage[line * pitch + TAG_TEXT_INSET ..][0..columns]); + layer.kind = .pane; + layer.id = @intCast(id); + layer.serial = pane.serial; + layer.line = @intCast(line); + layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = p.tagTop(pane, r) + @as(u16, @intCast(line)), .w = r.w - TAG_TEXT_INSET, .h = BOX_H }; + layer.cols = columns; + layer.bg = if (id == p.active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; + layer.cursor = if (p.header_focus) null else if (temporary.cursor) |cursor| + (if (cursor.y == line) .{ .col = cursor.x - TAG_TEXT_INSET, .bar = cursor.bar } else null) + else + null; + } + } + // With the workspace tag row handed to native chrome there is no + // workspace layer to render; the menu bar carries its commands. + if (p.settings.workspace_tag) { + for (0..p.topBarHeight()) |line| { + const index = if (line == 0) MAX_PANES + MAX_COLS else HEADER_LINE_LAYER_BASE + MAX_COLS * (MAX_TAG_ROWS - 1) + line - 1; + try renderHeaderLayer(p, arena, index, .workspace, 0, @intCast(line), .{ .x = 0, .y = @intCast(line), .w = p.screen_w, .h = TOPBAR_H }, modal.lineSlice(tagline.topbar(p), line), chrome.tag_bg, chrome.tag_fg); + } + } + // Each notice is its own tagline-shaped chip over the top of the body. + // Going through the same layer machinery the pane and column tags use + // is what gives it the tagline's height, its small-font metrics, the + // band offset and the border -- none of which a body-grid row can have + // just by wearing a tagline font. The geometry is the one the grid + // pass already chose and recorded, so the two cannot disagree and the + // GUI's "skip the cells a tag layer covers" leaves no stub behind. + // A prompt is one of them too: left on the grid, a pixel shell drew + // its tagline glyphs one to a BODY cell, spaced out like a banner. + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const r = p.rects[id]; + if (r.w <= TAG_TEXT_INSET or r.h <= pane.tag_rows) continue; + const first = p.bodyTop(pane, r); + var leader_buf: [16]u8 = undefined; + for (pane.notices.slice(), 0..) |kind, i| { + const text = Messages.noticeText(p, pane, i, &leader_buf); + if (text.len == 0) continue; + const cx = pane.notices.left[i]; + if (cx == std.math.maxInt(u16) or cx >= r.x + r.w) continue; + const chip = r.x + r.w - cx; + // Right aligned inside the chip, a blank cell short of its + // edge: the same one the grid pass leaves for a prompt caret. + // Wider than the chip, the text loses its head, as on the grid. + const room = p.tagCapacity(chip) -| 1; + const shown = panes.File.displayWidth(text); + var kept = text; + if (shown > room) { + var start = panes.File.rawAtDisplay(text, shown - room); + if (panes.File.rawDisplayCol(text, start) < shown - room) start = panes.File.rawAtDisplay(text, shown - room + 1); + kept = text[start..]; + } + const pad = room -| panes.File.displayWidth(kept); + const line = try arena.alloc(u8, pad + kept.len); + @memset(line[0..pad], ' '); + @memcpy(line[pad..], kept); + // A pixel shell slides the message in as it fades up, and + // fades it on the way out. + const motion: Messages.MessageMotion = if (Messages.noticeLife(pane, i)) |life| Messages.messageMotion(p, life) else .{}; + const fade = motion.alpha; + const page = p.theme().bg orelse chrome.tag_bg; + const layer_index = NOTICE_LAYER_BASE + id * Pane.Notices.max + i; + try renderHeaderLayer(p, arena, layer_index, .notice, @intCast(id), 0, .{ + .x = cx, + .y = first + @as(u16, pane.notices.row[i]), + .w = chip, + .h = BOX_H, + }, line, Messages.blendRgb(chrome.tag_bg, page, fade), Messages.blendRgb(chrome.tag_fg, page, fade)); + p.surface.tag_layers[layer_index].slide = motion.slide; + p.surface.tag_layers[layer_index].fade = fade; + // The caret rides the band, where the prompt's glyphs are, + // at the same place in the text the grid pass puts it. + if (kind != .prompt or id != p.active or pane.prompt == .del_side) continue; + const typed = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); + const dropped = shown - panes.File.displayWidth(kept); + if (typed < dropped) continue; + p.surface.tag_layers[layer_index].cursor = .{ .col = @intCast(pad + typed - dropped), .bar = pane.input.mode == .insert }; + } + } + if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { + if (p.col_w[column] == 0) continue; + const active = if (layout.findPane(p, p.active)) |found| found.col == column and p.settings.focus_tint else false; + for (0..p.columnBarHeight()) |line| { + const index = if (line == 0) MAX_PANES + column else HEADER_LINE_LAYER_BASE + column * (MAX_TAG_ROWS - 1) + line - 1; + try renderHeaderLayer(p, arena, index, .column, @intCast(column), @intCast(line), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight() + @as(u16, @intCast(line)), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, modal.lineSlice(tagline.columnTag(p, column), line), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); + } + }; +} + +/// One row of a header or a notice band as a tag layer: `text` is line +/// `line` of what it shows. +fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, index: usize, kind: TagKind, id: u16, line: u16, viewport: Rect, text: []const u8, bg: [3]u8, fg: [3]u8) !void { + _ = arena; + const layer = &p.surface.tag_layers[index]; + if (viewport.w == 0) { + layer.cols = 0; + return; + } + const columns: u16 = @intCast(@min(std.math.maxInt(u16), @max(p.tagCapacity(viewport.w), panes.File.displayWidth(text) + 1))); + if (layer.cells.len != columns) layer.cells = try p.gpa.realloc(layer.cells, columns); + layer.kind = kind; + layer.id = id; + layer.line = line; + layer.serial = if (kind == .column) p.col_serial[id] else 0; + layer.viewport = viewport; + layer.cols = columns; + layer.bg = bg; + layer.cursor = null; + layer.slide = 0; + layer.fade = 1; + var surface: Surface = .{ .cols = columns, .rows = 1, .cells = layer.cells }; + // A notice band carries a PANE id, not a column index, so it must not + // answer to the column being edited -- that would scroll and select + // its text with the column tag's offsets and give it a second caret. + const editing: ?*Text = if (p.header_focus and switch (kind) { + .workspace => p.header_column == null, + .column => p.header_column == id, + .pane, .notice => false, + }) tagline.focusedHeader(p) else null; + const scroll = if (editing != null) p.header_scroll else 0; + surface.fill(0, 0, columns, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + _ = surface.print(0, 0, columns, text[panes.File.rawAtDisplay(text, scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); + if (editing) |t| { + if (tagline.headerSelection(t, try edit.flatSurface(p, t), line)) |span| { + var col = panes.File.rawDisplayCol(text, span.lo) -| scroll; + const end = panes.File.rawDisplayCol(text, span.hi) -| scroll; + while (col < end and col < columns) : (col += 1) { + surface.at(@intCast(col), 0).style.bg = .{ .rgb = p.theme().sel_bg }; + surface.at(@intCast(col), 0).style.fg = .{ .rgb = p.theme().sel_fg }; + } + } + const caret = panes.File.rawDisplayCol(text, @min(@as(usize, @intCast(@max(0, t.cur_col))), text.len)) -| scroll; + if (t.cur_row == line and caret < columns) layer.cursor = .{ .col = @intCast(caret), .bar = t.mode == .insert }; + } else if (p.pointer_inside) { + const tag_hit = p.pointer_tag_hit; + const col: ?usize = if (tag_hit) |pointer| + (if (pointer.kind == kind and pointer.id == id and pointer.line == line) pointer.col else null) + else if (p.hover_row == viewport.y and p.hover_col >= viewport.x and p.hover_col - viewport.x < viewport.w) + p.hover_col - viewport.x + else + null; + if (col) |hover| if (wordBoundsAtCol(text, panes.File.rawAtDisplay(text, hover + scroll))) |bounds| { + var cell = panes.File.rawDisplayCol(text, bounds.lo) -| scroll; + const end = panes.File.rawDisplayCol(text, bounds.hi) -| scroll; + while (cell < end and cell < columns) : (cell += 1) { + surface.at(@intCast(cell), 0).style.bg = .{ .rgb = p.theme().sel_bg }; + surface.at(@intCast(cell), 0).style.fg = .{ .rgb = p.theme().sel_fg }; + } + }; + } +} + +pub fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, capacity: u16) !void { + const s = &p.surface; + const th = p.theme(); + const chrome = p.chromeTheme(); + const tx = r.x + @min(TAG_TEXT_INSET, r.w); + const tw = r.w -| TAG_TEXT_INSET; + const tag_y = p.tagTop(pane, r); + const body_y = p.bodyTop(pane, r); + const rows = pane.tag_rows; + const page_rgb = th.bg orelse th.tag_bg; + // Focus is visible along the tag without changing its live text grid. + const tag_bg = if (active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; + const tag_fg = if (active and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg; + const tag_style: CellStyle = .{ .fg = .{ .rgb = tag_fg }, .bg = .{ .rgb = tag_bg }, .font_role = .tagline }; + // Padding belongs to the same font row but keeps its default ink: a + // role must not manufacture a foreground color for blank cells. + s.fill(r.x + config.GUTTER, tag_y, @min(TAG_GAP, r.w -| config.GUTTER), rows, .{ .bg = .{ .rgb = tag_bg }, .font_role = .tagline }); + s.fill(tx, tag_y, tw, rows, .{ + .bg = .{ .rgb = tag_bg }, + .font_role = .tagline, + }); + const whole = try tagline.tagText(p, arena, pane); + const tail = tagline.curTail(pane); + const prefix_len = whole.len - tail.len; + // A row per line: the first carries the prefix, the rest are the + // tag's own text alone. + var lines: [MAX_TAG_ROWS][]const u8 = @splat(""); + var split = std.mem.splitScalar(u8, whole, '\n'); + for (lines[0..rows]) |*line| line.* = split.next() orelse ""; + // The keyboard's caret, as a row and a byte offset in that row's + // line: in the tag's own text when the tag has the keyboard, in the + // path while a name is drafted. + const Caret = struct { row: usize, at: usize }; + const caret: ?Caret = if (!active) + null + else if (pane.prompt == .name) + .{ .row = 0, .at = @min(lines[0].len, @as(usize, @intCast(@max(0, pane.input.cur_col)))) } + else if (pane.focus == .tag and pane.tag.cur_row < rows) caret: { + const row: usize = @intCast(@max(0, pane.tag.cur_row)); + const lead: usize = if (row == 0) prefix_len else 0; + break :caret .{ .row = row, .at = @min(lines[row].len, lead + @as(usize, @intCast(@max(0, pane.tag.cur_col)))) }; + } else null; + if (caret) |at| { + const line = lines[at.row]; + const col = panes.File.rawDisplayCol(line, at.at); + var scroll: usize = pane.tag_scroll; + if (col < scroll) scroll = col; + if (col >= scroll + capacity) scroll = col - capacity + 1; + var raw = panes.File.rawAtDisplay(line, scroll); + scroll = panes.File.rawDisplayCol(line, raw); + if (col >= scroll + capacity) { + raw = modal.nextGrapheme(line, raw); + scroll = panes.File.rawDisplayCol(line, raw); + } + pane.tag_scroll = @intCast(scroll); + } else if (pane.focus != .tag) pane.tag_scroll = 0; + for (lines[0..rows], 0..) |line, row| { + const start = panes.File.rawAtDisplay(line, pane.tag_scroll); + _ = s.print(tx, tag_y + @as(u16, @intCast(row)), tw, line[start..], tag_style); + } + const tag = lines[0]; + if (tagTintRange(pane, tag, prefix_len)) |name| { + const lo = @max(name.lo, panes.File.rawAtDisplay(tag, pane.tag_scroll)); + const hi = @min(name.hi, tag.len); + if (lo < hi) { + var col = panes.File.rawDisplayCol(tag, lo) -| pane.tag_scroll; + const end = panes.File.rawDisplayCol(tag, hi) -| pane.tag_scroll; + const name_fg = if (active and p.settings.focus_tint) chrome.tag_active_name_fg else chrome.tag_name_fg; + while (col < end and col < tw) : (col += 1) + s.at(tx + @as(u16, @intCast(col)), tag_y).style.fg = .{ .rgb = name_fg }; + } + } + if (p.look_hover_preview) |preview| { + if (preview.pane == id and preview.serial == pane.serial) if (preview.sel) |sel| if (@min(sel.r0, sel.r1) < rows) { + const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); + paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); + }; + } + // The tag's own selections, while it has the keyboard, a line at a + // time. A range of one grapheme is the block cursor, not a selection. + if (pane.focus == .tag) { + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = pane.tag.ranges(tail, 0, &ranges); + for (ranges[0..got.n]) |range| { + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + if (modal.nextGrapheme(tail, lo) >= hi) continue; + const first = modal.positionAt(tail, lo); + const last = modal.positionAt(tail, hi); + var row = first.row; + while (row <= last.row and row < rows) : (row += 1) { + const line = lines[row]; + const lead: usize = if (row == 0) prefix_len else 0; + const from = lead + if (row == first.row) first.col else 0; + const to = @min(line.len, lead + if (row == last.row) last.col else modal.lineSlice(tail, row).len); + var col = panes.File.rawDisplayCol(line, from) -| pane.tag_scroll; + const end = panes.File.rawDisplayCol(line, to); + const y = tag_y + @as(u16, @intCast(row)); + while (col + pane.tag_scroll < end and col < tw) : (col += 1) { + const cell = s.at(tx + @as(u16, @intCast(col)), y); + cell.default = false; + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + } + } + } + } + // the caret: bar while typing, block in normal mode (same rule as a body) + if (caret) |at| { + const col = panes.File.rawDisplayCol(lines[at.row], at.at) -| pane.tag_scroll; + const mode = if (pane.prompt == .name) pane.input.mode else pane.tag.mode; + if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y + @as(u16, @intCast(at.row)), .bar = mode == .insert }; + } + + for (pane.sel, 0..) |selection, button| { + if (selection.state == .none or (selection.state == .done and button != 0)) continue; + if (@min(selection.r0, selection.r1) >= rows) continue; + paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); + } +} diff --git a/src/builtins.zig b/src/builtins.zig index 74645376..e9f29102 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1,6 +1,7 @@ //! Command structs and runtime settings form the builtin registry; bindings live in config.zig. const std = @import("std"); const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const dump = @import("dump.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); @@ -742,7 +743,7 @@ pub const Grep = struct { pub const Left = struct { pub fn run(c: Ctx) void { if (c.p.header_focus) { - if (c.p.header_column) |column| if (column > 0) c.p.enterHeader(column - 1); + if (c.p.header_column) |column| if (column > 0) tagline.enterHeader(c.p, column - 1); return; } _ = layout.focusDir(c.p, c.id, .left); @@ -754,10 +755,10 @@ pub const Down = struct { if (c.p.header_focus) { const column = layout.findPane(c.p, c.id); if (c.p.header_column == null and c.p.columnBarHeight() > 0) - return c.p.enterHeader(if (column) |at| at.col else 0); + return tagline.enterHeader(c.p, if (column) |at| at.col else 0); // Onto the top pane of the column the header stands over. const col = c.p.header_column orelse if (column) |at| at.col else return; - c.p.exitHeader(); + tagline.exitHeader(c.p); if (col < c.p.ncol and c.p.col_n[col] > 0) c.p.active = c.p.col_panes[col][0]; return; } @@ -768,20 +769,20 @@ pub const Down = struct { pub const Up = struct { pub fn run(c: Ctx) void { if (c.p.header_focus) { - if (c.p.header_column != null and c.p.topBarHeight() > 0) c.p.enterHeader(null); + if (c.p.header_column != null and c.p.topBarHeight() > 0) tagline.enterHeader(c.p, null); return; } if (layout.focusDir(c.p, c.id, .up)) return; if (c.p.columnBarHeight() > 0) { - if (layout.findPane(c.p, c.id)) |at| c.p.enterHeader(at.col); - } else if (c.p.topBarHeight() > 0) c.p.enterHeader(null); + if (layout.findPane(c.p, c.id)) |at| tagline.enterHeader(c.p, at.col); + } else if (c.p.topBarHeight() > 0) tagline.enterHeader(c.p, null); } }; pub const Right = struct { pub fn run(c: Ctx) void { if (c.p.header_focus) { - if (c.p.header_column) |column| if (column + 1 < c.p.ncol) c.p.enterHeader(column + 1); + if (c.p.header_column) |column| if (column + 1 < c.p.ncol) tagline.enterHeader(c.p, column + 1); return; } _ = layout.focusDir(c.p, c.id, .right); diff --git a/src/colors.zig b/src/colors.zig index f92f67b1..bb366fc0 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -1,6 +1,7 @@ //! Colour themes: the Theme type, the curated and generated ring, chrome //! colours and their animation, theme files, and switching themes at runtime. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const panes = @import("panes.zig"); const std = @import("std"); const layout = @import("layout.zig"); @@ -602,7 +603,7 @@ test "line numbers stay quiet without a current-line tag background" { const moved = try p.render(p.scratch.allocator()); try std.testing.expect(!moved.at(x, y).style.bold); try std.testing.expect(moved.at(x, y + 1).style.bold); - p.enterTag(pane); + tagline.enterTag(p, pane); const tag_edit = try p.render(p.scratch.allocator()); try std.testing.expect(!tag_edit.at(x, y + 1).style.bold); } diff --git a/src/dump.zig b/src/dump.zig index aeb25a90..508e7300 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -7,6 +7,7 @@ const limits = @import("memory.zig").limits; // diagnostic is the only thing that says WHICH field went bad. const log = std.log.scoped(.dump); const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const layout = @import("layout.zig"); const filesystem = @import("fs.zig"); const ctlfs = @import("ninep/tree.zig"); @@ -603,7 +604,7 @@ pub fn dumpState(p: *Pardes) !void { for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; slot_to_pane[id] = panes_len; - const tag = try p.tagText(arena, pane); + const tag = try tagline.tagText(p, arena, pane); const body = try body_layer.bodyText(p, arena, pane); const scroll: usize = @intCast(@max(0, pane.scroll())); var dp: Pane = if (pane.file) |*f| try pardes.panes.File.dumpPane( @@ -784,7 +785,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo break :restore_image try pardes.panes.Image.restore(p, i, src); }, }; - p.restoreDumpTail(pane, src); + tagline.restoreDumpTail(p, pane, src); pane.vweight = src.vweight; pane.collapsed = src.collapsed; } diff --git a/src/edit.zig b/src/edit.zig index 36544d6b..edc86dd2 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -3,6 +3,7 @@ //! operations, replace, case, join, indent, comments, numbers, textobjects //! and surround, undo, yank and paste, and the pointer selections as text. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const mouse = @import("mouse.zig"); const normal = @import("normal.zig"); const std = @import("std"); @@ -15,7 +16,8 @@ const lsp = @import("lsp/lsp.zig"); const platform = pardes.platform; const Pane = panes.Pane; const Text = panes.Text; -const TagHit = @import("tag_layer.zig").Hit; +const tag_layer = @import("tag_layer.zig"); +const TagHit = tag_layer.Hit; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const Mouse = pardes.Mouse; @@ -72,7 +74,7 @@ pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) voi } pub fn applyPaste(p: *Pardes, bytes: []const u8) void { - if (p.focusedHeader()) |t| { + if (tagline.focusedHeader(p)) |t| { p.clip_pending = null; return pasteInto(p, t, bytes); } @@ -132,7 +134,7 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { /// (the tag's lines first, as many as it shows) pub fn paneText(p: *Pardes, pane: *Pane) ![]u8 { const arena = p.scratch.allocator(); - const tag = try p.tagText(arena, pane); + const tag = try tagline.tagText(p, arena, pane); const cut = modal.lineStartOffset(tag, pane.tag_rows); const shown = if (cut < tag.len) tag[0 .. cut - 1] else tag; return std.fmt.allocPrint(arena, "{s}\n{s}", .{ shown, try body_layer.bodyText(p, arena, pane) }); @@ -353,9 +355,9 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { switch (t.what) { .body => {}, - .tag => return Pardes.curTail(t.pane()), + .tag => return tagline.curTail(t.pane()), .input => return t.own orelse "", - .column, .workspace => return t.own orelse p.headerDefault(t.what), + .column, .workspace => return t.own orelse tagline.headerDefault(p, t.what), } const pane = t.pane(); if (pane.file) |f| return f.content; @@ -1617,7 +1619,7 @@ pub fn pointerTextSelection(p: *const Pardes, id: usize, col: u16, row: u16, bod const v = @as(i32, mapped_hit.row) + pane.tag_rows; return .{ .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, .on_tag = false }; }; - const tag_col = if (on_tag) mouse.tagColumn(p, .pane, id, tag_hit, false, row - tag_y) else null; + const tag_col = if (on_tag) tag_layer.columnAt(p, .pane, id, tag_hit, false, row - tag_y) else null; const c: i32 = (if (tag_col) |value| @as(i32, value) else @as(i32, col) - @as(i32, r.x + (if (on_tag) TAG_TEXT_INSET else config.GUTTER))) + (if (on_tag) @as(i32, pane.tag_scroll) else 0); const v: i32 = if (on_tag) @as(i32, row) - @as(i32, tag_y) else @as(i32, row) - @as(i32, body_y) + @as(i32, pane.tag_rows); diff --git a/src/exec.zig b/src/exec.zig index a673e9e7..a0e3d47f 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -3,6 +3,7 @@ //! chord hands over, the terminals commands run in, placing a document, and //! saving a pane. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const std = @import("std"); const layout = @import("layout.zig"); const modal = @import("modal.zig"); @@ -352,7 +353,7 @@ pub fn replaceStillborn(p: *Pardes) void { const out = file.output orelse return; if (out.from != .cmd or out.from.cmd != .New) return; if (file.revision != 0 or file.content.len != 0) return; - if (old.tag.own) |own| if (!std.mem.eql(u8, own, Pardes.defaultTail(old))) return; + if (old.tag.own) |own| if (!std.mem.eql(u8, own, tagline.defaultTail(old))) return; const was_active = p.active == old_id; layout.compute(p); // the joiner may have no rect yet; absorb snaps to rows p.removePane(old_id, new_id) catch |err| return p.reportError(old_id, "close", err); @@ -490,7 +491,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] const tagline_metrics_changed = setting.action == .tagline_size and p.settings.font.tagline_percent != previous_tagline_percent; if (p.settings.column_tags != previous_column_tags) { - if (p.header_column != null) p.exitHeader(); + if (p.header_column != null) tagline.exitHeader(p); } if (transition_changed or tagline_metrics_changed or p.settings.column_tags != previous_column_tags) { p.abandonPanelAnimations(); diff --git a/src/fs-help.txt b/src/fs-help.txt index 4eecad41..efdecf46 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -39,7 +39,7 @@ Pitfalls, one each: addr, dot and limit read the same pair of offsets they take, so cp between them works. dirty, mark and scroll read "0" or "1" and take "0" or "1"; truncating limit lifts it. Writing body appends; open it with truncation to replace; writes are whole UTF-8 sequences. - Truncating tag clears the part you may edit; truncating dot or addr empties it. + tag reads path++text; writes append to the text (newlines too); truncating clears it, and dot or addr. A terminal's body is a history snapshot frozen per open; pty/data is the live stream. A failing command is reported in the editor and in log, not as a write error; a bad line fails the write. pane//ctl: acme's status line; takes get (reload), lock/unlock on a held fd (exec 3>ctl; echo lock >&3). diff --git a/src/fs.zig b/src/fs.zig index 5374c843..7e387958 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -36,10 +36,12 @@ else const source_files = [_]Source{ .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, + .{ .path = "src/Text.zig", .contents = @embedFile("Text.zig") }, .{ .path = "src/surface.zig", .contents = @embedFile("surface.zig") }, .{ .path = "src/colors.zig", .contents = @embedFile("colors.zig") }, .{ .path = "src/Messages.zig", .contents = @embedFile("Messages.zig") }, .{ .path = "src/body_layer.zig", .contents = @embedFile("body_layer.zig") }, + .{ .path = "src/tagline.zig", .contents = @embedFile("tagline.zig") }, .{ .path = "src/edit.zig", .contents = @embedFile("edit.zig") }, .{ .path = "src/normal.zig", .contents = @embedFile("normal.zig") }, .{ .path = "src/mouse.zig", .contents = @embedFile("mouse.zig") }, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 7bf45676..415b21e8 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -7417,7 +7417,7 @@ test "pet overlay stays beyond workspace text and vanishes while its tag is edit try std.testing.expect(x >= 20 * 8 - 0.01); try std.testing.expect(y >= 0 and y < 20); } - core.enterHeader(null); + pardes.tagline.enterHeader(core, null); builder.len = 0; appendWorkspacePet(&g, core, &surface, &builder); try std.testing.expectEqual(@as(usize, 0), builder.len); diff --git a/src/layout.zig b/src/layout.zig index 54b89081..8e44f1d9 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1,5 +1,6 @@ const std = @import("std"); const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const dump = @import("dump.zig"); const config = @import("config.zig"); const panes = @import("panes.zig"); @@ -934,7 +935,7 @@ pub fn removePane(p: *Pardes, id: usize) void { while (k + 1 < p.col_n[c]) : (k += 1) p.col_panes[c][k] = p.col_panes[c][k + 1]; p.col_n[c] -= 1; if (p.col_n[c] == 0) { - p.exitHeader(); + tagline.exitHeader(p); if (p.ncol > 1) p.col_weight[if (c > 0) c - 1 else c + 1] +|= p.col_weight[c]; p.col_tags[c].deinit(p.gpa); var j = c; @@ -955,7 +956,7 @@ pub fn joinCol(p: *Pardes) void { const f = findPane(p, p.active) orelse return; const c = f.col; if (c + 1 >= p.ncol) return; - p.exitHeader(); + tagline.exitHeader(p); const dst = c + 1; p.col_weight[dst] +|= p.col_weight[c]; for (0..p.col_n[c]) |k| p.col_panes[dst][p.col_n[dst] + k] = p.col_panes[c][k]; @@ -1010,7 +1011,7 @@ pub fn splitColumn(p: *Pardes, source_id: usize, id: usize, before: bool) bool { const new_weight = old_weight - source_weight; p.col_weight[source_col] = source_weight; const c = source_col + @intFromBool(!before); - p.exitHeader(); + tagline.exitHeader(p); var j = p.ncol; while (j > c) : (j -= 1) { p.col_panes[j] = p.col_panes[j - 1]; @@ -2262,7 +2263,7 @@ test "column reorder moves only crossed state and preserves weights" { try std.testing.expectEqual(original_weights[2], p.col_weight[1]); try std.testing.expectEqual(@as(u32, 11), p.col_serial[3]); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(@as(i32, 21), p.focusedHeader().?.cur_col); + try std.testing.expectEqual(@as(i32, 21), tagline.focusedHeader(p).?.cur_col); try std.testing.expectEqual(@as(usize, 9), p.header_scroll); try std.testing.expectEqual(outer_x, p.col_x[0]); try std.testing.expectEqual(outer_w, p.col_w[0]); diff --git a/src/look.zig b/src/look.zig index 8aa2c0a1..cbdf0bea 100644 --- a/src/look.zig +++ b/src/look.zig @@ -19,7 +19,8 @@ const Color = @import("surface.zig").Color; const pdf = panes.Pdf.pdf; const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; -const TagHit = @import("tag_layer.zig").Hit; +const tag_layer = @import("tag_layer.zig"); +const TagHit = tag_layer.Hit; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const pathUnder = pardes.pathUnder; @@ -878,9 +879,9 @@ fn noteLookHover(p: *Pardes, col: u16, row: u16, body_hit: ?Mouse.BodyHit, tag_h if (comptime pdf_enabled) if (p.pdf_hover_preview) |shown| if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial) return; if (p.look_hover_preview) |shown| - if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial and mouse.sameBodyCell(shown.body_hit, body_hit) and mouse.sameTagCell(shown.tag_hit, tag_hit)) return; + if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial and mouse.sameBodyCell(shown.body_hit, body_hit) and tag_layer.sameCell(shown.tag_hit, tag_hit)) return; if (p.look_hover_wait) |waiting| - if (waiting.col == col and waiting.row == row and waiting.pane == id and waiting.serial == pane.serial and mouse.sameBodyCell(waiting.body_hit, body_hit) and mouse.sameTagCell(waiting.tag_hit, tag_hit)) return; + if (waiting.col == col and waiting.row == row and waiting.pane == id and waiting.serial == pane.serial and mouse.sameBodyCell(waiting.body_hit, body_hit) and tag_layer.sameCell(waiting.tag_hit, tag_hit)) return; cancelLookHover(p); p.look_hover_wait = .{ .col = col, .row = row, .pane = id, .serial = pane.serial, .body_hit = body_hit, .tag_hit = tag_hit }; diff --git a/src/mouse.zig b/src/mouse.zig index 4b624dca..df657ead 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -2,6 +2,7 @@ //! releases (acme's chords, border and seam drags, gestures), and the //! chrome targets a shell asks about. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); @@ -19,8 +20,7 @@ const pdf = panes.Pdf.pdf; const platform = pardes.platform; const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; -const TagHit = @import("tag_layer.zig").Hit; -const TagKind = @import("tag_layer.zig").Kind; +const tag_layer = @import("tag_layer.zig"); const TOPBAR_H = pardes.TOPBAR_H; const BOX_H = pardes.BOX_H; const TAG_GAP = pardes.TAG_GAP; @@ -176,30 +176,6 @@ pub fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clam return p.reprojectBodyHit(mapped_hit); } -pub fn sameTagCell(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.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 tagColumn(p: *const Pardes, kind: TagKind, 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) for (p.surface.tagLayers()) |*layer| { - if (layer.cols == 0 or layer.kind != kind or layer.id != id or layer.serial != point.serial or layer.line != line) continue; - const bw: f32 = @floatFromInt(point.metrics.body_w); - const bh: f32 = @floatFromInt(point.metrics.body_h); - const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const right = @as(f32, @floatFromInt(layer.viewport.x + layer.viewport.w)) * bw; - point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); - point.pixel_y = (@as(f32, @floatFromInt(layer.viewport.y)) + 0.5) * bh; - break; - }; - return if (p.reprojectTagHit(point)) |mapped| mapped.col else null; -} - pub fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { const first = a orelse return b == null; const second = b orelse return false; @@ -294,7 +270,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { } } if (p.header_drag and m.button == config.select_button and (m.kind == .drag or m.kind == .release)) { - const t = p.focusedHeader() orelse { + const t = tagline.focusedHeader(p) orelse { p.header_drag = false; return; }; @@ -303,7 +279,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const top = if (p.header_column != null) p.topBarHeight() else 0; const line: u16 = @intCast(@min(mrow -| top, modal.lineCount(text) -| 1, (if (p.header_column != null) p.columnBarHeight() else p.topBarHeight()) -| 1)); const bar = modal.lineSlice(text, line); - const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag, line) orelse (mcol -| x)) + p.header_scroll)); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tag_layer.columnAt(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag, line) orelse (mcol -| x)) + p.header_scroll)); // the anchor stays where the press put it t.cur_row = line; t.cur_col = @intCast(at); @@ -338,23 +314,23 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { if (line > 0 and line >= modal.lineCount(text)) return; const bar = modal.lineSlice(text, line); const scroll = if (focused) p.header_scroll else 0; - const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (column != null) .column else .workspace, column orelse 0, p.pointer_tag_hit, p.header_drag, line) orelse (mcol -| x)) + scroll)); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tag_layer.columnAt(p, if (column != null) .column else .workspace, column orelse 0, p.pointer_tag_hit, p.header_drag, line) orelse (mcol -| x)) + scroll)); if (m.button == config.select_button) { // A clicked header is typed straight into, as a clicked tag is. - if (!focused) p.enterHeader(column); + if (!focused) tagline.enterHeader(p, column); t.mode = .insert; t.cur_row = line; t.cur_col = @intCast(at); t.vsel = .{ .active = false, .row = line, .col = @intCast(at) }; p.header_drag = true; } else { - const span = if (focused) Pardes.headerSelection(t, text, line) else null; + const span = if (focused) tagline.headerSelection(t, text, line) else null; const selected = if (span) |sp| (if (at >= sp.lo and at < sp.hi) bar[sp.lo..sp.hi] else wordAtCol(bar, at)) else wordAtCol(bar, at); const word = p.scratch.allocator().dupe(u8, selected) catch return; - p.exitHeader(); + tagline.exitHeader(p); if (word.len > 0) { if (m.button == config.exec_button) { const named = std.meta.stringToEnum(Builtin, word); @@ -366,7 +342,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { return; } if (m.kind == .press) { - p.exitHeader(); + tagline.exitHeader(p); } switch (m.button) { @@ -484,7 +460,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { pane.tag.msel.active = false; pane.tag.nsel = 0; pane.tag.cur_pinned = true; - const at = p.tagOffsetAt(pane, @intCast(@max(0, pointed.sel.r0)), @intCast(@max(0, pointed.sel.c0))) orelse modal.Cursor{ .row = 0, .col = 0 }; + const at = tagline.tagOffsetAt(p, pane, @intCast(@max(0, pointed.sel.r0)), @intCast(@max(0, pointed.sel.c0))) orelse modal.Cursor{ .row = 0, .col = 0 }; pane.tag.cur_row = @intCast(at.row); pane.tag.cur_col = @intCast(at.col); } @@ -626,7 +602,7 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo // nearest the pointer. const tag_y = p.tagTop(pane, r); const tag_line: u16 = @intCast(std.math.clamp(@as(i32, mrow) - @as(i32, tag_y), 0, tag_rows - 1)); - if (pane.sel[b].r0 < tag_rows) if (tagColumn(p, .pane, s.id, p.pointer_tag_hit, true, tag_line)) |value| { + if (pane.sel[b].r0 < tag_rows) if (tag_layer.columnAt(p, .pane, s.id, p.pointer_tag_hit, true, tag_line)) |value| { pane.sel[b].c1 = @as(i32, value) + pane.tag_scroll; pane.sel[b].r1 = tag_line; return; @@ -683,7 +659,7 @@ fn reportGesture( fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: exec.PointerOperand) ctlfs.pane.State.Range { const pane = p.panes[id] orelse return .{}; if (on_tag) { - const tag = p.tagText(p.scratch.allocator(), pane) catch return .{}; + const tag = tagline.tagText(p, p.scratch.allocator(), pane) catch return .{}; const sel = operand.expanded orelse operand.preview orelse return .{}; const lead = if (sel.r0 < sel.r1 or (sel.r0 == sel.r1 and sel.c0 <= sel.c1)) sel else Pane.Sel{ .r0 = sel.r1, .c0 = sel.c1 }; const row: usize = @intCast(@max(0, lead.r0)); @@ -847,11 +823,11 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { if (sl.r0 < pane.tag_rows) { // On the tag the caret goes where the button came up. A // click on the path, if it can be renamed, drafts a name. - const at = p.tagOffsetAt(pane, @intCast(@max(0, sl.r1)), @intCast(@max(0, sl.c1))); + const at = tagline.tagOffsetAt(p, pane, @intCast(@max(0, sl.r1)), @intCast(@max(0, sl.c1))); if (at) |cursor| { pane.tag.cur_row = @intCast(cursor.row); pane.tag.cur_col = @intCast(cursor.col); - } else if (!dragged) p.draftName(pane, @intCast(@max(0, sl.c1))); + } else if (!dragged) tagline.draftName(p, pane, @intCast(@max(0, sl.c1))); return; } if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; @@ -908,13 +884,13 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const txt = operand.text; const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; if (clk.r0 == 0 and s.button == config.exec_button and pane.prompt == .name) { - const prefix_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); + const prefix_width = panes.File.displayWidth(tagline.tagPrefix(p, pane) catch return); const on_name = @as(usize, @intCast(@max(0, clk.c0))) < prefix_width; - if (!p.commitTagName(pane)) return; + if (!tagline.commitTagName(p, pane)) return; // Executing a staged filename commits it; executing its // command tail uses the new identity (especially Save). if (on_name) return; - const new_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); + const new_width = panes.File.displayWidth(tagline.tagPrefix(p, pane) catch return); const shift = @as(i32, @intCast(new_width)) - @as(i32, @intCast(prefix_width)); if (operand.expanded) |*sel| { sel.c0 += shift; @@ -962,8 +938,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { const start = if (forward) .{ sl.r0, sl.c0 } else .{ sl.r1, sl.c1 }; const end = if (forward) .{ sl.r1, sl.c1 } else .{ sl.r0, sl.c0 }; const origin: modal.Cursor = .{ .row = 0, .col = 0 }; - const from = p.tagOffsetAt(pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; - const to = p.tagOffsetAt(pane, @intCast(@max(0, end[0])), @intCast(@max(0, end[1]))) orelse origin; + const from = tagline.tagOffsetAt(p, pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; + const to = tagline.tagOffsetAt(p, pane, @intCast(@max(0, end[0])), @intCast(@max(0, end[1]))) orelse origin; t.cur_row = @intCast(to.row); t.cur_col = @intCast(to.col); t.cur_pinned = true; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 282ae473..8e827fba 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -3,6 +3,7 @@ //! mark and scroll, errors, event, look and exec. Terminals add pty/ (pty.zig). const std = @import("std"); const pardes = @import("../pardes.zig"); +const tagline = @import("../tagline.zig"); const exec = @import("../exec.zig"); const look = @import("../look.zig"); const panes = @import("../panes.zig"); @@ -79,7 +80,7 @@ pub fn fileOf(pane: *Pane) ?*panes.File.State { } pub fn tagOf(p: *Pardes, pane: *Pane) []const u8 { - return p.tagText(p.scratch.allocator(), pane) catch ""; + return tagline.tagText(p, p.scratch.allocator(), pane) catch ""; } pub fn dirOf(pane: *Pane) []const u8 { @@ -422,7 +423,7 @@ fn writeTag(req: Req, pane: *Pane) Reply { if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; // The tag's own text grows by what is written, newlines and all: a tag // is a text like any other (acme's tag file appends the same way). - const had = Pardes.curTail(pane).len; + const had = tagline.curTail(pane).len; const room = limits.max_tag_tail -| had; if (room == 0) return Reply.fail(req.tag, E.NOSPC); const take = wholeUtf8(req.data[0..@min(req.data.len, room)]); @@ -746,7 +747,7 @@ test "tag reads the whole tag and writes append to the editable tail" { const before = rd(p, node, 0, 4096).bytes.len; const w = wr(p, node, " Mine"); try testing.expectEqual(@as(u32, 5), w.reply.written); - try testing.expect(std.mem.endsWith(u8, Pardes.curTail(pane), " Mine")); + try testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Mine")); const after = rd(p, node, 0, 4096); try testing.expectEqual(before + 5, after.bytes.len); try testing.expect(std.mem.endsWith(u8, after.bytes, " Mine")); @@ -754,7 +755,7 @@ test "tag reads the whole tag and writes append to the editable tail" { // A tag is a text like the body: a newline written to it stays one, and // the tag reads back taller by it. try testing.expectEqual(@as(u32, 10), wr(p, node, "\nNext Line").reply.written); - try testing.expect(std.mem.endsWith(u8, Pardes.curTail(pane), " Mine\nNext Line")); + try testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Mine\nNext Line")); try testing.expect(std.mem.endsWith(u8, rd(p, node, 0, 4096).bytes, " Mine\nNext Line")); if (pane.tag.own) |own| p.gpa.free(own); @@ -887,7 +888,7 @@ test "truncating the tag clears its editable tail" { const pane = p.panes[0].?; const tag = Node.of(pane.serial, .tag); _ = wr(p, tag, " Mine"); - try testing.expect(Pardes.curTail(pane).len > 0); + try testing.expect(tagline.curTail(pane).len > 0); const cleared = call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true }); try testing.expectEqual(Status.ok, cleared.reply.status); try testing.expectEqualStrings("", pane.tag.own.?); diff --git a/src/normal.zig b/src/normal.zig index 630f7689..29d6d620 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -2,6 +2,7 @@ //! modal actions, replayed across every selection, and each action is done //! to the pane; PDF panes get their own normal keys. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); @@ -556,8 +557,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void // keyboard between them. .command_line => switch (t.what) { .tag => pane.focus = .body, - .column, .workspace => p.exitHeader(), - .body, .input => p.enterTag(pane), + .column, .workspace => tagline.exitHeader(p), + .body, .input => tagline.enterTag(p, pane), }, .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), .search => return p.startPrompt(pane, .{ .search = config.search_marker }), @@ -600,7 +601,7 @@ pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { p.leader_on = true; p.leader_n = 0; }, - .command_line => p.enterTag(pane), + .command_line => tagline.enterTag(p, pane), .search => p.startPrompt(pane, .{ .search = config.search_marker }), .search_forward => look.lookWalk(p, 1), .search_backward => look.lookWalk(p, -1), diff --git a/src/panes.zig b/src/panes.zig index 6887008c..3cd66eb7 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -299,7 +299,7 @@ pub const Pane = struct { /// Add `text` to the end of the tag's own text, which starts out as the /// default a pane of its kind shows. pub fn appendTag(pane: *Pane, text: []const u8) !void { - const had = pane.tag.own orelse pardes.Pardes.defaultTail(pane); + const had = pane.tag.own orelse pardes.tagline.defaultTail(pane); const grown = try std.mem.concat(pane.gpa, u8, &.{ had, text }); if (pane.tag.own) |old| pane.gpa.free(old); pane.tag.own = grown; diff --git a/src/pardes.zig b/src/pardes.zig index d07539ba..c802f0ea 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); pub const mouse = @import("mouse.zig"); pub const normal = @import("normal.zig"); @@ -445,6 +446,7 @@ pub const Loc = struct { }; test { + _ = @import("tagline.zig"); _ = @import("exec.zig"); _ = @import("look.zig"); _ = @import("mouse.zig"); @@ -459,48 +461,9 @@ test { _ = @import("tag_layer.zig"); } -const pane_tail = " " ++ config.pane_builtins_str; -const pdf_pane_tail = " " ++ config.pdf_pane_builtins_str; -const file_pane_tail = " " ++ config.file_pane_builtins_str; -const context_pane_tail = file_pane_tail ++ " TreeContext"; -const locations_pane_tail = file_pane_tail ++ " LocationsConfig"; -const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; -const dirty_marker = " *"; -const legacy_pane_tail = " Del"; -const legacy_file_pane_tail = " Save Del"; -// The defaults from the release before Newtty joined every tagline. Recognized -// so a dump written then upgrades instead of keeping the old word as a tail. -const prev_pane_tail = " New Del"; -const prev_file_pane_tail = " Save New Del"; -const legacy_terminal_pane_tail = " New Del Filter"; -// ...and the terminal default from the release before Save reached it, when a -// scrollback was not yet something you could write to a path. -const prev_terminal_pane_tail = " New Newtty Del Filter"; -const pre_tty_terminal_pane_tail = " Save New Newtty Del Filter"; -const pre_column_pane_tail = " New Newtty Del"; -const pre_column_file_pane_tail = " Save New Newtty Del"; -const pre_column_pdf_pane_tail = " New Newtty Del PdfSections PdfTint"; -const pre_column_terminal_pane_tail = " Save New Newtty Del Tty Filter"; -const pre_collapse_pane_tail = " Tty Del"; -const pre_collapse_file_pane_tail = " Save Tty Del"; -const pre_collapse_pdf_pane_tail = " Tty Del PdfSections PdfTint"; -const pre_collapse_terminal_pane_tail = " Save Tty Del Togglettymode Filter"; -const pre_tty_first_terminal_pane_tail = " Save Tty Del Togglettymode Filter Collapse"; -const pre_mode_terminal_pane_tail = " Tty Save Del Togglettymode Filter Collapse"; -// ...and the defaults from before the closing word moved to the end of every -// tagline, where a click cannot land on it by overshooting the one before. -const pre_close_last_pane_tail = " Tty Del Collapse"; -const pre_close_last_file_pane_tail = " Save Tty Del Collapse"; -const pre_close_last_pdf_pane_tail = " Tty Del PdfSections PdfTint Collapse"; -const pre_close_last_terminal_pane_tail = " Tty Save Del Mode Filter Collapse"; - pub const Builtin = builtins.registry.Builtin(); pub const test_api = if (@import("builtin").is_test) struct { - pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { - return p.tagText(arena, pane); - } - pub fn runBuiltin( p: *Pardes, name: []const u8, @@ -669,11 +632,11 @@ test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { p.acknowledgeShell(0, "/bin/sh", false); const pane = p.panes[0].?; - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(pane)); const tag_x = p.rects[0].x + TAG_TEXT_INSET; const tag_y = p.rects[0].y; - const rendered = try p.tagText(p.scratch.allocator(), pane); + const rendered = try tagline.tagText(p, p.scratch.allocator(), pane); const new_x = tag_x + @as(u16, @intCast(std.mem.indexOf(u8, rendered, "Tty").?)) + 1; var panes_before: usize = 0; for (p.panes) |s| if (s != null) { @@ -738,7 +701,7 @@ test "Collapse builtin keeps content and restores the pane from its default tag" p.sync(); const height = p.rects[0].h; const revision = pane.file.?.revision; - for ([_][]const u8{ pane_tail, file_pane_tail, pdf_pane_tail, terminal_pane_tail }) |tail| + for ([_][]const u8{ tagline.pane_tail, tagline.file_pane_tail, tagline.pdf_pane_tail, tagline.terminal_pane_tail }) |tail| try std.testing.expect(std.mem.endsWith(u8, tail, " Collapse Del")); try std.testing.expect(p.executeBuiltinLine(0, "Collapse")); @@ -749,7 +712,7 @@ test "Collapse builtin keeps content and restores the pane from its default tag" try std.testing.expectEqual(revision, pane.file.?.revision); try std.testing.expectEqualStrings("keep this text\n", pane.file.?.content); try std.testing.expect((try p.render(p.scratch.allocator())).cursor == null); - p.enterTag(pane); + tagline.enterTag(p, pane); const tag_cursor = (try p.render(p.scratch.allocator())).cursor orelse return error.MissingTagCursor; try std.testing.expectEqual(p.rects[0].y, tag_cursor.y); pane.focus = .body; @@ -761,9 +724,9 @@ test "Collapse builtin keeps content and restores the pane from its default tag" // Unedited defaults from the preceding version gain the new command. if (pane.tag.own) |own| p.gpa.free(own); pane.tag.own = null; - p.restoreTailAt(pane, pre_collapse_file_pane_tail, "", .file); + tagline.restoreTailAt(p, pane, tagline.pre_collapse_file_pane_tail, "", .file); try std.testing.expect(pane.tag.own == null); - try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(pane)); } test "LocationsConfig command reports partial updates and survives restore" { @@ -850,12 +813,12 @@ test "TreeContext command and custom tag survive a workspace round trip" { defer p.deinit(); const pane = try p.setTestFile("pub fn main() void {}\n"); try std.testing.expect(!panes.File.supportsContext(pane)); - try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(pane)); const path = try p.gpa.dupe(u8, "/test.zig"); p.gpa.free(pane.file.?.path); pane.file.?.path = path; if (!panes.File.supportsContext(pane)) return error.SkipZigTest; - try std.testing.expectEqualStrings(context_pane_tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tagline.context_pane_tail, tagline.curTail(pane)); try std.testing.expect(!pane.file.?.tree_context); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext on")); try std.testing.expect(pane.file.?.tree_context); @@ -872,14 +835,14 @@ test "TreeContext command and custom tag survive a workspace round trip" { defer restored.deinit(); const saved = restored.panes[0].?; try std.testing.expect(saved.file.?.tree_context); - try std.testing.expectEqualStrings(" Save Keep Del", Pardes.curTail(saved)); + try std.testing.expectEqualStrings(" Save Keep Del", tagline.curTail(saved)); } test "Togglettymode builtin and keyboard chord share mode transitions including edited tags" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); defer p.deinit(); const pane = p.panes[0].?; - try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Mode ") != null); + try std.testing.expect(std.mem.indexOf(u8, tagline.curTail(pane), " Mode ") != null); try pane.appendTag(" Togglettymode"); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); @@ -887,19 +850,19 @@ test "Togglettymode builtin and keyboard chord share mode transitions including p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); // The tag has its own mode: the body keeps tty while the tag is typed into. - p.enterTag(pane); + tagline.enterTag(p, pane); try std.testing.expect(pane.focus == .tag); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); try std.testing.expect(pane.focus == .body); - p.enterTag(pane); + tagline.enterTag(p, pane); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(pane.focus == .body); p.acknowledgePanelPresentation(&.{}); - const tag = try p.tagText(p.scratch.allocator(), pane); + const tag = try tagline.tagText(p, p.scratch.allocator(), pane); const x = p.rects[0].x + TAG_TEXT_INSET + @as(u16, @intCast(std.mem.indexOf(u8, tag, "Togglettymode").?)); const y = p.rects[0].y; p.update(.{ .mouse = .{ .button = .middle, .kind = .press, .col = x, .row = y } }); @@ -965,30 +928,30 @@ test "compact tag commands stay beside their own prefix across layout changes" { const above = p.panes[0].?; try std.testing.expectEqual(p.rects[0].x, p.rects[below_id].x); - const above_tag = try p.tagText(gpa, above); + const above_tag = try tagline.tagText(p, gpa, above); defer gpa.free(above_tag); - const below_tag = try p.tagText(p.scratch.allocator(), below); + const below_tag = try tagline.tagText(p, p.scratch.allocator(), below); try std.testing.expect(below_tag.len > above_tag.len); - const tail = terminal_pane_tail; + const tail = tagline.terminal_pane_tail; try std.testing.expectEqualStrings(tail, above_tag[above_tag.len - tail.len ..]); try std.testing.expectEqual(above.cwdSlice().len + tail.len, above_tag.len); p.update(.{ .resize = .{ .cols = 88, .rows = 30 } }); while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(above_tag, try p.tagText(p.scratch.allocator(), above)); + try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); p.update(.{ .resize = .{ .cols = 87, .rows = 30 } }); while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(above_tag, try p.tagText(p.scratch.allocator(), above)); + try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(tail, Pardes.curTail(below)); + try std.testing.expectEqualStrings(tail, tagline.curTail(below)); try below.appendTag(" lots and lots of typing out here"); - try std.testing.expectEqual(above_tag.len, (try p.tagText(p.scratch.allocator(), above)).len); + try std.testing.expectEqual(above_tag.len, (try tagline.tagText(p, p.scratch.allocator(), above)).len); p.update(.{ .resize = .{ .cols = 100, .rows = 2 } }); while (p.nextEffect()) |_| {} try std.testing.expectEqual(@as(u16, 0), p.rects[below_id].h); - try std.testing.expectEqualStrings(above_tag, try p.tagText(p.scratch.allocator(), above)); + try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); } test "legacy default tag tails upgrade while custom tails remain owned" { @@ -998,120 +961,120 @@ test "legacy default tag tails upgrade while custom tails remain owned" { const terminal = p.panes[0].?; const terminal_old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(terminal), - legacy_pane_tail, + try tagline.tagPrefix(p, terminal), + tagline.legacy_pane_tail, }); - p.restoreTail(terminal, terminal_old); + tagline.restoreTail(p, terminal, terminal_old); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); const terminal_previous = try std.fmt.allocPrint(p.scratch.allocator(), "{s} New Del", .{ - try p.tagPrefix(terminal), + try tagline.tagPrefix(p, terminal), }); - p.restoreTail(terminal, terminal_previous); + tagline.restoreTail(p, terminal, terminal_previous); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); const terminal_prefilter = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(terminal), - prev_terminal_pane_tail, + try tagline.tagPrefix(p, terminal), + tagline.prev_terminal_pane_tail, }); - p.restoreTail(terminal, terminal_prefilter); + tagline.restoreTail(p, terminal, terminal_prefilter); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); - for ([_][]const u8{ pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail }) |old_tail| { - const old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ try p.tagPrefix(terminal), old_tail }); - p.restoreTail(terminal, old); + for ([_][]const u8{ tagline.pre_mode_terminal_pane_tail, tagline.pre_tty_first_terminal_pane_tail, tagline.pre_collapse_terminal_pane_tail }) |old_tail| { + const old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ try tagline.tagPrefix(p, terminal), old_tail }); + tagline.restoreTail(p, terminal, old); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); } - const custom_mode = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s} Keep", .{ try p.tagPrefix(terminal), pre_mode_terminal_pane_tail }); - p.restoreTail(terminal, custom_mode); + const custom_mode = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s} Keep", .{ try tagline.tagPrefix(p, terminal), tagline.pre_mode_terminal_pane_tail }); + tagline.restoreTail(p, terminal, custom_mode); try std.testing.expect(terminal.tag.own != null); - try std.testing.expectEqualStrings(pre_mode_terminal_pane_tail ++ " Keep", Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.pre_mode_terminal_pane_tail ++ " Keep", tagline.curTail(terminal)); if (terminal.tag.own) |own| p.gpa.free(own); terminal.tag.own = null; const terminal_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Keep Del", .{ - try p.tagPrefix(terminal), + try tagline.tagPrefix(p, terminal), }); - p.restoreTail(terminal, terminal_custom); + tagline.restoreTail(p, terminal, terminal_custom); try std.testing.expect(terminal.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(terminal)); if (terminal.tag.own) |own| p.gpa.free(own); terminal.tag.own = null; - p.restoreDumpTail(terminal, .{ + tagline.restoreDumpTail(p, terminal, .{ .kind = .terminal, .tag = "TTY /historical/cwd Keep Del", .body = "", .terminal = .{ .cwd = "/historical/cwd" }, }); try std.testing.expect(terminal.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(terminal)); if (terminal.tag.own) |own| p.gpa.free(own); terminal.tag.own = null; - p.restoreDumpTail(terminal, .{ + tagline.restoreDumpTail(p, terminal, .{ .kind = .terminal, .tag = "TTY /historical/cwd New Del", .body = "", .terminal = .{ .cwd = "/historical/cwd" }, }); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); // This happens to be the historical FILE default, but on a terminal it is // user-owned text and must not be swallowed by migration. if (terminal.tag.own) |own| p.gpa.free(own); terminal.tag.own = null; const terminal_fileish = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Del", .{ - try p.tagPrefix(terminal), + try tagline.tagPrefix(p, terminal), }); - p.restoreTail(terminal, terminal_fileish); + tagline.restoreTail(p, terminal, terminal_fileish); try std.testing.expect(terminal.tag.own != null); - try std.testing.expectEqualStrings(" Save Del", Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(" Save Del", tagline.curTail(terminal)); // A savable file has a distinct old default. Save remains first after the // migration so the tag's established `:w` route is unchanged. const file = try p.setTestFile(""); const file_old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(file), - legacy_file_pane_tail, + try tagline.tagPrefix(p, file), + tagline.legacy_file_pane_tail, }); - p.restoreTail(file, file_old); + tagline.restoreTail(p, file, file_old); try std.testing.expect(file.tag.own == null); - try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(file)); + try std.testing.expectEqualStrings(" Save Tty Collapse Del", tagline.curTail(file)); const file_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Mine Del", .{ - try p.tagPrefix(file), + try tagline.tagPrefix(p, file), }); - p.restoreTail(file, file_custom); + tagline.restoreTail(p, file, file_custom); try std.testing.expect(file.tag.own != null); - try std.testing.expectEqualStrings(" Save Mine Del", Pardes.curTail(file)); + try std.testing.expectEqualStrings(" Save Mine Del", tagline.curTail(file)); // Conversely the generic pane's current default is a custom edit on a // savable file. Legacy recognition is scoped to the source pane class. if (file.tag.own) |own| p.gpa.free(own); file.tag.own = null; const file_generic = try std.fmt.allocPrint(p.scratch.allocator(), "{s} New Del", .{ - try p.tagPrefix(file), + try tagline.tagPrefix(p, file), }); - p.restoreTail(file, file_generic); + tagline.restoreTail(p, file, file_generic); try std.testing.expect(file.tag.own != null); - try std.testing.expectEqualStrings(" New Del", Pardes.curTail(file)); + try std.testing.expectEqualStrings(" New Del", tagline.curTail(file)); const image_doc = try panes.Image.create(p, 1, "/tmp/legacy image.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Collapse Del", Pardes.curTail(image_doc)); - p.restoreDumpTail(image_doc, .{ + try std.testing.expectEqualStrings(" Tty Collapse Del", tagline.curTail(image_doc)); + tagline.restoreDumpTail(p, image_doc, .{ .kind = .image, .tag = "img /tmp/legacy image.ppm Keep Del", .body = "", .image = .{ .path = "/tmp/legacy image.ppm" }, }); try std.testing.expect(image_doc.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(image_doc)); + try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(image_doc)); } test "Joincol folds the active column into its right neighbor, keeping its panes" { @@ -1245,19 +1208,19 @@ test "first document keeps its originating shell and only opens a column when it test "pane defaults keep creation of scratch panes in column tags" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); - for ([_][]const u8{ pane_tail, file_pane_tail, pdf_pane_tail, terminal_pane_tail, config.topbar_str }) |tag| { + for ([_][]const u8{ tagline.pane_tail, tagline.file_pane_tail, tagline.pdf_pane_tail, tagline.terminal_pane_tail, config.topbar_str }) |tag| { var words = std.mem.tokenizeScalar(u8, tag, ' '); while (words.next()) |word| try std.testing.expect(!std.mem.eql(u8, word, "New")); } - try std.testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", p.columnTag(0)); + try std.testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", tagline.columnTag(p, 0)); const terminal = p.panes[0].?; - p.restoreTailAt(terminal, pre_column_terminal_pane_tail, "", .terminal); + tagline.restoreTailAt(p, terminal, tagline.pre_column_terminal_pane_tail, "", .terminal); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); const file = try p.setTestFile("unchanged\n"); - p.restoreTailAt(file, pre_column_file_pane_tail, "", .file); + tagline.restoreTailAt(p, file, tagline.pre_column_file_pane_tail, "", .file); try std.testing.expect(file.tag.own == null); - try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(file)); + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(file)); } test "an unsaved file marker sits between its path and builtins until Save" { @@ -1267,29 +1230,29 @@ test "an unsaved file marker sits between its path and builtins until Save" { while (p.nextEffect()) |_| {} const pane = try p.setTestFile("before\n"); - const clean = try p.tagText(p.scratch.allocator(), pane); + const clean = try tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, clean, "/test.txt *") == null); panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "after\n")); - const dirty = try p.tagText(p.scratch.allocator(), pane); + const dirty = try tagline.tagText(p, p.scratch.allocator(), pane); const marker_at = std.mem.indexOf(u8, dirty, "/test.txt *") orelse return error.MissingDirtyMarker; const save_at = std.mem.indexOf(u8, dirty, "Save") orelse return error.MissingSaveBuiltin; try std.testing.expect(marker_at < save_at); try std.testing.expect(p.executeBuiltinLine(0, "Save")); while (p.nextEffect()) |effect| p.perform(effect); - const saved = try p.tagText(p.scratch.allocator(), pane); + const saved = try tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, saved, "/test.txt *") == null); panes.File.changed(p, 0, "external\n"); - const reloaded = try p.tagText(p.scratch.allocator(), pane); + const reloaded = try tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, reloaded, "/test.txt *") == null); // A generated output is file-shaped and Save can write it to a path, but // there is no file of its own for it to be dirty against. pane.file.?.output = .{ .from = .search }; panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "result\n")); - const output = try p.tagText(p.scratch.allocator(), pane); + const output = try tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, output, "/test.txt *") == null); } @@ -1422,7 +1385,7 @@ test "image dump restores source bytes renderer choices and exact custom tail" { try std.testing.expectEqual(image.PaletteMode.terminal, restored_pane.image.?.pmode); try std.testing.expect(!restored_pane.image.?.ascii); try std.testing.expect(restored_pane.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(restored_pane)); + try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(restored_pane)); try std.testing.expectEqualSlices(u8, source, restored_pane.image.?.raw); try dump.dumpState(restored); @@ -1903,7 +1866,7 @@ test "Save on an output buffer writes its rows out and leaves the buffer alone" defer gpa.free(rows); // Save leads its tagline now, and the path is REQUIRED: a bare Save asks - try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(out)); + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(out)); try std.testing.expect(p.executeBuiltinLine(id, "Save")); try std.testing.expect(out.prompt == .save); edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" }); @@ -2091,17 +2054,17 @@ test "Save reaches every tagline with text behind it and no other" { const out = try p.setTestFile("build.zig:1:1 pub fn main\n"); out.file.?.output = .{ .from = .search }; - try std.testing.expectEqualStrings(locations_pane_tail, Pardes.curTail(out)); + try std.testing.expectEqualStrings(tagline.locations_pane_tail, tagline.curTail(out)); // A dump written before Save reached output buffers carries the generic // tail. That is a DEFAULT and not something typed, so it upgrades. const dumped = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(out), - pane_tail, + try tagline.tagPrefix(p, out), + tagline.pane_tail, }); - p.restoreTail(out, dumped); + tagline.restoreTail(p, out, dumped); try std.testing.expect(out.tag.own == null); - try std.testing.expectEqualStrings(locations_pane_tail, Pardes.curTail(out)); + try std.testing.expectEqualStrings(tagline.locations_pane_tail, tagline.curTail(out)); // A scratch is an output buffer that has worn the FILE tails all along, // so its own older default upgrades from that family too. @@ -2109,18 +2072,18 @@ test "Save reaches every tagline with text behind it and no other" { if (out.tag.own) |own| p.gpa.free(own); out.tag.own = null; const scratch_dumped = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(out), - prev_file_pane_tail, + try tagline.tagPrefix(p, out), + tagline.prev_file_pane_tail, }); - p.restoreTail(out, scratch_dumped); + tagline.restoreTail(p, out, scratch_dumped); try std.testing.expect(out.tag.own == null); - try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(out)); + try std.testing.expectEqualStrings(" Save Tty Collapse Del", tagline.curTail(out)); // An image's bytes on disk already are what they are: nothing of the // pane's own is unwritten, so the word is absent and inert. const img_id = p.freeSlot().?; const img = try panes.Image.create(p, img_id, "/tmp/pardes-tag.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Collapse Del", Pardes.curTail(img)); + try std.testing.expectEqualStrings(" Tty Collapse Del", tagline.curTail(img)); try std.testing.expect(p.executeBuiltinLine(img_id, "Save")); try std.testing.expect(img.prompt != .save); var buf: [256]u8 = undefined; @@ -2545,7 +2508,7 @@ comptime { const WordBounds = struct { lo: usize, hi: usize }; -fn wordBoundsAtCol(str: []const u8, col: usize) ?WordBounds { +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; @@ -2636,7 +2599,7 @@ test "Unicode display cells map back to body and tag byte cursors" { // A click in the wide path glyph drafts a name with its caret at the // grapheme start; arrow motion then advances by the full UTF-8 cluster. - p.draftName(pane, 1); + tagline.draftName(p, pane, 1); try std.testing.expectEqual(@as(i32, 0), pane.input.cur_col); edit.insertKey(p, &pane.input, .{ .cp = Key.right }); try std.testing.expectEqual(@as(i32, 3), pane.input.cur_col); @@ -2644,15 +2607,15 @@ test "Unicode display cells map back to body and tag byte cursors" { try std.testing.expectEqual(@as(i32, 6), pane.input.cur_col); pane.closePrompt(); - const before = try gpa.dupe(u8, Pardes.curTail(pane)); + const before = try gpa.dupe(u8, tagline.curTail(pane)); defer gpa.free(before); - p.enterTag(pane); + tagline.enterTag(p, pane); const insertion = pane.tag.cur_col; edit.insertKey(p, &pane.tag, .{ .cp = 'λ', .text = "λ" }); try std.testing.expectEqual(insertion + 2, pane.tag.cur_col); edit.insertKey(p, &pane.tag, .{ .cp = Key.backspace }); try std.testing.expectEqual(insertion, pane.tag.cur_col); - try std.testing.expectEqualStrings(before, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(before, tagline.curTail(pane)); } test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { @@ -2726,23 +2689,23 @@ test "editable workspace and column tags are typed into and persist" { p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); p.update(.{ .key = .{ .cp = 'é', .text = "é" } }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(0), "éNew")); + try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "éNew")); p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(0), "New")); + try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "New")); p.update(.{ .paste = "Grep " }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(0), "Grep New")); + try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "Grep New")); try std.testing.expectEqualStrings("untouched\n", p.panes[0].?.file.?.content); try dump.dumpState(p); const restored = try dump.restore(p, p.dump_out.?); defer restored.deinit(); try std.testing.expectEqualStrings(p.global_tag.own.?, restored.global_tag.own.?); - try std.testing.expectEqualStrings(p.columnTag(0), restored.columnTag(0)); + try std.testing.expectEqualStrings(tagline.columnTag(p, 0), tagline.columnTag(restored, 0)); p.gpa.free(p.col_tags[0].own.?); p.col_tags[0].own = try p.gpa.dupe(u8, ""); try dump.dumpState(p); const empty = try dump.restore(p, p.dump_out.?); defer empty.deinit(); - try std.testing.expectEqualStrings("", empty.columnTag(0)); + try std.testing.expectEqualStrings("", tagline.columnTag(empty, 0)); } test "column tags follow their column through split and close" { @@ -2752,12 +2715,12 @@ test "column tags follow their column through split and close" { p.col_tags[0].own = try p.gpa.dupe(u8, "Left Find"); _ = exec.execute(p, 0, "Newcol"); try std.testing.expectEqual(@as(usize, 2), p.ncol); - try std.testing.expectEqualStrings("Left Find", p.columnTag(0)); + try std.testing.expectEqualStrings("Left Find", tagline.columnTag(p, 0)); p.col_tags[1].own = try p.gpa.dupe(u8, "Right Grep"); p.active = p.col_panes[0][0]; layout.joinCol(p); try std.testing.expectEqual(@as(usize, 1), p.ncol); - try std.testing.expectEqualStrings("Right Grep", p.columnTag(0)); + try std.testing.expectEqualStrings("Right Grep", tagline.columnTag(p, 0)); } test "column tags render edit hover and scroll from the column edge" { @@ -2780,7 +2743,7 @@ test "column tags render edit hover and scroll from the column edge" { try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, hovered.at(x, TOPBAR_H).style.bg); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = TOPBAR_H } }); try std.testing.expectEqual(column, p.header_column.?); - try std.testing.expectEqual(@as(i32, 0), p.focusedHeader().?.cur_col); + try std.testing.expectEqual(@as(i32, 0), tagline.focusedHeader(p).?.cur_col); const at_start = try p.render(frame.allocator()); try std.testing.expectEqual(x, at_start.cursor.?.x); p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = x + 3, .row = TOPBAR_H } }); @@ -2790,7 +2753,7 @@ test "column tags render edit hover and scroll from the column edge" { try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, selected.at(x + @as(u16, @intCast(offset)), TOPBAR_H).style.bg); p.update(.{ .key = .{ .cp = Key.home } }); p.update(.{ .key = .{ .cp = 'H', .text = "Help " } }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(column), "Help New Tty")); + try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, column), "Help New Tty")); const edited = try p.render(frame.allocator()); try std.testing.expectEqual(x + 5, edited.cursor.?.x); // Only the text viewport participates in caret reveal. @@ -2844,7 +2807,7 @@ test "header clicks beyond text append and long UTF-8 tags reveal their caret" { p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = 40, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 40, .row = TOPBAR_H } }); p.update(.{ .key = .{ .cp = 'x', .text = " extended" } }); - try std.testing.expectEqualStrings("New extended", p.columnTag(0)); + try std.testing.expectEqualStrings("New extended", tagline.columnTag(p, 0)); p.update(.{ .paste = " 界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界" }); const frame = try p.render(p.scratch.allocator()); try std.testing.expect(p.header_scroll > 0); @@ -2866,7 +2829,7 @@ test "a column tag with a newline in it takes a row per line and pushes its pane p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 40, .row = TOPBAR_H } }); p.update(.{ .key = .{ .cp = Key.enter } }); p.update(.{ .key = .{ .cp = 'S', .text = "Snarf" } }); - try std.testing.expectEqualStrings("New\nSnarf", p.columnTag(0)); + try std.testing.expectEqualStrings("New\nSnarf", tagline.columnTag(p, 0)); try std.testing.expectEqual(@as(u16, 2), p.columnBarHeight()); const frame = try p.render(p.scratch.allocator()); try std.testing.expectEqual(TOPBAR_H + 2, p.rects[0].y); @@ -2884,7 +2847,7 @@ test "a column tag with a newline in it takes a row per line and pushes its pane // Taking the newline back out gives the panes their row again. p.update(.{ .key = .{ .cp = Key.home } }); p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expectEqualStrings("NewSnarf", p.columnTag(0)); + try std.testing.expectEqualStrings("NewSnarf", tagline.columnTag(p, 0)); _ = try p.render(p.scratch.allocator()); try std.testing.expectEqual(TOPBAR_H + COLBAR_H, p.rects[0].y); } @@ -2916,7 +2879,7 @@ test "ColumnTags reclaims the row and releases hidden header focus without losin try std.testing.expectEqual(shown.h + COLBAR_H, p.rects[0].h); try std.testing.expect(!p.header_focus and p.header_column == null); try std.testing.expect(!p.header_drag); - try std.testing.expectEqualStrings("New Help", p.columnTag(0)); + try std.testing.expectEqualStrings("New Help", tagline.columnTag(p, 0)); p.update(.{ .command = "ColumnTags" }); try std.testing.expect(p.settings.column_tags); @@ -2932,7 +2895,7 @@ test "ColumnTags reclaims the row and releases hidden header focus without losin try std.testing.expect(!p.header_focus and p.header_column == null); p.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); try std.testing.expectEqual(shown, p.rects[0]); - try std.testing.expectEqualStrings("New Help", p.columnTag(0)); + try std.testing.expectEqualStrings("New Help", tagline.columnTag(p, 0)); try std.testing.expectEqualStrings("unchanged body\n", pane.file.?.content); } @@ -2940,7 +2903,7 @@ test "a header's execute key runs the word under its cursor and lets go of the k const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 12, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("body\n"); - p.enterHeader(null); + tagline.enterHeader(p, null); p.global_tag.cur_col = @intCast(std.mem.indexOf(u8, config.topbar_str, "Dump").?); p.update(.{ .key = .{ .cp = Key.tab } }); try std.testing.expect(!p.header_focus); @@ -4082,23 +4045,6 @@ pub const Pardes = struct { return a; } - /// What a column's tag says until someone edits it. - pub const column_tag_default = "New Tty Find Grep Joincol Delcol"; - - /// What a header says until someone edits it: for the workspace the - /// fixed builtins, plus `Restore ` once a dump exists. - pub fn headerDefault(p: *Pardes, what: Text.What) []const u8 { - if (what == .column) return column_tag_default; - const d = p.last_dump orelse return config.topbar_str; - return std.fmt.allocPrint(p.scratch.allocator(), config.topbar_str ++ " Restore {s}", .{d}) catch config.topbar_str; - } - - /// the topbar line -- render and click dispatch must agree on this exact - /// string - fn topbar(p: *Pardes) []const u8 { - return p.global_tag.own orelse p.headerDefault(.workspace); - } - /// The workspace tag's height: a row per line of it while the setting /// keeps it, zero once a native shell takes its commands over. Layout and /// hit testing read this rather than the constant, the way they read @@ -4119,36 +4065,6 @@ pub const Pardes = struct { return @intCast(@min(lines, MAX_TAG_ROWS, @max(COLBAR_H, p.screen_h / 3))); } - pub fn columnTag(p: *const Pardes, c: usize) []const u8 { - return p.col_tags[c].own orelse column_tag_default; - } - - /// The header with the keyboard, when one has it. - pub fn focusedHeader(p: *Pardes) ?*Text { - if (!p.header_focus) return null; - if (p.header_column) |c| return if (c < p.ncol) &p.col_tags[c] else null; - return &p.global_tag; - } - - fn revealHeader(p: *Pardes) void { - const t = p.focusedHeader() orelse { - p.header_scroll = 0; - return; - }; - const text = edit.flatSurface(p, t) catch return; - const line = modal.lineSlice(text, @intCast(@max(0, t.cur_row))); - const width = p.tagCapacity(if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else p.screen_w); - const col = panes.File.rawDisplayCol(line, @min(@as(usize, @intCast(@max(0, t.cur_col))), line.len)); - if (col < p.header_scroll) p.header_scroll = col; - if (col >= p.header_scroll + width) p.header_scroll = col -| (width -| 1); - var raw = panes.File.rawAtDisplay(line, p.header_scroll); - p.header_scroll = panes.File.rawDisplayCol(line, raw); - if (width > 0 and col >= p.header_scroll + width) { - raw = modal.nextGrapheme(line, raw); - p.header_scroll = panes.File.rawDisplayCol(line, raw); - } - } - fn detachCwds(p: *Pardes, parents: []const *Pane) !void { var copies: [MAX_PANES]?[]u8 = @splat(null); errdefer for (copies) |copy| if (copy) |bytes| p.gpa.free(bytes); @@ -4834,7 +4750,7 @@ pub const Pardes = struct { for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; if (pane.fs.readers == 0) continue; - const tag = p.tagText(p.scratch.allocator(), pane) catch continue; + const tag = tagline.tagText(p, p.scratch.allocator(), pane) catch continue; const snap = &pane.fs.tag_snap; if (std.mem.eql(u8, snap.items, tag)) continue; if (snap.capacity != 0 or snap.items.len != 0) @@ -4846,39 +4762,6 @@ pub const Pardes = struct { // ---- tag + selection text (chord sources) ---- - pub fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 { - const arena = p.scratch.allocator(); - if (comptime pdf_enabled) if (pane.pdf) |pv| return std.fmt.allocPrint( - arena, - "{s} [{d}/{d}]", - .{ pv.path, pv.page + 1, pv.page_count }, - ); - if (pane.image) |*state| return panes.Image.tagPrefix(arena, state); - if (pane.file) |f| { - const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; - if (panes.Output.fileTraits(f.output).saves and f.revision != f.saved_revision) - return std.fmt.allocPrint(arena, "{s}{s}", .{ name, dirty_marker }); - return arena.dupe(u8, name); - } - return arena.dupe(u8, pane.cwdSlice()); - } - - /// The tag's own text: what the user made of it, or until then the - /// default a pane of its kind starts with. - pub fn curTail(pane: *Pane) []const u8 { - return pane.tag.own orelse defaultTail(pane); - } - - pub fn defaultTail(pane: *const Pane) []const u8 { - if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; - if (pane.file) |file| if (file.output) |out| - if (panes.Output.usesLocationsConfig(out.from)) return locations_pane_tail; - if (panes.File.supportsContext(pane)) return context_pane_tail; - if (pane.file != null) return file_pane_tail; - if (pane.isTerminal()) return terminal_pane_tail; - return pane_tail; - } - pub fn paneIdOf(p: *const Pardes, pane: *const Pane) ?usize { for (p.panes, 0..) |slot, id| if (slot) |sp| { if (sp == pane) return id; @@ -4886,168 +4769,13 @@ pub const Pardes = struct { return null; } - /// The tag as it is shown, read and pointed at: its computed prefix and - /// its own text after it. - pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { - const prefix = try p.tagPrefix(pane); - const tail = curTail(pane); - const out = try arena.alloc(u8, prefix.len + tail.len); - @memcpy(out[0..prefix.len], prefix); - @memcpy(out[prefix.len..], tail); - return out; - } - - fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { lo: usize, hi: usize } { - if (pane.isTerminal()) { - var words = std.mem.tokenizeAny(u8, tag[prefix_len..], " \t\r\n"); - while (words.next()) |word| { - if (!std.mem.eql(u8, word, "Tty")) continue; - const lo = @intFromPtr(word.ptr) - @intFromPtr(tag.ptr); - return .{ .lo = lo, .hi = lo + word.len }; - } - return null; - } - var start: usize = 0; - const name = if (pane.file) |file| - if (pane.prompt == .name) pane.input.own orelse file.path else file.path - else if (pane.image) |state| blk: { - // Image tags put renderer controls before the path. - start = prefix_len -| state.path.len; - break :blk state.path; - } else if (comptime pdf_enabled) blk: { - break :blk if (pane.pdf) |state| state.path else return null; - } else return null; - const basename = if (std.mem.lastIndexOfScalar(u8, name, '/')) |slash| slash + 1 else 0; - if (basename == name.len) return null; - return .{ .lo = start + basename, .hi = start + name.len }; - } - - /// Give the keyboard to the tag in normal mode (`:`), its cursor where - /// the tag last had it. The first time there is nothing to remember, and - /// it starts on Save, so that `:` and the execute key write the file. - pub fn enterTag(p: *Pardes, pane: *Pane) void { - const t = &pane.tag; - const tail = curTail(pane); - if (!t.cur_pinned) { - var words = std.mem.tokenizeAny(u8, tail, " \t\n"); - const at = while (words.next()) |word| { - if (std.mem.eql(u8, word, "Save")) break @intFromPtr(word.ptr) - @intFromPtr(tail.ptr); - } else tail.len - std.mem.trimStart(u8, tail, " ").len; - const cursor = modal.positionAt(tail, @min(at, tail.len)); - t.cur_row = @intCast(cursor.row); - t.cur_col = @intCast(cursor.col); - t.cur_pinned = true; - // Reveal the suffix together with its commands, not merely the - // first command letter at the viewport's far right edge. - if (p.paneIdOf(pane)) |id| { - const tag = p.tagText(p.scratch.allocator(), pane) catch return; - const line = tag[0 .. std.mem.indexOfScalar(u8, tag, '\n') orelse tag.len]; - const width = p.tagCapacity(p.rects[id].w -| TAG_TEXT_INSET); - pane.tag_scroll = @intCast(panes.File.displayWidth(line) + 1 -| width); - } - } - // The text may have changed since (a 9P write, a rename), so the - // remembered cursor is pulled back inside it. It is the cursor that - // is remembered, not a selection. - const rows = modal.cursorLineCount(tail); - t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1)); - const line = modal.lineSlice(tail, @intCast(t.cur_row)); - t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); - t.vsel.active = false; - t.msel.active = false; - t.nsel = 0; - t.select = false; - t.append_at = null; - t.sticky_col = -1; - t.mode = .normal; - t.normal.clear(); - pane.focus = .tag; - } - - /// Where display column `col` of tag line `row` (tag scroll included) - /// lands in the tag's own text, or null when it is on the prefix, which - /// only the first line has. - pub fn tagOffsetAt(p: *Pardes, pane: *Pane, row: usize, col: usize) ?modal.Cursor { - const width = if (row == 0) panes.File.displayWidth(p.tagPrefix(pane) catch return null) else 0; - if (col < width) return null; - const line = modal.lineSlice(curTail(pane), row); - return .{ .row = row, .col = modal.graphemeStart(line, panes.File.rawAtDisplay(line, col - width)) }; - } - - /// Start a name draft for a file that can take one, its caret at display - /// column `col` of the path. Nothing changes until it is typed into. - pub fn draftName(p: *Pardes, pane: *Pane, col: usize) void { - const f = pane.file orelse return; - if (!panes.Output.fileTraits(f.output).saves) return; - const name = p.gpa.dupe(u8, f.path) catch return; - pane.closePrompt(); - pane.prompt = .name; - pane.input = .{ .what = .input, .own = name, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(@min(name.len, panes.File.rawAtDisplay(name, col))) }; - } - - /// Commit a drafted buffer name, never a disk rename or write. Keep the - /// draft visible on failure so the user can correct it or cancel with Esc. - pub fn commitTagName(p: *Pardes, pane: *Pane) bool { - if (pane.prompt != .name) return true; - const id = p.paneIdOf(pane) orelse return false; - const name = pane.input.own orelse ""; - if (name.len == 0 or name[name.len - 1] == '/' or !std.unicode.utf8ValidateSlice(name)) { - p.reportError(id, "name", error.InvalidName); - return false; - } - for (name) |byte| if (byte < ' ') { - p.reportError(id, "name", error.InvalidName); - return false; - }; - const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ paneDir(pane), name }) catch |err| { - p.reportError(id, "name", err); - return false; - }; - ctlfs.pane.nameBuffer(p, id, full, true) catch |err| { - p.reportError(id, "name", err); - return false; - }; - pane.closePrompt(); - return true; - } - - pub fn exitHeader(p: *Pardes) void { - p.header_focus = false; - p.header_column = null; - p.header_drag = false; - p.header_scroll = 0; - } - - /// Give the keyboard to a column's tag, or the workspace's for null, in - /// normal mode, its cursor where that header last had it. - pub fn enterHeader(p: *Pardes, column: ?usize) void { - p.exitHeader(); - if (p.panes[p.active]) |pane| pane.focus = .body; - p.header_focus = true; - p.header_column = column; - const t = p.focusedHeader() orelse return p.exitHeader(); - const text = edit.flatSurface(p, t) catch ""; - const rows = modal.cursorLineCount(text); - t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1)); - const line = modal.lineSlice(text, @intCast(t.cur_row)); - t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); - t.cur_pinned = true; - t.vsel.active = false; - t.msel.active = false; - t.nsel = 0; - t.select = false; - t.append_at = null; - t.mode = .normal; - t.normal.clear(); - } - /// Cycle only the body modes supported by this pane. pub fn cycleMode(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; if (pane.file == null and !pane.isTerminal()) return; const previous = pane.body.mode; p.active = id; - p.exitHeader(); + tagline.exitHeader(p); pane.focus = .body; pane.closePrompt(); switch (previous) { @@ -5068,7 +4796,7 @@ pub const Pardes = struct { const pane = p.panes[id] orelse return; if (!pane.isTerminal()) return; p.active = id; - p.exitHeader(); + tagline.exitHeader(p); pane.focus = .body; pane.closePrompt(); if (pane.body.mode == .tty) { @@ -5089,7 +4817,7 @@ pub const Pardes = struct { return; } const pane = p.panes[p.active] orelse return; - const header = p.focusedHeader(); + const header = tagline.focusedHeader(p); if (header == null and pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { p.leader_on = false; p.ctrl_w_pending = false; @@ -5136,7 +4864,7 @@ pub const Pardes = struct { // global window ops (any mode): Alt-n new terminal below, Alt-c move // the active terminal into a fresh column if (hit(key, config.new_shell_below)) { - p.exitHeader(); + tagline.exitHeader(p); const free = p.freeSlot() orelse return; const nt = p.newShell(free, "") catch return; nt.greet = true; @@ -5150,11 +4878,11 @@ pub const Pardes = struct { } for (config.jump_keys) |jk| { if (!hit(key, &.{jk.chord})) continue; - p.exitHeader(); + tagline.exitHeader(p); return exec.runBuiltin(p, jk.cmd, p.active, "", null); } if (hit(key, config.pane_to_new_column)) { - p.exitHeader(); + tagline.exitHeader(p); const f = layout.findPane(p, p.active).?; if (p.ncol < MAX_COLS and p.col_n[f.col] > 1) { _ = layout.splitColumn(p, p.active, p.active, false); @@ -5170,7 +4898,7 @@ pub const Pardes = struct { // Enter or the execute key commits the draft and the keyboard // goes back to the body; Esc drops it. if (hit(key, config.look_key) or hit(key, config.exec_key)) { - if (p.commitTagName(pane)) pane.focus = .body; + if (tagline.commitTagName(p, pane)) pane.focus = .body; return; } if (hit(key, config.escape)) { @@ -5209,7 +4937,7 @@ pub const Pardes = struct { // text as it is shown: a tag's prefix is part of what a word is. const arena = p.scratch.allocator(); const own = arena.dupe(u8, edit.flatSurface(p, t) catch return) catch return; - const shown = if (t.what == .tag) p.tagText(arena, pane) catch return else own; + const shown = if (t.what == .tag) tagline.tagText(p, arena, pane) catch return else own; const range = t.primaryRange(own, 0); const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); @@ -5221,7 +4949,7 @@ pub const Pardes = struct { }; // Out of the tag or header FIRST: Del frees the pane, Kill // and Restore the whole session. - if (header != null) p.exitHeader() else pane.focus = .body; + if (header != null) tagline.exitHeader(p) else pane.focus = .body; if (txt.len > 0) exec.runBuiltin(p, cmd, p.active, "", txt); return; } @@ -5615,90 +5343,6 @@ pub const Pardes = struct { // ---- dump / load (acme-style: `pardes -l state.zon` restores a session) ---- - pub fn restoreDumpTail(p: *Pardes, pane: *Pane, src: dump.Pane) void { - if (src.tag_tail) |tail| { - pane.tag.own = p.gpa.dupe(u8, tail) catch return; - return; - } - const tail_class = tailClass(pane); - if (src.kind == .image and panes.Pdf.isPath(src.image.?.path)) { - if (panes.Pdf.legacySavedPrefix(src.image.?.path, src.tag)) |prefix| - return p.restoreTailAt(pane, src.tag, prefix, .generic); - } - if (src.kind == .terminal and std.mem.startsWith(u8, src.tag, "TTY ")) { - const legacy = std.fmt.allocPrint(p.scratch.allocator(), "TTY {s}", .{src.terminal.?.cwd}) catch return; - if (std.mem.startsWith(u8, src.tag, legacy)) - return p.restoreTailAt(pane, src.tag, legacy, .terminal); - } - const current = p.tagPrefix(pane) catch return; - if (std.mem.startsWith(u8, src.tag, current)) - return p.restoreTailAt(pane, src.tag, savedPrefix(src.tag, current, tail_class), tail_class); - if (src.kind != .image) return; - const saved = src.image.?; - if (pane.image) |*state| if (panes.Image.legacySavedPrefix(state, src.tag)) |legacy| - return p.restoreTailAt(pane, src.tag, legacy, .generic); - if (panes.Pdf.isPath(saved.path)) if (panes.Pdf.legacySavedPrefix(saved.path, src.tag)) |legacy| - p.restoreTailAt(pane, src.tag, legacy, .generic); - } - - fn restoreTail(p: *Pardes, pane: *Pane, saved_tag: []const u8) void { - const pfx = p.tagPrefix(pane) catch return; - const class = tailClass(pane); - p.restoreTailAt(pane, saved_tag, savedPrefix(saved_tag, pfx, class), class); - } - - const TailClass = enum { generic, file, output, terminal }; - - fn tailClass(pane: *const Pane) TailClass { - if (pane.file) |f| return if (f.output == null) .file else .output; - if (pane.isTerminal()) return .terminal; - return .generic; - } - - fn savedPrefix(saved_tag: []const u8, live: []const u8, class: TailClass) []const u8 { - if (class == .generic or class == .terminal) return live; - if (!std.mem.startsWith(u8, saved_tag, live)) return live; - const marked_len = live.len + dirty_marker.len; - if (saved_tag.len >= marked_len and std.mem.eql(u8, saved_tag[live.len..marked_len], dirty_marker)) - return saved_tag[0..marked_len]; - return live; - } - - fn restoreTailAt( - p: *Pardes, - pane: *Pane, - saved_tag: []const u8, - pfx: []const u8, - class: TailClass, - ) void { - if (!std.mem.startsWith(u8, saved_tag, pfx)) return; - const rest = saved_tag[pfx.len..]; - const said = std.mem.trimStart(u8, rest, " "); - const defaults: []const []const u8 = switch (class) { - .generic => &.{ pdf_pane_tail, pane_tail, pre_close_last_pdf_pane_tail, pre_close_last_pane_tail, pre_collapse_pdf_pane_tail, pre_collapse_pane_tail, pre_column_pdf_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, - .file => &.{ context_pane_tail, file_pane_tail, pre_close_last_file_pane_tail, pre_collapse_file_pane_tail, pre_column_file_pane_tail, prev_file_pane_tail, legacy_file_pane_tail }, - .output => &.{ - locations_pane_tail, - file_pane_tail, - pre_close_last_file_pane_tail, - pre_close_last_pane_tail, - prev_file_pane_tail, - legacy_file_pane_tail, - pane_tail, - prev_pane_tail, - legacy_pane_tail, - pre_column_file_pane_tail, - pre_column_pane_tail, - pre_collapse_file_pane_tail, - pre_collapse_pane_tail, - }, - .terminal => &.{ terminal_pane_tail, pre_close_last_terminal_pane_tail, pre_close_last_pane_tail, pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail, pre_column_terminal_pane_tail, pre_tty_terminal_pane_tail, prev_terminal_pane_tail, legacy_terminal_pane_tail, pane_tail, pre_collapse_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, - }; - for (defaults) |default| - if (std.mem.eql(u8, said, std.mem.trimStart(u8, default, " "))) return; - pane.tag.own = p.gpa.dupe(u8, rest) catch return; - } - /// Close a pane; its rows go to `to`, or where layout.absorbVWeight /// sends them when that is null. pub fn removePane(p: *Pardes, id: usize, to: ?usize) !void { @@ -5854,7 +5498,7 @@ pub const Pardes = struct { /// deferred greetings. The mirror of the prototype's loop epilogue. pub fn sync(p: *Pardes) void { if (p.header_column != null and p.columnBarHeight() == 0) { - p.exitHeader(); + tagline.exitHeader(p); } p.reapPanes(); layout.compute(p); @@ -5886,7 +5530,7 @@ pub const Pardes = struct { const r = p.rects[id]; // The tag takes a row per line, leaving the body one row if it // had any; a folded pane shows its first line only. - const lines = std.mem.count(u8, curTail(pane), "\n") + 1; + const lines = std.mem.count(u8, tagline.curTail(pane), "\n") + 1; pane.tag_rows = @intCast(@min(lines, MAX_TAG_ROWS, @max(BOX_H, r.h -| 1))); if (pane.collapsed) pane.tag_rows = BOX_H; const cols = @max(1, r.w -| config.GUTTER); @@ -5976,7 +5620,7 @@ pub const Pardes = struct { return if (p.settings.tag_bottom) r.y + r.h -| pane.tag_rows else r.y; } - fn tagCapacity(p: *const Pardes, physical_width: u16) u16 { + pub fn tagCapacity(p: *const Pardes, physical_width: u16) u16 { const layer: TagLayer = .{ .viewport = .{ .x = 0, .y = 0, .w = physical_width, .h = 1 } }; return layer.capacity(p.row_metrics); } @@ -6107,110 +5751,8 @@ pub const Pardes = struct { } } - // global tagbar: full width, top rows — unless a native shell has - // taken its commands over, in which case the rows are not ours to draw - p.revealHeader(); - const global = p.topbar(); - const global_rows = p.topBarHeight(); - const global_scroll = if (p.header_focus and p.header_column == null) p.header_scroll else 0; - if (p.settings.workspace_tag) { - s.fill(0, 0, s.cols, global_rows, .{ - .bg = .{ .rgb = chrome.tag_bg }, - .font_role = .tagline, - }); - for (0..global_rows) |row| { - const line = modal.lineSlice(global, row); - _ = s.print(0, @intCast(row), s.cols, line[panes.File.rawAtDisplay(line, global_scroll)..], .{ - .fg = .{ .rgb = chrome.tag_fg }, - .bg = .{ .rgb = chrome.tag_bg }, - .font_role = .tagline, - }); - } - } - if (p.pointer_inside and p.hover_row < global_rows) { - const bar = modal.lineSlice(global, p.hover_row); - if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col + global_scroll))) |bounds| { - var col = panes.File.rawDisplayCol(bar, bounds.lo) -| global_scroll; - const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| global_scroll; - while (col < hi and col < s.cols) : (col += 1) { - const cell = s.at(@intCast(col), p.hover_row); - cell.default = false; - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; - } - } - } - const column_rows = p.columnBarHeight(); - if (column_rows > 0) for (0..p.ncol) |c| { - const grip = @min(config.GUTTER, p.col_w[c]); - const inset = @min(TAG_TEXT_INSET, p.col_w[c]); - const x = p.col_x[c] + inset; - const w = p.col_w[c] - inset; - const y0 = global_rows; - if (p.col_w[c] == 0 or p.col_x[c] >= s.cols) continue; - const active_col = if (layout.findPane(p, p.active)) |f| f.col == c else false; - const bg = if (active_col and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - const fg = if (active_col and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg; - // A grip is muted until it is grabbed; then it lights, as a pane's - // box does for the active pane, so the drag shows what it holds. - const grabbed = p.drag == .column_move and layout.columnBySerial(p, p.drag.column_move.serial) == c; - const grip_bg = if (grabbed) chrome.column_box else chrome.column_box_dim; - const lum = (@as(u16, grip_bg[0]) * 3 + @as(u16, grip_bg[1]) * 6 + @as(u16, grip_bg[2])) / 10; - const ink: [3]u8 = if (lum > 140) .{ 0, 0, 0 } else .{ 255, 255, 255 }; - const grip_style: CellStyle = .{ .bg = .{ .rgb = grip_bg }, .fg = .{ .rgb = ink }, .font_role = .tagline }; - s.fill(p.col_x[c], y0, grip, column_rows, grip_style); - s.fill(p.col_x[c] + grip, y0, inset - grip, column_rows, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - - s.fill(x, y0, w, column_rows, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - const bar_scroll = if (p.header_focus and p.header_column == c) p.header_scroll else 0; - const tag = p.columnTag(c); - for (0..column_rows) |row| { - const line = modal.lineSlice(tag, row); - _ = s.print(x, y0 + @as(u16, @intCast(row)), w, line[panes.File.rawAtDisplay(line, bar_scroll)..], .{ - .fg = .{ .rgb = fg }, - .bg = .{ .rgb = bg }, - .font_role = .tagline, - }); - } - // A carried column's pointer is aiming at a place, not a word. - if (p.pointer_inside and p.drag != .column_move and p.hover_row >= y0 and p.hover_row < y0 + column_rows and p.hover_col >= x and p.hover_col < x + w) { - const bar = modal.lineSlice(tag, p.hover_row - y0); - if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col - x + bar_scroll))) |bounds| { - var col = panes.File.rawDisplayCol(bar, bounds.lo) -| bar_scroll; - const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| bar_scroll; - while (col < hi and col < w) : (col += 1) { - const cell = s.at(x + @as(u16, @intCast(col)), p.hover_row); - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; - } - } - } - }; - if (p.focusedHeader()) |t| { - const text = try edit.flatSurface(p, t); - const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; - const w = if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else s.cols; - const y: u16 = if (p.header_column != null) global_rows else 0; - const rows = if (p.header_column != null) column_rows else global_rows; - for (0..rows) |row| { - const bar = modal.lineSlice(text, row); - const span = headerSelection(t, text, row) orelse continue; - var col = panes.File.rawDisplayCol(bar, span.lo) -| p.header_scroll; - const hi = panes.File.rawDisplayCol(bar, span.hi) -| p.header_scroll; - while (col < hi and col < w) : (col += 1) { - const cell = s.at(x + @as(u16, @intCast(col)), y + @as(u16, @intCast(row))); - cell.style.fg = .{ .rgb = th.sel_fg }; - cell.style.bg = .{ .rgb = th.sel_bg }; - } - } - if (t.cur_row >= 0 and t.cur_row < rows) { - const bar = modal.lineSlice(text, @intCast(t.cur_row)); - const caret = panes.File.rawDisplayCol(bar, @min(@as(usize, @intCast(@max(0, t.cur_col))), bar.len)) -| p.header_scroll; - if (caret < w) s.cursor = .{ .x = x + @as(u16, @intCast(caret)), .y = y + @as(u16, @intCast(t.cur_row)), .bar = t.mode == .insert }; - } - } - - try p.renderTagLayers(arena); + try body_layer.paintHeaders(p); + try body_layer.renderTagLayers(p, arena); switch (p.drag) { .border_v => |d| { @@ -6450,204 +5992,6 @@ pub const Pardes = struct { return !cell.default and !(cell.len == 1 and cell.text[0] == ' '); } - fn renderTagLayers(p: *Pardes, arena: std.mem.Allocator) !void { - const chrome = p.chromeTheme(); - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const r = p.rects[id]; - if (r.w <= TAG_TEXT_INSET or r.h == 0) continue; - const tag = try p.tagText(arena, pane); - const rows = pane.tag_rows; - // As wide as the widest line it shows, and never narrower than - // its viewport. - var widest: usize = 0; - var split = std.mem.splitScalar(u8, tag, '\n'); - for (0..rows) |_| widest = @max(widest, panes.File.displayWidth(split.next() orelse "")); - const columns: u16 = @intCast(@min(std.math.maxInt(u16) - TAG_TEXT_INSET, @max(p.tagCapacity(r.w - TAG_TEXT_INSET), widest + 1))); - const pitch = @as(usize, columns) + TAG_TEXT_INSET; - const storage = try arena.alloc(Cell, pitch * rows); - @memset(storage, .{}); - var temporary: Surface = .{ .cols = columns + TAG_TEXT_INSET, .rows = rows, .cells = storage }; - std.mem.swap(Surface, &p.surface, &temporary); - p.paintPaneTag(arena, pane, .{ .x = 0, .y = 0, .w = columns + TAG_TEXT_INSET, .h = rows }, id, id == p.active, p.tagCapacity(r.w - TAG_TEXT_INSET)) catch |err| { - std.mem.swap(Surface, &p.surface, &temporary); - return err; - }; - std.mem.swap(Surface, &p.surface, &temporary); - // A layer to a line: the first in the pane's own slot, the rest - // in the slots kept for the lines of taller tags. - for (0..rows) |line| { - const layer = &p.surface.tag_layers[if (line == 0) id else TAG_LINE_LAYER_BASE + id * (MAX_TAG_ROWS - 1) + line - 1]; - if (layer.cells.len != columns) layer.cells = try p.gpa.realloc(layer.cells, columns); - @memcpy(layer.cells, storage[line * pitch + TAG_TEXT_INSET ..][0..columns]); - layer.kind = .pane; - layer.id = @intCast(id); - layer.serial = pane.serial; - layer.line = @intCast(line); - layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = p.tagTop(pane, r) + @as(u16, @intCast(line)), .w = r.w - TAG_TEXT_INSET, .h = BOX_H }; - layer.cols = columns; - layer.bg = if (id == p.active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - layer.cursor = if (p.header_focus) null else if (temporary.cursor) |cursor| - (if (cursor.y == line) .{ .col = cursor.x - TAG_TEXT_INSET, .bar = cursor.bar } else null) - else - null; - } - } - // With the workspace tag row handed to native chrome there is no - // workspace layer to render; the menu bar carries its commands. - if (p.settings.workspace_tag) { - for (0..p.topBarHeight()) |line| { - const index = if (line == 0) MAX_PANES + MAX_COLS else HEADER_LINE_LAYER_BASE + MAX_COLS * (MAX_TAG_ROWS - 1) + line - 1; - try p.renderHeaderLayer(arena, index, .workspace, 0, @intCast(line), .{ .x = 0, .y = @intCast(line), .w = p.screen_w, .h = TOPBAR_H }, modal.lineSlice(p.topbar(), line), chrome.tag_bg, chrome.tag_fg); - } - } - // Each notice is its own tagline-shaped chip over the top of the body. - // Going through the same layer machinery the pane and column tags use - // is what gives it the tagline's height, its small-font metrics, the - // band offset and the border -- none of which a body-grid row can have - // just by wearing a tagline font. The geometry is the one the grid - // pass already chose and recorded, so the two cannot disagree and the - // GUI's "skip the cells a tag layer covers" leaves no stub behind. - // A prompt is one of them too: left on the grid, a pixel shell drew - // its tagline glyphs one to a BODY cell, spaced out like a banner. - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const r = p.rects[id]; - if (r.w <= TAG_TEXT_INSET or r.h <= pane.tag_rows) continue; - const first = p.bodyTop(pane, r); - var leader_buf: [16]u8 = undefined; - for (pane.notices.slice(), 0..) |kind, i| { - const text = Messages.noticeText(p, pane, i, &leader_buf); - if (text.len == 0) continue; - const cx = pane.notices.left[i]; - if (cx == std.math.maxInt(u16) or cx >= r.x + r.w) continue; - const chip = r.x + r.w - cx; - // Right aligned inside the chip, a blank cell short of its - // edge: the same one the grid pass leaves for a prompt caret. - // Wider than the chip, the text loses its head, as on the grid. - const room = p.tagCapacity(chip) -| 1; - const shown = panes.File.displayWidth(text); - var kept = text; - if (shown > room) { - var start = panes.File.rawAtDisplay(text, shown - room); - if (panes.File.rawDisplayCol(text, start) < shown - room) start = panes.File.rawAtDisplay(text, shown - room + 1); - kept = text[start..]; - } - const pad = room -| panes.File.displayWidth(kept); - const line = try arena.alloc(u8, pad + kept.len); - @memset(line[0..pad], ' '); - @memcpy(line[pad..], kept); - // A pixel shell slides the message in as it fades up, and - // fades it on the way out. - const motion: Messages.MessageMotion = if (Messages.noticeLife(pane, i)) |life| Messages.messageMotion(p, life) else .{}; - const fade = motion.alpha; - const page = p.theme().bg orelse chrome.tag_bg; - const layer_index = NOTICE_LAYER_BASE + id * Pane.Notices.max + i; - try p.renderHeaderLayer(arena, layer_index, .notice, @intCast(id), 0, .{ - .x = cx, - .y = first + @as(u16, pane.notices.row[i]), - .w = chip, - .h = BOX_H, - }, line, Messages.blendRgb(chrome.tag_bg, page, fade), Messages.blendRgb(chrome.tag_fg, page, fade)); - p.surface.tag_layers[layer_index].slide = motion.slide; - p.surface.tag_layers[layer_index].fade = fade; - // The caret rides the band, where the prompt's glyphs are, - // at the same place in the text the grid pass puts it. - if (kind != .prompt or id != p.active or pane.prompt == .del_side) continue; - const typed = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); - const dropped = shown - panes.File.displayWidth(kept); - if (typed < dropped) continue; - p.surface.tag_layers[layer_index].cursor = .{ .col = @intCast(pad + typed - dropped), .bar = pane.input.mode == .insert }; - } - } - if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { - if (p.col_w[column] == 0) continue; - const active = if (layout.findPane(p, p.active)) |found| found.col == column and p.settings.focus_tint else false; - for (0..p.columnBarHeight()) |line| { - const index = if (line == 0) MAX_PANES + column else HEADER_LINE_LAYER_BASE + column * (MAX_TAG_ROWS - 1) + line - 1; - try p.renderHeaderLayer(arena, index, .column, @intCast(column), @intCast(line), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight() + @as(u16, @intCast(line)), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, modal.lineSlice(p.columnTag(column), line), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); - } - }; - } - - /// The span a header's selection covers on line `row` of its text, in - /// that line's bytes: up to the caret while typing, and over the - /// cursor's own cell too in normal mode, where a cursor is a cell. - pub fn headerSelection(t: *const Text, text: []const u8, row: usize) ?struct { lo: usize, hi: usize } { - if (!t.vsel.active) return null; - const anchor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) }); - const cursor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); - const lo = @min(anchor, cursor); - const hi = if (t.mode == .insert) @max(anchor, cursor) else modal.nextGrapheme(text, @max(anchor, cursor)); - const start = modal.lineStartOffset(text, row); - const end = modal.lineEndOffset(text, row); - if (hi <= start or lo >= end) return null; - return .{ .lo = @max(lo, start) - start, .hi = @min(hi, end) - start }; - } - - /// One row of a header or a notice band as a tag layer: `text` is line - /// `line` of what it shows. - fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, index: usize, kind: TagKind, id: u16, line: u16, viewport: Rect, text: []const u8, bg: [3]u8, fg: [3]u8) !void { - _ = arena; - const layer = &p.surface.tag_layers[index]; - if (viewport.w == 0) { - layer.cols = 0; - return; - } - const columns: u16 = @intCast(@min(std.math.maxInt(u16), @max(p.tagCapacity(viewport.w), panes.File.displayWidth(text) + 1))); - if (layer.cells.len != columns) layer.cells = try p.gpa.realloc(layer.cells, columns); - layer.kind = kind; - layer.id = id; - layer.line = line; - layer.serial = if (kind == .column) p.col_serial[id] else 0; - layer.viewport = viewport; - layer.cols = columns; - layer.bg = bg; - layer.cursor = null; - layer.slide = 0; - layer.fade = 1; - var surface: Surface = .{ .cols = columns, .rows = 1, .cells = layer.cells }; - // A notice band carries a PANE id, not a column index, so it must not - // answer to the column being edited -- that would scroll and select - // its text with the column tag's offsets and give it a second caret. - const editing: ?*Text = if (p.header_focus and switch (kind) { - .workspace => p.header_column == null, - .column => p.header_column == id, - .pane, .notice => false, - }) p.focusedHeader() else null; - const scroll = if (editing != null) p.header_scroll else 0; - surface.fill(0, 0, columns, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - _ = surface.print(0, 0, columns, text[panes.File.rawAtDisplay(text, scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); - if (editing) |t| { - if (headerSelection(t, try edit.flatSurface(p, t), line)) |span| { - var col = panes.File.rawDisplayCol(text, span.lo) -| scroll; - const end = panes.File.rawDisplayCol(text, span.hi) -| scroll; - while (col < end and col < columns) : (col += 1) { - surface.at(@intCast(col), 0).style.bg = .{ .rgb = p.theme().sel_bg }; - surface.at(@intCast(col), 0).style.fg = .{ .rgb = p.theme().sel_fg }; - } - } - const caret = panes.File.rawDisplayCol(text, @min(@as(usize, @intCast(@max(0, t.cur_col))), text.len)) -| scroll; - if (t.cur_row == line and caret < columns) layer.cursor = .{ .col = @intCast(caret), .bar = t.mode == .insert }; - } else if (p.pointer_inside) { - const tag_hit = p.pointer_tag_hit; - const col: ?usize = if (tag_hit) |pointer| - (if (pointer.kind == kind and pointer.id == id and pointer.line == line) pointer.col else null) - else if (p.hover_row == viewport.y and p.hover_col >= viewport.x and p.hover_col - viewport.x < viewport.w) - p.hover_col - viewport.x - else - null; - if (col) |hover| if (wordBoundsAtCol(text, panes.File.rawAtDisplay(text, hover + scroll))) |bounds| { - var cell = panes.File.rawDisplayCol(text, bounds.lo) -| scroll; - const end = panes.File.rawDisplayCol(text, bounds.hi) -| scroll; - while (cell < end and cell < columns) : (cell += 1) { - surface.at(@intCast(cell), 0).style.bg = .{ .rgb = p.theme().sel_bg }; - surface.at(@intCast(cell), 0).style.fg = .{ .rgb = p.theme().sel_fg }; - } - }; - } - } - fn renderPane(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool) !void { const tz = tracy.zone(@src(), "renderPane"); defer tz.end(); @@ -6687,7 +6031,7 @@ pub const Pardes = struct { .tty => config.tag_tty, }, box_style); - try p.paintPaneTag(arena, pane, r, id, active, p.tagCapacity(r.w -| TAG_TEXT_INSET)); + try body_layer.paintPaneTag(p, arena, pane, r, id, active, p.tagCapacity(r.w -| TAG_TEXT_INSET)); // Folded panes retain their body state, but neither body pixels nor // its cursor belong outside the one-row tag rectangle. @@ -6714,127 +6058,6 @@ pub const Pardes = struct { try body_layer.renderBody(p, arena, pane, r, id, active, true); } - fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, capacity: u16) !void { - const s = &p.surface; - const th = p.theme(); - const chrome = p.chromeTheme(); - const tx = r.x + @min(TAG_TEXT_INSET, r.w); - const tw = r.w -| TAG_TEXT_INSET; - const tag_y = p.tagTop(pane, r); - const body_y = p.bodyTop(pane, r); - const rows = pane.tag_rows; - const page_rgb = th.bg orelse th.tag_bg; - // Focus is visible along the tag without changing its live text grid. - const tag_bg = if (active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - const tag_fg = if (active and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg; - const tag_style: CellStyle = .{ .fg = .{ .rgb = tag_fg }, .bg = .{ .rgb = tag_bg }, .font_role = .tagline }; - // Padding belongs to the same font row but keeps its default ink: a - // role must not manufacture a foreground color for blank cells. - s.fill(r.x + config.GUTTER, tag_y, @min(TAG_GAP, r.w -| config.GUTTER), rows, .{ .bg = .{ .rgb = tag_bg }, .font_role = .tagline }); - s.fill(tx, tag_y, tw, rows, .{ - .bg = .{ .rgb = tag_bg }, - .font_role = .tagline, - }); - const whole = try p.tagText(arena, pane); - const tail = curTail(pane); - const prefix_len = whole.len - tail.len; - // A row per line: the first carries the prefix, the rest are the - // tag's own text alone. - var lines: [MAX_TAG_ROWS][]const u8 = @splat(""); - var split = std.mem.splitScalar(u8, whole, '\n'); - for (lines[0..rows]) |*line| line.* = split.next() orelse ""; - // The keyboard's caret, as a row and a byte offset in that row's - // line: in the tag's own text when the tag has the keyboard, in the - // path while a name is drafted. - const Caret = struct { row: usize, at: usize }; - const caret: ?Caret = if (!active) - null - else if (pane.prompt == .name) - .{ .row = 0, .at = @min(lines[0].len, @as(usize, @intCast(@max(0, pane.input.cur_col)))) } - else if (pane.focus == .tag and pane.tag.cur_row < rows) caret: { - const row: usize = @intCast(@max(0, pane.tag.cur_row)); - const lead: usize = if (row == 0) prefix_len else 0; - break :caret .{ .row = row, .at = @min(lines[row].len, lead + @as(usize, @intCast(@max(0, pane.tag.cur_col)))) }; - } else null; - if (caret) |at| { - const line = lines[at.row]; - const col = panes.File.rawDisplayCol(line, at.at); - var scroll: usize = pane.tag_scroll; - if (col < scroll) scroll = col; - if (col >= scroll + capacity) scroll = col - capacity + 1; - var raw = panes.File.rawAtDisplay(line, scroll); - scroll = panes.File.rawDisplayCol(line, raw); - if (col >= scroll + capacity) { - raw = modal.nextGrapheme(line, raw); - scroll = panes.File.rawDisplayCol(line, raw); - } - pane.tag_scroll = @intCast(scroll); - } else if (pane.focus != .tag) pane.tag_scroll = 0; - for (lines[0..rows], 0..) |line, row| { - const start = panes.File.rawAtDisplay(line, pane.tag_scroll); - _ = s.print(tx, tag_y + @as(u16, @intCast(row)), tw, line[start..], tag_style); - } - const tag = lines[0]; - if (tagTintRange(pane, tag, prefix_len)) |name| { - const lo = @max(name.lo, panes.File.rawAtDisplay(tag, pane.tag_scroll)); - const hi = @min(name.hi, tag.len); - if (lo < hi) { - var col = panes.File.rawDisplayCol(tag, lo) -| pane.tag_scroll; - const end = panes.File.rawDisplayCol(tag, hi) -| pane.tag_scroll; - const name_fg = if (active and p.settings.focus_tint) chrome.tag_active_name_fg else chrome.tag_name_fg; - while (col < end and col < tw) : (col += 1) - s.at(tx + @as(u16, @intCast(col)), tag_y).style.fg = .{ .rgb = name_fg }; - } - } - if (p.look_hover_preview) |preview| { - if (preview.pane == id and preview.serial == pane.serial) if (preview.sel) |sel| if (@min(sel.r0, sel.r1) < rows) { - const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); - body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); - }; - } - // The tag's own selections, while it has the keyboard, a line at a - // time. A range of one grapheme is the block cursor, not a selection. - if (pane.focus == .tag) { - var ranges: [Text.max_selections]modal.Selection = undefined; - const got = pane.tag.ranges(tail, 0, &ranges); - for (ranges[0..got.n]) |range| { - const lo = @min(range.anchor, range.head); - const hi = @max(range.anchor, range.head); - if (modal.nextGrapheme(tail, lo) >= hi) continue; - const first = modal.positionAt(tail, lo); - const last = modal.positionAt(tail, hi); - var row = first.row; - while (row <= last.row and row < rows) : (row += 1) { - const line = lines[row]; - const lead: usize = if (row == 0) prefix_len else 0; - const from = lead + if (row == first.row) first.col else 0; - const to = @min(line.len, lead + if (row == last.row) last.col else modal.lineSlice(tail, row).len); - var col = panes.File.rawDisplayCol(line, from) -| pane.tag_scroll; - const end = panes.File.rawDisplayCol(line, to); - const y = tag_y + @as(u16, @intCast(row)); - while (col + pane.tag_scroll < end and col < tw) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), y); - cell.default = false; - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; - } - } - } - } - // the caret: bar while typing, block in normal mode (same rule as a body) - if (caret) |at| { - const col = panes.File.rawDisplayCol(lines[at.row], at.at) -| pane.tag_scroll; - const mode = if (pane.prompt == .name) pane.input.mode else pane.tag.mode; - if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y + @as(u16, @intCast(at.row)), .bar = mode == .insert }; - } - - for (pane.sel, 0..) |selection, button| { - if (selection.state == .none or (selection.state == .done and button != 0)) continue; - if (@min(selection.r0, selection.r1) >= rows) continue; - body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); - } - } - pub fn appendImagePlace(p: *Pardes, place: ImagePlace) bool { const s = &p.surface; if (s.nimages == s.images.len) { @@ -6954,7 +6177,7 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" const modal_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(rect.x + config.GUTTER + 1, modal_cursor.x); try std.testing.expectEqual(body_y, modal_cursor.y); - p.enterTag(pane); + tagline.enterTag(p, pane); const tag_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(if (p.settings.tag_bottom) rect.y + rect.h - BOX_H else rect.y, tag_cursor.y); pane.focus = .body; diff --git a/src/tag_layer.zig b/src/tag_layer.zig index ac7c4ac2..7cfe5bbf 100644 --- a/src/tag_layer.zig +++ b/src/tag_layer.zig @@ -78,3 +78,28 @@ test "tag text capacity uses its own pitch and excludes the physical grip" { try std.testing.expect(layer.hitAt(120, 85, std.math.nan(f32), 20, 6, 12) == null); try std.testing.expect(layer.hitAt(120, 85, 10, 20, 0, 12) == null); } + +/// Whether two pointer hits name the same cell of the same tag line. +pub fn sameCell(a: ?Hit, b: ?Hit) 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: ?Hit, clamp: bool, line: u16) ?u16 { + var point = supplied orelse return null; + if (point.kind != kind or point.id != id) return null; + if (clamp) for (p.surface.tagLayers()) |*layer| { + if (layer.cols == 0 or layer.kind != kind or layer.id != id or layer.serial != point.serial or layer.line != line) continue; + const bw: f32 = @floatFromInt(point.metrics.body_w); + const bh: f32 = @floatFromInt(point.metrics.body_h); + const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; + const right = @as(f32, @floatFromInt(layer.viewport.x + layer.viewport.w)) * bw; + point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); + point.pixel_y = (@as(f32, @floatFromInt(layer.viewport.y)) + 0.5) * bh; + break; + }; + return if (p.reprojectTagHit(point)) |mapped| mapped.col else null; +} diff --git a/src/tagline.zig b/src/tagline.zig new file mode 100644 index 00000000..1021e9db --- /dev/null +++ b/src/tagline.zig @@ -0,0 +1,360 @@ +//! The tags (acme's tag half of wind.c): a pane's computed prefix and its +//! default and saved tails, going into a tag and out again, the path drafted +//! as a new name, and the column and workspace tags above the panes. +const pardes = @import("pardes.zig"); +const std = @import("std"); +const modal = @import("modal.zig"); +const ctlfs = @import("ninep/tree.zig"); +const panes = @import("panes.zig"); +const edit = @import("edit.zig"); +const config = @import("config.zig"); +const pdf_enabled = panes.Pdf.enabled; +const dump = @import("dump.zig"); +const Pane = panes.Pane; +const Text = panes.Text; +const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; +const Pardes = pardes.Pardes; + +pub const pane_tail = " " ++ config.pane_builtins_str; +pub const pdf_pane_tail = " " ++ config.pdf_pane_builtins_str; +pub const file_pane_tail = " " ++ config.file_pane_builtins_str; +pub const context_pane_tail = file_pane_tail ++ " TreeContext"; +pub const locations_pane_tail = file_pane_tail ++ " LocationsConfig"; +pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; +const dirty_marker = " *"; +pub const legacy_pane_tail = " Del"; +pub const legacy_file_pane_tail = " Save Del"; +// The defaults from the release before Newtty joined every tagline. Recognized +// so a dump written then upgrades instead of keeping the old word as a tail. +const prev_pane_tail = " New Del"; +pub const prev_file_pane_tail = " Save New Del"; +const legacy_terminal_pane_tail = " New Del Filter"; +// ...and the terminal default from the release before Save reached it, when a +// scrollback was not yet something you could write to a path. +pub const prev_terminal_pane_tail = " New Newtty Del Filter"; +const pre_tty_terminal_pane_tail = " Save New Newtty Del Filter"; +const pre_column_pane_tail = " New Newtty Del"; +pub const pre_column_file_pane_tail = " Save New Newtty Del"; +const pre_column_pdf_pane_tail = " New Newtty Del PdfSections PdfTint"; +pub const pre_column_terminal_pane_tail = " Save New Newtty Del Tty Filter"; +const pre_collapse_pane_tail = " Tty Del"; +pub const pre_collapse_file_pane_tail = " Save Tty Del"; +const pre_collapse_pdf_pane_tail = " Tty Del PdfSections PdfTint"; +pub const pre_collapse_terminal_pane_tail = " Save Tty Del Togglettymode Filter"; +pub const pre_tty_first_terminal_pane_tail = " Save Tty Del Togglettymode Filter Collapse"; +pub const pre_mode_terminal_pane_tail = " Tty Save Del Togglettymode Filter Collapse"; +// ...and the defaults from before the closing word moved to the end of every +// tagline, where a click cannot land on it by overshooting the one before. +const pre_close_last_pane_tail = " Tty Del Collapse"; +const pre_close_last_file_pane_tail = " Save Tty Del Collapse"; +const pre_close_last_pdf_pane_tail = " Tty Del PdfSections PdfTint Collapse"; +const pre_close_last_terminal_pane_tail = " Tty Save Del Mode Filter Collapse"; + +/// What a column's tag says until someone edits it. +pub const column_tag_default = "New Tty Find Grep Joincol Delcol"; + +/// What a header says until someone edits it: for the workspace the +/// fixed builtins, plus `Restore ` once a dump exists. +pub fn headerDefault(p: *Pardes, what: Text.What) []const u8 { + if (what == .column) return column_tag_default; + const d = p.last_dump orelse return config.topbar_str; + return std.fmt.allocPrint(p.scratch.allocator(), config.topbar_str ++ " Restore {s}", .{d}) catch config.topbar_str; +} + +/// the topbar line -- render and click dispatch must agree on this exact +/// string +pub fn topbar(p: *Pardes) []const u8 { + return p.global_tag.own orelse headerDefault(p, .workspace); +} + +pub fn columnTag(p: *const Pardes, c: usize) []const u8 { + return p.col_tags[c].own orelse column_tag_default; +} + +/// The header with the keyboard, when one has it. +pub fn focusedHeader(p: *Pardes) ?*Text { + if (!p.header_focus) return null; + if (p.header_column) |c| return if (c < p.ncol) &p.col_tags[c] else null; + return &p.global_tag; +} + +pub fn revealHeader(p: *Pardes) void { + const t = focusedHeader(p) orelse { + p.header_scroll = 0; + return; + }; + const text = edit.flatSurface(p, t) catch return; + const line = modal.lineSlice(text, @intCast(@max(0, t.cur_row))); + const width = p.tagCapacity(if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else p.screen_w); + const col = panes.File.rawDisplayCol(line, @min(@as(usize, @intCast(@max(0, t.cur_col))), line.len)); + if (col < p.header_scroll) p.header_scroll = col; + if (col >= p.header_scroll + width) p.header_scroll = col -| (width -| 1); + var raw = panes.File.rawAtDisplay(line, p.header_scroll); + p.header_scroll = panes.File.rawDisplayCol(line, raw); + if (width > 0 and col >= p.header_scroll + width) { + raw = modal.nextGrapheme(line, raw); + p.header_scroll = panes.File.rawDisplayCol(line, raw); + } +} + +pub fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 { + const arena = p.scratch.allocator(); + if (comptime pdf_enabled) if (pane.pdf) |pv| return std.fmt.allocPrint( + arena, + "{s} [{d}/{d}]", + .{ pv.path, pv.page + 1, pv.page_count }, + ); + if (pane.image) |*state| return panes.Image.tagPrefix(arena, state); + if (pane.file) |f| { + const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; + if (panes.Output.fileTraits(f.output).saves and f.revision != f.saved_revision) + return std.fmt.allocPrint(arena, "{s}{s}", .{ name, dirty_marker }); + return arena.dupe(u8, name); + } + return arena.dupe(u8, pane.cwdSlice()); +} + +/// The tag's own text: what the user made of it, or until then the +/// default a pane of its kind starts with. +pub fn curTail(pane: *Pane) []const u8 { + return pane.tag.own orelse defaultTail(pane); +} + +pub fn defaultTail(pane: *const Pane) []const u8 { + if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; + if (pane.file) |file| if (file.output) |out| + if (panes.Output.usesLocationsConfig(out.from)) return locations_pane_tail; + if (panes.File.supportsContext(pane)) return context_pane_tail; + if (pane.file != null) return file_pane_tail; + if (pane.isTerminal()) return terminal_pane_tail; + return pane_tail; +} + +/// The tag as it is shown, read and pointed at: its computed prefix and +/// its own text after it. +pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { + const prefix = try tagPrefix(p, pane); + const tail = curTail(pane); + const out = try arena.alloc(u8, prefix.len + tail.len); + @memcpy(out[0..prefix.len], prefix); + @memcpy(out[prefix.len..], tail); + return out; +} + +/// Give the keyboard to the tag in normal mode (`:`), its cursor where +/// the tag last had it. The first time there is nothing to remember, and +/// it starts on Save, so that `:` and the execute key write the file. +pub fn enterTag(p: *Pardes, pane: *Pane) void { + const t = &pane.tag; + const tail = curTail(pane); + if (!t.cur_pinned) { + var words = std.mem.tokenizeAny(u8, tail, " \t\n"); + const at = while (words.next()) |word| { + if (std.mem.eql(u8, word, "Save")) break @intFromPtr(word.ptr) - @intFromPtr(tail.ptr); + } else tail.len - std.mem.trimStart(u8, tail, " ").len; + const cursor = modal.positionAt(tail, @min(at, tail.len)); + t.cur_row = @intCast(cursor.row); + t.cur_col = @intCast(cursor.col); + t.cur_pinned = true; + // Reveal the suffix together with its commands, not merely the + // first command letter at the viewport's far right edge. + if (p.paneIdOf(pane)) |id| { + const tag = tagText(p, p.scratch.allocator(), pane) catch return; + const line = tag[0 .. std.mem.indexOfScalar(u8, tag, '\n') orelse tag.len]; + const width = p.tagCapacity(p.rects[id].w -| TAG_TEXT_INSET); + pane.tag_scroll = @intCast(panes.File.displayWidth(line) + 1 -| width); + } + } + // The text may have changed since (a 9P write, a rename), so the + // remembered cursor is pulled back inside it. It is the cursor that + // is remembered, not a selection. + const rows = modal.cursorLineCount(tail); + t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1)); + const line = modal.lineSlice(tail, @intCast(t.cur_row)); + t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); + t.vsel.active = false; + t.msel.active = false; + t.nsel = 0; + t.select = false; + t.append_at = null; + t.sticky_col = -1; + t.mode = .normal; + t.normal.clear(); + pane.focus = .tag; +} + +/// Where display column `col` of tag line `row` (tag scroll included) +/// lands in the tag's own text, or null when it is on the prefix, which +/// only the first line has. +pub fn tagOffsetAt(p: *Pardes, pane: *Pane, row: usize, col: usize) ?modal.Cursor { + const width = if (row == 0) panes.File.displayWidth(tagPrefix(p, pane) catch return null) else 0; + if (col < width) return null; + const line = modal.lineSlice(curTail(pane), row); + return .{ .row = row, .col = modal.graphemeStart(line, panes.File.rawAtDisplay(line, col - width)) }; +} + +/// Start a name draft for a file that can take one, its caret at display +/// column `col` of the path. Nothing changes until it is typed into. +pub fn draftName(p: *Pardes, pane: *Pane, col: usize) void { + const f = pane.file orelse return; + if (!panes.Output.fileTraits(f.output).saves) return; + const name = p.gpa.dupe(u8, f.path) catch return; + pane.closePrompt(); + pane.prompt = .name; + pane.input = .{ .what = .input, .own = name, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(@min(name.len, panes.File.rawAtDisplay(name, col))) }; +} + +/// Commit a drafted buffer name, never a disk rename or write. Keep the +/// draft visible on failure so the user can correct it or cancel with Esc. +pub fn commitTagName(p: *Pardes, pane: *Pane) bool { + if (pane.prompt != .name) return true; + const id = p.paneIdOf(pane) orelse return false; + const name = pane.input.own orelse ""; + if (name.len == 0 or name[name.len - 1] == '/' or !std.unicode.utf8ValidateSlice(name)) { + p.reportError(id, "name", error.InvalidName); + return false; + } + for (name) |byte| if (byte < ' ') { + p.reportError(id, "name", error.InvalidName); + return false; + }; + const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(pane), name }) catch |err| { + p.reportError(id, "name", err); + return false; + }; + ctlfs.pane.nameBuffer(p, id, full, true) catch |err| { + p.reportError(id, "name", err); + return false; + }; + pane.closePrompt(); + return true; +} + +pub fn exitHeader(p: *Pardes) void { + p.header_focus = false; + p.header_column = null; + p.header_drag = false; + p.header_scroll = 0; +} + +/// Give the keyboard to a column's tag, or the workspace's for null, in +/// normal mode, its cursor where that header last had it. +pub fn enterHeader(p: *Pardes, column: ?usize) void { + exitHeader(p); + if (p.panes[p.active]) |pane| pane.focus = .body; + p.header_focus = true; + p.header_column = column; + const t = focusedHeader(p) orelse return exitHeader(p); + const text = edit.flatSurface(p, t) catch ""; + const rows = modal.cursorLineCount(text); + t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1)); + const line = modal.lineSlice(text, @intCast(t.cur_row)); + t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); + t.cur_pinned = true; + t.vsel.active = false; + t.msel.active = false; + t.nsel = 0; + t.select = false; + t.append_at = null; + t.mode = .normal; + t.normal.clear(); +} + +pub fn restoreDumpTail(p: *Pardes, pane: *Pane, src: dump.Pane) void { + if (src.tag_tail) |tail| { + pane.tag.own = p.gpa.dupe(u8, tail) catch return; + return; + } + const tail_class = tailClass(pane); + if (src.kind == .image and panes.Pdf.isPath(src.image.?.path)) { + if (panes.Pdf.legacySavedPrefix(src.image.?.path, src.tag)) |prefix| + return restoreTailAt(p, pane, src.tag, prefix, .generic); + } + if (src.kind == .terminal and std.mem.startsWith(u8, src.tag, "TTY ")) { + const legacy = std.fmt.allocPrint(p.scratch.allocator(), "TTY {s}", .{src.terminal.?.cwd}) catch return; + if (std.mem.startsWith(u8, src.tag, legacy)) + return restoreTailAt(p, pane, src.tag, legacy, .terminal); + } + const current = tagPrefix(p, pane) catch return; + if (std.mem.startsWith(u8, src.tag, current)) + return restoreTailAt(p, pane, src.tag, savedPrefix(src.tag, current, tail_class), tail_class); + if (src.kind != .image) return; + const saved = src.image.?; + if (pane.image) |*state| if (panes.Image.legacySavedPrefix(state, src.tag)) |legacy| + return restoreTailAt(p, pane, src.tag, legacy, .generic); + if (panes.Pdf.isPath(saved.path)) if (panes.Pdf.legacySavedPrefix(saved.path, src.tag)) |legacy| + restoreTailAt(p, pane, src.tag, legacy, .generic); +} + +pub fn restoreTail(p: *Pardes, pane: *Pane, saved_tag: []const u8) void { + const pfx = tagPrefix(p, pane) catch return; + const class = tailClass(pane); + restoreTailAt(p, pane, saved_tag, savedPrefix(saved_tag, pfx, class), class); +} + +const TailClass = enum { generic, file, output, terminal }; + +fn tailClass(pane: *const Pane) TailClass { + if (pane.file) |f| return if (f.output == null) .file else .output; + if (pane.isTerminal()) return .terminal; + return .generic; +} + +fn savedPrefix(saved_tag: []const u8, live: []const u8, class: TailClass) []const u8 { + if (class == .generic or class == .terminal) return live; + if (!std.mem.startsWith(u8, saved_tag, live)) return live; + const marked_len = live.len + dirty_marker.len; + if (saved_tag.len >= marked_len and std.mem.eql(u8, saved_tag[live.len..marked_len], dirty_marker)) + return saved_tag[0..marked_len]; + return live; +} + +pub fn restoreTailAt( + p: *Pardes, + pane: *Pane, + saved_tag: []const u8, + pfx: []const u8, + class: TailClass, +) void { + if (!std.mem.startsWith(u8, saved_tag, pfx)) return; + const rest = saved_tag[pfx.len..]; + const said = std.mem.trimStart(u8, rest, " "); + const defaults: []const []const u8 = switch (class) { + .generic => &.{ pdf_pane_tail, pane_tail, pre_close_last_pdf_pane_tail, pre_close_last_pane_tail, pre_collapse_pdf_pane_tail, pre_collapse_pane_tail, pre_column_pdf_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, + .file => &.{ context_pane_tail, file_pane_tail, pre_close_last_file_pane_tail, pre_collapse_file_pane_tail, pre_column_file_pane_tail, prev_file_pane_tail, legacy_file_pane_tail }, + .output => &.{ + locations_pane_tail, + file_pane_tail, + pre_close_last_file_pane_tail, + pre_close_last_pane_tail, + prev_file_pane_tail, + legacy_file_pane_tail, + pane_tail, + prev_pane_tail, + legacy_pane_tail, + pre_column_file_pane_tail, + pre_column_pane_tail, + pre_collapse_file_pane_tail, + pre_collapse_pane_tail, + }, + .terminal => &.{ terminal_pane_tail, pre_close_last_terminal_pane_tail, pre_close_last_pane_tail, pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail, pre_column_terminal_pane_tail, pre_tty_terminal_pane_tail, prev_terminal_pane_tail, legacy_terminal_pane_tail, pane_tail, pre_collapse_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, + }; + for (defaults) |default| + if (std.mem.eql(u8, said, std.mem.trimStart(u8, default, " "))) return; + pane.tag.own = p.gpa.dupe(u8, rest) catch return; +} + +/// The span a header's selection covers on line `row` of its text, in +/// that line's bytes: up to the caret while typing, and over the +/// cursor's own cell too in normal mode, where a cursor is a cell. +pub fn headerSelection(t: *const Text, text: []const u8, row: usize) ?struct { lo: usize, hi: usize } { + if (!t.vsel.active) return null; + const anchor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) }); + const cursor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); + const lo = @min(anchor, cursor); + const hi = if (t.mode == .insert) @max(anchor, cursor) else modal.nextGrapheme(text, @max(anchor, cursor)); + const start = modal.lineStartOffset(text, row); + const end = modal.lineEndOffset(text, row); + if (hi <= start or lo >= end) return null; + return .{ .lo = @max(lo, start) - start, .hi = @min(hi, end) - start }; +} diff --git a/test/column_drag.zig b/test/column_drag.zig index f128aa61..feea1bf7 100644 --- a/test/column_drag.zig +++ b/test/column_drag.zig @@ -37,7 +37,7 @@ fn expectOrder(p: *Pardes, before: []const Snapshot, order: []const usize) !void try std.testing.expectEqual(saved.serial, p.col_serial[column]); try std.testing.expectEqual(saved.count, p.col_n[column]); try std.testing.expectEqualSlices(usize, saved.panes[0..saved.count], p.col_panes[column][0..p.col_n[column]]); - try std.testing.expectEqualStrings(saved.tag, p.columnTag(column)); + try std.testing.expectEqualStrings(saved.tag, pardes.tagline.columnTag(p, column)); } } @@ -67,7 +67,7 @@ test "column grip drag moves only its interval and keeps tag caret with the colu _ = try p.render(frame.allocator()); var before: [4]Snapshot = undefined; for (&before, 0..) |*saved, column| { - saved.* = .{ .weight = p.col_weight[column], .serial = p.col_serial[column], .count = p.col_n[column], .tag = p.columnTag(column) }; + saved.* = .{ .weight = p.col_weight[column], .serial = p.col_serial[column], .count = p.col_n[column], .tag = pardes.tagline.columnTag(p, column) }; @memcpy(saved.panes[0..saved.count], p.col_panes[column][0..saved.count]); } const layer = try tagLayer(p, 1); @@ -75,8 +75,8 @@ test "column grip drag moves only its interval and keeps tag caret with the colu p.update(.{ .mouse = headerMouse(layer, 10, .press) }); p.update(.{ .mouse = headerMouse(layer, 10, .release) }); try std.testing.expectEqual(@as(?usize, 1), p.header_column); - const caret = p.focusedHeader().?.cur_col; - const anchor = p.focusedHeader().?.vsel; + const caret = pardes.tagline.focusedHeader(p).?.cur_col; + const anchor = pardes.tagline.focusedHeader(p).?.vsel; const scroll = p.header_scroll; const target = p.col_x[3] + p.col_w[3] - 2; const last_rect = p.rects[p.col_panes[3][0]]; @@ -93,14 +93,14 @@ test "column grip drag moves only its interval and keeps tag caret with the colu try expectOrder(p, &before, &.{ 0, 2, 3, 1 }); try std.testing.expectEqual(active, p.active); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); - try std.testing.expectEqual(anchor, p.focusedHeader().?.vsel); + try std.testing.expectEqual(caret, pardes.tagline.focusedHeader(p).?.cur_col); + try std.testing.expectEqual(anchor, pardes.tagline.focusedHeader(p).?.vsel); try std.testing.expectEqual(scroll, p.header_scroll); // The old tag envelope must not edit the new occupant of its old index, // including the interval before hosts request another rendered frame. p.update(.{ .mouse = stale }); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); + try std.testing.expectEqual(caret, pardes.tagline.focusedHeader(p).?.cur_col); _ = try p.render(frame.allocator()); try std.testing.expectEqual(before[1].serial, (try tagLayer(p, 3)).serial); try std.testing.expectEqual(p.col_w[3] - pardes.TAG_TEXT_INSET, (try tagLayer(p, 3)).viewport.w); @@ -110,7 +110,7 @@ test "column grip drag moves only its interval and keeps tag caret with the colu mouse(p, .release, back); try expectOrder(p, &before, &.{ 0, 1, 2, 3 }); try std.testing.expectEqual(@as(?usize, 1), p.header_column); - try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); + try std.testing.expectEqual(caret, pardes.tagline.focusedHeader(p).?.cur_col); try std.testing.expectEqual(active, p.active); // A structural change between press and release must not retarget the // in-flight drag to whichever column now occupies the original index. @@ -165,7 +165,7 @@ test "column grip is separate from compact text and the resize seam" { try std.testing.expect(p.drag != .column_move); try std.testing.expect(p.header_drag); p.update(.{ .mouse = headerMouse(layer, 0, .release) }); - try std.testing.expectEqual(@as(i32, 0), p.focusedHeader().?.cur_col); + try std.testing.expectEqual(@as(i32, 0), pardes.tagline.focusedHeader(p).?.cur_col); mouse(p, .press, p.col_x[1] + config.GUTTER - 1); try std.testing.expect(p.drag == .column_move); mouse(p, .release, p.col_x[1] + config.GUTTER - 1); diff --git a/test/fs_bench.zig b/test/fs_bench.zig index a816ebbd..da9da47c 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -65,7 +65,7 @@ const Session = struct { .file_id = id, .file_serial = pane.serial, .body_bytes = pane.file.?.content.len, - .tag = try core.tagText(backing, pane), + .tag = try pardes.tagline.tagText(core, backing, pane), }; } diff --git a/test/mode.zig b/test/mode.zig index c429ea72..c7d7d548 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -11,7 +11,7 @@ fn mode(p: *Pardes, id: usize, expected: panes.Text.Mode) !void { fn clickModeTag(p: *Pardes) !void { const pane = p.panes[0].?; - const text = try p.tagText(p.scratch.allocator(), pane); + const text = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); const col = std.mem.indexOf(u8, text, "Mode") orelse return error.MissingModeTag; const rect = p.rects[0]; const row = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; @@ -33,7 +33,7 @@ test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); - try std.testing.expect(std.mem.indexOf(u8, try p.tagText(p.scratch.allocator(), pane), " Mode") != null); + try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, p.scratch.allocator(), pane), " Mode") != null); try mode(p, 0, .normal); try mode(p, 0, .insert); // A clicked tag is typed into; its execute key is a normal-mode key, as @@ -67,7 +67,7 @@ test "Mode from actual tag Exec preserves parked file and output insert transact p.presentation.enabled = false; const pane = try p.setTestFile("ab\n"); if (output) pane.file.?.output = .{ .from = .search }; - try std.testing.expect(std.mem.indexOf(u8, try p.tagText(p.scratch.allocator(), pane), " Mode") == null); + try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, p.scratch.allocator(), pane), " Mode") == null); try customTag(pane, " Mode"); try mode(p, 0, .insert); p.update(.{ .key = .{ .cp = '界', .text = "界" } }); diff --git a/test/panes.zig b/test/panes.zig index 4804c497..954e431b 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -15,7 +15,7 @@ const filesystem = pardes.filesystem; /// The tag's caret as a byte offset into the tag as it is shown, prefix /// included. fn tagCaret(p: *Pardes, pane: *Pane) !usize { - return (try p.tagPrefix(pane)).len + @as(usize, @intCast(pane.tag.cur_col)); + return (try pardes.tagline.tagPrefix(p, pane)).len + @as(usize, @intCast(pane.tag.cur_col)); } fn setTag(pane: *Pane, text: []const u8) !void { @@ -52,7 +52,7 @@ const TagLayerTests = struct { defer frame.deinit(); _ = try p.render(frame.allocator()); const layer = try findLayer(p, .pane, 0); - const text = try p.tagText(frame.allocator(), pane); + const text = try pardes.tagline.tagText(p, frame.allocator(), pane); const at = std.mem.indexOf(u8, text, "END").?; const col = panes.File.displayWidth(text[0..at]); try std.testing.expect(col > p.rects[0].w); @@ -70,7 +70,7 @@ const TagLayerTests = struct { try std.testing.expectEqual(at, try tagCaret(p, pane)); p.update(.{ .key = .{ .cp = 'X', .text = "X" } }); _ = try p.render(frame.allocator()); - const edited = try p.tagText(frame.allocator(), pane); + const edited = try pardes.tagline.tagText(p, frame.allocator(), pane); try std.testing.expect(std.mem.endsWith(u8, edited, "界 XEND")); try std.testing.expectEqual(@as(u16, 0), pane.tag_scroll); try std.testing.expectEqualStrings("body\n", pane.file.?.content); @@ -140,7 +140,7 @@ const TagLayerTests = struct { try setTag(left, " " ++ "a" ** 110); _ = try p.render(frame.allocator()); const left_layer = try findLayer(p, .pane, 0); - const left_text = try p.tagText(frame.allocator(), left); + const left_text = try pardes.tagline.tagText(p, frame.allocator(), left); const start_x = @as(f32, @floatFromInt(left_layer.viewport.x)) * 10 + 12.5; const beyond_x = edge + 12.5; p.update(.{ .mouse = mouse(left_layer, start_x, .press) }); @@ -161,7 +161,7 @@ const TagLayerTests = struct { const x = @as(f32, @floatFromInt(header.viewport.x)) * 10 + 62.5 * 5; p.update(.{ .mouse = mouse(header, x, .press) }); p.update(.{ .mouse = mouse(header, x, .release) }); - try std.testing.expectEqual(@as(i32, 63), p.focusedHeader().?.cur_col); + try std.testing.expectEqual(@as(i32, 63), pardes.tagline.focusedHeader(p).?.cur_col); if (kind == .column) try std.testing.expectEqual(@as(?usize, 1), p.header_column) else try std.testing.expect(p.header_column == null); p.update(.{ .key = .{ .cp = Key.escape } }); } @@ -184,7 +184,7 @@ test "a tag with a newline in it is as tall as its lines, and each line is typed p.update(.{ .key = .{ .cp = 'A' } }); p.update(.{ .key = .{ .cp = Key.enter } }); p.update(.{ .key = .{ .cp = 'S', .text = "Second" } }); - try std.testing.expect(std.mem.endsWith(u8, Pardes.curTail(pane), "\nSecond")); + try std.testing.expect(std.mem.endsWith(u8, pardes.tagline.curTail(pane), "\nSecond")); try std.testing.expectEqual(@as(u16, 2), pane.tag_rows); // The pane keeps its height; the body gives the tag its row. try std.testing.expectEqual(height, p.rects[0].h); @@ -252,7 +252,7 @@ const TagNavigationTests = struct { // Nothing to remember yet: `:` lands on Save, in normal mode. key(p, ':'); try std.testing.expect(first.focus == .tag and first.tag.mode == .normal); - const tail = Pardes.curTail(first); + const tail = pardes.tagline.curTail(first); try std.testing.expectEqualStrings("Save", tail[@intCast(first.tag.cur_col)..][0..4]); key(p, Key.home); for (0..3) |_| key(p, Key.right); @@ -278,7 +278,7 @@ const TagNavigationTests = struct { _ = try p.render(frame.allocator()); const rect = p.rects[0]; const y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; - const prefix: u16 = @intCast(panes.File.displayWidth(try p.tagPrefix(first))); + const prefix: u16 = @intCast(panes.File.displayWidth(try pardes.tagline.tagPrefix(p, first))); ClickCursorTests.click(p, .left, rect.x + pardes.TAG_TEXT_INSET + prefix + 6, y); try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expect(first.focus == .tag and first.tag.mode == .insert); @@ -316,7 +316,7 @@ const TagNavigationTests = struct { try std.testing.expectEqual(chord == Key.tab, saved); // ...and the tag still knows where it was. key(p, ':'); - try std.testing.expectEqualStrings("Save", Pardes.curTail(pane)[@intCast(pane.tag.cur_col)..][0..4]); + try std.testing.expectEqualStrings("Save", pardes.tagline.curTail(pane)[@intCast(pane.tag.cur_col)..][0..4]); } } @@ -403,14 +403,14 @@ const TagNavigationTests = struct { key(p, ':'); key(p, 'i'); key(p, Key.end); - const before = Pardes.curTail(pane).len; + const before = pardes.tagline.curTail(pane).len; try std.testing.expect(pane.focus == .tag and pane.tag.mode == .insert and pane.body.mode == .normal); for ("hjklHJKL:") |letter| { const text = [_]u8{letter}; p.update(.{ .key = .{ .cp = letter, .text = &text } }); try std.testing.expect(pane.focus == .tag and pane.tag.mode == .insert); } - try std.testing.expectEqualStrings("hjklHJKL:", Pardes.curTail(pane)[before..]); + try std.testing.expectEqualStrings("hjklHJKL:", pardes.tagline.curTail(pane)[before..]); try std.testing.expectEqualStrings("body\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), p.active); } @@ -1187,7 +1187,7 @@ const TagNameTintTests = struct { var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const surface = try p.render(arena.allocator()); - const text = try p.tagText(arena.allocator(), pane); + const text = try pardes.tagline.tagText(p, arena.allocator(), pane); const base = std.mem.lastIndexOfScalar(u8, name, '/') orelse return error.MissingDirectory; const rect = p.rects[id]; const y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; @@ -1235,7 +1235,7 @@ const TagNameTintTests = struct { configure(p); defer p.custom_theme = null; const name = "/a/very/long/directory/that/extends/past/the/tag/界e\u{301}name-with-a-long-tail.zig"; - p.draftName(pane, 0); + pardes.tagline.draftName(p, pane, 0); redraft(pane, name); pane.input.cur_col = @intCast(std.mem.indexOf(u8, name, "界").?); try std.testing.expect((try check(p, 0, name)) > 0); @@ -1304,7 +1304,7 @@ test "pane filename drafts commit and cancel without changing body or command ta const original = try p.gpa.dupe(u8, pane.file.?.path); defer p.gpa.free(original); try pane.appendTag(" SyntaxBold"); - const tail = try p.gpa.dupe(u8, Pardes.curTail(pane)); + const tail = try p.gpa.dupe(u8, pardes.tagline.curTail(pane)); defer p.gpa.free(tail); for ([_]bool{ false, true }) |commit| { clickPathEnd(p, pane); @@ -1312,13 +1312,13 @@ test "pane filename drafts commit and cancel without changing body or command ta p.update(.{ .paste = "/new name.zig" }); try std.testing.expectEqualStrings(original, pane.file.?.path); try std.testing.expectEqualStrings("/new name.zig", pane.input.own.?); - try std.testing.expectEqualStrings(tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tail, pardes.tagline.curTail(pane)); try std.testing.expectEqualStrings("original body\n", pane.file.?.content); p.update(.{ .key = .{ .cp = if (commit) Key.enter else Key.escape } }); try std.testing.expect(pane.focus == .body); try std.testing.expect(pane.prompt == .none); try std.testing.expectEqualStrings(if (commit) "/new name.zig" else original, pane.file.?.path); - try std.testing.expectEqualStrings(tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tail, pardes.tagline.curTail(pane)); while (p.nextEffect()) |effect| try std.testing.expect(std.meta.activeTag(effect) != .save_file); } try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); @@ -1351,13 +1351,13 @@ test "leaving a pane or entering a header cancels an uncommitted filename" { const pane = try p.setTestFile("untouched\n"); for ([_]bool{ false, true }) |header| { p.active = 0; - p.exitHeader(); + pardes.tagline.exitHeader(p); p.update(.tick); clickPathEnd(p, pane); p.update(.{ .paste = "/draft" }); try std.testing.expect(pane.prompt == .name); if (header) { - p.enterHeader(null); + pardes.tagline.enterHeader(p, null); p.update(.tick); } else { try std.testing.expect(p.executeBuiltinLine(0, "New")); @@ -1379,7 +1379,7 @@ test "middle clicking Save commits the drafted filename before issuing a save" { var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); _ = try p.render(arena.allocator()); - const text = try p.tagText(arena.allocator(), pane); + const text = try pardes.tagline.tagText(p, arena.allocator(), pane); const save_at = std.mem.indexOf(u8, text, "Save").?; const x: u16 = @intCast(p.rects[0].x + pardes.TAG_TEXT_INSET + save_at - pane.tag_scroll); const y = p.rects[0].y; @@ -1421,15 +1421,15 @@ test "paste into pane commands and prompts never inserts into the body" { p.update(.{ .key = .{ .cp = 'A' } }); // A tag takes a paste as a body does, newline and all. p.update(.{ .paste = " Custom\nCommand" }); - try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); + try std.testing.expect(std.mem.indexOf(u8, pardes.tagline.curTail(pane), " Custom\nCommand") != null); p.update(.{ .key = .{ .cp = Key.escape } }); p.startPrompt(pane, .{ .search = config.search_marker }); p.update(.{ .paste = "t\r\nwo" }); try std.testing.expectEqualStrings(config.search_marker ++ "two", pane.promptText().?); - try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); + try std.testing.expect(std.mem.indexOf(u8, pardes.tagline.curTail(pane), " Custom\nCommand") != null); try std.testing.expectEqualStrings("one two one\n", pane.file.?.content); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); + try std.testing.expect(std.mem.indexOf(u8, pardes.tagline.curTail(pane), " Custom\nCommand") != null); } test "long pane tags reveal commands and map visible clicks to whole tag addresses" { @@ -1446,7 +1446,7 @@ test "long pane tags reveal commands and map visible clicks to whole tag address const surface = try p.render(arena.allocator()); try std.testing.expect(pane.tag_scroll > 0); try std.testing.expect(surface.cursor.?.x < p.rects[0].x + p.rects[0].w); - const text = try p.tagText(p.gpa, pane); + const text = try pardes.tagline.tagText(p, p.gpa, pane); defer p.gpa.free(text); const offset = std.mem.indexOf(u8, text, "SyntaxBold").?; const x: u16 = @intCast(p.rects[0].x + pardes.TAG_TEXT_INSET + panes.File.rawDisplayCol(text, offset) - pane.tag_scroll); @@ -1455,7 +1455,7 @@ test "long pane tags reveal commands and map visible clicks to whole tag address p.update(.{ .mouse = .{ .col = x, .row = y, .button = config.exec_button, .kind = .press } }); p.update(.{ .mouse = .{ .col = x, .row = y, .button = config.exec_button, .kind = .release } }); try std.testing.expectEqual(!before, p.settings.syntax_bold); - try std.testing.expectEqualStrings(text, try p.tagText(p.scratch.allocator(), pane)); + try std.testing.expectEqualStrings(text, try pardes.tagline.tagText(p, p.scratch.allocator(), pane)); } test "terminal overlay recoloring never materializes unrelated history" { @@ -4155,7 +4155,7 @@ test "cancelled normal gestures leave no count or subprefix after mouse and focu const tag_y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; const body_y = p.bodyTop(pane, rect); const x = if (gesture == .tag) - rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(try p.tagPrefix(pane)))) + 3 + rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(try pardes.tagline.tagPrefix(p, pane)))) + 3 else rect.x + config.GUTTER + @as(u16, @intCast(panes.File.gutterWidth(pane))) + 3; const y = if (gesture == .tag) tag_y else body_y; diff --git a/test/pdf.zig b/test/pdf.zig index 745ecb1a..3a592451 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -612,7 +612,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_y); try std.testing.expectEqual(@as(u16, 8), p.cell_pixels.w); try std.testing.expectEqual(@as(u16, 16), p.cell_pixels.h); - const initial_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const initial_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); const expected_tag = try std.fmt.allocPrint(p.scratch.allocator(), "{s} [1/{d}]{s}", .{ pane.pdf.?.path, pane.pdf.?.page_count, pane_tail }); try std.testing.expectEqualStrings(expected_tag, initial_tag); try std.testing.expect(std.mem.endsWith(u8, initial_tag, pane_tail)); @@ -833,7 +833,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { revision_before_toggle, panes.Pdf.rasterForPage(&pane.pdf.?, pane.pdf.?.page).?.revision, ); - const height_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const height_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); const expected_height_tag = try std.fmt.allocPrint(p.scratch.allocator(), "{s} [{d}/{d}]{s}", .{ pane.pdf.?.path, pane.pdf.?.page + 1, pane.pdf.?.page_count, pane_tail }); try std.testing.expectEqualStrings(expected_height_tag, height_tag); for (p.panes) |slot| { @@ -1250,7 +1250,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { return error.MissingPdfTintBuiltin; try std.testing.expectEqual(PdfTintMode.filtered, pv.tint); - const initial_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const initial_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.startsWith(u8, initial_tag, pv.path)); try std.testing.expect(std.mem.endsWith(u8, initial_tag, " PdfSections PdfTint Collapse Del")); try std.testing.expect(std.mem.indexOf(u8, initial_tag, "filtered") == null); @@ -1263,7 +1263,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { null, )); try std.testing.expectEqual(PdfTintMode.full, pv.tint); - const full_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const full_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expectEqualStrings(initial_tag, full_tag); try std.testing.expect(std.mem.indexOf(u8, full_tag, "full") == null); @@ -1291,7 +1291,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { null, )); try std.testing.expectEqual(PdfTintMode.disabled, pv.tint); - const disabled_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const disabled_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expectEqualStrings(initial_tag, disabled_tag); try std.testing.expect(std.mem.indexOf(u8, disabled_tag, "disabled") == null); try std.testing.expect(pardes.test_api.runBuiltin( -- cgit v1.3 From f5eaddb2cf28a9b72d5dd5b3b10502a316d4de85 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 09:41:55 -0300 Subject: Split control messages by scope: the root ctl takes the session's builtins and reads the settings, a pane's ctl its own Every builtin could only be clicked, or written to exec, and the settings could be read only as the Config window's prose. acme keeps window verbs on a window's ctl, and webfs and upas/fs keep session settings on a root ctl. Each builtin now declares its scope (scope = .session; settings are all session, the rest pane), read by the registry. The root /ctl takes session builtins and reads every setting in the words a write takes, so its read written back changes nothing (panel and scene effects now take on/off like the toggles, to make that true); a pane's ctl takes the pane's builtins beside get, lock and unlock. Writes are checked whole and refused in Plan 9's ctl words (unknown control message "X", wrong #args ...), which 9ns now maps to EINVAL (cloud9 re-pinned at a8c7a715). A builtin that would prompt for its argument fails the write instead, and a refusal is answered at once, not after the frame. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 11 +- build.zig.zon | 4 +- docs/fs.md | 31 ++++- src/9p_io.zig | 4 + src/builtins.zig | 59 +++++++++- src/config.zig | 83 ++++++++----- src/fs-help.txt | 4 +- src/fs.zig | 7 ++ src/ninep/ctl.zig | 237 +++++++++++++++++++++++++++++++++++--- src/ninep/tree.zig | 8 +- src/pardes.zig | 6 + test/fs.py | 20 +++- 12 files changed, 412 insertions(+), 62 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 5e2280f9..5540db5f 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -53,6 +53,8 @@ $m/log recent events, then EOF: new|del|rename|save , msg $m/screen the rendered screen as JSON, frozen per open $m/listeners this session's dial addresses $m/focus the serial of the pane with the keyboard; echo a serial into it to move the keyboard +$m/ctl the settings, one a line as a write takes them; write a setting or a session builtin + (Newcol, Dump, Kill, Theme x); a pane's builtins (Del, Save f) go to $m/pane//ctl $m/pane/new open it to make a pane, read names it; rmdir $m/pane/ closes it $m/os/ the host filesystem ``` @@ -131,8 +133,13 @@ written until someone writes or truncates it, so writing an address and reading it back evaluates it, and two clients addressing the same pane will interfere. `$pane/ctl` reads acme's window status line — serial, tag length, body length, a reserved zero, the dirty flag, the width in cells, the font and the tab -width, then `current` or `notcurrent` — and takes `get` (reload from disk) and -`lock`/`unlock`. The lock binds only clients that take it, and is held by the +width, then `current` or `notcurrent` — and takes `get` (reload from disk), +`lock`/`unlock`, and any builtin that acts on a pane (`Del`, `Save f`, +`Collapse`). Session builtins and settings go to the root `ctl`, which reads +back every setting in the syntax it takes. A ctl write is checked whole +first and refused as `unknown control message "X"` (EINVAL) and the like; a +builtin that would open a prompt (`Save` on a scratch, bare `Find`) fails +there instead of prompting. The lock binds only clients that take it, and is held by the open that wrote it, so a shell holds an fd across the edit: `exec 3>$pane/ctl; echo lock >&3; ...; exec 3>&-`. diff --git a/build.zig.zon b/build.zig.zon index 165e9b54..4cfba514 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,8 +9,8 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#cca47d63c3ba774cb4de6f76603ba6edc5b475fe", - .hash = "cloud9-0.1.0-yt86qobpHQDOvgZw-CSB4UHvMmtpp-N4IG0XyTbJlS2y", + .url = "git+https://git.sr.ht/~gbrls/cloud9#a8c7a7158cc9d3bde78e34db6de11c084fde3d65", + .hash = "cloud9-0.1.0-yt86qjLsHQC_9qrMuOQEcDOan4KTH6ermuxZvm0kgwpL", }, // ZLS as a LIBRARY, not a language server: src/lsp_zls.zig imports the // `zls` module its build.zig publishes and calls the analyser in diff --git a/docs/fs.md b/docs/fs.md index c2819adb..b3f3cb45 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -81,6 +81,7 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. /screen rendered screen JSON; frozen per open handle /listeners the session's dial addresses /focus the serial of the pane with the keyboard; write a serial to give it the keyboard +/ctl the settings, one a line as a write takes them; write a setting or a session builtin /pane/new open it to make a pane; the read answers that pane's serial /pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec, plus pty/{ctl,status,data} on terminals @@ -88,6 +89,33 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. /src/ the editor's embedded sources, only when built with -Dembed-sources=true ``` +Control messages are split by what they act on, as acme keeps window verbs +on a window's ctl and webfs and upas/fs keep session settings on a root ctl. +Each builtin declares its scope in src/builtins.zig (`scope = .session`; +every setting is one, the rest act on a pane). `/ctl` takes the session's +builtins, one a line, at whichever pane has the keyboard as each runs -- +`Newcol`, `Dump`, `Kill`, `Mount name dial`, `Theme ink`, `Verbose off` -- +and reads every setting there is, one a line, in the words a write of it +takes (`Verbose on`, `WindowOpacity 70`, `PanelSlide off`, `DumpDir` bare +for the default directory, `LocationsConfig ...`), so writing what it reads +back changes nothing; platform and startup facts are `/status`'s and the +Config window's, not settings. A pane's `ctl` takes the builtins that act on +a pane (`Del`, `Save f`, `Collapse`, `Find pat`) beside acme's `get`, `lock` +and `unlock`. The words are case-sensitive and do not alias: acme's verbs +are lowercase and the builtins keep their tag spelling, so `Get` is no word +and `del` none either. A write is checked whole before any line runs, and a +line is refused in Plan 9's words for a ctl (kernel/misc/parse.c:82-97): +`unknown control message "X"`, `wrong #args in control message "X"` for an +argument to a builtin that takes none, `bad value in control message "X"` +for a setting's value it does not take, and `not a session control message +"X"` or `not a window control message "X"` for a word of the other ctl; 9ns +maps them all to EINVAL. A builtin that would ask at a prompt for its +argument (`Save` on a scratch, `Find` bare) fails the write with `control +message needs its argument` rather than open one nobody is there to answer, +though a click on the same word written to `exec` still opens it. Like any +write, a ctl write answers once the editor has performed what it asked for +(a save written, a shell started). + `/focus` reads the serial of the pane with the keyboard, and a serial written to it gives that pane the keyboard, off any column or workspace tag that had it -- rio's `current` written to a window's `wctl`, named once for the whole @@ -161,7 +189,8 @@ pane's Look and Exec clicks to that client; writing a record back performs the action. `ctl` reads acme's window status line — serial, tag length, body length, a reserved zero, the dirty flag, the width in cells, the font and the tab width — followed by rio's `current` or `notcurrent` (rio(4), `wctl`): -whether the pane has the keyboard. It takes `get`, which reloads the buffer from the name it +whether the pane has the keyboard. It takes the pane's builtins (below), +`get`, which reloads the buffer from the name it carries, and acme's `lock` and `unlock` (editors/acme/xfid.c:603-611), for an edit of several writes to `addr` and `data` that another client must not land in the middle of. As in acme the lock binds only the clients that take diff --git a/src/9p_io.zig b/src/9p_io.zig index 7b0976bc..02b9efb5 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -258,6 +258,10 @@ pub const Listener = struct { // file written. A change carries no payload, so the reply is still // whole after the wait. l.kick(); + // A refusal answers at once: its text may be in the core's one + // buffer for it, which a request run while this one waited would + // write over. + if (reply.status == .err) return conn.reply(&reply, ""); const restoring = core.restore_req != null; if (core.effects_len != 0) pardes.turn.awaitSettled(epoch); // Once a wait returns `core` may be gone: a Restore meanwhile put a diff --git a/src/builtins.zig b/src/builtins.zig index ffb00ff6..ed0a07dd 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -30,6 +30,14 @@ pub const capabilities: config.Runtime.Capabilities = .{ .ligatures = pardes.platform == .gui, }; +/// Where a builtin acts: at the pane it runs from, or on the editor as a +/// whole. acme keeps its window verbs on a window's ctl and its session +/// commands elsewhere, as webfs and upas/fs keep session settings on a root +/// ctl; pardes's root `ctl` takes the session builtins and a pane's `ctl` +/// the pane ones. A builtin says `pub const scope: Scope = .session;`, +/// and every setting is one; the rest act on their pane. +pub const Scope = enum { pane, session }; + pub const Ctx = struct { p: *Pardes, pane: *Pane, @@ -133,9 +141,14 @@ pub const registry = struct { pub fn takesArg(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| if (@intFromEnum(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return setting.takesArg(); - unreachable; + // Every setting takes its value, and a switch flips when bare. + return true; + } + + pub fn scope(b: Builtin()) Scope { + inline for (manualBuiltinList(), 0..) |T, i| + if (@intFromEnum(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; + return .session; // a setting } pub fn outputTraits(b: Builtin()) ?OutputTraits { @@ -173,6 +186,17 @@ test "capabilities exactly gate setting and effect-source builtins" { try std.testing.expectEqual(EffectCode.enabled, effect_code_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 "Look does not announce itself on the message row; Del still does" { const Builtin = registry.Builtin(); try std.testing.expect(!registry.announces(Builtin.Look)); @@ -233,6 +257,7 @@ pub const Exec = struct { // ---- session ---- pub const Kill = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { c.p.quit = true; c.p.emit(.quit); @@ -240,12 +265,14 @@ pub const Kill = struct { }; pub const Dump = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { dump.dumpState(c.p) catch {}; } }; pub const Restore = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub fn run(c: Ctx) void { const path = c.arg orelse (c.p.last_dump orelse return); @@ -256,6 +283,7 @@ pub const Restore = struct { }; pub const Attach = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { @@ -270,6 +298,7 @@ pub const Attach = struct { }; pub const Detach = struct { + pub const scope: Scope = .session; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { if (comptime enabled) @@ -280,6 +309,7 @@ pub const Detach = struct { }; pub const Mount = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { @@ -293,6 +323,7 @@ pub const Mount = struct { }; pub const Unmount = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { @@ -318,12 +349,14 @@ pub const Msg = struct { }; pub const NextColor = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { colors.setThemeIndex(c.p, (@as(usize, c.p.settings.theme) + 1) % pardes.themes.len); } }; pub const ThemeSel = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.themes_buffer, .steps = true, .commands = true }; pub fn run(c: Ctx) void { panes.Output.openThemes(c.p, c.id) catch |err| c.p.reportError(c.id, "themes", err); @@ -331,6 +364,7 @@ pub const ThemeSel = struct { }; pub const ThemeFile = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { @@ -342,6 +376,7 @@ pub const ThemeFile = struct { }; pub const DumpThemes = struct { + pub const scope: Scope = .session; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime enabled) { @@ -355,6 +390,7 @@ pub const DumpThemes = struct { }; pub const FontSel = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.fonts_buffer, .steps = true, .commands = true }; pub const enabled = capabilities.font_picker; pub fn run(c: Ctx) void { @@ -496,6 +532,7 @@ pub const New = struct { /// The same empty scratch, opened in a fresh column beside the calling pane. pub const Newcol = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { c.p.newScratchColumn(c.id); } @@ -603,12 +640,14 @@ pub const Tty9p = struct { /// Fold the active pane's column into the one on its right, keeping its panes. /// The horizontal mirror of the vertical stacking `New` does. pub const Joincol = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { layout.joinCol(c.p); } }; pub const Tutor = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { const free = c.p.freeSlot() orelse return; const nt = c.p.openTutorView(free) catch return; @@ -617,6 +656,7 @@ pub const Tutor = struct { }; pub const Help = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.help_buffer }; pub fn run(c: Ctx) void { panes.Output.openHelp(c.p, c.id, "") catch |err| c.p.reportError(c.id, "help", err); @@ -624,6 +664,7 @@ pub const Help = struct { }; pub const Config = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.config_buffer }; pub fn run(c: Ctx) void { panes.Output.openConfig(c.p, c.id) catch |err| c.p.reportError(c.id, "config", err); @@ -631,6 +672,7 @@ pub const Config = struct { }; pub const LocationsConfig = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const output: OutputTraits = .{ .name = "+LocationsConfig" }; @@ -660,6 +702,7 @@ pub const LocationsConfig = struct { }; pub const Messages = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.messages_buffer }; pub fn run(c: Ctx) void { panes.Output.openMessages(c.p, c.id) catch |err| c.p.reportError(c.id, "messages", err); @@ -669,6 +712,7 @@ pub const Messages = struct { /// This build's version and what changed to reach it, printed into an output /// buffer the same way Config prints the live settings. pub const Changelog = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.changelog_buffer }; pub fn run(c: Ctx) void { panes.Output.openChangelog(c.p, c.id) catch |err| c.p.reportError(c.id, "changelog", err); @@ -676,6 +720,7 @@ pub const Changelog = struct { }; pub const EffectCode = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = capabilities.panel_transitions or capabilities.scene_shaders; pub const output: OutputTraits = .{ .name = config.effect_code_buffer }; @@ -690,6 +735,7 @@ pub const EffectCode = struct { /// An optional SDL workspace-tag companion; never consumes input or text cells. pub const Pet = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = pardes.platform == .gui; pub fn run(c: Ctx) void { @@ -793,6 +839,7 @@ pub const Right = struct { /// Ctrl-o: one step back into the history. pub const Back = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { c.p.jumpBy(-1); } @@ -800,6 +847,7 @@ pub const Back = struct { /// Ctrl-i: one step forward again, up to wherever Back started. pub const Forward = struct { + pub const scope: Scope = .session; pub fn run(c: Ctx) void { c.p.jumpBy(1); } @@ -821,6 +869,7 @@ pub const Last = struct { }; pub const Jumplist = struct { + pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.jumps_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { panes.Output.openJumps(c.p, c.id) catch |err| c.p.reportError(c.id, "jumplist", err); @@ -920,6 +969,7 @@ pub const Lspwhy = struct { }; pub const Peek = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = Board.enabled; pub const output: OutputTraits = .{ .name = config.peek_buffer }; @@ -932,6 +982,7 @@ pub const Peek = struct { }; pub const Poke = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = Board.enabled; pub fn run(c: Ctx) void { @@ -943,6 +994,7 @@ pub const Poke = struct { }; pub const Hexdump = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = Board.enabled; pub const output: OutputTraits = .{ .name = config.hexdump_buffer }; @@ -955,6 +1007,7 @@ pub const Hexdump = struct { }; pub const Gpio = struct { + pub const scope: Scope = .session; pub const takes_arg = true; pub const enabled = Board.enabled; pub const output: OutputTraits = .{ .name = config.gpio_buffer }; diff --git a/src/config.zig b/src/config.zig index 8c37a7ce..f898df11 100644 --- a/src/config.zig +++ b/src/config.zig @@ -705,15 +705,6 @@ pub const Runtime = struct { action: Action, availability: ?Capability = null, - pub fn takesArg(setting: Setting) bool { - return switch (setting.action) { - // A toggle flips when it is a bare tagline word and SETS when - // it is given `on` or `off`, so the report is configuration. - .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .dump_dir, .toggle => true, - else => false, - }; - } - pub fn enabled(setting: Setting, capabilities: Capabilities) bool { const capability = setting.availability orelse return true; return switch (capability) { @@ -831,15 +822,7 @@ pub const Runtime = struct { // it SETS, so the report `writeReport` prints (`Verbose on`) can // be fed straight back as configuration and mean what it says. .toggle => |field| { - const text = std.mem.trim(u8, argument orelse "", " \t\r\n"); - const want: ?bool = if (text.len == 0) - null - else if (std.mem.eql(u8, text, "on")) - true - else if (std.mem.eql(u8, text, "off")) - false - else - return false; + const want = switchedTo(argument) catch return false; switch (field) { inline else => |f| @field(state, @tagName(f)) = want orelse !@field(state, @tagName(f)), } @@ -881,18 +864,42 @@ pub const Runtime = struct { inline else => |w| @field(state, "message_" ++ @tagName(w) ++ "_ms") = ms, } }, - .transition => |effect| state.toggleTransition(effect), - .scene => |effect| switch (effect) { - inline else => |field| { - const value = &@field(state.scene_effects, @tagName(field)); - value.* = !value.*; - }, + // Panel effects are one choice, so `on` picks this one and `off` + // turns it off only if it is the one on. + .transition => |effect| { + const want = switchedTo(argument) catch return false; + if (want == null) { + state.toggleTransition(effect); + } else if (want.?) { + state.panel_transition = effect; + } else if (state.panel_transition == effect) { + state.panel_transition = .off; + } + }, + .scene => |effect| { + const want = switchedTo(argument) catch return false; + switch (effect) { + inline else => |field| { + const value = &@field(state.scene_effects, @tagName(field)); + value.* = want orelse !value.*; + }, + } }, .theme, .font => return false, } return true; } + /// What `on`, `off` or nothing after a switch word asks for: null flips + /// it, as a bare tagline word does. + fn switchedTo(argument: ?[]const u8) error{NotOnOrOff}!?bool { + const text = std.mem.trim(u8, argument orelse "", " \t\r\n"); + if (text.len == 0) return null; + if (std.mem.eql(u8, text, "on")) return true; + if (std.mem.eql(u8, text, "off")) return false; + return error.NotOnOrOff; + } + // Slices are borrowed for one writeReport call. pub const ReportContext = struct { startup_config_path: ?[]const u8, @@ -1055,15 +1062,32 @@ pub const Runtime = struct { try out.print("Pet: {s}\n", .{@tagName(state.pet)}); } - test "setting names are unique and argument metadata follows actions" { + test "setting names are unique" { for (settings, 0..) |setting, i| { try std.testing.expect(setting.word.len > 0); for (settings[i + 1 ..]) |later| try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); - try std.testing.expectEqual(switch (setting.action) { - .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .dump_dir, .toggle => true, - else => false, - }, setting.takesArg()); + } + } + + test "panel and scene effects flip bare and are set by on and off" { + var state: Runtime = .{}; + const slide = findAction(.{ .transition = .slide }).?; + const zoom = findAction(.{ .transition = .zoom }).?; + try std.testing.expect(apply(&state, slide, "on")); + try std.testing.expectEqual(layout.Transition.slide, state.panel_transition); + try std.testing.expect(apply(&state, zoom, "off")); + try std.testing.expectEqual(layout.Transition.slide, state.panel_transition); + try std.testing.expect(apply(&state, slide, "on")); + try std.testing.expectEqual(layout.Transition.slide, state.panel_transition); + try std.testing.expect(apply(&state, slide, null)); + try std.testing.expectEqual(layout.Transition.off, state.panel_transition); + try std.testing.expect(!apply(&state, slide, "yes")); + const scene = findAction(.{ .scene = std.enums.values(Scene)[0] }).?; + try std.testing.expect(apply(&state, scene, "on")); + try std.testing.expect(apply(&state, scene, "on")); + switch (std.enums.values(Scene)[0]) { + inline else => |f| try std.testing.expect(@field(state.scene_effects, @tagName(f))), } } @@ -1125,7 +1149,6 @@ pub const Runtime = struct { var state: Runtime = .{}; try std.testing.expectEqual(@as(u8, 100), state.window_opacity); try std.testing.expect(state.window_opacity_pending); - try std.testing.expect(setting.takesArg()); try std.testing.expectEqual(Capability.window_opacity, setting.availability.?); for ([_][]const u8{ "0", " 85\n", "100" }, [_]u8{ 0, 85, 100 }) |argument, expected| { diff --git a/src/fs-help.txt b/src/fs-help.txt index 235ce072..f9e9c6bd 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -10,6 +10,7 @@ log recent events, one a line: new/del/rename/save , and screen rendered screen as JSON, frozen from open to close listeners the session's dial addresses focus the serial of the pane with the keyboard; write a serial to give it the keyboard +ctl the settings, one a line as a write takes them; write one, or Newcol, Dump, Kill... pane/new open it to make a pane; the read answers that pane's serial pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec, and pty/ for terminals; rmdir closes it @@ -26,7 +27,6 @@ Below, $m is the mount point (PARDES_MOUNT in a Tty9p shell; 9ns and 9p work too echo 'Msg hello' > $m/exec show text in the editor echo '#0,#5' > $m/pane/$n/addr; printf NEW >> $m/pane/$n/data replace bytes 0..5 cp $m/pane/$n/addr $m/pane/$n/dot; cat $m/pane/$n/sel select the range, read it - cat $m/pane/$n/dirty; echo 0 > $m/pane/$n/dirty is it modified? say it is not exec 3<>$m/log; echo follow >&3; cat <&3 what happened lately, then wait for more cat $m/pane/$n/event hold it open to own that pane's clicks echo exec > $m/pane/$n/pty/ctl restart a shell; also winsize C R, sig INT @@ -42,4 +42,4 @@ Pitfalls, one each: tag reads path++text; writes append to the text (newlines too); truncating clears it, and dot or addr. A terminal's body is a history snapshot frozen per open; pty/data is the live stream. A failing command is reported in the editor and in log, not as a write error; a bad line fails the write. - pane//ctl: acme's status line, then current or notcurrent; takes get (reload), lock/unlock on a held fd. + pane//ctl: acme's status line + current; takes get, lock/unlock (on a held fd) and pane builtins (Del). diff --git a/src/fs.zig b/src/fs.zig index 7e387958..339910a4 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1256,6 +1256,13 @@ pub const Namespace = struct { out: std.ArrayList(u8) = .empty, listeners: u16 = 0, origin: u8 = 'K', + /// A ctl write is running builtins: one that would open a prompt for + /// its argument refuses (`refused`), since nobody is at the prompt. + no_prompt: bool = false, + refused: bool = false, + /// A refusal that quotes the message it refuses, as Plan 9's cmderror + /// does (kernel/misc/parse.c:82); answered at once (src/9p_io.zig). + ename: [128]u8 = undefined, /// Something a held read may be waiting on changed since they were last /// answered: a record queued, a run answered, a pane gone. news: bool = false, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 5cc238a7..b43d7b20 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2,8 +2,9 @@ //! a right click on it and writing one to `exec` a middle click, at the //! active pane from the root and at that pane from /pane//; reading either //! answers the serials the last command made or touched. /status reports the -//! editor, and a pane's ctl its acme status line and the verbs no file of its -//! own would say any better: `get`, `lock` and `unlock`. +//! editor. The root ctl reads the settings and takes the session's builtins; +//! a pane's ctl reads its acme status line and takes acme's verbs `get`, +//! `lock` and `unlock` and the builtins that act on a pane. const std = @import("std"); const pardes = @import("../pardes.zig"); const look = @import("../look.zig"); @@ -11,6 +12,8 @@ const panes = @import("../panes.zig"); const config = @import("../config.zig"); const fs = @import("../fs.zig"); const tagline = @import("../tagline.zig"); +const builtins = @import("../builtins.zig"); +const exec_line = @import("../exec.zig"); const tree = @import("tree.zig"); const pane_files = @import("pane.zig"); @@ -177,6 +180,134 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { return w.buffered(); } +// ---- control messages: the builtins, by scope ---- + +const Builtin = builtins.registry.Builtin(); + +/// Refuses a control message, quoting it the way Plan 9's cmderror does +/// (kernel/misc/parse.c:82): `unknown control message "Bogus 3"`. +fn refuse(p: *Pardes, req: Req, why: []const u8, line: []const u8) Reply { + const room = p.fs.ename.len - why.len - 3; + const text = std.fmt.bufPrint(&p.fs.ename, "{s} \"{s}\"", .{ why, line[0..@min(line.len, room)] }) catch why; + return tree.failText(req.tag, E.INVAL, text); +} + +/// Checks one line written to a ctl as a builtin of `scope` before any line +/// of the write runs: a word the registry knows, of this ctl's scope, given +/// an argument only if it takes one, and for a setting a value it takes. +/// Answers the refusal, or null. Words are the builtins' own, capitalised +/// as on a tag; acme's lowercase verbs are the pane ctl's and alias none. +fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ?Reply { + const sp = std.mem.indexOfAny(u8, line, " \t"); + const word = line[0 .. sp orelse line.len]; + const arg = if (sp) |s| std.mem.trim(u8, line[s + 1 ..], " \t") else ""; + const b = std.meta.stringToEnum(Builtin, word) orelse return refuse(p, req, "unknown control message", line); + if (builtins.registry.scope(b) != scope) + return refuse(p, req, if (scope == .pane) "not a window control message" else "not a session control message", line); + if (arg.len > 0 and !builtins.registry.takesArg(b)) return refuse(p, req, "wrong #args in control message", line); + const setting = config.Runtime.find(word) orelse return null; + const takes = switch (setting.action) { + .theme => for (pardes.themes) |t| { + if (std.mem.eql(u8, t.name, arg)) break true; + } else false, + .font => config.Runtime.FontSpec.parse(arg) != null, + else => probe: { + var probe = p.settings; + break :probe probe.apply(setting, if (arg.len > 0) arg else null); + }, + }; + return if (takes) null else refuse(p, req, "bad value in control message", line); +} + +/// Runs a checked control message at pane `id`, as a click on its word +/// would; false when it would have opened a prompt for an argument, which +/// nobody writing to a file is there to type. +fn runBuiltin(p: *Pardes, id: usize, line: []const u8) bool { + p.fs.no_prompt = true; + p.fs.refused = false; + defer p.fs.no_prompt = false; + _ = exec_line.executeBuiltinLine(p, id, line); + return !p.fs.refused; +} + +const e_prompt = "control message needs its argument"; + +// ---- the root ctl ---- + +/// Every setting, one a line, in the words a write of it takes, so that the +/// file read back is the configuration, as webfs's ctl reads (webfs(4)). +/// What is not a setting -- platform, themes, where the config came from -- +/// is /status's or the Config window's. +fn writeSettings(p: *Pardes, w: *std.Io.Writer) !void { + const s = &p.settings; + inline for (config.Runtime.settings) |setting| { + if (comptime !setting.enabled(builtins.capabilities)) continue; + const word = setting.word; + switch (setting.action) { + .toggle => |field| try w.print("{s} {s}\n", .{ word, if (@field(s, @tagName(field))) "on" else "off" }), + .theme => try w.print("{s} {s}\n", .{ word, p.theme().name }), + .shell => { + const chosen = s.shell.requested.get(); + try w.print("{s} {s}\n", .{ word, if (chosen.len > 0) chosen else config.default_shell }); + }, + .font => { + const requested = s.font.requested_name.get(); + const name = if (requested.len > 0) requested else s.font.effective_name.get(); + const size = if (s.font.requested_size_hundredths != 0) s.font.requested_size_hundredths else s.font.effective_size_hundredths; + if (name.len > 0 and size != 0) + try w.print("{s} {s}:{d}.{d:0>2}\n", .{ word, name, size / 100, size % 100 }) + else if (name.len > 0) + try w.print("{s} {s}\n", .{ word, name }); + }, + .tagline_size => try w.print("{s} {d}\n", .{ word, s.font.tagline_percent }), + .window_opacity => try w.print("{s} {d}\n", .{ word, s.window_opacity }), + .window_blur => try w.print("{s} {d}\n", .{ word, s.window_blur }), + .message_ms => |which| try w.print("{s} {d}\n", .{ word, @field(s, "message_" ++ @tagName(which) ++ "_ms") }), + // Bare, it names the default directory. + .dump_dir => if (s.dump_dir.len > 0) try w.print("{s} {s}\n", .{ word, s.dump_dir.get() }) else try w.print("{s}\n", .{word}), + .transition => |effect| try w.print("{s} {s}\n", .{ word, if (s.panel_transition == effect) "on" else "off" }), + .scene => |effect| try w.print("{s} {s}\n", .{ word, if (@field(s.scene_effects, @tagName(effect))) "on" else "off" }), + } + } + try w.writeAll("LocationsConfig "); + try p.locations_config.write(w); + try w.writeByte('\n'); + if (comptime builtins.Pet.enabled) try w.print("Pet {s}\n", .{@tagName(s.pet)}); +} + +pub fn rootLen(p: *Pardes) u64 { + var buf: [256]u8 = undefined; + var counting: std.Io.Writer.Discarding = .init(&buf); + writeSettings(p, &counting.writer) catch return 0; + return counting.fullCount(); +} + +pub fn readRoot(p: *Pardes, req: Req) Reply { + var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + writeSettings(p, &text.writer) catch return Reply.fail(req.tag, E.NOMEM); + p.fs.stage(p.gpa).appendSlice(p.gpa, text.written()) catch return Reply.fail(req.tag, E.NOMEM); + return tree.stagedReply(p, req); +} + +/// One session builtin a line, at whichever pane has the keyboard as each +/// runs, as the root's look and exec click there; all are checked first. +pub fn writeRoot(p: *Pardes, req: Req) Reply { + for ([2]bool{ false, true }) |apply| { + var it = std.mem.splitScalar(u8, req.data, '\n'); + while (it.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0) continue; + if (!apply) { + if (checkBuiltin(p, req, line, .session)) |refusal| return refusal; + continue; + } + if (p.panes[p.active] == null) return Reply.fail(req.tag, E.NOENT); + if (!runBuiltin(p, p.active, line)) return tree.failText(req.tag, E.INVAL, e_prompt); + } + } + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + // ---- /focus ---- /// The pane with the keyboard, which a write of a serial moves, the way @@ -207,8 +338,8 @@ pub fn readPane(p: *Pardes, req: Req, pane: *Pane) Reply { } /// `get` reloads the buffer from the name it carries, wherever that name -/// resolves. Repeating it in one write would only reload the same bytes, so -/// it runs once. +/// resolves. Any other line is a builtin that acts on a pane (`Del`, +/// `Save f`), run at this one; a session's builtin is the root ctl's. /// /// `lock` and `unlock` are acme's (editors/acme/xfid.c:603-611), so that a /// client can make an edit of several writes to addr and data without @@ -229,7 +360,7 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { if (o == null or o.?.what != .ctl) pane.fs.lock = null; } const other = pane.fs.lock != null and pane.fs.lock != mine; - var asked = false; + const serial = pane.serial; // Checked whole before anything applies, so a write that must wait for // the lock has done nothing yet when it goes again. for ([2]bool{ false, true }) |apply| { @@ -238,8 +369,12 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { while (it.next()) |raw| { const line = std.mem.trim(u8, raw, " \t\r"); if (line.len == 0) continue; + // A line before this one may have closed the pane (`Del`). + if (apply and p.paneBySerial(serial) == null) return Reply.fail(req.tag, E.NOENT); if (std.mem.eql(u8, line, "get")) { - asked = true; + if (!apply) continue; + const errno = get(p, pane); + if (errno != 0) return Reply.fail(req.tag, errno); } else if (std.mem.eql(u8, line, "lock")) { if (mine == null) return tree.failText(req.tag, E.INVAL, tree.e_bad_ctl); if (other) return .{ .tag = req.tag, .status = .again }; @@ -252,13 +387,13 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { pane.fs.lock = null; pardes.turn.parked = true; // a `lock` waiting goes again } - } else return tree.failText(req.tag, E.INVAL, tree.e_bad_ctl); + } else if (!apply) { + if (checkBuiltin(p, req, line, .pane)) |refusal| return refusal; + } else if (!runBuiltin(p, p.paneBySerial(serial).?, line)) { + return tree.failText(req.tag, E.INVAL, e_prompt); + } } } - if (asked) { - const errno = get(p, pane); - if (errno != 0) return Reply.fail(req.tag, errno); - } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } @@ -342,20 +477,84 @@ test "focus reads the pane with the keyboard, and a serial written to it moves t try testing.expectEqual(p.paneBySerial(first).?, p.active); } -test "the pane ctl takes get, lock and unlock, and nothing that a file of its own now answers" { +test "the pane ctl takes acme's verbs and the pane's builtins, and refuses the rest in Plan 9's words" { const gpa = testing.allocator; const p = try withFile(gpa, "one\ntwo\n"); defer p.deinit(); - const ctl_node = Node.of(serialOf(p), .ctl); + const serial = serialOf(p); + const ctl_node = Node.of(serial, .ctl); + // acme's other ctl words have files of their own here, and a builtin is + // its own capitalised word: `Get`, `DEL` and `del` are none of them. for ([_][]const u8{ - "menu", "nomenu", "dump echo hi", "font Go Mono", "lock x", "bogus", "DEL", - "name x.txt", "put", "del", "delete", "Look x", "Exec Save", "clean", - "dirty", "cleartag", "dot=addr", "addr=dot", "show", "mark", "nomark", - "scroll", "limit=addr", "get x", "look /tmp", "exec Del", - }) |bad| try testing.expectEqual(E.INVAL, wr(p, ctl_node, bad).errno()); - try testing.expect(p.paneBySerial(serialOf(p)) != null); + "menu", "nomenu", "dump echo hi", "font Go Mono", "lock x", "bogus", "DEL", + "put", "del", "delete", "clean", "dirty", "show", "mark", + "Get", "limit=addr", "get x", "look /tmp", "exec Del", + }) |bad| { + const refused = wr(p, ctl_node, bad); + try testing.expectEqual(E.INVAL, refused.errno()); + var want: [64]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "unknown control message \"{s}\"", .{bad}), refused.reply.ename); + } + try testing.expectEqualStrings("not a window control message \"Newcol\"", wr(p, ctl_node, "Newcol").reply.ename); + try testing.expectEqualStrings("not a window control message \"Verbose off\"", wr(p, ctl_node, "Verbose off").reply.ename); + try testing.expectEqualStrings("wrong #args in control message \"Collapse now\"", wr(p, ctl_node, "Collapse now").reply.ename); + // Checked whole first: a bad line anywhere and nothing ran. + try testing.expectEqual(E.INVAL, wr(p, ctl_node, "Msg first\nbogus").errno()); + try testing.expect(p.panes[0].?.msg_len == 0 or !std.mem.eql(u8, p.panes[0].?.msg[0..p.panes[0].?.msg_len], "first")); + + // A pane's builtin runs at that pane. + try testing.expectEqual(Status.ok, wr(p, ctl_node, "Msg from ctl\n").reply.status); + const pane = p.panes[p.paneBySerial(serial).?].?; + try testing.expectEqualStrings("from ctl", pane.msg[0..pane.msg_len]); + // One that would ask at a prompt for its argument fails instead. + try testing.expectEqualStrings(e_prompt, wr(p, ctl_node, "Find").reply.ename); + try testing.expect(pane.prompt == .none); + try testing.expect(!p.fs.no_prompt); + // Save with no name on a scratch would ask for one: refused, not asked. + const other = try th.newPane(p); + try testing.expectEqualStrings(e_prompt, wr(p, Node.of(other, .ctl), "Save").reply.ename); + try testing.expect(p.panes[p.paneBySerial(other).?].?.prompt == .none); + // A line after the one that closed the pane has nowhere to run. + try testing.expectEqual(E.NOENT, wr(p, Node.of(other, .ctl), "Del\nMsg after").errno()); + try testing.expect(p.paneBySerial(other) == null); } +test "the root ctl reads the settings as a write takes them, and takes the session's builtins" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + const root_ctl = @intFromEnum(tree.TopFile.ctl); + const first = rd(p, root_ctl, 0, 1 << 16); + try testing.expectEqual(Status.ok, first.reply.status); + const settings = try gpa.dupe(u8, first.bytes); + defer gpa.free(settings); + try testing.expectEqual(@as(u64, settings.len), call(p, .{ .tag = 1, .op = .getattr, .node = root_ctl }).reply.attr.size); + try testing.expect(std.mem.indexOf(u8, settings, "Verbose on\n") != null); + try testing.expect(std.mem.indexOf(u8, settings, "LocationsConfig ") != null); + // Settings only: nothing /status or the Config window says. + try testing.expect(std.mem.indexOf(u8, settings, "Platform") == null); + try testing.expect(std.mem.indexOf(u8, settings, "requested") == null); + + // Every line written back is taken, and changes nothing. + try testing.expectEqual(Status.ok, wr(p, root_ctl, settings).reply.status); + try testing.expectEqualStrings(settings, rd(p, root_ctl, 0, 1 << 16).bytes); + + try testing.expectEqual(Status.ok, wr(p, root_ctl, "Verbose off\n").reply.status); + try testing.expect(!p.settings.verbose); + try testing.expect(std.mem.indexOf(u8, rd(p, root_ctl, 0, 1 << 16).bytes, "Verbose off\n") != null); + const columns = p.ncol; + try testing.expectEqual(Status.ok, wr(p, root_ctl, "Newcol\n").reply.status); + try testing.expectEqual(columns + 1, p.ncol); + + try testing.expectEqualStrings("not a session control message \"Del\"", wr(p, root_ctl, "Del").reply.ename); + try testing.expectEqualStrings("unknown control message \"Nonsense 1\"", wr(p, root_ctl, "Nonsense 1").reply.ename); + try testing.expectEqualStrings("bad value in control message \"Verbose maybe\"", wr(p, root_ctl, "Verbose maybe").reply.ename); + try testing.expectEqualStrings("bad value in control message \"Theme no-such-theme\"", wr(p, root_ctl, "Theme no-such-theme").reply.ename); + try testing.expectEqualStrings("wrong #args in control message \"Newcol 2\"", wr(p, root_ctl, "Newcol 2").reply.ename); + try testing.expect(!p.settings.verbose); +} + + test "a second lock waits until the holder unlocks or closes, and binds nobody else" { const p = try withFile(testing.allocator, "one\ntwo\n"); defer p.deinit(); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index b0de446e..13dfb0cf 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -175,6 +175,7 @@ pub const TopFile = enum(u4) { pane, new, focus, + ctl, pub fn fileName(f: TopFile) []const u8 { return if (f == .root) "/" else @tagName(f); @@ -183,7 +184,7 @@ pub const TopFile = enum(u4) { pub fn mode(f: TopFile) u16 { return switch (f) { .root, .pane => 0o755, - .look, .exec, .log, .focus => 0o666, + .look, .exec, .log, .focus, .ctl => 0o666, .README, .index, .status, .screen, .listeners, .new => 0o444, }; } @@ -445,6 +446,7 @@ fn topSize(p: *Pardes, f: TopFile) u64 { .look, .exec => ctl.resultsLen(p), .log => events.logLen(&p.fs.log), .listeners => screen.listenersLen(p), + .ctl => ctl.rootLen(p), .focus => focus: { const pn = p.panes[p.active] orelse break :focus 0; var digits: [16]u8 = undefined; @@ -523,7 +525,7 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); // After the first ten, which older clients list by position. - inline for (.{TopFile.focus}) |t| { + inline for (.{ TopFile.focus, TopFile.ctl }) |t| { if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); } sources.stage(p, out, "", &skip); @@ -716,6 +718,7 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { .screen => screen.readSnapshot(p, req, null), .listeners => screen.readListeners(p, req), .focus => ctl.readFocus(p, req), + .ctl => ctl.readRoot(p, req), // The serial the open handed this fid, so that two reads of one // fid answer the same pane: the read observes, the open acted. .new => serial: { @@ -749,6 +752,7 @@ fn write(p: *Pardes, req: Req, target: Target) Reply { .look, .exec => ctl.command(p, req, null, f == .exec), .log => events.writeLog(p, req), .focus => ctl.writeFocus(p, req), + .ctl => ctl.writeRoot(p, req), else => Reply.fail(req.tag, E.PERM), }, .pane => |t| { diff --git a/src/pardes.zig b/src/pardes.zig index 321a6b3c..fbc3e119 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5081,6 +5081,12 @@ pub const Pardes = struct { pipe: modal.Normal.PipeBehavior, save, }) void { + // Nobody is at the keyboard to answer a command a script wrote to a + // ctl file: the write fails instead (src/ninep/ctl.zig). + if (p.fs.no_prompt) { + p.fs.refused = true; + return; + } const marker = switch (request) { .search => |marker| marker, .save => config.save_marker, diff --git a/test/fs.py b/test/fs.py index ccf3eb89..82d7cf0b 100644 --- a/test/fs.py +++ b/test/fs.py @@ -245,6 +245,24 @@ def discovery(binary, embedded=False): raise AssertionError('focus took a serial no pane has') except OSError as refused: assert 'no such window' in str(refused), refused + # /ctl reads the settings as a write takes them and takes the + # session's builtins; a pane's ctl takes the pane's. + settings = client.read('/ctl') + assert b'Verbose ' in settings and b'Platform' not in settings, settings + client.write('/ctl', settings) + assert client.read('/ctl') == settings + client.write('/ctl', b'Verbose off\n') + assert b'Verbose off\n' in client.read('/ctl') + for path, line, why in (('/ctl', b'Del\n', 'not a session control message "Del"'), + ('/ctl', b'Nope 3\n', 'unknown control message "Nope 3"'), + (f'/pane/{first}/ctl', b'Newcol\n', 'not a window control message "Newcol"')): + try: + client.write(path, line) + raise AssertionError(f'{path} took {line!r}') + except OSError as refused: + assert why in str(refused), refused + client.write(f'/pane/{first}/ctl', b'Msg said through ctl\n') + assert 'said through ctl' in ''.join(cell[0] for cell in client.screen()['cells']) assert set(client.list('/pane')) == {'new', str(fixture), str(first), str(second)} client.write(f'/pane/{first}/body', b'first pane', truncate=True) assert client.read(f'/pane/{first}/body') == b'first pane' @@ -315,7 +333,7 @@ def discovery(binary, embedded=False): assert client.read('/src/pardes.zig').startswith(b'const std') assert client.stat('/src/pardes.zig')['mode'] == 0o444 assert b'pub const Pardes' in client.read(f'/pane/{look(client, "/virtual/src/pardes.zig")}/body') - print('9P discovery: listing/stat/find are inert; new, remove, look, exec, name, sel, log, ctl lock and focus behave') + print('9P discovery: listing/stat/find are inert; new, remove, look, exec, name, sel, log, ctl lock, focus and the ctl split behave') def run_file(binary): -- cgit v1.3 From c44894f53decbacc68c0e4e9d1118fc082bc63a0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 10:02:33 -0300 Subject: A ctl write fails when a builtin it runs fails, and a missing required argument is refused before anything runs A ctl write failed only on a malformed line: Mount x reported its error in the editor while the write succeeded, and a bare Mount failed only as it ran, after earlier lines of the write. acme's ctl answers a command's error (editors/acme/xfid.c:700). Builtins now declare requires_arg beside takes_arg (settings: those with a value to set), and the check refuses a bare one as wrong #args before any line runs; while a ctl runs, the first error a builtin reports fails the write, quoted with its line, and the prompt refusal quotes its line too. Docs say what a failure mid-write leaves done. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 8 +++++--- docs/fs.md | 34 ++++++++++++++++++++----------- src/Messages.zig | 6 ++++++ src/builtins.zig | 31 +++++++++++++++++++++++++++++ src/fs.zig | 6 +++++- src/ninep/ctl.zig | 42 +++++++++++++++++++++++++++++---------- 6 files changed, 100 insertions(+), 27 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index ec5f811f..a17a5dac 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -138,9 +138,11 @@ width, then `current` or `notcurrent` — and takes `get` (reload from disk), `lock`/`unlock`, and any builtin that acts on a pane (`Del`, `Save f`, `Collapse`). Session builtins and settings go to the root `ctl`, which reads back every setting in the syntax it takes. A ctl write is checked whole -first and refused as `unknown control message "X"` (EINVAL) and the like; a -builtin that would open a prompt (`Save` on a scratch, bare `Find`) fails -there instead of prompting. The lock binds only clients that take it, and is held by the +first and refused as `unknown control message "X"` (EINVAL) and the like, +a required argument missing included (`wrong #args ... "Mount"`); then a line +whose builtin reports an error fails the write with that error and the line +(EIO), after the lines before it took effect. A `Save` on a scratch fails +rather than prompt. The lock binds only clients that take it, and is held by the open that wrote it, so a shell holds an fd across the edit: `exec 3>$pane/ctl; echo lock >&3; ...; exec 3>&-`. diff --git a/docs/fs.md b/docs/fs.md index b97f34fa..c08500f1 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -104,18 +104,28 @@ Config window's, not settings. A pane's `ctl` takes the builtins that act on a pane (`Del`, `Save f`, `Collapse`, `Find pat`) beside acme's `get`, `lock` and `unlock`. The words are case-sensitive and do not alias: acme's verbs are lowercase and the builtins keep their tag spelling, so `Get` is no word -and `del` none either. A write is checked whole before any line runs, and a -line is refused in Plan 9's words for a ctl (kernel/misc/parse.c:82-97): -`unknown control message "X"`, `wrong #args in control message "X"` for an -argument to a builtin that takes none, `bad value in control message "X"` -for a setting's value it does not take, and `not a session control message -"X"` or `not a window control message "X"` for a word of the other ctl; 9ns -maps them all to EINVAL. A builtin that would ask at a prompt for its -argument (`Save` on a scratch, `Find` bare) fails the write with `control -message needs its argument` rather than open one nobody is there to answer, -though a click on the same word written to `exec` still opens it. Like any -write, a ctl write answers once the editor has performed what it asked for -(a save written, a shell started). +and `del` none either. + +A write is checked whole before any line of it runs, and a line is refused +in Plan 9's words for a ctl (kernel/misc/parse.c:82-97), quoting the line: +`unknown control message "X"`; `wrong #args in control message "X"` for an +argument to a builtin that takes none, or none to one that needs it (`Msg`, +`Mount`, `Find`, a setting's value but a switch's, which flips bare); +`bad value in control message "X"` for a setting's value it does not take; +and `not a session control message "X"` or `not a window control message +"X"` for a word of the other ctl. 9ns maps them all to EINVAL, and a write +refused here has done nothing. A line that then fails as it runs fails the +write with the error the editor reports for it and the line, e.g. `Mount: +AlreadyMounted "Mount peer /tmp/s"` (EIO); so does `control message needs +its argument "Save"`, for a builtin that would have asked at a prompt (a +`Save` on a scratch) rather than open one nobody is there to answer. The +lines before a failing one have taken effect and those after it never run, +which is what acme's ctl loop does (editors/acme/xfid.c:600-790). An error +that only happens as the editor performs what a line asked for -- a `Save` +whose disk write fails -- is reported in the editor and /log, not in the +write's answer. Like any write, a ctl write answers once the editor has +performed what it asked for (a save written, a shell started). A click on +the same word, or the word written to `exec`, still opens its prompt. `/commands` lists every builtin the registry holds, in registry order, one a line: its word, `arg` when it takes one, and `root` or `pane` for the ctl diff --git a/src/Messages.zig b/src/Messages.zig index c7ff09be..f4ea1c3e 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -388,6 +388,12 @@ pub fn messageLog(m: *const Messages, i: usize) ?*const LoggedMessage { pub fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) void { var buf: [256]u8 = undefined; const text = std.fmt.bufPrint(&buf, "{s}: {s}", .{ operation, @errorName(err) }) catch operation; + // A builtin a ctl write runs: its first error is also the write's. + if (p.fs.no_prompt and p.fs.failure_len == 0) { + const n = @min(text.len, p.fs.failure.len); + @memcpy(p.fs.failure[0..n], text[0..n]); + p.fs.failure_len = @intCast(n); + } setMessage(p, id, text); } diff --git a/src/builtins.zig b/src/builtins.zig index ed0a07dd..2dac8a59 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -145,6 +145,22 @@ pub const registry = struct { return true; } + /// Whether the word means nothing without its argument (`Mount`, + /// `Msg`, a setting's value), or would ask for it at a prompt (`Find`): + /// a ctl refuses it bare before any line of the write runs. A builtin + /// says `pub const requires_arg = true;` beside `takes_arg`. + pub fn requiresArg(b: Builtin()) bool { + inline for (manualBuiltinList(), 0..) |T, i| + if (@intFromEnum(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; + inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + if (@intFromEnum(b) == i) return switch (setting.action) { + // a switch flips bare, and DumpDir bare is the default + .toggle, .transition, .scene, .dump_dir => false, + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms => true, + }; + unreachable; + } + pub fn scope(b: Builtin()) Scope { inline for (manualBuiltinList(), 0..) |T, i| if (@intFromEnum(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; @@ -237,6 +253,7 @@ comptime { pub const Look = struct { pub const takes_arg = true; + pub const requires_arg = true; // a look's answer is the pane it opens or the place it jumps to; its own // name on the message row would only be noise over that pub const quiet = true; @@ -247,6 +264,7 @@ pub const Look = struct { pub const Exec = struct { pub const takes_arg = true; + pub const requires_arg = true; pub fn run(c: Ctx) void { // the destination pane is Look's business (it focuses what answered); // an execute deliberately leaves you where you were @@ -311,6 +329,7 @@ pub const Detach = struct { pub const Mount = struct { pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime !enabled) unreachable; @@ -325,6 +344,7 @@ pub const Mount = struct { pub const Unmount = struct { pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime !enabled) unreachable; @@ -339,6 +359,7 @@ pub const Unmount = struct { pub const Msg = struct { pub const takes_arg = true; + pub const requires_arg = true; pub const quiet = true; // it IS the message row pub fn run(c: Ctx) void { if (c.arg) |text| @@ -366,6 +387,7 @@ pub const ThemeSel = struct { pub const ThemeFile = struct { pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime enabled) @@ -722,6 +744,7 @@ pub const Changelog = struct { pub const EffectCode = struct { pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = capabilities.panel_transitions or capabilities.scene_shaders; pub const output: OutputTraits = .{ .name = config.effect_code_buffer }; pub fn run(c: Ctx) void { @@ -737,6 +760,7 @@ pub const EffectCode = struct { pub const Pet = struct { pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = pardes.platform == .gui; pub fn run(c: Ctx) void { const name = std.mem.trim(u8, c.arg orelse return, " \t\r\n"); @@ -758,6 +782,7 @@ pub const Mini = struct { pub const Find = struct { pub const takes_arg = true; + pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true }; pub fn run(c: Ctx) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); @@ -771,6 +796,7 @@ pub const Find = struct { /// matches file CONTENTS under every pane's directory at once. pub const Grep = struct { pub const takes_arg = true; + pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); @@ -940,6 +966,7 @@ pub const Subtypes = struct { pub const Rename = struct { pub const takes_arg = true; + pub const requires_arg = true; pub fn run(c: Ctx) void { const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (a.len > 0) return c.p.lspRequest(c.id, .rename, a); @@ -949,6 +976,7 @@ pub const Rename = struct { pub const WsSymbols = struct { pub const takes_arg = true; + pub const requires_arg = true; pub fn run(c: Ctx) void { const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (a.len > 0) return c.p.lspRequest(c.id, .workspace_symbols, a); @@ -971,6 +999,7 @@ pub const Lspwhy = struct { pub const Peek = struct { pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = Board.enabled; pub const output: OutputTraits = .{ .name = config.peek_buffer }; pub fn run(c: Ctx) void { @@ -984,6 +1013,7 @@ pub const Peek = struct { pub const Poke = struct { pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = Board.enabled; pub fn run(c: Ctx) void { if (comptime enabled) { @@ -996,6 +1026,7 @@ pub const Poke = struct { pub const Hexdump = struct { pub const scope: Scope = .session; pub const takes_arg = true; + pub const requires_arg = true; pub const enabled = Board.enabled; pub const output: OutputTraits = .{ .name = config.hexdump_buffer }; pub fn run(c: Ctx) void { diff --git a/src/fs.zig b/src/fs.zig index 339910a4..022a326a 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1257,9 +1257,13 @@ pub const Namespace = struct { listeners: u16 = 0, origin: u8 = 'K', /// A ctl write is running builtins: one that would open a prompt for - /// its argument refuses (`refused`), since nobody is at the prompt. + /// its argument refuses (`refused`), since nobody is at the prompt, and + /// the first error one reports (`failure`) fails the write, as acme's + /// ctl answers a command's error (editors/acme/xfid.c:700). no_prompt: bool = false, refused: bool = false, + failure: [96]u8 = undefined, + failure_len: u8 = 0, /// A refusal that quotes the message it refuses, as Plan 9's cmderror /// does (kernel/misc/parse.c:82); answered at once (src/9p_io.zig). ename: [128]u8 = undefined, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 945119ca..e47dec16 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -180,7 +180,8 @@ fn refuse(p: *Pardes, req: Req, why: []const u8, line: []const u8) Reply { /// Checks one line written to a ctl as a builtin of `scope` before any line /// of the write runs: a word the registry knows, of this ctl's scope, given -/// an argument only if it takes one, and for a setting a value it takes. +/// an argument if and only if it takes or requires one, and for a setting a +/// value it takes. /// Answers the refusal, or null. Words are the builtins' own, capitalised /// as on a tag; acme's lowercase verbs are the pane ctl's and alias none. fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ?Reply { @@ -191,6 +192,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? if (builtins.registry.scope(b) != scope) return refuse(p, req, if (scope == .pane) "not a window control message" else "not a session control message", line); if (arg.len > 0 and !builtins.registry.takesArg(b)) return refuse(p, req, "wrong #args in control message", line); + if (arg.len == 0 and builtins.registry.requiresArg(b)) return refuse(p, req, "wrong #args in control message", line); const setting = config.Runtime.find(word) orelse return null; const takes = switch (setting.action) { .theme => for (pardes.themes) |t| { @@ -206,14 +208,19 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? } /// Runs a checked control message at pane `id`, as a click on its word -/// would; false when it would have opened a prompt for an argument, which -/// nobody writing to a file is there to type. -fn runBuiltin(p: *Pardes, id: usize, line: []const u8) bool { +/// would. Answers the refusal when it would have opened a prompt for an +/// argument, which nobody writing to a file is there to type, or when it +/// reported an error: `Mount: AlreadyMounted "Mount peer /tmp/s"`. +fn runBuiltin(p: *Pardes, req: Req, id: usize, line: []const u8) ?Reply { p.fs.no_prompt = true; p.fs.refused = false; + p.fs.failure_len = 0; defer p.fs.no_prompt = false; _ = exec_line.executeBuiltinLine(p, id, line); - return !p.fs.refused; + if (p.fs.refused) return refuse(p, req, e_prompt, line); + if (p.fs.failure_len == 0) return null; + const refusal = refuse(p, req, p.fs.failure[0..p.fs.failure_len], line); + return .{ .tag = req.tag, .status = .err, .errno = E.IO, .ename = refusal.ename }; } const e_prompt = "control message needs its argument"; @@ -288,7 +295,7 @@ pub fn writeRoot(p: *Pardes, req: Req) Reply { continue; } if (p.panes[p.active] == null) return Reply.fail(req.tag, E.NOENT); - if (!runBuiltin(p, p.active, line)) return tree.failText(req.tag, E.INVAL, e_prompt); + if (runBuiltin(p, req, p.active, line)) |refusal| return refusal; } } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; @@ -404,8 +411,8 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { } } else if (!apply) { if (checkBuiltin(p, req, line, .pane)) |refusal| return refusal; - } else if (!runBuiltin(p, p.paneBySerial(serial).?, line)) { - return tree.failText(req.tag, E.INVAL, e_prompt); + } else if (runBuiltin(p, req, p.paneBySerial(serial).?, line)) |refusal| { + return refusal; } } } @@ -542,13 +549,15 @@ test "the pane ctl takes acme's verbs and the pane's builtins, and refuses the r try testing.expectEqual(Status.ok, wr(p, ctl_node, "Msg from ctl\n").reply.status); const pane = p.panes[p.paneBySerial(serial).?].?; try testing.expectEqualStrings("from ctl", pane.msg[0..pane.msg_len]); - // One that would ask at a prompt for its argument fails instead. - try testing.expectEqualStrings(e_prompt, wr(p, ctl_node, "Find").reply.ename); + // One that means nothing bare is refused before anything runs. + try testing.expectEqualStrings("wrong #args in control message \"Find\"", wr(p, ctl_node, "Find").reply.ename); + try testing.expectEqual(E.INVAL, wr(p, ctl_node, "Msg first\nMsg").errno()); + try testing.expect(!std.mem.eql(u8, pane.msg[0..pane.msg_len], "first")); try testing.expect(pane.prompt == .none); try testing.expect(!p.fs.no_prompt); // Save with no name on a scratch would ask for one: refused, not asked. const other = try th.newPane(p); - try testing.expectEqualStrings(e_prompt, wr(p, Node.of(other, .ctl), "Save").reply.ename); + try testing.expectEqualStrings(e_prompt ++ " \"Save\"", wr(p, Node.of(other, .ctl), "Save").reply.ename); try testing.expect(p.panes[p.paneBySerial(other).?].?.prompt == .none); // A line after the one that closed the pane has nowhere to run. try testing.expectEqual(E.NOENT, wr(p, Node.of(other, .ctl), "Del\nMsg after").errno()); @@ -587,7 +596,18 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi try testing.expectEqualStrings("bad value in control message \"Verbose maybe\"", wr(p, root_ctl, "Verbose maybe").reply.ename); try testing.expectEqualStrings("bad value in control message \"Theme no-such-theme\"", wr(p, root_ctl, "Theme no-such-theme").reply.ename); try testing.expectEqualStrings("wrong #args in control message \"Newcol 2\"", wr(p, root_ctl, "Newcol 2").reply.ename); + try testing.expectEqualStrings("wrong #args in control message \"Theme\"", wr(p, root_ctl, "Theme").reply.ename); + // A bare required word fails the check, so the line before never runs. + try testing.expectEqual(E.INVAL, wr(p, root_ctl, "Verbose on\nMount").errno()); try testing.expect(!p.settings.verbose); + // A builtin that fails as it runs fails the write, quoting its error and + // its line; the lines before it have taken effect, as in acme. + const failed = wr(p, root_ctl, "Verbose on\nMount x\nVerbose off"); + try testing.expectEqual(E.IO, failed.errno()); + try testing.expectEqualStrings("Mount name dial: MissingArgument \"Mount x\"", failed.reply.ename); + try testing.expect(p.settings.verbose); + try testing.expect(!p.fs.no_prompt); + try testing.expectEqual(Status.ok, wr(p, root_ctl, "Verbose off").reply.status); } -- cgit v1.3 From 5cf50930dee214fb641bb95bbf8639b8f76930d9 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 11:12:10 -0300 Subject: Normal mode's s and S search as addr does, through one shared regexp.zig The sam-style calling convention for mvzr (a line per haystack, . made [^\\n] only when a pattern names \\n) lived in addr.zig; normal mode's s and S called mvzr over the raw selection, where ^ meant the selection's start and . crossed lines. src/regexp.zig now holds the one Regex (compile, find) both call, and fs.zig and pardes.zig drop an unused mvzr import. hxdiff and hxparity stay at their known 17 and 6 mismatches, none of them regex cases. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 2 ++ docs/helix-keys.md | 6 +++- src/fs.zig | 1 - src/ninep/addr.zig | 87 ++++++-------------------------------------- src/normal.zig | 53 +++++++++++++++++++++------ src/pardes.zig | 2 +- src/regexp.zig | 104 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 165 insertions(+), 90 deletions(-) create mode 100644 src/regexp.zig (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index c54cfc4d..af57a468 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -274,6 +274,8 @@ takes the longest (`/gam|gamma/` finds `gam`); in a search begun in the middle of a line, `^` inside an alternation can match there; and in a pattern that spans lines, `^`, `$` and `[^...]` keep mvzr's own meaning. pardes has no regex engine of its own on purpose; these are its limits. +Normal mode's `s` and `S` search a selection the same way (src/regexp.zig +is the one place both call), so `^` there also means a line's start. An address that does not evaluate fails the write with why: `bad address syntax`, `no match for regexp`, `address out of range` or `bad regular diff --git a/docs/helix-keys.md b/docs/helix-keys.md index f46f5234..0f847405 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -245,7 +245,11 @@ re-runs the final pattern down the same path, so a submit can never disagree with what is on screen. Pressed in a tag, column tag or workspace tag they select in that tag's own text, and so does `|` pipe it; `/` searches the body wherever it is pressed (`Pane.prompt_for`). Engine: **mvzr** (`build.zig.zon`), a bytecode VM that -compiles a runtime pattern with no allocator. +compiles a runtime pattern with no allocator, called the way sam searches +(`src/regexp.zig`, shared with a pane's `addr` file): each line is its own +haystack, so `^` and `$` match at every line's start and end and `.` never +crosses a newline, and a pattern naming `\n` runs over the whole selection. +Where helix's `^` is only the selection's start, this is sam's. | Key | Behavior | Notes | Status | | --- | --- | --- | --- | diff --git a/src/fs.zig b/src/fs.zig index 022a326a..0b620c9f 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -6,7 +6,6 @@ const config = @import("config.zig"); const lsp = @import("lsp/lsp.zig"); const ninep_io = @import("9p_io.zig"); const panes = @import("panes.zig"); -const mvzr = @import("mvzr"); const modal = @import("modal.zig"); const look = @import("look.zig"); pub const tree = @import("ninep/tree.zig"); diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index 95e699e3..347a2d11 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -1,7 +1,7 @@ //! The address language of a pane's `addr` file, acme's (editors/acme/ -//! addr.c), its regular expressions run by mvzr the way sam's run. +//! addr.c), its regular expressions searched as sam searches (regexp.zig). const std = @import("std"); -const mvzr = @import("mvzr"); +const regexp_ = @import("../regexp.zig"); const modal = @import("../modal.zig"); const pane_files = @import("pane.zig"); @@ -196,92 +196,27 @@ pub const Addr = struct { a.err = "no previous regular expression"; return null; } - // sam searches the text as lines: `^` and `$` at any line's start - // and end, and `.` never a newline. mvzr has no such mode (its `^` - // and `$` are the haystack's ends, its `.` any byte), so each line - // is its own haystack, and a pattern that names a newline (`\n`) - // runs over the whole text with its `.`s made `[^\n]`. - // ponytail: mvzr takes the first alternative that matches, not - // sam's longest (`/gam|gamma/` finds `gam`); a search from the middle - // of a line lets `^` match there unless the pattern starts with it; - // across lines, `^`, `$` and `[^...]` keep mvzr's meaning. A regex - // engine of sam's own would lift these; the user chose not to. - const spans = std.mem.indexOf(u8, pat, "\\n") != null; - var buf: [256]u8 = undefined; - var len: usize = 0; - var i: usize = 0; - var in_class = false; - while (i < pat.len) : (i += 1) { - const c = pat[i]; - const piece: []const u8 = if (c == '\\') piece: { - if (i + 1 >= pat.len) break :piece ""; - i += 1; - break :piece pat[i - 1 .. i + 1]; - } else if (c == '.' and spans and !in_class) "[^\\n]" else pat[i .. i + 1]; - if (piece.len == 0 or len + piece.len > buf.len) { - a.err = e_regexp; - return null; - } - if (c == '[') in_class = true; - if (c == ']') in_class = false; - @memcpy(buf[len..][0..piece.len], piece); - len += piece.len; - } - const re = mvzr.compile(buf[0..len]) orelse { + const rx = regexp_.Regex.compile(pat) orelse { a.err = e_regexp; return null; }; - const anchored = pat[0] == '^'; - const Search = struct { - /// The first match starting in `from..=last` that ends by `hi`. - fn first(rx: *const mvzr.Regex, text: []const u8, from: usize, last: usize, hi: usize, whole: bool, bol: bool) ?Range { - if (whole) { - const m = rx.matchPos(from, text[0..hi]) orelse return null; - return if (m.start <= last) .{ .q0 = clip(m.start), .q1 = clip(m.end) } else null; - } - var start = if (std.mem.lastIndexOfScalar(u8, text[0..from], '\n')) |nl| nl + 1 else 0; - var at = from - start; - // `^` cannot match in the middle of a line. - if (bol and at > 0) { - start = (std.mem.indexOfScalarPos(u8, text[0..hi], from, '\n') orelse return null) + 1; - at = 0; - } - while (start <= hi and start <= last) { - const end = std.mem.indexOfScalarPos(u8, text[0..hi], start, '\n') orelse hi; - const line = text[start..end]; - // matchPos finds nothing at a line's very end, where - // `$` or an empty pattern still match. - const hit: ?[2]usize = if (at < line.len) - (if (rx.matchPos(at, line)) |m| .{ m.start, m.end } else null) - else if (at == line.len and rx.isMatch(line[at..])) .{ at, at } else null; - if (hit) |h| { - if (start + h[0] > last) return null; - return .{ .q0 = clip(start + h[0]), .q1 = clip(start + h[1]) }; - } - if (end == hi) return null; - start = end + 1; - at = 0; - } - return null; - } - }; - const found: ?Range = if (back) found: { + const found = if (back) found: { var last: ?Range = null; var before: ?Range = null; var at: usize = 0; while (at <= a.text.len) { - const m = Search.first(&re, a.text, at, a.text.len, a.text.len, spans, anchored) orelse break; - if (m.q1 <= r.q0) before = m; - last = m; - at = if (m.q1 > m.q0) m.q1 else m.q1 + 1; + const m = rx.find(a.text, at, a.text.len, a.text.len) orelse break; + const found_range: Range = .{ .q0 = clip(m.start), .q1 = clip(m.end) }; + if (found_range.q1 <= r.q0) before = found_range; + last = found_range; + at = if (m.end > m.start) m.end else m.end + 1; } break :found before orelse last; } else found: { const hi = if (a.lim) |l| @min(@as(usize, l.q1), a.text.len) else a.text.len; const from = @min(@as(usize, r.q1), hi); - if (Search.first(&re, a.text, from, hi, hi, spans, anchored)) |m| break :found m; - if (a.lim != null or from == 0) break :found null; - break :found Search.first(&re, a.text, 0, from - 1, hi, spans, anchored); + const m = rx.find(a.text, from, hi, hi) orelse (if (a.lim != null or from == 0) null else rx.find(a.text, 0, from - 1, hi)) orelse break :found null; + break :found Range{ .q0 = clip(m.start), .q1 = clip(m.end) }; }; return found orelse { a.err = e_no_match; diff --git a/src/normal.zig b/src/normal.zig index ffbb49d5..8c5f232d 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -6,7 +6,7 @@ const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); -const mvzr = @import("mvzr"); +const regexp = @import("regexp.zig"); const modal = @import("modal.zig"); const panes = @import("panes.zig"); const edit = @import("edit.zig"); @@ -92,7 +92,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, split: const snap = pane.sel_snap[0..pane.nsel_snap]; var out: [Text.max_selections]modal.Selection = undefined; var m: usize = 0; - if (pat.len > 0) if (mvzr.compile(pat)) |re| { + if (regexp.Regex.compile(pat)) |re| { var hay_all = text; if (for (pat) |c| { if (std.ascii.isUpper(c)) break false; @@ -105,17 +105,18 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, split: const from = @min(r.anchor, r.head); const to = @min(@max(r.anchor, r.head), text.len); if (from >= to) continue; - const hay = hay_all[from..to]; - var at: usize = 0; + // Searched as sam searches, the way addr does (regexp.zig): the + // text around the selection still says where its lines begin. + var at = from; var piece = from; // split: where the next piece begins - while (at < hay.len and m < Text.max_selections) { - const hit_at = re.matchPos(at, hay) orelse break; + while (at < to and m < Text.max_selections) { + const hit_at = re.find(hay_all, at, to, to) orelse break; if (split) { - out[m] = .{ .anchor = piece, .head = from + hit_at.start }; + out[m] = .{ .anchor = piece, .head = hit_at.start }; m += 1; - piece = from + hit_at.end; - } else if (from + hit_at.start != to) { - out[m] = .{ .anchor = from + hit_at.start, .head = from + hit_at.end }; + piece = hit_at.end; + } else if (hit_at.start != to) { + out[m] = .{ .anchor = hit_at.start, .head = hit_at.end }; m += 1; } // an empty match would otherwise never advance @@ -126,7 +127,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, split: m += 1; } } - }; + } if (m == 0) { // the text CAN move under an armed prompt (a tag chord runs a // builtin), and these are raw offsets into the surface as it was @@ -730,3 +731,33 @@ test "flat text movement and selection replay need no scratch rows" { executeNormalAction(p, &pane.body, .match_bracket); try std.testing.expectEqual(@as(i32, 8), pane.body.cur_col); } + +test "s and S search a multi-line selection as addr does: ^ and $ per line, . within one" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); + defer p.deinit(); + const text = "alpha x\nbeta alpha\nalphabet\n"; + const pane = try p.setTestFile(text); + const Case = struct { pat: []const u8, split: bool, want: []const [2]usize }; + for ([_]Case{ + // ^ at each line's start, not only the selection's + .{ .pat = "^alpha", .split = false, .want = &.{ .{ 0, 5 }, .{ 19, 24 } } }, + // $ at each line's end + .{ .pat = "alpha$", .split = false, .want = &.{.{ 13, 18 }} }, + // . stops at the newline: one selection per line, not one for all + .{ .pat = "a.*", .split = false, .want = &.{ .{ 0, 7 }, .{ 11, 18 }, .{ 19, 27 } } }, + // S splits on a line's end + .{ .pat = "$", .split = true, .want = &.{ .{ 0, 7 }, .{ 7, 18 }, .{ 18, 27 }, .{ 27, 28 } } }, + }) |c| { + pane.sel_snap[0] = .{ .anchor = 0, .head = text.len }; + pane.nsel_snap = 1; + applySelRegex(p, pane, &pane.body, c.pat, c.split); + var out: [Text.max_selections]modal.Selection = undefined; + const got = pane.body.ranges(text, 0, &out); + try std.testing.expectEqual(c.want.len, got.n); + for (c.want, out[0..got.n]) |w, r| { + try std.testing.expectEqual(w[0], @min(r.anchor, r.head)); + try std.testing.expectEqual(w[1], @max(r.anchor, r.head)); + } + } +} diff --git a/src/pardes.zig b/src/pardes.zig index 9d336db3..05f6710a 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -2,7 +2,6 @@ const std = @import("std"); pub const layout = @import("layout.zig"); const uucode = @import("uucode"); const vaxis = @import("vaxis"); -const mvzr = @import("mvzr"); pub const modal = @import("modal.zig"); pub const look = @import("look.zig"); pub const filesystem = @import("fs.zig"); @@ -451,6 +450,7 @@ test { _ = @import("look.zig"); _ = @import("mouse.zig"); _ = @import("normal.zig"); + _ = @import("regexp.zig"); _ = @import("edit.zig"); _ = @import("Messages.zig"); _ = @import("selection_pipe.zig"); diff --git a/src/regexp.zig b/src/regexp.zig new file mode 100644 index 00000000..665e51d5 --- /dev/null +++ b/src/regexp.zig @@ -0,0 +1,104 @@ +//! How pardes runs a regular expression over text: mvzr's, searched the way +//! sam searches (editors/acme/regx.c). `addr` (src/ninep/addr.zig) and +//! normal mode's `s` and `S` (src/normal.zig) both call it. +const std = @import("std"); +const mvzr = @import("mvzr"); + +/// A compiled pattern and how to run it. +/// +/// sam searches the text as lines: `^` and `$` at any line's start and end, +/// and `.` never a newline. mvzr has no such mode (its `^` and `$` are the +/// haystack's ends, its `.` any byte), so each line is its own haystack, and +/// a pattern that names a newline (`\n`) runs over the whole text with its +/// `.`s made `[^\n]`. +/// ponytail: mvzr takes the first alternative that matches, not sam's +/// longest (`gam|gamma` finds `gam`); a search from the middle of a line lets +/// `^` match there unless the pattern starts with it; across lines, `^`, `$` +/// and `[^...]` keep mvzr's meaning. A regex engine of sam's own would lift +/// these; the user chose not to have one. +pub const Regex = struct { + re: mvzr.Regex, + /// The pattern names a newline: it runs over the whole text. + spans: bool, + /// The pattern starts with `^`: a search begun mid-line skips the line. + bol: bool, + + pub fn compile(pat: []const u8) ?Regex { + if (pat.len == 0) return null; + const spans = std.mem.indexOf(u8, pat, "\\n") != null; + var buf: [256]u8 = undefined; + var len: usize = 0; + var i: usize = 0; + var in_class = false; + while (i < pat.len) : (i += 1) { + const c = pat[i]; + const piece: []const u8 = if (c == '\\') piece: { + if (i + 1 >= pat.len) return null; + i += 1; + break :piece pat[i - 1 .. i + 1]; + } else if (c == '.' and spans and !in_class) "[^\\n]" else pat[i .. i + 1]; + if (len + piece.len > buf.len) return null; + if (c == '[') in_class = true; + if (c == ']') in_class = false; + @memcpy(buf[len..][0..piece.len], piece); + len += piece.len; + } + return .{ .re = mvzr.compile(buf[0..len]) orelse return null, .spans = spans, .bol = pat[0] == '^' }; + } + + /// The first match that starts in `from..=last` and ends by `hi`, as + /// offsets into `text`. The text before `from` still says where lines + /// begin. + pub fn find(rx: *const Regex, text: []const u8, from: usize, last: usize, hi: usize) ?struct { start: usize, end: usize } { + if (rx.spans) { + const m = rx.re.matchPos(from, text[0..hi]) orelse return null; + return if (m.start <= last) .{ .start = m.start, .end = m.end } else null; + } + var start = if (std.mem.lastIndexOfScalar(u8, text[0..from], '\n')) |nl| nl + 1 else 0; + var at = from - start; + // `^` cannot match in the middle of a line. + if (rx.bol and at > 0) { + start = (std.mem.indexOfScalarPos(u8, text[0..hi], from, '\n') orelse return null) + 1; + at = 0; + } + while (start <= hi and start <= last) { + const end = std.mem.indexOfScalarPos(u8, text[0..hi], start, '\n') orelse hi; + const line = text[start..end]; + // matchPos finds nothing at a line's very end, where `$` or an + // empty match still can. + const hit: ?[2]usize = if (at < line.len) + (if (rx.re.matchPos(at, line)) |m| .{ m.start, m.end } else null) + else if (at == line.len and rx.re.isMatch(line[at..])) .{ at, at } else null; + if (hit) |h| { + if (start + h[0] > last) return null; + return .{ .start = start + h[0], .end = start + h[1] }; + } + if (end == hi) return null; + start = end + 1; + at = 0; + } + return null; + } +}; + +test "lines are haystacks: ^ and $ at each line, . never a newline, \\n spans lines" { + const text = "alpha beta\nbeta gamma\ngamma\n"; + const Case = struct { pat: []const u8, from: usize, start: usize, end: usize }; + for ([_]Case{ + .{ .pat = "^beta", .from = 0, .start = 11, .end = 15 }, + .{ .pat = "beta$", .from = 0, .start = 6, .end = 10 }, + .{ .pat = "a.*", .from = 0, .start = 0, .end = 10 }, + .{ .pat = "a\\nbeta", .from = 0, .start = 9, .end = 15 }, + .{ .pat = "t.\\nbeta", .from = 0, .start = 8, .end = 15 }, + .{ .pat = "^", .from = 1, .start = 11, .end = 11 }, + }) |c| { + const rx = Regex.compile(c.pat).?; + const m = rx.find(text, c.from, text.len, text.len).?; + try std.testing.expectEqual(c.start, m.start); + try std.testing.expectEqual(c.end, m.end); + } + try std.testing.expect(Regex.compile("a.*a\\nq") != null); + try std.testing.expect((Regex.compile("zzz").?).find(text, 0, text.len, text.len) == null); + try std.testing.expect(Regex.compile("") == null); + try std.testing.expect(Regex.compile("a\\") == null); +} -- cgit v1.3 From 0e2afeecf6b8c0e9ac81da51f5f8c23a5be1a5ae Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:52:18 -0300 Subject: Errors are said in words, and a refusal names what it takes A failure read `Del k|j: InvalidArgument`, `Kill: NoSuchCommand`, `ill-formed control message`, or nothing at all. reportError now spells an error's name as words, and the refusals name their accepted forms: pty/ctl lists its verbs, a flag file takes 1 or 0, a setting word takes on or off, Del takes k, j or nothing, Repl takes - or a language. Kill with nothing to stop says so, /focus says pane, a Look that found nothing says no match, and pty/run on a command pane says it is not a shell. A ctl write's failure has room for the Repl list and is cut between words, the Repl word at a character. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 6 ++++-- src/Messages.zig | 49 +++++++++++++++++++++++++++++++++++++++++-------- src/builtins.zig | 14 +++++++++----- src/esp32p4.zig | 2 +- src/exec.zig | 6 +++++- src/fs.zig | 6 +++--- src/gui/gui.zig | 2 +- src/look.zig | 7 +++++++ src/ninep/ctl.zig | 6 +++--- src/ninep/events.zig | 2 +- src/ninep/pane.zig | 6 ++++-- src/ninep/pty.zig | 28 ++++++++++++++++++++++++++-- src/pardes.zig | 20 ++++++++++++++++---- test/fs.py | 2 +- 14 files changed, 122 insertions(+), 34 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 8caaff3c..58c57867 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -186,7 +186,7 @@ the keyboard no pane does: `/focus` reads empty and every pane's `ctl` says `notcurrent`. A write gives the keyboard and nothing else: a folded pane stays folded (unfold it with `Collapse` on its ctl), as rio keeps `current` apart from `unhide`. A serial no pane has fails with `no such -window`; anything but a number, with `ill-formed control message`. +pane`; anything but a number, with `ill-formed control message`. A pane is made by **opening** `/pane/new`, and closed by Tremove on `/pane/` (`rmdir`), which is the only remove the tree serves; Tcreate is @@ -500,7 +500,9 @@ for ever: cancel the read (interrupt it, or close the open) to give up; `error not run` when the shell refused the line without running it (a fish syntax error; the line is taken back off the prompt); `error shell gone` when the pane closed or its shell was -replaced; `error no prompt marks` for a shell pardes could not instrument. +replaced; `error no prompt marks` for a shell pardes could not instrument; +`error command done; not a shell` (or `error a command runs here, not a +shell`) on a command pane, whose child is its command. It relies on the OSC 133 marks pardes injects into bash and fish, tagged `aid=pardes` so fish's own marks and a nested shell's are ignored. A second line on an open whose command still runs fails the write. `exec zsh` or a diff --git a/src/Messages.zig b/src/Messages.zig index f8178629..66261eb4 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -416,23 +416,51 @@ pub fn messageLog(m: *const Messages, i: usize) ?*const LoggedMessage { return &m.log[(first + i) % limits.message_log]; } +/// `: `: FileNotFound reads "file not found". pub fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) void { var buf: [256]u8 = undefined; - const text = std.fmt.bufPrint(&buf, "{s}: {s}", .{ operation, @errorName(err) }) catch operation; - reportFailure(p, id, text); + var w = std.Io.Writer.fixed(&buf); + w.print("{s}: ", .{operation}) catch {}; + for (@errorName(err), 0..) |c, i| { + if (std.ascii.isUpper(c) and i > 0) w.writeByte(' ') catch break; + w.writeByte(std.ascii.toLower(c)) catch break; + } + reportFailure(p, id, w.buffered()); +} + +/// 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 { + if (text.len <= max) return text; + if (std.mem.lastIndexOfScalar(u8, text[0 .. max + 1], ' ')) |sp| return text[0..sp]; + var n = max; + while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1; + return text[0..n]; } /// reportError with the words already chosen. pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { - // A builtin a ctl write runs: its first error is also the write's. + // A builtin a ctl write runs: its first error is also the write's, cut + // between words. if (p.fs.no_prompt and p.fs.failure_len == 0) { - const n = @min(text.len, p.fs.failure.len); - @memcpy(p.fs.failure[0..n], text[0..n]); + const kept = if (text.len > p.fs.failure.len) clip(text, p.fs.failure.len - 3) else text; + @memcpy(p.fs.failure[0..kept.len], kept); + var n = kept.len; + if (kept.len < text.len) { + @memcpy(p.fs.failure[n..][0..3], "..."); + n += 3; + } p.fs.failure_len = @intCast(n); } 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 @@ -534,14 +562,14 @@ test "Msg writes the transient row by hand, bare or with text, and input ends it // ...on the pane that ran it, and nowhere else try std.testing.expectEqualStrings("", row(p, 0)); - // Bare, it reports ITSELF through reportError — the `: ` + // Bare, it reports ITSELF through reportError — the `: ` // every failed save and refused Look arrives in. try std.testing.expect(p.executeBuiltinLine(2, "Msg")); - try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); + try std.testing.expectEqualStrings("Msg: no message", row(p, 2)); // Input starts its exit: it lingers, dissolves, and is gone. p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); + try std.testing.expectEqualStrings("Msg: no message", row(p, 2)); for (0..200) |_| p.update(.tick); try std.testing.expectEqualStrings("", row(p, 2)); // ...and with neither linger nor animation it is as old as your last input. @@ -764,6 +792,11 @@ test "a builtin announces itself on the message row, and Verbose silences it" { // for its announcement, which is correct and not what this is testing. try std.testing.expect(p.executeBuiltinLine(p.active, "Wrap")); try std.testing.expectEqualStrings("Wrap", pane.msg[0..pane.msg_len]); + // A value it does not take is said, in place of the announcement. + const wrapped = p.settings.wrap; + try std.testing.expect(p.executeBuiltinLine(p.active, "Wrap maybe")); + try std.testing.expectEqualStrings("Wrap: takes on or off", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(wrapped, p.settings.wrap); // The notice list is what the paint pass reads, so the announcement has to // reach it, not just the buffer. diff --git a/src/builtins.zig b/src/builtins.zig index 79c45325..2f34c647 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -319,8 +319,9 @@ test "Kill stops the commands pardes typed, bare all and by name those that matc } }; p.host = .{ .vtable = &killed.vtable }; - // Nothing running: nothing to stop, and never the shell. + // 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. @@ -488,7 +489,10 @@ pub const Kill = struct { } if (stopped) return; if (jobless) return c.p.reportFailure(c.id, "Kill: no job to signal (its shell runs it without job control)"); - if (names.len > 0) c.p.reportError(c.id, "Kill", error.NoSuchCommand); + if (names.len > 0) + c.p.reportFailure(c.id, "Kill: no running command has that first word") + else // said, but no failure: a script's Kill has nothing left to do + c.p.setMessage(c.id, "Kill: nothing running"); } }; @@ -804,7 +808,7 @@ pub const Del = struct { else if (std.mem.eql(u8, side, "j")) below orelse above else if (side.len > 0) - return c.p.reportError(c.id, "Del k|j", error.InvalidArgument) + return c.p.reportFailure(c.id, "Del: takes k, j or nothing") else null; // Someone at the keyboard with a real choice to make is asked, on the @@ -939,9 +943,9 @@ pub const Repl = struct { const named: ?u8 = if (manifest.byName(arg)) |i| if (grammars[i].exts.len > 0) @intCast(i) else null else null; const lang: u8 = named orelse { var w = std.Io.Writer.fixed(&buf); - w.print("Repl: no language \"{s}\"; one of", .{arg[0..@min(arg.len, 32)]}) catch {}; + w.print("Repl: no language \"{s}\"; - or one of:", .{@import("Messages.zig").clip(arg, 24)}) catch {}; for (grammars) |g| if (g.exts.len > 0) w.print(" {s}", .{g.name}) catch break; - return c.p.reportFailure(c.id, w.buffered()); + return c.p.reportFailure(c.id, @import("Messages.zig").clip(w.buffered(), 256)); }; if (pane.repl) |r| if (r.lang == lang) return c.p.setMessage(c.id, std.fmt.bufPrint(&buf, "Repl: {s}", .{exec.replId(&idbuf, pane)}) catch "Repl"); diff --git a/src/esp32p4.zig b/src/esp32p4.zig index 0d532e1e..45126a74 100644 --- a/src/esp32p4.zig +++ b/src/esp32p4.zig @@ -610,7 +610,7 @@ export fn pardes_esp32p4_quit() callconv(.c) bool { const pardes_host: pardes.Host.VTable = .{ .present = present, .gpio_toggle = gpioToggle }; /// The `Gpio` word's one seam to the board. Nothing here knows what a pad is; it forwards, and -/// answers false when the firmware brought none, which is what puts "gpio: NoPads" on the message +/// answers false when the firmware brought none, which is what puts "gpio: no pads" on the message /// row rather than a trap. fn gpioToggle(_: ?*anyopaque, pin: u16, was: *u8, now: *u8) bool { const f = host_gpio orelse return false; diff --git a/src/exec.zig b/src/exec.zig index 12934c3c..584d1b96 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -740,7 +740,11 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] if (!p.settings.requestFont(matches[0].path, matches[0].name, spec.size_hundredths)) return; p.font_request_taken = false; }, - else => _ = p.settings.apply(setting, arg), + else => if (!p.settings.apply(setting, arg) and p.announce) { + var text: [96]u8 = undefined; + const takes = if (setting.action == .toggle) "takes on or off" else "does not take that value"; + p.reportFailure(p.active, std.fmt.bufPrint(&text, "{s}: {s}", .{ setting.word, takes }) catch takes); + }, } if (p.settings.colors != previous_colors) { for (p.panes) |slot| { diff --git a/src/fs.zig b/src/fs.zig index 0b620c9f..b2e2751d 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1261,11 +1261,11 @@ pub const Namespace = struct { /// ctl answers a command's error (editors/acme/xfid.c:700). no_prompt: bool = false, refused: bool = false, - failure: [96]u8 = undefined, - failure_len: u8 = 0, + failure: [256]u8 = undefined, + failure_len: u16 = 0, /// A refusal that quotes the message it refuses, as Plan 9's cmderror /// does (kernel/misc/parse.c:82); answered at once (src/9p_io.zig). - ename: [128]u8 = undefined, + ename: [320]u8 = undefined, /// Something a held read may be waiting on changed since they were last /// answered: a record queued, a run answered, a pane gone. news: bool = false, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 0cfe80f5..cf708a0e 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1660,7 +1660,7 @@ test "GUI LSP worker limit rejects before allocation and recovers after owned wo try std.testing.expect(core.lsp_wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "WorkersBusy") != null); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "workers busy") != null); try std.testing.expectEqual(@as(usize, 0), failing.alloc_index); try std.testing.expect(!failing.has_induced_failure); try std.testing.expectEqual(rejected, queue.lsp_id.?); diff --git a/src/look.zig b/src/look.zig index d7e763d3..136a9ede 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1162,6 +1162,13 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { pane.search_row = null; _ = searchStep(p, id, 1); } + // A path that is not there searches for its text, and a search + // that found nothing says so rather than leave an empty buffer. + const results = if (pane.search_pane) |rid| p.panes[rid] else null; + if (results) |r| if (r.file) |f| if (f.content.len == 0) { + var said: [96]u8 = undefined; + p.setMessage(id, std.fmt.bufPrint(&said, "Look: no match for \"{s}\"", .{@import("Messages.zig").clip(trimmed, 48)}) catch "Look: no match"); + }; }, .pane => |t| { if (t.id >= MAX_PANES) return; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 4e1c039b..680a09b0 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -200,7 +200,7 @@ const Builtin = builtins.registry.Builtin(); /// Refuses a control message, quoting it the way Plan 9's cmderror does /// (kernel/misc/parse.c:82): `unknown control message "Bogus 3"`. fn refuse(p: *Pardes, req: Req, why: []const u8, line: []const u8) Reply { - const room = p.fs.ename.len - why.len - 3; + const room = p.fs.ename.len -| (why.len + 3); const text = std.fmt.bufPrint(&p.fs.ename, "{s} \"{s}\"", .{ why, line[0..@min(line.len, room)] }) catch why; return tree.failText(req.tag, E.INVAL, text); } @@ -399,7 +399,7 @@ pub fn writeFocus(p: *Pardes, req: Req) Reply { return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } -const e_no_pane = "no such window"; +const e_no_pane = "no such pane"; pub fn readPane(p: *Pardes, req: Req, pane: *Pane) Reply { var buf: [pane_text_cap]u8 = undefined; @@ -666,7 +666,7 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi // its line; the lines before it have taken effect, as in acme. const failed = wr(p, root_ctl, "Verbose on\nMount x\nVerbose off"); try testing.expectEqual(E.IO, failed.errno()); - try testing.expectEqualStrings("Mount name dial: MissingArgument \"Mount x\"", failed.reply.ename); + try testing.expectEqualStrings("Mount name dial: missing argument \"Mount x\"", failed.reply.ename); try testing.expect(p.settings.verbose); try testing.expect(!p.fs.no_prompt); try testing.expectEqual(Status.ok, wr(p, root_ctl, "Verbose off").reply.status); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index cff42c55..ffdea95b 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -877,7 +877,7 @@ test "a refused or failed write is an err record in the log, saying which file a _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus"); try testing.expectEqualStrings("err - ctl: unknown control message \"Bogus\"\n", next.record(p, f, frozen)); _ = wr(p, @intFromEnum(tree.TopFile.focus), "99999"); - try testing.expectEqualStrings("err - focus: no such window\n", next.record(p, f, frozen)); + try testing.expectEqualStrings("err - focus: no such pane\n", next.record(p, f, frozen)); // A write that succeeds says nothing. _ = wr(p, Node.of(serial, .addr), "#0"); try testing.expectEqual(Status.again, call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .off = frozen, .size = 4096 }).reply.status); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 77be80c6..d2b2a791 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -507,7 +507,7 @@ fn writeRange(req: Req, pane: *Pane, file: PaneFile) Reply { fn writeFlag(p: *Pardes, req: Req, pane: *Pane, file: PaneFile) Reply { const word = std.mem.trim(u8, req.data, " \t\r\n"); - if (!std.mem.eql(u8, word, "1") and !std.mem.eql(u8, word, "0")) return Reply.fail(req.tag, E.INVAL); + if (!std.mem.eql(u8, word, "1") and !std.mem.eql(u8, word, "0")) return tree.failText(req.tag, E.INVAL, "takes 1 or 0"); const on = word[0] == '1'; const pf = &pane.fs; switch (file) { @@ -873,8 +873,10 @@ test "the flag files read and write the state acme kept behind ctl verbs" { for ([_]u64{ dirty, mark, scroll }) |node| { try testing.expectEqual(@as(u64, 2), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size); - for ([_][]const u8{ "", "yes", "2", "0 1", "true" }) |bad| + for ([_][]const u8{ "", "yes", "2", "0 1", "true" }) |bad| { try testing.expectEqual(E.INVAL, wr(p, node, bad).errno()); + try testing.expectEqualStrings("takes 1 or 0", wr(p, node, bad).reply.ename); + } } try testing.expectEqualStrings("0\n", rd(p, dirty, 0, 8).bytes); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 88dafdfc..a2a40811 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -43,7 +43,7 @@ pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply { while (it.next()) |raw| { const line = std.mem.trim(u8, raw, " \t\r"); if (line.len == 0) continue; - if (!verb(p, id, line, apply)) return tree.failText(req.tag, E.INVAL, tree.e_bad_ctl); + if (!verb(p, id, line, apply)) return tree.failText(req.tag, E.INVAL, e_bad_pty_ctl); } } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; @@ -165,7 +165,10 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { const pf = &pane.fs; const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); const marks = &state.stream.handler; - if (pf.unmarked) { + if (pane.command != null) { + // Its child is the command, and no shell is there to take a line. + answer(p, slot, "error {s}", .{if (pane.command_done) "command done; not a shell" else "a command runs here, not a shell"}); + } else if (pf.unmarked) { answer(p, slot, "error no prompt marks", .{}); } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and (marks.phase != .input or !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)))) @@ -335,6 +338,7 @@ fn waitingRun(p: *Pardes, pane: *Pane) ?*Run { } const e_bad_line = "bad command line"; +const e_bad_pty_ctl = tree.e_bad_ctl ++ "; takes winsize COLS ROWS, sig INT|TERM|HUP|QUIT|KILL, or exec"; pub fn readData(p: *Pardes, req: Req, pf: *pane_files.State) Reply { if (pf.pty_out.empty()) return .{ .tag = req.tag, .status = .again }; @@ -505,6 +509,7 @@ test "every pty/ctl verb, and every refusal" { }) |bad| { const a = wr(p, ctl, bad); try testing.expectEqual(E.INVAL, a.errno()); + try testing.expectEqualStrings(e_bad_pty_ctl, a.reply.ename); // names what it takes try testing.expect(a.winsize == null); try testing.expect(a.signal == null); try testing.expect(!a.spawned); @@ -743,6 +748,25 @@ test "run answers how its command ended once the shell is back at a prompt" { for (p.fs.opens) |o| try testing.expect(o.node == 0); } +test "run on a command pane says no shell is there" { + const gpa = testing.allocator; + const p = try withTerm(gpa); + defer p.deinit(); + const node = Node.of(serialOf(p), .pty_run); + const pane = p.panes[0].?; + pane.command = try gpa.dupe(u8, "make"); + for ([_]struct { bool, []const u8 }{ + .{ false, "error a command runs here, not a shell\n" }, + .{ true, "error command done; not a shell\n" }, + }) |case| { + pane.command_done = case[0]; + const o = call(p, .{ .tag = 1, .op = .open, .node = node }); + _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = o.reply.handle, .data = "ls\n" }); + try testing.expectEqualStrings(case[1], call(p, .{ .tag = 3, .op = .read, .node = node, .handle = o.reply.handle, .size = 64 }).bytes); + _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = o.reply.handle }); + } +} + test "a run's answer says cut when its output's start is gone, and reads a bounded tail" { const gpa = testing.allocator; const p = try withTerm(gpa); diff --git a/src/pardes.zig b/src/pardes.zig index c5413672..45d96f88 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -552,7 +552,7 @@ test "Detach asks the frontend to leave, and says so when there is nothing to le p.perform(.{ .detach = asked }); const pane = p.panes[0].?; - try std.testing.expectEqualStrings("detach: NotAttached", pane.msg[0..pane.msg_len]); + try std.testing.expectEqualStrings("detach: not attached", pane.msg[0..pane.msg_len]); try std.testing.expect(!p.quit); } @@ -1924,14 +1924,14 @@ test "owned cwd preserves long paths aliases and failed updates" { try std.testing.expect(p.panes[free] == null); exec.saveTo(p, 0, "file.txt"); try std.testing.expectEqual(effects, p.effects_len); - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "PathTooLong") != null); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "path too long") != null); const current = pane.cwdSlice(); allocator.fail_index = allocator.alloc_index; p.setCwd(0, "/replacement"); try std.testing.expectEqual(current.ptr, pane.cwdSlice().ptr); try std.testing.expectEqualStrings(&path, pane.cwdSlice()); - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "OutOfMemory") != null); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "out of memory") != null); allocator.fail_index = std.math.maxInt(usize); p.setCwd(0, "/replacement"); try std.testing.expectEqualStrings("/replacement", pane.cwdSlice()); @@ -2482,7 +2482,7 @@ test "a builtin that needs a pane reports capacity failure when every slot is fu }; const help = std.meta.stringToEnum(Builtin, "Help") orelse return error.MissingHelpBuiltin; exec.runBuiltin(p, help, 0, "", null); - try std.testing.expect(std.mem.indexOf(u8, p.panes[0].?.msg[0..p.panes[0].?.msg_len], "help: NoPaneSlots") != null); + try std.testing.expect(std.mem.indexOf(u8, p.panes[0].?.msg[0..p.panes[0].?.msg_len], "help: no pane slots") != null); } test "Font keeps requested and acknowledged faces as separate plain state" { @@ -6997,6 +6997,7 @@ test "Del from a key asks which neighbour takes the rows; nothing else asks" { // A word that is not a side closes nothing. try std.testing.expect(p.executeBuiltinLine(again, "Del x")); + try std.testing.expectEqualStrings("Del: takes k, j or nothing", p.panes[again].?.msg[0..p.panes[again].?.msg_len]); try std.testing.expect(p.panes[again] != null); // DelAbove is Del k, and a line that is not a key never asks. try std.testing.expect(p.executeBuiltinLine(again, "DelAbove")); @@ -7024,6 +7025,17 @@ test "Del from a key asks which neighbour takes the rows; nothing else asks" { try std.testing.expect(p.panes[low] == null); } +test "a Look that finds nothing says so" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + p.newScratchBelow(p.active); + const id = p.active; + p.sync(); + look.lookAt(p, id, "/no/such/zzqq"); + try std.testing.expectEqualStrings("Look: no match for \"/no/such/zzqq\"", p.panes[id].?.msg[0..p.panes[id].?.msg_len]); +} + test "focus on a closed pane goes to the pane that takes its place, not the one focused before" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); diff --git a/test/fs.py b/test/fs.py index 45c38c2e..53a9d4df 100644 --- a/test/fs.py +++ b/test/fs.py @@ -246,7 +246,7 @@ def discovery(binary, embedded=False): client.write('/focus', b'99999\n') raise AssertionError('focus took a serial no pane has') except OSError as refused: - assert 'no such window' in str(refused), refused + assert 'no such pane' in str(refused), refused # /ctl reads the settings as a write takes them and takes the # session's builtins; a pane's ctl takes the pane's. settings = client.read('/ctl') -- cgit v1.3 From 63d584a0ba7806759f7139e87f45e411c9a1573d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 17:27:30 -0300 Subject: A Save the host cannot do fails the 9P write that asked for it, and the log names the path and why The write answered ok and the pane stayed dirty, with `save: AccessDenied` on its message row: a script saw success. The failure now says `Save : `, and a 9P write that waited on the save fails with EIO and that text, logged as an err record. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 8 ++++++++ src/detached/server.zig | 2 +- src/fs.zig | 5 +++++ src/gui/gui.zig | 2 +- src/macos.zig | 2 +- src/pardes.zig | 16 ++++++++++++---- src/tty/tty.zig | 2 +- test/fs.py | 10 ++++++++++ 8 files changed, 39 insertions(+), 8 deletions(-) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 2ca11a87..6bd03049 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -296,7 +296,15 @@ pub const Listener = struct { // Set with the turn still held, so `reset` sees it and waits. if (restoring) l.restore_writer.store(true, .release); defer if (restoring) l.restore_writer.store(false, .release); + core.fs.late_failure_len = 0; if (core.effects_len != 0) pardes.turn.awaitSettled(epoch); + // ponytail: one slot, so a failure of another client's effects that + // settle in the same wait is told to this write too. + if (l.core == core and core.fs.late_failure_len != 0) { + const failed = pardes.ctlfs.failText(req.tag, pardes.ctlfs.E.IO, core.fs.late_failure[0..core.fs.late_failure_len]); + pardes.ctlfs.events.noteError(core, req, failed); + return conn.reply(&failed, ""); + } // The Restore's own write is answered once it is done, and before // `reset` hangs every connection up, this one too, so the writer // hears that it happened rather than a cut; a failed one leaves the diff --git a/src/detached/server.zig b/src/detached/server.zig index 5374bf73..3921d8d9 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -555,7 +555,7 @@ pub const Session = struct { fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { const s = of(ctx); filesystem.write(s.core, path, bytes) catch |err| - return s.core.saveFailed(pane, "save", err); + return s.core.saveFailed(pane, path, err); if (s.core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { if (s.watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, diff --git a/src/fs.zig b/src/fs.zig index b2e2751d..2dc3394b 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1263,6 +1263,11 @@ pub const Namespace = struct { refused: bool = false, failure: [256]u8 = undefined, failure_len: u16 = 0, + /// What went wrong performing a write's effects after it was answered + /// by the core (a save the host could not do): the 9P write, which + /// waits for them, fails with it (src/9p_io.zig). + late_failure: [256]u8 = undefined, + late_failure_len: u16 = 0, /// A refusal that quotes the message it refuses, as Plan 9's cmderror /// does (kernel/misc/parse.c:82); answered at once (src/9p_io.zig). ename: [320]u8 = undefined, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 5bc1ea6d..84ec1c5c 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -4422,7 +4422,7 @@ fn killJob(ctx: ?*anyopaque, pane: u8) bool { fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { const s = shellOf(ctx); filesystem.write(s.core, path, bytes) catch |err| - return s.core.saveFailed(pane, "save", err); + return s.core.saveFailed(pane, path, err); if (s.core.panes[pane]) |pane_state| if (pane_state.file) |f| { if (std.mem.eql(u8, f.path, path)) if (s.watches[pane]) |*w| if (w.serial == pane_state.serial) switch (w.generation) { diff --git a/src/macos.zig b/src/macos.zig index b472e6cc..b180d7ba 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -2487,7 +2487,7 @@ fn killJob(ctx: ?*anyopaque, pane: u8) bool { fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { const st = hostState(ctx); filesystem.write(st.core, path, bytes) catch |err| - return st.core.saveFailed(pane, "save", err); + return st.core.saveFailed(pane, path, err); st.file_watches.restampText(pane, path, std.hash.Wyhash.hash(0, bytes)); var mbuf: [256]u8 = undefined; st.core.setMessage(pane, message.stamp(&mbuf, "saved", path)); diff --git a/src/pardes.zig b/src/pardes.zig index f559b125..581f616e 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -2261,7 +2261,7 @@ test "a save the host could not do leaves the pane dirty" { const Refusing = struct { fn writeFile(ctx: ?*anyopaque, pane: u8, _: []const u8, _: []const u8) void { const core: *Pardes = @ptrCast(@alignCast(ctx.?)); - core.saveFailed(pane, "save", error.PermissionDenied); + core.saveFailed(pane, "/x/y.txt", error.PermissionDenied); } }; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); @@ -4906,15 +4906,23 @@ pub const Pardes = struct { if (p.host.vtable.write_file) |f| return f(p.host.ctx, pane, path, bytes); // The in-process filesystem reports the same way a real host does, so // an OOM here leaves the pane dirty rather than looking saved. - if (!p.fallback.writeFile(path, bytes)) p.saveFailed(pane, "save", error.OutOfMemory); + if (!p.fallback.writeFile(path, bytes)) p.saveFailed(pane, path, error.OutOfMemory); } - pub fn saveFailed(p: *Pardes, id: u8, what: []const u8, err: anyerror) void { + /// A write of `path` the host could not do: the pane stays dirty, the + /// message row says `Save : `, and the 9P write that asked + /// for it, waiting on the save, fails with that (`fs.late_failure`). + pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { if (p.panes[id]) |pane| if (pane.file) |*f| { // The `-%` spelling fs.zig already uses for "make this dirty". f.saved_revision = f.revision -% 1; }; - p.reportError(id, what, err); + var what: [limits.host_path_cap + 8]u8 = undefined; + p.reportError(id, std.fmt.bufPrint(&what, "Save {s}", .{path}) catch "Save", err); + const said = if (p.panes[id]) |pane| pane.msg[0..pane.msg_len] else "Save failed"; + const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len); + @memcpy(p.fs.late_failure[0..kept.len], kept); + p.fs.late_failure_len = @intCast(kept.len); } /// The path a watch is about: a real file's, or a PDF's. diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 822c2d7f..d17316e8 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1314,7 +1314,7 @@ const Shell = struct { fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { const s = of(ctx); filesystem.write(s.core, path, bytes) catch |err| - return s.core.saveFailed(pane, "save", err); + return s.core.saveFailed(pane, path, err); if (s.core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { if (s.watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, diff --git a/test/fs.py b/test/fs.py index 53a9d4df..72c52b7e 100644 --- a/test/fs.py +++ b/test/fs.py @@ -360,6 +360,16 @@ def discovery(binary, embedded=False): # Through a mount both read as EINVAL; the log says which and why. assert f'err {scratch} addr: no match for regexp\n'.encode() in client.read('/log') client.remove(f'/pane/{scratch}') + # A save the host cannot do fails the write that asked for it, + # and the log's err record names the path and why. + unsaved = new_pane(client, b'unsaved\n') + try: + client.write(f'/pane/{unsaved}/ctl', b'Save /nonexistent-pardes-dir/x.txt\n') + raise AssertionError('a Save into a missing directory succeeded') + except OSError as refused: + assert 'Save /nonexistent-pardes-dir/x.txt: ' in str(refused), refused + assert f'err {unsaved} ctl: Save /nonexistent-pardes-dir/x.txt: '.encode() in client.read('/log'), client.read('/log') + client.remove(f'/pane/{unsaved}') print('9P discovery: listing/stat/find are inert; new, remove, look, exec, name, sel, log, ctl lock, focus, the ctl split and commands behave') -- cgit v1.3 From c5fcbc0cb9c1e76bb01283e9ccfa00ed5bc4bef8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 17:58:05 -0300 Subject: What a root ctl write says is the session's in the log, msg -, not the active pane's A session builtin written to /ctl runs at the active pane, so its messages were logged under that pane's serial, as if the pane had said them. They are now `msg -`, and still shown on the active pane. Co-Authored-By: Claude Opus 5.5 --- src/Messages.zig | 2 +- src/fs.zig | 3 +++ src/ninep/ctl.zig | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) (limited to 'src/fs.zig') diff --git a/src/Messages.zig b/src/Messages.zig index ea62041f..cc4b3656 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -407,7 +407,7 @@ pub fn blendRgb(from: [3]u8, to: [3]u8, amount: f32) [3]u8 { fn logMessage(p: *Pardes, id: usize, text: []const u8) void { if (text.len == 0) return; - const serial: u32 = if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; + const serial: u32 = if (p.fs.session_write) 0 else if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; const kept = text[0..@min(text.len, LoggedMessage.cap)]; // /log hears every one: a client that retried and failed the same way // is waiting on that second line. Only the +Messages view collapses. diff --git a/src/fs.zig b/src/fs.zig index 2dc3394b..42d761ca 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1260,6 +1260,9 @@ pub const Namespace = struct { /// the first error one reports (`failure`) fails the write, as acme's /// ctl answers a command's error (editors/acme/xfid.c:700). no_prompt: bool = false, + /// The root ctl is running a session builtin: its messages are the + /// session's, logged `msg -`, though shown on the active pane. + session_write: bool = false, refused: bool = false, failure: [256]u8 = undefined, failure_len: u16 = 0, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 8b73e8f7..bb562672 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -344,6 +344,8 @@ pub fn writeRoot(p: *Pardes, req: Req) Reply { continue; } if (p.panes[p.active] == null) return Reply.fail(req.tag, E.NOENT); + p.fs.session_write = true; + defer p.fs.session_write = false; if (runBuiltin(p, req, p.active, line)) |refusal| return refusal; } } @@ -742,6 +744,21 @@ test "a second lock is refused until the holder unlocks or closes, and binds nob for (p.fs.opens) |o| try testing.expect(o.node == 0); } +test "a message from a root ctl write is the session's in the log" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + p.update(.tick); // the pane's `new` is logged before the log is opened + while (p.nextEffect()) |_| {} + const log = @intFromEnum(tree.TopFile.log); + const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; + const frozen = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 8192 }).bytes.len; + _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); + try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "Kill\n").reply.status); + // The builtin's name, then what it said: both the session's. + try testing.expectEqualStrings("msg - Kill\n", call(p, .{ .tag = 4, .op = .read, .node = log, .handle = f, .off = frozen, .size = 4096 }).bytes); + try testing.expectEqualStrings("msg - Kill: nothing running\n", call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .off = frozen, .size = 4096 }).bytes); +} + test "a look takes acme's :addr and file:addr, and a miss changes nothing" { const gpa = testing.allocator; const p = try withFile(gpa, "foo x foo y\nbar\n"); -- cgit v1.3 From 8948c9ec1b8ade3d1e4ed7103fd4f6d17a8ea23e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 19:00:49 -0300 Subject: A replace through data or body, truncate then write, is one undo step A shell's printf x > data truncates the addressed range and then writes, and each pushed its own undo point, so one replace took two Undos. A truncation of data, xdata or body now lets the write that follows it at once join its step, as acme's replace is one. Co-Authored-By: Claude Opus 5.5 --- src/fs.zig | 3 ++- src/ninep/pane.zig | 22 +++++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index 42d761ca..0a4473d6 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -598,7 +598,8 @@ test "virtual body writes can read their input from the same pane" { 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); - try std.testing.expectEqual(@as(usize, 2), pane.file.?.history.undo_len); + // The truncation and the write are one undo step. + try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); const events = &p.panes[p.active].?.fs.events; try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "ED")); events.pop(); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index a5acccbc..50fc220e 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -47,6 +47,10 @@ pub const State = struct { event_reader: bool = false, events: events.Queue = .{}, nomark: bool = false, + /// The revision a truncation of `data`, `xdata` or `body` left: the + /// write that follows it at once joins its undo step, so a shell's + /// `printf x > data` is one step, as acme's replace is. + joined: ?u32 = null, noscroll: bool = false, tag_snap: std.ArrayList(u8) = .empty, /// An open reads pty/data, so output queues for it; a second is refused. @@ -190,7 +194,9 @@ pub fn spliceBody(p: *Pardes, pane: *Pane, q0: usize, q1: usize, bytes: []const @memcpy(new[0..lo], f.content[0..lo]); @memcpy(new[lo..][0..take], bytes[0..take]); @memcpy(new[lo + take ..], f.content[hi..]); - if (!pane.fs.nomark) panes.File.pushUndo(p, pane); + const join = pane.fs.joined == f.revision; + pane.fs.joined = null; + if (!pane.fs.nomark and !join) panes.File.pushUndo(p, pane); panes.File.setContent(p, f, new); return take; } @@ -614,6 +620,7 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { switch (file) { .body => if (fileOf(pane) != null) { _ = spliceBody(p, pane, 0, bodyOf(pane).len, "") orelse return .err; + pf.joined = fileOf(pane).?.revision; pf.addr = .{}; setDot(pane, .{}); }, @@ -623,6 +630,7 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { const q1 = @max(q0, pf.addr.q1); const before = dotOf(pane); _ = spliceBody(p, pane, q0, q1, "") orelse return .err; + pf.joined = fileOf(pane).?.revision; setDot(pane, .{ .q0 = shiftOne(before.q0, q0, q1 - q0, 0), .q1 = shiftOne(before.q1, q0, q1 - q0, 0) }); pf.addr = .{ .q0 = q0, .q1 = q0 }; }, @@ -909,6 +917,18 @@ test "the flag files read and write the state acme kept behind ctl verbs" { try testing.expectEqual(E.INVAL, wr(term, Node.of(serialOf(term), .dirty), "1").errno()); } +test "a replace through data, truncate then write, is one undo step" { + const p = try withFile(testing.allocator, "one two\n"); + defer p.deinit(); + const serial = serialOf(p); + _ = wr(p, Node.of(serial, .addr), "/two/"); + _ = call(p, .{ .tag = 1, .op = .setattr, .node = Node.of(serial, .data), .truncate = true }); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .data), "2").reply.status); + try testing.expectEqualStrings("one 2\n", rd(p, Node.of(serial, .body), 0, 64).bytes); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status); + try testing.expectEqualStrings("one two\n", rd(p, Node.of(serial, .body), 0, 64).bytes); +} + test "writes under mark 0 are one undo step, even with no history before them" { const p = try withFile(testing.allocator, "one\n"); defer p.deinit(); -- cgit v1.3 From 64b6a0dbdaab4b314ccbce667709d71a8561daf0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 00:01:04 -0300 Subject: The tree serves the layout: /layout, /tag and /col//tag A script could not see where the panes sit or edit the tags a person clicks in. /layout lists each column, its index, x and width in cells, current or not, empty or full, and its panes' serials, then the active column; /tag is the workspace tag and /col//tag a column's, read and written as a pane tag is (one line: a newline written in is a space, and a truncating write drops the one ending it); /index's lines end with the pane's column; the log says newcol and delcol . acme serves no column files, and the docs say so. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 4 +- README.md | 5 +- docs/fs.md | 16 +++- src/fs-help.txt | 5 +- src/fs.zig | 5 ++ src/layout.zig | 11 ++- src/ninep/cols.zig | 163 ++++++++++++++++++++++++++++++++++++++ src/ninep/events.zig | 4 + src/ninep/pane.zig | 15 +++- src/ninep/tree.zig | 111 +++++++++++++++++++++----- test/selfmount.py | 6 +- 11 files changed, 315 insertions(+), 30 deletions(-) create mode 100644 src/ninep/cols.zig (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index b16039d2..a5447991 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -52,7 +52,7 @@ match this document, that session predates the change; restart it. ``` $m/README the served guide, worth reading first -$m/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name +$m/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name, column $m/status pid, version, panes $m/look write a line = a right click on it at the active pane (file:/re/, file:#n, :/re/ select by address, as acme's look, from the file's dot: file:0/re/ for the @@ -82,6 +82,8 @@ $m/ctl the settings, one a line as a write takes them; write a setting or a pane's builtins (Del, Save f, Collapse, which folds that pane, and the column word Delcol, which closes that pane's column) go to $m/pane//ctl $m/commands every builtin: `Word`, `Word arg`, then `root` or `pane` (which ctl takes it) +$m/layout one line per column: index x width current|notcurrent empty|full serials...; active +$m/tag the workspace tag (> replaces, >> appends, one line); $m/col//tag a column's, n from 0 $m/pane/new open it to make a pane (a scratch named /+New), read names it; it goes in the ACTIVE column (the one last typed or clicked in, or Newcol's), filling it if empty, else taking the bottom half of its last pane (ctl `Placement pardes`: the old rules); diff --git a/README.md b/README.md index 267b5ca7..e487bf9c 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,10 @@ to refresh. Mini snapshots survive Dump/Restore without rereading the source. On Linux, `Tty9p` (`SPC n 9`) opens a terminal with the session's 9P tree mounted through kernel v9fs. It asks sudo in that pane, then starts your shell as your normal user. Access the tree through `$PARDES_MOUNT`. -See [mounted terminals](docs/v9fs.md). +See [mounted terminals](docs/v9fs.md). Beyond acme's per-window files the tree +serves the layout: `/layout` lists the columns, their places and panes, and +`/tag` and `/col//tag` are the workspace and column tags, editable like a +window's ([the tree](docs/fs.md#the-served-tree)). ## Requirements diff --git a/docs/fs.md b/docs/fs.md index 89a513e8..5f382e7e 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -92,7 +92,7 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. ``` /README this guide, also src/fs-help.txt -/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name +/index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name, column /status pid, version and pane count /look write a line: a right click on it at the active pane; read: the serials the last look, exec or ctl write touched (made, else acted at) @@ -105,6 +105,10 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. /focus the serial of the pane with the keyboard; write a serial to give it the keyboard /ctl the settings, one a line as a write takes them; write a setting or a session builtin /commands every builtin: word, `arg` if it takes one, `root` or `pane` (the ctl that takes it), a setting's values +/layout one line per column: index x width current|notcurrent empty|full serials...; + then active (- when no column has the keyboard) +/tag the workspace tag; > replaces it, >> appends, one line +/col//tag column n's tag, the same way; columns count from 0, left to right /pane/new open it to make a pane; the read answers that pane's serial /pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec, plus pty/{ctl,status,data} on terminals @@ -112,6 +116,16 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. /src/ the editor's embedded sources, only when built with -Dembed-sources=true ``` +`/layout`, `/tag` and `/col` go past acme, which serves no column files -- +its columns are only where a window sits. They are here so a script can see +where the panes are (`/index`'s last word is each one's column, the same +index) and edit the tags a person clicks in: a column tag is one line, a +newline written into it a space, and a truncating write (`echo Make > +col/0/tag`) clears it and drops the newline that ends it, as a pane tag's +does. A column is named by its index, so the columns right of one that +closes move down one; the log says `newcol ` and `delcol ` as they come +and go, with /layout to read again. + Control messages are split by what they act on, as acme keeps window verbs on a window's ctl and webfs and upas/fs keep session settings on a root ctl. Each builtin declares its scope in src/builtins.zig (`scope = .session`; diff --git a/src/fs-help.txt b/src/fs-help.txt index 0121a831..2f944c8e 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -1,7 +1,7 @@ Pardes control filesystem ========================= README this guide -index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name (+New if unnamed) +index one line per pane: serial, kind (text|term|pdf|image), dirty flag, name (+New if unnamed), column status pid, version and pane count look write a line: a right click on it at the active pane; read: the serials it touched exec write a line: a middle click, an editor command word or a shell line; read the same @@ -11,6 +11,9 @@ listeners the session's dial addresses focus the serial of the pane with the keyboard (empty on a column tag); write a serial to give it the keyboard ctl settings, one a line; or Newcol (an empty column), Dump, Exit (quits, asks once), Kill [w] (stops what pardes ran, w: by first word) commands every builtin: its word, arg if it takes one, and root or pane: which ctl takes it +layout one line per column: index x width current|notcurrent empty|full serials...; then active +tag the workspace tag: read it, > replaces it, >> appends (one line) +col//tag a column's tag, the same way (columns count from 0, as in layout) pane/new open it to make a pane (named +New) in the active column, filling it if empty; the read answers its serial pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll errors (write-only: appended to its directory's +Errors pane) event look exec, pty/ on terminals; rmdir closes diff --git a/src/fs.zig b/src/fs.zig index 0a4473d6..21ccc94e 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1270,6 +1270,11 @@ pub const Namespace = struct { /// What went wrong performing a write's effects after it was answered /// by the core (a save the host could not do): the 9P write, which /// waits for them, fails with it (src/9p_io.zig). + /// A header tag truncated by an open not yet released (ninep/cols.zig): + /// 0 the workspace's, a column's its index + 1; and whether the newline + /// that ended its last write is held back. + header_rewrite: ?u32 = null, + header_held: bool = false, late_failure: [256]u8 = undefined, late_failure_len: u16 = 0, /// A refusal that quotes the message it refuses, as Plan 9's cmderror diff --git a/src/layout.zig b/src/layout.zig index c58f3bcf..6de7a912 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -280,7 +280,7 @@ pub fn applyRowSplit(p: *Pardes, cc: usize, k: usize, cur_y: u16) void { b.vweight = pair - a.vweight; } -pub fn findPane(p: *Pardes, id: usize) ?struct { col: usize, idx: usize } { +pub fn findPane(p: *const Pardes, id: usize) ?struct { col: usize, idx: usize } { for (0..p.ncol) |c| { for (0..p.col_n[c]) |k| { if (p.col_panes[c][k] == id) return .{ .col = c, .idx = k }; @@ -325,6 +325,14 @@ pub fn dropColumn(p: *Pardes, c: usize) void { p.ncol -= 1; p.col_tags[p.ncol] = .{ .what = .column, .gpa = p.gpa }; p.col_serial[p.ncol] = 0; + noteColumn(p, "delcol", c); +} + +/// `newcol ` or `delcol ` in the log: the index, as /layout and +/// /col number columns, the ones after it moving up or down one. +fn noteColumn(p: *Pardes, what: []const u8, c: usize) void { + var buf: [16]u8 = undefined; + pardes.ctlfs.events.notePath(p, what, std.fmt.bufPrint(&buf, "{d}", .{c}) catch return); } /// Fold column `c` into the one on its right, its panes below theirs. @@ -480,6 +488,7 @@ pub fn insertColumn(p: *Pardes, col: usize, before: bool) ?usize { p.col_serial[c] = 0; p.col_n[c] = 0; p.ncol += 1; + noteColumn(p, "newcol", c); return c; } diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig new file mode 100644 index 00000000..e1688517 --- /dev/null +++ b/src/ninep/cols.zig @@ -0,0 +1,163 @@ +//! The layout and the header tags: /layout, /tag (the workspace's) and +//! /col//tag (each column's). acme serves no column files -- its columns +//! are only a window's place -- so these go past it: a script can see where +//! the panes are and edit the tags a person clicks in. +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const Pardes = pardes.Pardes; +const tree = @import("tree.zig"); +const tagline = pardes.tagline; +const layout = pardes.layout; +const Text = pardes.panes.Text; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; + +/// The column with the keyboard: the header's, when a column tag has it, +/// else the active pane's. Null when the workspace tag has it and no pane +/// is active. +pub fn activeColumn(p: *const Pardes) ?usize { + if (p.header_focus) if (p.header_column) |c| return if (c < p.ncol) c else null; + const at = layout.findPane(p, p.active) orelse return null; + return at.col; +} + +/// One line a column: its index, x and width in cells, `current` or +/// `notcurrent` (rio's words, for the column with the keyboard), `empty` or +/// `full`, and its panes' serials, top to bottom; then `active `. +pub fn writeLayout(p: *const Pardes, w: *std.Io.Writer) !void { + const active = activeColumn(p); + for (0..p.ncol) |c| { + try w.print("{d} {d} {d} {s} {s}", .{ + c, p.col_x[c], p.col_w[c], + if (active == c) "current" else "notcurrent", if (p.col_n[c] == 0) "empty" else "full", + }); + for (p.col_panes[c][0..p.col_n[c]]) |id| if (p.panes[id]) |pane| try w.print(" {d}", .{pane.serial}); + try w.writeByte('\n'); + } + if (active) |c| try w.print("active {d}\n", .{c}) else try w.writeAll("active -\n"); +} + +pub fn layoutLen(p: *const Pardes) u64 { + var buf: [256]u8 = undefined; + var counting: std.Io.Writer.Discarding = .init(&buf); + writeLayout(p, &counting.writer) catch return 0; + return counting.fullCount(); +} + +/// The header a node names: the workspace's (`col` null) or a column's. +fn header(p: *Pardes, col: ?usize) ?*Text { + const c = col orelse return &p.global_tag; + return if (c < p.ncol) &p.col_tags[c] else null; +} + +pub fn headerText(p: *Pardes, col: ?usize) ?[]const u8 { + const c = col orelse return tagline.topbar(p); + return if (c < p.ncol) tagline.columnTag(p, c) else null; +} + +pub fn read(p: *Pardes, req: Req, col: ?usize) Reply { + const text = headerText(p, col) orelse return Reply.fail(req.tag, E.NOENT); + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM); + out.append(p.gpa, '\n') catch return Reply.fail(req.tag, E.NOMEM); + return tree.stagedReply(p, req); +} + +/// A write appends, as a pane tag's does; the tag is one line, so a newline +/// in it becomes a space (tagline.flattenHeaders), but after a truncation +/// the newline that ends the write is dropped, as a pane tag drops it. +pub fn write(p: *Pardes, req: Req, col: ?usize) Reply { + const t = header(p, col) orelse return Reply.fail(req.tag, E.NOENT); + if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; + const was = headerText(p, col).?; + var data = req.data; + const rewriting = p.fs.header_rewrite == rewriteKey(col); + // A newline held from the write before goes in once more text follows. + const held: []const u8 = if (rewriting and p.fs.header_held) " " else ""; + p.fs.header_held = false; + if (rewriting and data[data.len - 1] == '\n') { + data = data[0 .. data.len - 1]; + p.fs.header_held = true; + } + const next = std.mem.concat(p.gpa, u8, &.{ was, held, data }) catch return Reply.fail(req.tag, E.NOMEM); + std.mem.replaceScalar(u8, next, '\n', ' '); + if (t.own) |own| p.gpa.free(own); + t.own = next; + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +/// Truncating clears it, as a pane tag's `cleartag`: its default words go +/// too, and `u` in it brings them back. +pub fn truncate(p: *Pardes, col: ?usize) tree.Status { + const t = header(p, col) orelse return .err; + const empty = p.gpa.alloc(u8, 0) catch return .err; + t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null); + if (t.own) |own| p.gpa.free(own); + t.own = empty; + t.cur_row = 0; + t.cur_col = 0; + p.fs.header_rewrite = rewriteKey(col); + p.fs.header_held = false; + return .ok; +} + +/// Which header a truncation was of: the workspace's is 0, a column's its +/// index + 1. +fn rewriteKey(col: ?usize) u32 { + return if (col) |c| @intCast(c + 1) else 0; +} + +pub fn released(p: *Pardes, col: ?usize) void { + if (p.fs.header_rewrite != rewriteKey(col)) return; + p.fs.header_rewrite = null; + p.fs.header_held = false; +} + +// ---- 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(); + p.newColumn(p.active); + p.sync(); + const layout_node = @intFromEnum(tree.TopFile.layout); + const text = th.rd(p, layout_node, 0, 4096).bytes; + var want: [256]u8 = undefined; + const first = try std.fmt.bufPrint(&want, "0 {d} {d} notcurrent full {d}\n", .{ p.col_x[0], p.col_w[0], p.panes[0].?.serial }); + try testing.expect(std.mem.startsWith(u8, text, first)); + // Newcol gives the new, empty column's tag the keyboard. + try testing.expect(std.mem.indexOf(u8, text, "current empty\n") != null); + try testing.expect(std.mem.endsWith(u8, text, "active 1\n")); + try testing.expectEqual(@as(u64, text.len), th.call(p, .{ .tag = 1, .op = .getattr, .node = layout_node }).reply.attr.size); + // /index says which column each pane is in, last. + try testing.expect(std.mem.endsWith(u8, th.rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, " 0\n")); + try testing.expect(th.logHas(p, "newcol 1\n")); +} + +test "a column's tag and the workspace's read, replace and append as a pane tag does, on one line" { + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + const col_dir = @intFromEnum(tree.TopFile.col); + try testing.expectEqual(tree.Status.ok, th.look_up(p, col_dir, "0").reply.status); + try testing.expectEqual(E.NOENT, th.look_up(p, col_dir, "7").errno()); + const tag = Node.ofCol(0, .tag); + try testing.expectEqual(tree.Status.ok, th.look_up(p, Node.ofCol(0, .dir), "tag").reply.status); + try testing.expectEqualStrings("New Tty Find Grep Joincol Delcol\n", th.rd(p, tag, 0, 4096).bytes); + // `echo Make > tag`: cleared, then the newline ending the write dropped. + _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true }); + _ = th.wr(p, tag, "Make\n"); + try testing.expectEqualStrings("Make\n", th.rd(p, tag, 0, 4096).bytes); + _ = th.call(p, .{ .tag = 2, .op = .release, .node = tag }); + // `>>` appends; a newline in a one-line tag is a space. + _ = th.wr(p, tag, " Lint\nNow"); + try testing.expectEqualStrings("Make Lint Now\n", th.rd(p, tag, 0, 4096).bytes); + const top = @intFromEnum(tree.TopFile.tag); + _ = th.call(p, .{ .tag = 3, .op = .setattr, .node = top, .truncate = true }); + _ = th.wr(p, top, "Newcol Exit\n"); + try testing.expectEqualStrings("Newcol Exit", tagline.topbar(p)); +} diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 0e489be7..fc410d5a 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -172,6 +172,10 @@ pub fn noteError(p: *Pardes, req: Req, reply: Reply) void { if (req.node != pardes.filesystem.os_root and req.node & pardes.filesystem.os_node == 0 and req.node & tree.sources.archive_node == 0) { if (tree.Node.target(req.node)) |t| switch (t) { .top => |f| file = f.fileName(), + .col => |c| { + serial = "-"; + file = std.fmt.bufPrint(&name, "col/{d}/tag", .{c.index}) catch "col"; + }, .pane => |pt| { serial = std.fmt.bufPrint(&name, "{d}", .{pt.serial}) catch "-"; file = switch (pt.file) { diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3eafdbce..6542d747 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -265,6 +265,12 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { // ---- the index ---- +/// The column a pane is in, as /layout and /col number them; the last word +/// of its /index line. +pub fn columnOf(p: *const Pardes, id: usize) usize { + return if (pardes.layout.findPane(p, id)) |at| at.col else 0; +} + pub fn indexLen(p: *Pardes) u64 { var n: u64 = 0; var last: u32 = 0; @@ -274,6 +280,7 @@ pub fn indexLen(p: *Pardes) u64 { var digits: [16]u8 = undefined; n += (std.fmt.bufPrint(&digits, "{d}", .{serial}) catch unreachable).len; n += 1 + kindOf(pane).len + 3 + nameOf(pane).len + 1; + n += 1 + (std.fmt.bufPrint(&digits, "{d}", .{columnOf(p, p.paneBySerial(serial).?)}) catch unreachable).len; } return n; } @@ -703,7 +710,7 @@ test "index lists serial kind dirty flag and name and stat reports its length" { const a = rd(p, index, 0, 4096); try testing.expectEqual(Status.ok, a.reply.status); var want: [64]u8 = undefined; - const clean_row = try std.fmt.bufPrint(&want, "{d} text 0 /test.txt\n", .{pane.serial}); + const clean_row = try std.fmt.bufPrint(&want, "{d} text 0 /test.txt 0\n", .{pane.serial}); try testing.expect(std.mem.indexOf(u8, a.bytes, clean_row) != null); const at = std.mem.indexOf(u8, a.bytes, clean_row).?; const stat = call(p, .{ .tag = 1, .op = .getattr, .node = index }); @@ -712,7 +719,7 @@ test "index lists serial kind dirty flag and name and stat reports its length" { pane.file.?.saved_revision = pane.file.?.revision -% 1; var dirty_want: [64]u8 = undefined; - const dirty_row = try std.fmt.bufPrint(&dirty_want, "{d} text 1 /test.txt\n", .{pane.serial}); + const dirty_row = try std.fmt.bufPrint(&dirty_want, "{d} text 1 /test.txt 0\n", .{pane.serial}); try testing.expect(std.mem.indexOf(u8, rd(p, index, 0, 4096).bytes, dirty_row) != null); const kind = at + std.mem.indexOfScalar(u8, clean_row, ' ').? + 1; try testing.expectEqualStrings("text", rd(p, index, kind, 4).bytes); @@ -722,7 +729,7 @@ test "index lists serial kind dirty flag and name and stat reports its length" { try testing.expectEqual(@as(u64, both.bytes.len), indexLen(p)); var expected: [4200]u8 = undefined; const made = p.panes[p.paneBySerial(serial).?].?; - try testing.expect(std.mem.endsWith(u8, both.bytes, try std.fmt.bufPrint(&expected, "\n{d} text 0 {s}\n", .{ serial, nameOf(made) }))); + try testing.expect(std.mem.endsWith(u8, both.bytes, try std.fmt.bufPrint(&expected, "\n{d} text 0 {s} {d}\n", .{ serial, nameOf(made), columnOf(p, p.paneBySerial(serial).?) }))); } test "a terminal is listed as term with its directory as name" { @@ -734,7 +741,7 @@ test "a terminal is listed as term with its directory as name" { try testing.expect(std.mem.indexOf( u8, rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, - try std.fmt.bufPrint(&want, "{d} term 0 /work/dir\n", .{pane.serial}), + try std.fmt.bufPrint(&want, "{d} term 0 /work/dir 0\n", .{pane.serial}), ) != null); try testing.expectEqualStrings("/work/dir\n", rd(p, Node.of(pane.serial, .name), 0, 4096).bytes); const refused = wr(p, Node.of(pane.serial, .name), "/elsewhere\n"); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 7279b64a..9459be4f 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -18,6 +18,7 @@ pub const events = @import("events.zig"); pub const pane = @import("pane.zig"); pub const addr = @import("addr.zig"); pub const ctl = @import("ctl.zig"); +pub const cols = @import("cols.zig"); pub const pty = @import("pty.zig"); pub const sources = @import("sources.zig"); pub const screen = @import("screen.zig"); @@ -171,7 +172,7 @@ pub fn openOf(p: *Pardes, req: Req) ?*Open { // ---- nodes ---- -pub const TopFile = enum(u4) { +pub const TopFile = enum(u5) { root = 1, README, index, @@ -186,6 +187,9 @@ pub const TopFile = enum(u4) { focus, ctl, commands, + layout, + tag, + col, pub fn fileName(f: TopFile) []const u8 { return if (f == .root) "/" else @tagName(f); @@ -193,14 +197,14 @@ pub const TopFile = enum(u4) { pub fn mode(f: TopFile) u16 { return switch (f) { - .root, .pane => 0o755, - .look, .exec, .log, .focus, .ctl => 0o666, - .README, .index, .status, .screen, .listeners, .new, .commands => 0o444, + .root, .pane, .col => 0o755, + .look, .exec, .log, .focus, .ctl, .tag => 0o666, + .README, .index, .status, .screen, .listeners, .new, .commands, .layout => 0o444, }; } pub fn dir(f: TopFile) bool { - return f == .root or f == .pane; + return f == .root or f == .pane or f == .col; } }; @@ -264,6 +268,11 @@ pub const PaneFile = enum(u5) { } }; +/// /col/ and its tag: a column is named by its index, which a serial +/// never is (serials are 32 bits; this bit is past them). +pub const ColFile = enum(u5) { dir = 0, tag = 1 }; +const col_bit: u59 = 1 << 58; + pub const Node = packed struct(u64) { file: u5 = 0, serial: u59 = 0, @@ -273,11 +282,19 @@ pub const Node = packed struct(u64) { return @bitCast(Node{ .file = @intFromEnum(file), .serial = serial }); } + pub fn ofCol(index: usize, file: ColFile) u64 { + return @bitCast(Node{ .file = @intFromEnum(file), .serial = col_bit | @as(u59, @intCast(index)) }); + } + pub fn target(node: u64) ?Target { const n: Node = @bitCast(node); if (n.serial == 0) { return .{ .top = std.enums.fromInt(TopFile, n.file) orelse return null }; } + if (n.serial & col_bit != 0) return .{ .col = .{ + .index = std.math.cast(u32, n.serial & ~col_bit) orelse return null, + .file = std.enums.fromInt(ColFile, n.file) orelse return null, + } }; return .{ .pane = .{ .serial = std.math.cast(u32, n.serial) orelse return null, .file = std.enums.fromInt(PaneFile, n.file) orelse return null, @@ -288,6 +305,7 @@ pub const Node = packed struct(u64) { pub const Target = union(enum) { top: TopFile, pane: struct { serial: u32, file: PaneFile }, + col: struct { index: u32, file: ColFile }, }; /// Opening /pane/new makes a pane and reading the open fid answers its @@ -388,7 +406,7 @@ pub fn handle(p: *Pardes, req: Req) Reply { const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) { .pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'), - .top => 'F', + .top, .col => 'F', }; return switch (req.op) { .lookup => lookup(p, req, target), @@ -410,7 +428,7 @@ pub fn handle(p: *Pardes, req: Req) Reply { fn runAttr(p: *Pardes, req: Req, target: Target) ?Reply.Attr { const t = switch (target) { .pane => |t| t, - .top => return null, + .top, .col => return null, }; if (t.file != .pty_run) return null; const run = if (req.handle != 0) openOf(p, req) else for (&p.fs.opens) |*o| { @@ -429,6 +447,19 @@ fn attrOf(p: *Pardes, target: Target) ?Reply.Attr { .mode = f.mode(), .size = topSize(p, f), .mtime = p.fs.started, + .append = f == .tag, + }, + .col => |c| { + if (c.index >= p.ncol) return null; + return .{ + .name = if (c.file == .dir) (std.fmt.bufPrint(&p.fs.node_name, "{d}", .{c.index}) catch unreachable) else "tag", + .node = Node.ofCol(c.index, c.file), + .dir = c.file == .dir, + .mode = if (c.file == .dir) 0o755 else 0o666, + .size = if (c.file == .tag) cols.headerText(p, c.index).?.len + 1 else 0, + .mtime = p.fs.started, + .append = c.file == .tag, + }; }, .pane => |t| { const id = p.paneBySerial(t.serial) orelse return null; @@ -461,7 +492,9 @@ fn topSize(p: *Pardes, f: TopFile) u64 { return switch (f) { // ponytail: /screen has no length until an open renders its frame, // and /pane/new none until an open has a pane to name. - .root, .pane, .screen, .new => 0, + .root, .pane, .col, .screen, .new => 0, + .layout => cols.layoutLen(p), + .tag => cols.headerText(p, null).?.len + 1, .index => pane.indexLen(p), .README => fs.help.len, .status => ctl.statusLen(p), @@ -492,6 +525,7 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { .pty => Node.of(t.serial, .dir), else => return Reply.fail(req.tag, E.NOTDIR), }, + .col => |c| if (c.file == .dir) @intFromEnum(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR), }; return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent }); } @@ -514,8 +548,19 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { if (serial == 0) return Reply.fail(req.tag, E.NOENT); break :pane Node.of(serial, .dir); }, + // A column is its index, in decimal digits. + .col => col: { + if (name.len > 4) return Reply.fail(req.tag, E.NOENT); + for (name) |c| if (c < '0' or c > '9') return Reply.fail(req.tag, E.NOENT); + break :col Node.ofCol(std.fmt.parseInt(u32, name, 10) catch return Reply.fail(req.tag, E.NOENT), .dir); + }, else => return Reply.fail(req.tag, E.NOTDIR), }, + .col => |c| col: { + if (c.file != .dir) return Reply.fail(req.tag, E.NOTDIR); + if (!std.mem.eql(u8, name, "tag")) return Reply.fail(req.tag, E.NOENT); + break :col Node.ofCol(c.index, .tag); + }, .pane => |t| pane: { _ = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); const f = switch (t.file) { @@ -555,7 +600,7 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { .root => { // The guide, then what describes the session, then the // files that act, then the directories. - inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.look, TopFile.exec, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.pane }) |t| { + inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.look, TopFile.exec, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.layout, TopFile.tag, TopFile.pane, TopFile.col }) |t| { if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); @@ -575,8 +620,21 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { stageDirent(out, p.gpa, Node.of(serial, .dir), true, name); } }, + .col => for (0..p.ncol) |c| { + if (skip > 0) { + skip -= 1; + continue; + } + var buf: [16]u8 = undefined; + stageDirent(out, p.gpa, Node.ofCol(c, .dir), true, std.fmt.bufPrint(&buf, "{d}", .{c}) catch unreachable); + }, else => return Reply.fail(req.tag, E.NOTDIR), }, + .col => |c| { + if (c.index >= p.ncol) return Reply.fail(req.tag, E.NOENT); + if (c.file != .dir) return Reply.fail(req.tag, E.NOTDIR); + if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, Node.ofCol(c.index, .tag), false, "tag"); + }, .pane => |t| { const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); const terminal = p.panes[id].?.isTerminal(); @@ -610,6 +668,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { .log => .{ .log = .{} }, else => return .{ .tag = req.tag }, }, + .col => |c| return if (c.index < p.ncol) .{ .tag = req.tag } else Reply.fail(req.tag, E.NOENT), .pane => |t| what: { const pn = p.panes[p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT)].?; if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); @@ -665,7 +724,7 @@ fn remove(p: *Pardes, req: Req) Reply { const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT); const t = switch (target) { .pane => |t| t, - .top => return Reply.fail(req.tag, E.PERM), + .top, .col => return Reply.fail(req.tag, E.PERM), }; if (t.file != .dir) return Reply.fail(req.tag, E.PERM); const id = p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT); @@ -690,6 +749,8 @@ fn releaseHandle(p: *Pardes, req: Req) void { p.panes[id].?.fs.tag_rewrite = false; p.panes[id].?.fs.tag_held_newline = false; }; + if (t == .col and t.col.file == .tag) cols.released(p, t.col.index); + if (t == .top and t.top == .tag) cols.released(p, null); const o = openOf(p, req) orelse return; const of: ?*Pane = if (t == .pane) (if (p.paneBySerial(t.pane.serial)) |id| p.panes[id] else null) else null; if (of) |pn| switch (o.what) { @@ -725,7 +786,8 @@ fn setattr(p: *Pardes, req: Req, target: Target) Reply { return failText(req.tag, E.INVAL, pane.e_addr_failed); if (pane.truncate(p, p.panes[id].?, t.file) != .ok) return Reply.fail(req.tag, E.NOMEM); }, - .top => {}, + .col => |c| if (c.file == .tag and cols.truncate(p, c.index) != .ok) return Reply.fail(req.tag, E.NOENT), + .top => |f| if (f == .tag and cols.truncate(p, null) != .ok) return Reply.fail(req.tag, E.NOMEM), }; return .{ .tag = req.tag, .attr = attrOf(p, target) orelse return Reply.fail(req.tag, E.NOENT) }; } @@ -770,8 +832,9 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { var last: u32 = 0; while (nextSerialAfter(p, last)) |serial| { last = serial; - const pn = p.panes[p.paneBySerial(serial).?].?; - out.print(p.gpa, "{d} {s} {d} {s}\n", .{ serial, pane.kindOf(pn), @intFromBool(pane.dirtyOf(pn)), pane.nameOf(pn) }) catch {}; + const id = p.paneBySerial(serial).?; + const pn = p.panes[id].?; + out.print(p.gpa, "{d} {s} {d} {s} {d}\n", .{ serial, pane.kindOf(pn), @intFromBool(pane.dirtyOf(pn)), pane.nameOf(pn), pane.columnOf(p, id) }) catch {}; } break :index stagedReply(p, req); }, @@ -783,6 +846,13 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { .focus => ctl.readFocus(p, req), .ctl => ctl.readRoot(p, req), .commands => ctl.readCommands(p, req), + .layout => layout: { + var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + cols.writeLayout(p, &text.writer) catch break :layout Reply.fail(req.tag, E.NOMEM); + p.fs.stage(p.gpa).appendSlice(p.gpa, text.written()) catch break :layout Reply.fail(req.tag, E.NOMEM); + break :layout stagedReply(p, req); + }, + .tag => cols.read(p, req, null), // The serial the open handed this fid, so that two reads of one // fid answer the same pane: the read observes, the open acted. .new => serial: { @@ -791,7 +861,7 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { break :serial Reply.fail(req.tag, E.NOMEM); break :serial stagedReply(p, req); }, - .root, .pane => Reply.fail(req.tag, E.PERM), + .root, .pane, .col => Reply.fail(req.tag, E.PERM), }, .pane => |t| { // A run's answer outlives the pane it ran in. @@ -807,6 +877,7 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); return pane.read(p, req, id, pn, t.file); }, + .col => |c| return if (c.file == .tag) cols.read(p, req, c.index) else Reply.fail(req.tag, E.PERM), } } @@ -817,6 +888,7 @@ fn write(p: *Pardes, req: Req, target: Target) Reply { .log => events.writeLog(p, req), .focus => ctl.writeFocus(p, req), .ctl => ctl.writeRoot(p, req), + .tag => cols.write(p, req, null), else => Reply.fail(req.tag, E.PERM), }, .pane => |t| { @@ -825,6 +897,7 @@ fn write(p: *Pardes, req: Req, target: Target) Reply { if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT); return pane.write(p, req, id, pn, t.file); }, + .col => |c| return if (c.file == .tag) cols.write(p, req, c.index) else Reply.fail(req.tag, E.PERM), } } @@ -836,6 +909,7 @@ test { _ = addr; _ = ctl; _ = pty; + _ = cols; _ = sources; _ = screen; } @@ -968,12 +1042,13 @@ test "readdir lists the root and a pane directory without creating anything" { @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); try testing.expect(top.len >= 10); - for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "look", "exec", "log", "screen", "listeners", "pane", "os" }, 0..) |name, i| { + for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "look", "exec", "log", "screen", "listeners", "layout", "tag", "pane", "col", "os" }, 0..) |name, i| { try testing.expectEqualStrings(name, top[i].name); - try testing.expectEqual(i >= 11, top[i].dir); + try testing.expectEqual(i >= 13, top[i].dir); } - try testing.expectEqual(@intFromEnum(TopFile.pane), top[11].node); - try testing.expectEqual(fs.os_root, top[12].node); + try testing.expectEqual(@intFromEnum(TopFile.pane), top[13].node); + try testing.expectEqual(@intFromEnum(TopFile.col), top[14].node); + try testing.expectEqual(fs.os_root, top[15].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); try testing.expect(th.nameAt(top, "self") == null); diff --git a/test/selfmount.py b/test/selfmount.py index cc889a93..90960bed 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -75,7 +75,7 @@ def run(binary): mount = f'/mnt/9p/pardes/{name}' with Client(sock) as client: index = client.read('/index').decode() - rows = [row.split(maxsplit=3) for row in index.splitlines()] + rows = [row.rsplit(maxsplit=1)[0].split(maxsplit=3) for row in index.splitlines()] first = rows[0][0] # A Look at the tree's own index: realpath, stat and read all go # out through 9ns and back in, and the write returns when the @@ -84,7 +84,7 @@ def run(binary): client.write('/look', (mount + '/index\n').encode()) took = time.monotonic() - started check(took < 5, f'look at the mounted index returned ({took:.2f}s)') - rows = [row.split(maxsplit=3) for row in client.read('/index').decode().splitlines()] + rows = [row.rsplit(maxsplit=1)[0].split(maxsplit=3) for row in client.read('/index').decode().splitlines()] opened = [row for row in rows if len(row) == 4 and row[3] == mount + '/index'] check(len(opened) == 1, 'a pane opened on the mounted index') if opened: @@ -94,7 +94,7 @@ def run(binary): # and a Save: the save writes back through the mount into pane 1, # and the exec returns once it has. client.write('/look', f'{mount}/pane/{first}/body\n'.encode()) - rows = [row.split(maxsplit=3) for row in client.read('/index').decode().splitlines()] + rows = [row.rsplit(maxsplit=1)[0].split(maxsplit=3) for row in client.read('/index').decode().splitlines()] mirror = [row for row in rows if len(row) == 4 and row[3] == f'{mount}/pane/{first}/body'] check(len(mirror) == 1, 'a pane opened on the mounted body') if mirror: -- cgit v1.3 From 6732ce6edcf1562d3e126ed02f96466ab07c498e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 00:40:03 -0300 Subject: A desktop session holds 64 panes, and every route that finds none free says so Sixteen panes was far too few for a real session. MAX_PANES is now 64 on a desktop and stays 16 on the board; the 48 more slots cost about 3.7 KB each in fixed tables (the core 1.33 to 1.45 MB, its surface 19 to 72 KB), and a pane itself (84 KB and its terminal) is allocated only when it opens. At the cap, pane/new fails with `pane/new: no pane slots: 64 max` and an err record rather than a bare ENFILE, a 9P look or exec that would open a pane fails its write with the same words and reads back empty, and New, Tty, Tutor and Alt-n say it on the message row (their ctl writes fail with it). Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 5 ++++- src/Messages.zig | 12 ++++++++++++ src/builtins.zig | 2 +- src/dump.zig | 2 +- src/exec.zig | 4 ++-- src/fs.zig | 4 ++++ src/ninep/ctl.zig | 7 +++++++ src/ninep/tree.zig | 31 ++++++++++++++++++++++++++++++- src/pardes.zig | 12 ++++++++---- 9 files changed, 69 insertions(+), 10 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index fd18d523..55660bc0 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -109,7 +109,10 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. empty|full pane-serials...; then active (- when no column has the keyboard) /tag the workspace tag; > replaces it, >> appends, one line /col//tag the tag of the column with serial n, the same way -/pane/new open it to make a pane; the read answers that pane's serial +/pane/new open it to make a pane; the read answers that pane's serial. A session holds + 64 panes (16 on the board); at that, every route that would open one -- this + open, look, exec, New, Tty -- fails with `no pane slots: 64 max` and an err + record, and look reads back empty /pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec, plus pty/{ctl,status,data} on terminals /os/ the host filesystem diff --git a/src/Messages.zig b/src/Messages.zig index 8b6c795d..7d284e6b 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -445,10 +445,22 @@ pub fn messageLog(m: *const Messages, i: usize) ?*const LoggedMessage { } /// `: `: FileNotFound reads "file not found". +/// What a route that would open a pane says when every slot is taken. +pub const no_pane_slots = "no pane slots: {d} max"; + pub fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) void { var buf: [256]u8 = undefined; var w = std.Io.Writer.fixed(&buf); w.print("{s}: ", .{operation}) catch {}; + // Every route that opens a pane says the cap the same way. + if (err == error.NoPaneSlots) { + w.print(no_pane_slots, .{pardes.MAX_PANES}) catch {}; + // A 9P look or exec that would open the pane fails with it too. + p.fs.no_pane_slot = true; + @memcpy(p.fs.ename[0..w.buffered().len], w.buffered()); + p.fs.no_pane_slot_len = @intCast(w.buffered().len); + return reportFailure(p, id, w.buffered()); + } for (@errorName(err), 0..) |c, i| { if (std.ascii.isUpper(c) and i > 0) w.writeByte(' ') catch break; w.writeByte(std.ascii.toLower(c)) catch break; diff --git a/src/builtins.zig b/src/builtins.zig index 5b1b4dcb..32e3cd84 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1102,7 +1102,7 @@ pub const Joincol = struct { pub const Tutor = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { - const free = c.p.freeSlot() orelse return; + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Tutor", error.NoPaneSlots); _ = c.p.openTutorView(free) catch return; exec.placeNew(c.p, c.id, c.id, free, .doc); // a doc like any other } diff --git a/src/dump.zig b/src/dump.zig index 77e2c2ba..61aeabbf 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -73,7 +73,7 @@ pub fn defaultDirectory(buf: []u8) ?[]const u8 { pub const magic = "pardes-dump"; pub const version: u32 = 1; -pub const max_panes: usize = 16; +pub const max_panes: usize = MAX_PANES; pub const max_cols: usize = 6; /// Output arguments are typed in the same bounded one-line tag storage. Keep /// the schema limit named independently so a dump reader can validate it diff --git a/src/exec.zig b/src/exec.zig index 2f279d8e..d4480e00 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -312,7 +312,7 @@ pub fn spawnV9fsTty(p: *Pardes, from: usize) void { fn spawnTtyWithMount(p: *Pardes, from: usize, v9fs: bool) ?*Pane { const src = p.panes[from] orelse return null; const free = p.freeSlot() orelse { - p.reportFailure(from, "Tty: no pane free"); + p.reportError(from, "Tty", error.NoPaneSlots); return null; }; const nt = p.newShell(free, Pardes.paneDir(src)) catch |err| { @@ -609,7 +609,7 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { return id; } const free = p.freeSlot() orelse { - p.reportFailure(from, "exec: no pane free for the command"); + p.reportError(from, "exec", error.NoPaneSlots); return null; }; const pane = p.newCommand(free, dir, line) catch |err| { diff --git a/src/fs.zig b/src/fs.zig index 21ccc94e..88ffb4a3 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1274,6 +1274,10 @@ pub const Namespace = struct { /// 0 the workspace's, a column's its index + 1; and whether the newline /// that ended its last write is held back. header_rewrite: ?u32 = null, + /// A look or exec a 9P write made found every pane slot taken; the + /// write fails with what was said, kept at the head of `ename`. + no_pane_slot: bool = false, + no_pane_slot_len: u16 = 0, header_held: bool = false, late_failure: [256]u8 = undefined, late_failure_len: u16 = 0, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 11de3c1c..325fc8c8 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -138,7 +138,14 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool) Reply { if (!apply) continue; const id = if (serial) |s| p.paneBySerial(s) orelse break else p.active; if (p.panes[id] == null) return Reply.fail(req.tag, E.NOENT); + p.fs.no_pane_slot = false; run(p, id, exec, text); + // A pane it would have opened had no slot: the write fails, and + // a look reads back nothing. + if (p.fs.no_pane_slot) { + p.fs.results_len = 0; + return tree.failText(req.tag, E.IO, p.fs.ename[0..p.fs.no_pane_slot_len]); + } } } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 3be75960..c4ade1f7 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -664,7 +664,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { // pane it made, so reading it twice answers the same one and // closing it leaves the pane alone. .new => { - const slot = p.freeSlot() orelse return Reply.fail(req.tag, E.NFILE); + const slot = p.freeSlot() orelse return failText(req.tag, E.NFILE, std.fmt.bufPrint(&p.fs.ename, "pane/new: " ++ pardes.Messages.no_pane_slots, .{pardes.MAX_PANES}) catch "no pane slots"); p.newScratchFor(p.active, .fs); const made = p.panes[slot] orelse return Reply.fail(req.tag, E.NFILE); return .{ .tag = req.tag, .handle = made.serial }; @@ -1284,3 +1284,32 @@ test "editor paths resolve to the same nodes the wire serves" { try testing.expect(resolveSelf(p, "pane/new/body") == null); try testing.expectEqual(before, p.next_serial); } + +test "at the pane cap, pane/new, look and New each say so, and look reads back empty" { + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + const new = @intFromEnum(TopFile.new); + while (p.freeSlot() != null) try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status); + var want: [64]u8 = undefined; + const said = try std.fmt.bufPrint(&want, "no pane slots: {d} max", .{pardes.MAX_PANES}); + const refused = call(p, .{ .tag = 2, .op = .open, .node = new }); + try testing.expectEqual(E.NFILE, refused.errno()); + try testing.expect(std.mem.endsWith(u8, refused.reply.ename, said)); + try testing.expect(th.logHas(p, said)); + // A look that would open a pane fails its write, and says the same. + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "f.txt", .data = "f\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + var line: [4200]u8 = undefined; + const look_node = @intFromEnum(TopFile.look); + const looked = th.wr(p, look_node, try std.fmt.bufPrint(&line, "{s}/f.txt\n", .{dir})); + try testing.expect(looked.errno() != 0); + try testing.expect(std.mem.indexOf(u8, looked.reply.ename, said) != null); + try testing.expectEqualStrings("", th.rd(p, look_node, 0, 64).bytes); + // New from a pane's ctl fails as well. + const ctl_node = Node.of(p.panes[0].?.serial, .ctl); + const made = th.wr(p, ctl_node, "New\n"); + try testing.expect(std.mem.indexOf(u8, made.reply.ename, said) != null); +} diff --git a/src/pardes.zig b/src/pardes.zig index 8dbe6744..a6a088de 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -250,7 +250,11 @@ pub const pdf_raster_policy: PdfRasterPolicy = switch (platform) { pub const Pane = panes.Pane; const Text = panes.Text; -pub const MAX_PANES = 16; +/// Pane slots: 64 on a desktop, where a session keeps many files and +/// terminals open; the board keeps its 16. A slot costs its share of the +/// fixed tables (MAX_PANES-sized arrays in the core and its surface) whether +/// or not a pane is in it; a pane itself is allocated when it opens. +pub const MAX_PANES = if (platform == .esp32p4) 16 else 64; pub const Layer = @import("Layer.zig"); pub const RowMetrics = Layer.Metrics; pub const TagHit = Layer.TagHit; @@ -4797,7 +4801,7 @@ pub const Pardes = struct { /// A scratch for New (`.scratch`) or 9P's pane/new (`.fs`). pub fn newScratchFor(p: *Pardes, from_id: usize, kind: exec.NewPane) void { - const free = p.freeSlot() orelse return; + const free = p.freeSlot() orelse return p.reportError(from_id, "New", error.NoPaneSlots); _ = p.newScratch(from_id, free) catch return; exec.placeNew(p, from_id, from_id, free, kind); } @@ -5305,7 +5309,7 @@ pub const Pardes = struct { p.raw_hover_intent = false; look.cancelLookHover(p); const reply = ctlfs.handle(p, req); - if (reply.status == .err and (req.op == .write or req.op == .setattr)) ctlfs.events.noteError(p, req, reply); + if (reply.status == .err and (req.op == .write or req.op == .setattr or (req.op == .open and reply.errno == ctlfs.E.NFILE))) ctlfs.events.noteError(p, req, reply); // The request was a whole step of its own, so it settles the way a // step does: the cursor and scroll reconciled, the scripted panes // told, and the panes it made announced to /log now rather than at @@ -5665,7 +5669,7 @@ pub const Pardes = struct { // global window ops (any mode): Alt-n new terminal below, Alt-c move // the active terminal into a fresh column if (hit(key, config.new_shell_below)) { - const free = p.freeSlot() orelse return; + const free = p.freeSlot() orelse return p.reportError(p.active, "Tty", error.NoPaneSlots); const nt = p.newShell(free, "") catch return; nt.greet = true; // From a tag, as a 9P new is: acme's t->w == nil. -- cgit v1.3 From e563be42a5b3e9243e2c01d34cf8e94d2047b753 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 00:45:33 -0300 Subject: A terminal's body reads as logical lines, the last one ending in a newline A terminal's body came back as the screen's rows, a long line cut where the terminal wrapped it and the last line with no newline. The body (and a terminal's Save, and the length its ctl reports) now joins wrapped rows by ghostty's wrap flags, as pty/run's output does, and ends the last line with a newline. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 6 +++++- src/Terminal.zig | 60 +++++++++++++++++++++++++++++++++++++++++++--------- src/fs-help.txt | 2 +- src/fs.zig | 2 +- src/ninep/screen.zig | 22 +++++++++++++++---- 5 files changed, 75 insertions(+), 17 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index a5d3c4ca..a4fec333 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -375,7 +375,11 @@ selection, and leaves `look` reading back empty. `/pane//name` reads the pane's file name (a terminal's directory) and writing it renames the buffer; a relative name resolves against the pane's -directory. `body` appends on write and replaces on truncating open. `sel` +directory. `body` appends on write and replaces on truncating open. A +terminal's `body` is its history as plain text, frozen per open, in logical +lines: a row the terminal wrapped is joined back to the row before it (the +wrap is ghostty's, as `pty/run`'s output unwraps), and the last line ends +with a newline. `sel` reads the selected text and writing it replaces the selection. `errors` appends to the directory's `+Errors` pane. Holding `event` open redirects the pane's Look and Exec clicks to that client, and so does a line written to the diff --git a/src/Terminal.zig b/src/Terminal.zig index 504ab887..4808298e 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -385,26 +385,66 @@ pub fn mouseFormatSgr(pane: *const Pane) bool { return state.vt.modes.get(.mouse_format_sgr); } -/// The whole scrollback as plain text, `gpa`-owned: what `Save` writes out. +/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body +/// reads and `Save` writes out. Logical lines: rows the terminal wrapped +/// are joined again (ghostty's wrap flags, as pty/run's output is), and +/// the last line ends with a newline. pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { if (comptime !enabled) return &.{}; - const state = pane.terminal orelse return &.{}; - return state.vt.screens.active.dumpStringAlloc(gpa, .{ .screen = .{} }); + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try writeScreenText(pane, &out.writer); + return out.toOwnedSlice(); } +fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const screen = state.vt.screens.active; + const br = screen.pages.getBottomRight(.screen) orelse return; + var both: TeeWriter = .{ .a = w }; + try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); + if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); +} + +/// Passes bytes through, remembering how many and the last one. +const TeeWriter = struct { + a: *std.Io.Writer, + count: usize = 0, + final: u8 = 0, + writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, + + fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); + var n: usize = 0; + for (data[0 .. data.len - 1]) |bytes| { + try t.a.writeAll(bytes); + t.note(bytes); + n += bytes.len; + } + const pattern = data[data.len - 1]; + for (0..splat) |_| { + try t.a.writeAll(pattern); + t.note(pattern); + n += pattern.len; + } + return n; + } + + fn note(t: *TeeWriter, bytes: []const u8) void { + if (bytes.len == 0) return; + t.count += bytes.len; + t.final = bytes[bytes.len - 1]; + } +}; + /// How long `screenTextAlloc` would be, counted without keeping it: the /// length a terminal's body reads as, which its ctl line reports. pub fn screenTextLen(pane: *Pane) usize { if (comptime !enabled) return 0; - const state = pane.terminal orelse return 0; - const screen = state.vt.screens.active; var buf: [256]u8 = undefined; var counting: std.Io.Writer.Discarding = .init(&buf); - screen.dumpString(&counting.writer, .{ - .tl = screen.pages.getTopLeft(.screen), - .br = screen.pages.getBottomRight(.screen) orelse return 0, - .unwrap = false, - }) catch return 0; + writeScreenText(pane, &counting.writer) catch return 0; return @intCast(counting.fullCount()); } diff --git a/src/fs-help.txt b/src/fs-help.txt index 50dc5d9c..50e9e7fc 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -41,7 +41,7 @@ Pitfalls, one each: addr: #n,#m, 12:5 or /re/ from the current address (^ $ per line); > never resets it, 0 does; a miss refuses data. data: > replaces the addr range, : > deletes it, a 2nd > inserts (addr moved); body: > empties all. tag reads the path, then its own text; > replaces that text (default words too), >> appends. - A terminal's body is a history snapshot frozen per open; pty/data is the live stream. + A terminal's body is a history snapshot frozen per open, wrapped rows joined into lines; pty/data is the live stream. exec: a non-builtin line runs as a command pane (ctl's Shell -c; exit N shown, logged), a shell's typed in. Through a mount a malformed write is EINVAL, a well-formed one that fails EIO: log's err says why. lock/unlock need a held ctl fd (exec 3>ctl), a held lock fails: retry. A column's last pane leaves it empty; the last pane of all quits. diff --git a/src/fs.zig b/src/fs.zig index 88ffb4a3..65e5d276 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -491,7 +491,7 @@ test "bounded reads release terminal snapshots after success and size refusal" { 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"; + 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); diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 462ea40f..f496da03 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -146,7 +146,7 @@ test "terminal body handles keep one history snapshot across fragmented reads" { try testing.expectEqualStrings("", call(p, .{ .tag = 4, .op = .read, .node = node, .handle = opened.reply.handle, .off = original.len, .size = 3 }).bytes); _ = call(p, .{ .tag = 5, .op = .release, .node = node, .handle = opened.reply.handle }); const newer = call(p, .{ .tag = 6, .op = .open, .node = node }); - try testing.expectEqualStrings("new output", call(p, .{ .tag = 7, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); + try testing.expectEqualStrings("new output\n", call(p, .{ .tag = 7, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); _ = call(p, .{ .tag = 8, .op = .release, .node = node, .handle = newer.reply.handle }); } @@ -162,7 +162,7 @@ test "an empty terminal body snapshot stays empty while output continues" { try testing.expectEqualStrings("", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = opened.reply.handle, .size = 32 }).bytes); _ = call(p, .{ .tag = 4, .op = .release, .node = node, .handle = opened.reply.handle }); const newer = call(p, .{ .tag = 5, .op = .open, .node = node }); - try testing.expectEqualStrings("new output", call(p, .{ .tag = 6, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); + try testing.expectEqualStrings("new output\n", call(p, .{ .tag = 6, .op = .read, .node = node, .handle = newer.reply.handle, .size = 32 }).bytes); _ = call(p, .{ .tag = 7, .op = .release, .node = node, .handle = newer.reply.handle }); } @@ -194,13 +194,13 @@ test "terminal body snapshots are lazy bounded and released after the pane close try testing.expectEqual(E.NOMEM, failed.errno()); try testing.expect(p.fs.opens[handles[0] - 1].what.snapshot == null); const first = call(p, .{ .tag = 4, .op = .read, .node = node, .handle = handles[0], .size = 32 }); - try testing.expectEqualStrings("latest output", first.bytes); + try testing.expectEqualStrings("latest output\n", first.bytes); const saved = p.fs.opens[handles[0] - 1].what.snapshot.?; failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); p.gpa = failing.allocator(); const second = call(p, .{ .tag = 5, .op = .read, .node = node, .handle = handles[0], .off = 7, .size = 32 }); p.gpa = gpa; - try testing.expectEqualStrings("output", second.bytes); + try testing.expectEqualStrings("output\n", second.bytes); try testing.expect(!failing.has_induced_failure); try testing.expectEqual(saved.ptr, p.fs.opens[handles[0] - 1].what.snapshot.?.ptr); try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .read, .node = screen_node, .handle = handles[0], .size = 32 }).errno()); @@ -328,3 +328,17 @@ test "screen inspection preserves acknowledged presentation and the next real fr } } } + +test "a terminal's body is its logical lines: a row the terminal wrapped is joined again" { + const p = try th.withTerm(testing.allocator); + defer p.deinit(); + const pane = p.panes[0].?; + const long = "w" ** 50 ++ "x" ** 150; // wider than the pane: it wraps + try testing.expect(long.len > pane.cols); + p.update(.{ .output = .{ .pane = 0, .bytes = long ++ "\r\nnext" } }); + while (p.nextEffect()) |_| {} + const node = Node.of(pane.serial, .body); + const body = th.rd(p, node, 0, 4096).bytes; + try testing.expectEqualStrings(long ++ "\nnext\n", body); + try testing.expectEqual(@as(u64, body.len), th.call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size); +} -- cgit v1.3 From e0aadf23d5ff5759fd53267dbafa8e278a324107 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 00:58:36 -0300 Subject: The tree's README and fs.md answer round 8's doc questions The README's log line names newcol, delcol, ask, restored and restoredcol; it says what $m is under 9ns --unix; and a build that embeds no sources no longer lists src/ (derived from the build, and tested). fs.md says what the rest of a typed line does after Kill for each shell (fish runs on, bash abandons it), that Exec in a .py pane runs a command and never the REPL, and why appending to a tag wants printf and a leading blank. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 16 +++++++++++----- src/fs-help.txt | 8 +++++--- src/fs.zig | 13 ++++++++++++- 3 files changed, 28 insertions(+), 9 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 46fe9f86..742506f1 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -181,8 +181,10 @@ in a shell running without job control (`set +m`) the job shares the shell's group, so there is none to signal: Kill says `Kill: no job to signal`, and a write of it to `ctl` fails with that; with nothing running it says `Kill: nothing running`; and, of a typed line, only the -foreground job, so of `sleep 30; echo done` typed at a prompt the `echo` -still runs once the `sleep` is stopped -- +foreground job, after which what the rest of the line does is the shell's +affair: of `sleep 30; echo done` typed at a prompt, fish goes on and runs +the `echo`, and bash abandons the line, as each does when a job it waits +on is killed -- and reads every setting there is, one a line, in the words a write of it takes (`Verbose on`, `WindowOpacity 70`, `PanelSlide off`, `DumpDir `, `LocationsConfig ...`), so writing what it reads @@ -344,7 +346,9 @@ terminal's while a program other than its shell holds the tty -- after Ctrl-D the shell would run the text, so nothing is sent and the pane says so. Still commands, whatever is bound: a word in a tag (so the tag is how to run `make` from that file), `Exec ` run by name -(typed, a 2-1 chord onto `Exec`, a `ctl` line) and a command word @`cmd` in +(typed, a 2-1 chord onto `Exec`, a `ctl` line) -- in a `.py` pane bound to +a REPL, `Exec print(1)` runs `print(1)` as a command, never in the REPL -- +and a command word @`cmd` in the text, looked at or clicked (`# @`pytest -x`` in a script). A 9P `exec` is no gesture and is never sent: a script writes to the REPL pane's `pty/data`, multi-line code as a bracketed paste (`\e[200~\e[201~`, @@ -544,8 +548,10 @@ words (`Del`, `Put` and the rest) with it, since they are that text until you edit it, so `echo Make > tag` leaves only `Make` -- a truncating write drops the one newline that ends what it wrote, which would draw an empty row, and keeps any other; append with `>>` to -keep them, with `printf ' Make' >> tag`: `echo` ends its word with a -newline, which starts a new line of the tag. The clearing is an edit of the tag like a typed one and its undo +keep them, with `printf ' Make' >> tag`. The leading blank is needed: the +tag reads back with no blank after its last word, so `printf Make >> tag` +glues `Make` onto it; and `echo ' Make' >> tag` ends with a newline, which +starts a new line of the tag. The clearing is an edit of the tag like a typed one and its undo history is kept: `u` in the tag brings back the text it cleared, words included. diff --git a/src/fs-help.txt b/src/fs-help.txt index 08a7e262..73a49e9b 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -5,7 +5,8 @@ index one line per pane: serial, kind (text|term|pdf|image), dirty flag, n status pid, version and pane count look write a line: a right click on it at the active pane; read: the serials it touched exec write a line: a middle click, an editor command word or a shell line; read the same -log events: new/del/rename/save , run/exit/send ..., dump/restore , msg, err +log events: new/del/rename/save , newcol/delcol , run/exit/send ..., + ask , dump/restore , restored/restoredcol , msg, err screen rendered screen as JSON, frozen from open to close listeners the session's dial addresses focus the serial of the pane with the keyboard (empty on a column tag); write a serial to give it the keyboard @@ -18,9 +19,10 @@ col//ctl Delcol, Joincol, New or Tty on that column; col//exec a word as a pane/new open it to make a pane (named +New) in the active column, filling it if empty; the read answers its serial pane// name body tag ctl addr dot limit data xdata sel dirty mark scroll errors (write-only: appended to its directory's +Errors pane) event look exec, pty/ on terminals; rmdir closes -os/, src/ the host filesystem; the editor's own sources (-Dembed-sources=true builds only) +os/, src/ the host filesystem; the editor's own sources -Below, $m is the mount: $NINE_MOUNT/pardes/; PARDES_MOUNT in a Tty9p shell. +Below, $m is the mount: $NINE_MOUNT/pardes/; PARDES_MOUNT in a Tty9p shell; +$NINE_MOUNT itself under `9ns --unix SOCKET -- cmd`, which mounts one session as its root. cat $m/index which panes exist n=$(cat $m/pane/new) make a pane, take its serial diff --git a/src/fs.zig b/src/fs.zig index 65e5d276..8be728a6 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -19,7 +19,14 @@ const Reply = tree.Reply; const E = tree.E; /// The served README; tree.zig answers it. -pub const help = @embedFile("fs-help.txt"); +/// The tree's README; a build that embeds no sources lists no src/. +pub const help = help: { + const raw = @embedFile("fs-help.txt"); + if (limits.embedded_sources) break :help raw; + const both = "os/, src/ the host filesystem; the editor's own sources"; + const at = std.mem.indexOf(u8, raw, both) orelse @compileError("fs-help.txt no longer lists os/, src/"); + break :help raw[0..at] ++ "os/ the host filesystem" ++ raw[at + both.len ..]; +}; /// Host filesystem nodes: the root, and one hashed node per path a client walked to. pub const os_root: u64 = (1 << 63) + 2; @@ -1364,3 +1371,7 @@ pub fn unmount(p: *Pardes, name: []const u8) !void { test { _ = tree; } + +test "the tree's README lists src/ only when the build serves it" { + try std.testing.expectEqual(limits.embedded_sources, std.mem.indexOf(u8, help, "src/") != null); +} -- cgit v1.3 From cf2415cc6527cb92898694aae88fd84d54aac28c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 03:08:56 -0300 Subject: A failed builtin's err replaces its msg, and (xN) is a running total A builtin failing a ctl write logged its Verbose announcement, its words as a msg, and the write's err, so the same failure again never repeated the newest record and never collapsed. Its err alone is logged now (the msg is still shown and kept in +Messages). A repeat of a record a follower has read is a new line with the running total, (xN) being N in all. fs.md states both rules. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 18 +++++++++++------- src/Messages.zig | 15 ++++++++++++--- src/fs.zig | 3 +++ src/ninep/ctl.zig | 15 +++++++++++++++ src/ninep/events.zig | 49 ++++++++++++++++++++++++++++++------------------- 5 files changed, 71 insertions(+), 29 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 428cc84c..5836215f 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -625,18 +625,22 @@ mapping the serial it had to the one it has now, and `restoredcol for every line the editor says (with `verbose` on, that includes each builtin announcing itself as it runs, on purpose: the log says which ran -- unless the builtin then says something of its own that starts with its -name, `Kill: nothing running`, which takes the announcement's place; a line -said again word for word before any follower read it is that line counted, -`msg 3 Undo: nothing to undo (x40)`, as `err` is; its serial is the pane it ran at, `-` when the keyboard was on a +name, `Kill: nothing running`, which takes the announcement's place; a +builtin that fails a ctl write is logged by that write's `err` alone, no +announcement and no `msg`, so the same failure again is the same record +again; a line said again word for word is counted, `msg 3 Undo: nothing to +undo (x40)`, as `err` is (below); its serial is the pane it ran at, `-` when the keyboard was on a column or workspace tag, or the line came to the root's ctl, `/tagexec` or a column's ctl or exec), and `err : ` for every write or truncation the tree refused or that failed -- through a mount a shell sees only the errno its kernel mapped the reply to, usually `Invalid argument`, and this is the reason (`err 3 addr: -no match for regexp`). The same err again, before any follower has read -the first, is that record counted (`err 3 addr: no match for regexp (x4)`), -so a client retrying a failing write does not push the rest out of the -ring; a follower that read it gets each repeat. Through a kernel mount a client sees only an errno, which 9ns reads from the +no match for regexp`). A record said again word for word, straight after +itself, is counted rather than repeated (`err 3 addr: no match for regexp +(x4)`: four in all, counting the first), so a client retrying a failing +write does not push the rest out of the ring. A record a follower has +already read is never rewritten: the next repeat is a line of its own +carrying the running total, `(x5)`, and counting goes on from there. Through a kernel mount a client sees only an errno, which 9ns reads from the error's words (cloud9's 9ns/src/nine.zig, `enameToErrno`): a malformed write -- an unknown or ill-formed control message, `bad address syntax`, `bad regular expression` -- is EINVAL; a lock another open holds, EBUSY; a pane diff --git a/src/Messages.zig b/src/Messages.zig index daf195bb..7970908e 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -412,9 +412,8 @@ fn logMessage(p: *Pardes, id: usize, text: []const u8) void { if (text.len == 0) return; const serial: u32 = if (p.fs.session_write) 0 else if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; const kept = text[0..@min(text.len, LoggedMessage.cap)]; - // /log hears every one: a client that retried and failed the same way - // is waiting on that second line. Only the +Messages view collapses. - ctlfs.events.noteMessage(p, serial, kept); + // /log hears every one (a failure of a ctl write as its err record). + if (!p.fs.unlogged) ctlfs.events.noteMessage(p, serial, kept); if (p.messages.len > 0) { const last = &p.messages.log[(p.messages.head + limits.message_log - 1) % limits.message_log]; if (last.serial == serial and @@ -498,6 +497,16 @@ pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { } p.fs.failure_len = @intCast(n); } + // The write fails with it, and its err record says it: no msg for it, + // and no Verbose announcement before that, so the same failure again is + // the same record again, counted (events.pushCounting). + if (p.fs.no_prompt) { + const serial: u32 = if (p.fs.session_write) 0 else if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; + ctlfs.events.dropAnnouncement(p, serial, text); + p.fs.unlogged = true; + defer p.fs.unlogged = false; + return setMessage(p, id, text); + } setMessage(p, id, text); } diff --git a/src/fs.zig b/src/fs.zig index 8be728a6..2c739115 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1271,6 +1271,9 @@ pub const Namespace = struct { /// The root ctl is running a session builtin: its messages are the /// session's, logged `msg -`, though shown on the active pane. session_write: bool = false, + /// A ctl write's failure is being said: its err record logs it, so + /// no msg does (Messages.reportFailure). + unlogged: bool = false, refused: bool = false, failure: [256]u8 = undefined, failure_len: u16 = 0, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 76f09084..d1bb5907 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1406,3 +1406,18 @@ test "Shell refuses a path that is no executable, and bare it goes back to the d var want: [300]u8 = undefined; try testing.expect(std.mem.indexOf(u8, rd(p, root_ctl, 0, 8192).bytes, try std.fmt.bufPrint(&want, "Shell {s}\n", .{config.defaultShell()})) != null); } + +test "a builtin that fails a ctl write logs only its err, so the same failure again is counted" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + p.update(.tick); // the pane's `new` is logged first + while (p.nextEffect()) |_| {} + const ctl_node = @intFromEnum(tree.TopFile.ctl); + for (0..3) |_| try testing.expectEqual(Status.err, wr(p, ctl_node, "Kill zzz\n").reply.status); + const log = @intFromEnum(tree.TopFile.log); + const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; + const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; + try testing.expect(std.mem.endsWith(u8, text, "err - ctl: Kill: no running command has that first word \"Kill zzz\" (x3)\n")); + try testing.expect(std.mem.indexOf(u8, text, "msg - Kill") == null); + _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); +} diff --git a/src/ninep/events.zig b/src/ninep/events.zig index c54d8454..e0e66800 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -154,16 +154,7 @@ pub fn noteMessage(p: *Pardes, serial: u32, text: []const u8) void { // A builtin's own word for what it did stands in for its Verbose // announcement just before (`Undo` then `Undo: nothing to undo`), so // that 1000 Undos with nothing left are one line, counted, as err's are. - if (newest(p)) |last| if (!followerRead(p, last.seq) and std.mem.startsWith(u8, last.text, "msg ")) { - const rest = last.text["msg ".len..]; - const sp = std.mem.indexOfScalar(u8, rest, ' ') orelse rest.len; - const word = rest[@min(sp + 1, rest.len)..]; - var who: [16]u8 = undefined; - const mine = if (serial == 0) "-" else std.fmt.bufPrint(&who, "{d}", .{serial}) catch ""; - if (std.mem.eql(u8, rest[0..sp], mine) and word.len > 0 and std.mem.indexOfScalar(u8, word, ' ') == null and - text.len > word.len and std.mem.startsWith(u8, text, word) and text[word.len] == ':') - p.fs.log.buf.shrinkRetainingCapacity(last.at); - }; + dropAnnouncement(p, serial, text); pushCounting(p, (if (serial == 0) std.fmt.bufPrint(&buf, "msg - {s}\n", .{text}) else @@ -218,8 +209,27 @@ pub fn noteError(p: *Pardes, req: Req, reply: Reply) void { pushCounting(p, record); } +/// Drops the newest record when it is the Verbose announcement (`msg +/// `) of the builtin whose words `text` are (`Word: ...`): +/// what the builtin said, or the err its failure logs, takes its place. +/// Not one a follower has read. +pub fn dropAnnouncement(p: *Pardes, serial: u32, text: []const u8) void { + const last = newest(p) orelse return; + if (followerRead(p, last.seq) or !std.mem.startsWith(u8, last.text, "msg ")) return; + const rest = last.text["msg ".len..]; + const sp = std.mem.indexOfScalar(u8, rest, ' ') orelse rest.len; + const word = rest[@min(sp + 1, rest.len)..]; + var who: [16]u8 = undefined; + const mine = if (serial == 0) "-" else std.fmt.bufPrint(&who, "{d}", .{serial}) catch ""; + if (std.mem.eql(u8, rest[0..sp], mine) and word.len > 0 and std.mem.indexOfScalar(u8, word, ' ') == null and + text.len > word.len and std.mem.startsWith(u8, text, word) and text[word.len] == ':') + p.fs.log.buf.shrinkRetainingCapacity(last.at); +} + /// Pushes `record`, or, when it repeats the newest record word for word, -/// counts that one instead: ` (x2)`. +/// counts that one instead: ` (x2)`, the count being every time it +/// was said. One a follower has already read is not rewritten: the repeat +/// is a new line carrying the running count, `(x3)`. fn pushCounting(p: *Pardes, record: []u8) void { // A client retrying a write that fails the same way would fill the ring // with one line, so a repeat of the newest record is that record counted, @@ -234,10 +244,10 @@ fn pushCounting(p: *Pardes, record: []u8) void { said = said[0..x]; } else |_| {} }; - if (!std.mem.eql(u8, said, record[0 .. record.len - 1]) or followerRead(p, last.seq)) return pushLog(p, record); + if (!std.mem.eql(u8, said, record[0 .. record.len - 1])) return pushLog(p, record); var counted: [pardes.Messages.LoggedMessage.cap + 64]u8 = undefined; const again = std.fmt.bufPrint(&counted, "{s} (x{d})\n", .{ said, times +| 1 }) catch return; - p.fs.log.buf.shrinkRetainingCapacity(last.at); + if (!followerRead(p, last.seq)) p.fs.log.buf.shrinkRetainingCapacity(last.at); pushLog(p, again); } @@ -900,7 +910,7 @@ test "the log records whether or not anyone reads, and an open that follows wait } try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "msg {d} same failure\n", .{said_by}), pieced[0..got]); p.setMessage(0, "same failure"); - try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "msg {d} same failure\n", .{said_by}), rdf.next(p, log, fh, frozen).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "msg {d} same failure (x2)\n", .{said_by}), rdf.next(p, log, fh, frozen).bytes); // A follower the ring outran hears how much it missed, then carries on. var filler: [200]u8 = @splat('x'); @@ -951,19 +961,20 @@ test "a refused or failed write is an err record in the log, saying which file a // A write that succeeds says nothing. _ = wr(p, Node.of(serial, .addr), "#0"); try testing.expectEqual(Status.again, call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .off = frozen, .size = 4096 }).reply.status); - // A follower that has read an err waits on its repeat: a line of its own. + // A follower that has read an err waits on its repeat: a line of its + // own, with the running count. _ = wr(p, Node.of(serial, .addr), "/nowhere/"); try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "err {d} addr: no match for regexp\n", .{serial}), next.record(p, f, frozen)); _ = wr(p, Node.of(serial, .addr), "/nowhere/"); - try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "err {d} addr: no match for regexp\n", .{serial}), next.record(p, f, frozen)); + try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "err {d} addr: no match for regexp (x2)\n", .{serial}), next.record(p, f, frozen)); _ = call(p, .{ .tag = 6, .op = .release, .node = log, .handle = f }); - // With the follower gone, repeats are the newest record counted: the - // one it read, and three more. + // With the follower gone, repeats are the newest record counted on: + // its two, and three more. for (0..3) |_| _ = wr(p, Node.of(serial, .addr), "/elsewhere/"); const g = call(p, .{ .tag = 7, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 8, .op = .read, .node = log, .handle = g, .size = 1 << 16 }).bytes; - try testing.expect(std.mem.endsWith(u8, text, try std.fmt.bufPrint(&want, "regexp\nerr {d} addr: no match for regexp (x4)\n", .{serial}))); + try testing.expect(std.mem.endsWith(u8, text, try std.fmt.bufPrint(&want, "regexp\nerr {d} addr: no match for regexp (x5)\n", .{serial}))); _ = call(p, .{ .tag = 9, .op = .release, .node = log, .handle = g }); } -- cgit v1.3 From 637ab988f0922173055ea98b1f76916e42f4222a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 05:24:25 -0300 Subject: A prompt a 9P request opens is an ask, answered with answer, never stacked Save through exec on a terminal (or a scratch) opened its path prompt on screen, where no script could see or answer it, and a second Save stacked another. Opened while a 9P request is served, it now logs ask save path; answer on the pane's ctl saves there and closes it, answer - closes it; asked again, the open one stands. A pane closed with it open logs answer -. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 5 ++++- src/fs.zig | 3 +++ src/ninep/ctl.zig | 32 ++++++++++++++++++++++++++++++++ src/ninep/events.zig | 2 +- src/pardes.zig | 13 +++++++++++++ 5 files changed, 53 insertions(+), 2 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 09738816..14b82d48 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -660,7 +660,10 @@ it opened in, since a terminal is named by its directory and nothing else on it says where it is -- since a terminal is named by its directory), `exit ` before the `del` of a terminal whose shell exited by itself, `ask -` when a pane asks a question (answered by `answer` on its ctl), +` when a pane asks a question (answered by `answer` on its ctl; +`ask save path` when a Save made over 9P, on a terminal or a +scratch, opens its prompt for a path, answered `answer ` or `answer +-`; asked again, the one open stands, not a second), `answer ` when it is answered, by key or ctl, `-` for taken back or for its pane closing with the question standing, `changed ` when a pane's file changed on disk under its unsaved diff --git a/src/fs.zig b/src/fs.zig index 2c739115..cb89648c 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1274,6 +1274,9 @@ pub const Namespace = struct { /// A ctl write's failure is being said: its err record logs it, so /// no msg does (Messages.reportFailure). unlogged: bool = false, + /// A 9P request is being served (Pardes.serveFs): a prompt it opens is + /// a question for the log (`ask`), answered with `answer`. + serving: bool = false, refused: bool = false, failure: [256]u8 = undefined, failure_len: u16 = 0, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 3282c743..d3b008ff 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -741,6 +741,16 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "answer takes {s} or -", .{choices}) catch std.fmt.bufPrint(&why, "answer takes a choice or -", .{}) catch "answer takes a choice or -"); } return tree.failText(req.tag, E.INVAL, "answer takes a choice or -"); + } else if (std.mem.startsWith(u8, line, "answer ") and p.panes[p.paneBySerial(serial).?].?.prompt == .save) { + // Save's path, asked over 9P (`ask save path`). + if (!apply) continue; + const id = p.paneBySerial(serial).?; + const asked = p.panes[id].?; + const path = std.mem.trim(u8, line["answer ".len..], " "); + var rec: [300]u8 = undefined; + pardes.ctlfs.events.notePath(p, "answer", std.fmt.bufPrint(&rec, "{d} {s}", .{ serial, path[0..@min(path.len, 256)] }) catch ""); + if (!std.mem.eql(u8, path, "-")) exec_line.saveTo(p, id, path); + asked.closePrompt(); } else if (std.mem.startsWith(u8, line, "answer ")) { // The pane's question (its `ask` in the log), answered. const choice = std.mem.trim(u8, line["answer ".len..], " "); @@ -1743,3 +1753,25 @@ test "Newcol at the column cap fails the write and says the cap" { try testing.expect(std.mem.indexOf(u8, refused.reply.ename, try std.fmt.bufPrint(&want, "no space for a column: {d} max", .{pardes.MAX_COLS})) != null); try testing.expect(th.logHas(p, "no space for a column")); } + +test "Save on a terminal asked over 9P is an ask in the log, answered with a path, and not asked twice" { + const p = try th.withTerm(testing.allocator); + defer p.deinit(); + const serial = serialOf(p); + const id = p.paneBySerial(serial).?; + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .tagexec), "Save\n").reply.status); + var want: [48]u8 = undefined; + try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "ask {d} save path\n", .{serial}))); + try testing.expect(p.panes[id].?.prompt == .save); + // Again: the one open stands, one ask in the log. + _ = wr(p, Node.of(serial, .tagexec), "Save\n"); + const log = @intFromEnum(tree.TopFile.log); + const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; + try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, "save path\n")); + _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); + // Answered: the path is written to, the prompt goes. + const answered = wr(p, Node.of(serial, .ctl), "answer /tmp/pardes-ask-save.txt\n"); + try testing.expectEqual(Status.ok, answered.reply.status); + try testing.expect(p.panes[id].?.prompt == .none); + try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} /tmp/pardes-ask-save.txt\n", .{serial}))); +} diff --git a/src/ninep/events.zig b/src/ninep/events.zig index d2beecd1..105397f3 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -124,7 +124,7 @@ pub fn noteRetire(p: *Pardes, pane: *Pane) void { } // A question still standing ends with it, so a follower of its `ask` // hears the end. - if (pane.prompt == .repl_choice or pane.prompt == .del_side) { + if (pane.prompt == .repl_choice or pane.prompt == .del_side or pane.prompt == .save) { var rec: [32]u8 = undefined; notePath(p, "answer", std.fmt.bufPrint(&rec, "{d} -", .{pane.serial}) catch ""); } diff --git a/src/pardes.zig b/src/pardes.zig index a55a22e0..7e426ba4 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5386,7 +5386,9 @@ pub const Pardes = struct { p.needs_frame = true; p.raw_hover_intent = false; look.cancelLookHover(p); + p.fs.serving = true; const reply = ctlfs.handle(p, req); + p.fs.serving = false; if (reply.status == .err and (req.op == .write or req.op == .setattr or (req.op == .open and reply.errno == ctlfs.E.NOSPC) or (req.op == .release and req.remove))) ctlfs.events.noteError(p, req, reply); // The request was a whole step of its own, so it settles the way a // step does: the cursor and scroll reconciled, the scripted panes @@ -5632,6 +5634,8 @@ pub const Pardes = struct { const asked = p.panes[id] orelse return null; switch (asked.prompt) { .del_side => return "k j", + // Any path; `-` takes it back. + .save => return "", .repl_choice => { const ask = p.repl_ask orelse return null; var w = std.Io.Writer.fixed(buf); @@ -5990,6 +5994,15 @@ pub const Pardes = struct { p.fs.refused = true; return; } + // Asked for over 9P (Save from an exec on a terminal): a question + // the log says, `ask save path`, answered on the pane's + // ctl with `answer ` or `answer -`; asked again, the one + // already open stands, not a second on top of it. + if (request == .save and p.fs.serving) { + if (pane.prompt == .save) return; + var rec: [32]u8 = undefined; + ctlfs.events.notePath(p, "ask", std.fmt.bufPrint(&rec, "{d} save path", .{pane.serial}) catch ""); + } const marker = switch (request) { .search => |marker| marker, .save => config.save_marker, -- cgit v1.3 From 554181b73fd53b898841203066382e4287b83e89 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 06:05:08 -0300 Subject: One rule for failing builtins: the write fails, one err, no msg A builtin that failed through a ctl failed the write and logged its err, but through look, exec, tagexec or a column's exec it only said so on the message row, logged as a msg, and the write succeeded. Now every click write runs its builtin as a ctl line does (ctl.captured): a failure fails the write, with its words (EINVAL for malformed input, else EIO or what the words name), logs one err and no msg or announcement. get's Modified and a look miss are shown but logged once, as their err. A control character's refusal names its reason, a failed click reads back nothing, and look never reads back a pane closed since. The special case for a cut-short Edit through exec goes (the rule covers it); fs.md's table of exceptions becomes the one rule, as does the skill. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 9 ++++-- docs/fs.md | 28 +++++++++-------- src/Messages.zig | 5 ++-- src/builtins.zig | 16 +--------- src/fs.zig | 4 +++ src/look.zig | 3 ++ src/ninep/cols.zig | 4 +-- src/ninep/ctl.zig | 63 +++++++++++++++++++++++++++++++++++++-- test/fs.py | 17 +++++++++-- 9 files changed, 108 insertions(+), 41 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 4f903d5d..9e540de8 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -154,9 +154,12 @@ an open that wrote, until its next write); open again, or seek to 0, to read it again. Each command line runs once whole, however a mount cuts a big write; a last line with no newline runs when the open closes, and an Edit block still open then fails there (an `err`: ``unmatched `{'``, or an a/c/i text with no `.` -line), changing nothing. A command that fails is reported in -the editor, not as a write error, so inspect the resulting pane, index, message -or screen; only a malformed line fails the write itself. A word no builtin +line), changing nothing. One rule: a builtin that fails, whether through a +ctl, look, exec, tagexec or a column's exec, fails the write (EINVAL for a +malformed line, else EIO or an errno that fits) and logs one `err` with the +reason, no `msg`. A look that finds nothing is no failure: it answers +nothing and logs one `err`. A command line run in a command pane is judged +by its `exit` record. A word no builtin knows (a typo included) is a command line: written at a terminal at its prompt it is typed into that shell; from anywhere else it runs as a command pane, a terminal whose child is the root ctl's `Shell` ($SHELL, else /bin/sh, unless set) diff --git a/docs/fs.md b/docs/fs.md index 0a7cee7d..07b380aa 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -410,8 +410,8 @@ only its pane's; a command they run starts in the session's directory, where pardes started, not the focused pane's), and what the word says is logged as the session's, `msg -`. Blank lines are skipped, and every other line is checked before any of them runs, so a control character fails the whole -write with EINVAL; a command that fails inside the editor is reported on the -message row, not as a write error. Reading any of these files answers the +write with EINVAL; a builtin that fails there fails the write as well +(below: one rule). Reading any of these files answers the serials of the panes the last command created, or, when it created none, the pane a look focused or the pane an exec acted on (even one it closed), one per line; a look that found text answers the pane the text is selected in, @@ -631,17 +631,19 @@ pane. Every `data`, `xdata` or `body` write is an undo step of its own while `mark` is 1; to make a loop's writes one step, write `1` (an undo point here), then `0`, the writes, then `1` again. -Which writes fail and which only say so: - -| file | a write fails (the errno, an `err` record) | said on the message row and logged as `msg`, the write succeeding | -|---|---|---| -| `ctl` (root, pane, column) | a malformed line, an unknown word, a builtin's failure, a refusal (Modified...) | what a builtin says when it works | -| `look`, `exec`, `tagexec`, a column's `exec` | a control character, a line over 1024 bytes, no pane slot or room | a look that finds nothing, a command's own failure, a builtin's failure | -| `addr`, `dot`, `limit` | an address that does not evaluate | -- | -| `data`, `xdata` | no address (the last one failed) | -- | -| `body`, `tag`, `name`, `sel`, the flag files | a bad value, a pane gone | -- | -| `event` | a malformed record, a range past the text | what the action it runs says | -| `pty/ctl`, `pty/data`, `pty/run` | a malformed verb, a size out of range, a pane that is no terminal | -- | +One rule for what fails: a write fails whenever what it asked for fails, +whether it came to a `ctl` (the root's, a pane's, a column's), `look`, +`exec`, `tagexec` or a column's `exec`, or to any other file -- with an +errno that fits, EINVAL for malformed input (an unknown word, a control +character, a command line over 1024 bytes, a `size` or `winsize` out of +range, a bad address or event record), else EIO or the errno the words +name (ENOENT for a pane or file gone, ENOSPC for no room or slot, EBUSY +for a held lock) -- and logs its reason exactly once, as `err +: `, with no `msg` for it. A builtin a click runs (Save, get's +`Modified`, Tty with no room, Edit) is no exception. What is not a +failure: a look that finds nothing answers nothing and logs one `err` +(`look: no match for ...`), the write succeeding; and a command line run in +a command pane ends in its own time, told by its `exit` record. `tag` reads the whole tag as the pane shows it: the computed path or PDF page (no mark for unsaved text: the grip shows that, and `dirty` says it), diff --git a/src/Messages.zig b/src/Messages.zig index 7970908e..d8aeea0c 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -487,7 +487,8 @@ pub fn clip(text: []const u8, max: usize) []const u8 { pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { // A builtin a ctl write runs: its first error is also the write's, cut // between words. - if (p.fs.no_prompt and p.fs.failure_len == 0) { + const failing_write = p.fs.no_prompt or p.fs.capturing; + if (failing_write and p.fs.failure_len == 0) { const kept = if (text.len > p.fs.failure.len) clip(text, p.fs.failure.len - 3) else text; @memcpy(p.fs.failure[0..kept.len], kept); var n = kept.len; @@ -500,7 +501,7 @@ pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { // The write fails with it, and its err record says it: no msg for it, // and no Verbose announcement before that, so the same failure again is // the same record again, counted (events.pushCounting). - if (p.fs.no_prompt) { + if (failing_write) { const serial: u32 = if (p.fs.session_write) 0 else if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; ctlfs.events.dropAnnouncement(p, serial, text); p.fs.unlogged = true; diff --git a/src/builtins.zig b/src/builtins.zig index 6ca216e3..dfd1e84c 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -946,21 +946,7 @@ pub const Edit = struct { var why: sam.Why = .{}; var said: [260]u8 = undefined; const res = sam.run(arena, f.content, ninep_pane.dotOf(c.pane), f.path, c.arg orelse "", &why) catch |err| switch (err) { - error.Edit => { - const text = std.fmt.bufPrint(&said, "Edit: {s}", .{why.text()}) catch "Edit: failed"; - // A block cut short (no `.` line, no `}`) that came over - // 9P through an exec, whose write does not fail for what - // a command says, is still the write's fault: an err. - const cut = std.mem.eql(u8, why.text(), "unmatched `{'") or std.mem.startsWith(u8, why.text(), "a, c or i text not ended"); - if (cut and c.p.fs.serving and !c.p.fs.no_prompt) { - var rec: [300]u8 = undefined; - pardes.ctlfs.events.notePath(c.p, "err", std.fmt.bufPrint(&rec, "{d} exec: {s}", .{ c.pane.serial, text }) catch "- exec: Edit failed"); - c.p.fs.unlogged = true; - defer c.p.fs.unlogged = false; - return c.p.reportFailure(c.id, text); - } - return c.p.reportFailure(c.id, text); - }, + error.Edit => return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Edit: {s}", .{why.text()}) catch "Edit: failed"), error.OutOfMemory => return c.p.reportError(c.id, "Edit", err), }; if (res.undo != 0) { diff --git a/src/fs.zig b/src/fs.zig index cb89648c..71e2cbad 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1274,6 +1274,10 @@ pub const Namespace = struct { /// A ctl write's failure is being said: its err record logs it, so /// no msg does (Messages.reportFailure). unlogged: bool = false, + /// A 9P write of clicks (look, exec, tagexec, a column's exec) is running + /// one: a builtin's failure is the write's, as a ctl line's is (no_prompt, + /// which also refuses prompts, which a click may open). + capturing: bool = false, /// A 9P request is being served (Pardes.serveFs): a prompt it opens is /// a question for the log (`ask`), answered with `answer`. serving: bool = false, diff --git a/src/look.zig b/src/look.zig index d53ac76a..796eb5bb 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1209,7 +1209,10 @@ fn missed(p: *Pardes, id: usize, comptime fmt: []const u8, args: anytype) void { var said: [miss_path_cap + 64]u8 = undefined; const why = std.fmt.bufPrint(&said, fmt, args) catch "no match"; var msg: [said.len + 8]u8 = undefined; + // Shown on the pane; logged once, as the err below, not a msg too. + p.fs.unlogged = true; p.setMessage(id, std.fmt.bufPrint(&msg, "Look: {s}", .{why}) catch "Look: no match"); + p.fs.unlogged = false; const serial = if (p.panes[id]) |pane| pane.serial else 0; var rec: [said.len + 32]u8 = undefined; pardes.ctlfs.events.notePath(p, "err", std.fmt.bufPrint(&rec, "{d} look: {s}", .{ serial, why }) catch return); diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index ebe3279a..7745ee5e 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -164,7 +164,7 @@ pub fn writeExec(p: *Pardes, req: Req, serial: ?u32) Reply { while (lines.next()) |raw| { const line = std.mem.trim(u8, raw, " \t\r"); if (line.len == 0) continue; - for (line) |c| if (c < ' ' and c != '\t') return Reply.fail(req.tag, E.INVAL); + for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, pardes.ctlfs.ctl.e_control); if (pardes.ctlfs.ctl.tooLong(req, line)) |refusal| return refusal; const col = if (serial) |s| layout.columnBySerial(p, s) orelse return Reply.fail(req.tag, E.NOENT) else null; if (p.panes[p.active] == null) return Reply.fail(req.tag, E.NOENT); @@ -172,7 +172,7 @@ pub fn writeExec(p: *Pardes, req: Req, serial: ?u32) Reply { defer p.exec_column = null; p.exec_header = true; defer p.exec_header = false; - pardes.ctlfs.ctl.run(p, p.active, true, line, true); + if (pardes.ctlfs.ctl.captured(p, req, p.active, true, line, true)) |refusal| return refusal; } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 112df099..3f7da44c 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -174,13 +174,13 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep while (it.next()) |text| { if (text.len == 0) continue; // Only an Edit block holds newlines (Messages). - for (text) |c| if (c < ' ' and c != '\t' and c != '\n') return Reply.fail(req.tag, E.INVAL); + for (text) |c| if (c < ' ' and c != '\t' and c != '\n') return tree.failText(req.tag, E.INVAL, e_control); if (exec) if (tooLong(req, text)) |refusal| return refusal; if (!apply) continue; const id = if (serial) |s| p.paneBySerial(s) orelse break else p.active; if (p.panes[id] == null) return Reply.fail(req.tag, E.NOENT); p.fs.no_pane_slot = false; - run(p, id, exec, text, in_tag); + if (captured(p, req, id, exec, text, in_tag)) |refusal| return refusal; // A pane it would have opened had no slot: the write fails, and // a look reads back nothing. if (p.fs.no_pane_slot) { @@ -206,6 +206,24 @@ pub fn tooLong(req: Req, line: []const u8) ?Reply { return tree.failText(req.tag, E.INVAL, e_too_long); } +pub const e_control = "a command line holds no control character but a tab"; + +/// Runs one click (`run`) as a 9P write's: a builtin that fails there fails +/// the write, with its words and an err record, and no msg, as a ctl line +/// does (runBuiltin). The refusal, or null. +pub fn captured(p: *Pardes, req: Req, id: usize, exec: bool, text: []const u8, in_tag: bool) ?Reply { + p.fs.capturing = true; + p.fs.failure_len = 0; + defer p.fs.capturing = false; + run(p, id, exec, text, in_tag); + if (p.fs.failure_len == 0) return null; + // A failed click answers nothing: look reads back empty. + p.fs.results_len = 0; + const failure = p.fs.failure[0..p.fs.failure_len]; + // A slot or a place refused keeps its errno words (no space: ENOSPC). + return tree.failText(req.tag, E.IO, std.fmt.bufPrint(&p.fs.ename, "{s}", .{failure}) catch failure); +} + pub fn resultsLen(p: *Pardes) u64 { var n: u64 = 0; for (p.fs.results[0..p.fs.results_len]) |serial| { @@ -221,7 +239,14 @@ pub fn readResults(p: *Pardes, req: Req) Reply { const out = p.fs.stage(p.gpa); const o = tree.openOf(p, req); const kept = if (o) |open| open.results.list[0..open.results.len] else p.fs.results[0..p.fs.results_len]; - for (kept) |serial| + // A look answers panes to go to: never one closed since (an exec may + // answer the pane it closed, which is what it acted on). + const looking = if (tree.Node.target(req.node)) |t| switch (t) { + .top => |f| f == .look, + .pane => |pt| pt.file == .look, + .col => false, + } else false; + for (kept) |serial| if (!looking or p.paneBySerial(serial) != null) out.print(p.gpa, "{d}\n", .{serial}) catch return Reply.fail(req.tag, E.NOMEM); const open = o orelse return tree.stagedReply(p, req); if (!open.results.wrote) return tree.stagedReply(p, req); @@ -792,6 +817,9 @@ fn getRefused(p: *Pardes, pane: *Pane) ?[]const u8 { if (pane.discard_warned) |w| if (w.revision == f.revision and w.by == .get) return null; pane.discard_warned = .{ .revision = f.revision, .by = .get }; const said = std.fmt.bufPrint(&p.fs.ename, "{s}: Modified (get again to discard)", .{f.path}) catch "Modified (get again to discard)"; + // Shown; the write's err record logs it, not a msg too. + p.fs.unlogged = true; + defer p.fs.unlogged = false; p.setMessage(p.paneBySerial(pane.serial).?, said); return said; } @@ -1452,6 +1480,10 @@ test "look and exec read back what the last command touched, a ctl write's too" // A ctl write that makes nothing names the pane it ran at. try testing.expectEqual(tree.Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "Verbose off\n").reply.status); try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), rd(p, root_exec, 0, 64).bytes); + // Closed, it is no pane to go to: a fresh read of look is empty. + try testing.expectEqual(tree.Status.ok, wr(p, Node.of(made, .ctl), "Del\n").reply.status); + try testing.expect(p.paneBySerial(made) == null); + try testing.expectEqualStrings("", rd(p, @intFromEnum(tree.TopFile.look), 0, 64).bytes); } test "an error's words give the errno a mount reads: EINVAL for what is malformed, EIO for what failed" { @@ -1820,3 +1852,28 @@ test "get names the path it could not read, logs the edits it threw away, and a try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, try std.fmt.bufPrint(&rec, "changed {d} deleted\n", .{serial}))); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); } + +test "a builtin that fails through exec, tagexec or a column's exec fails the write with one err and no msg" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + p.update(.tick); // the pane's `new` is logged first + while (p.nextEffect()) |_| {} + const serial = serialOf(p); + for ([_]u64{ root_exec, Node.of(serial, .exec), @intFromEnum(tree.TopFile.tagexec), Node.ofCol(pardes.layout.columnSerial(p, 0), .exec) }) |node| { + const failed = wr(p, node, "Kill zzz\n"); + try testing.expectEqual(Status.err, failed.reply.status); + try testing.expect(std.mem.indexOf(u8, failed.reply.ename, "Kill: no running command has that first word") != null); + } + const log = @intFromEnum(tree.TopFile.log); + const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; + const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; + try testing.expect(std.mem.indexOf(u8, text, "msg ") == null); + try testing.expectEqual(@as(usize, 4), std.mem.count(u8, text, "Kill: no running command has that first word")); + _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); + // A control character is refused with its reason. + try testing.expectEqualStrings(e_control, wr(p, root_exec, "Msg a\x01b\n").reply.ename); + // A look miss: one err, no msg. + _ = wr(p, @intFromEnum(tree.TopFile.look), "zzqqnotthere\n"); + try testing.expect(th.logHas(p, "look: no match for \"zzqqnotthere\"")); + try testing.expect(!th.logHas(p, "msg 1 Look: no match")); +} diff --git a/test/fs.py b/test/fs.py index b7e8adcc..8d16d718 100644 --- a/test/fs.py +++ b/test/fs.py @@ -133,6 +133,16 @@ def execute(client, serial, command): client.write(f'/pane/{serial}/exec', f'{command}\n'.encode()) +def execute_refused(client, serial, command, words): + """A middle click on a builtin that fails: the write fails, saying why.""" + try: + execute(client, serial, command) + except OSError as why: + assert words in str(why), (command, why) + return + raise AssertionError(f'{command!r} was taken') + + def walk_tree(client, path='/', skip=('/log', '/os', '/screen')): """Stat every entry below `path`, as `find` does, without opening anything.""" seen = [] @@ -725,8 +735,9 @@ def test(binary, quic=False): execute(remote, control, 'Mount peer ' + str(address)) opened = look(remote, '/n/peer/pane/1/body', source=control) assert remote.read(f'/pane/{opened}/body') == client.read('/pane/1/body') - execute(remote, control, 'Mount peer ' + str(own_address)) - execute(remote, control, 'Unmount peer') + # A builtin that fails through exec fails the write (one rule). + execute_refused(remote, control, 'Mount peer ' + str(own_address), 'already mounted') + execute_refused(remote, control, 'Unmount peer', 'mount in use') # a pane is open on it remote.write(f'/pane/{opened}/body', b'runtime mounted Save\n', truncate=True) remote.write(f'/pane/{opened}/exec', b'Save\n') assert client.read('/pane/1/body') == b'runtime mounted Save\n' @@ -753,7 +764,7 @@ def test(binary, quic=False): with session(binary, root, name, tty=tty) as (old, address): old.write('/pane/1/body', b'dumped state\n', truncate=True) control = new_pane(old, b'') - execute(old, control, 'Restore ' + str(root / 'missing dump.zon')) + execute_refused(old, control, 'Restore ' + str(root / 'missing dump.zon'), 'no such file') assert old.read('/pane/1/body') == b'dumped state\n' execute(old, control, 'Mount own ' + str(address)) execute(old, control, 'Dump') -- cgit v1.3 From 1b513045336b3c7381c447ffa8c9167f8b1a5a0a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 07:05:46 -0300 Subject: A builtin's Verbose announcement is logged only when it succeeds A failure said while it ran (Exit's refusal, a Del refused) or later by the host (a Save's write, a Dump's) left `msg N Save` in the log as if it had worked. The announcement's record is remembered and taken back out on either, unless a follower read it already. A refused pane/new logs its err alone, and a failed Dump says its reason in words (`file not found`, not `FileNotFound`) so its msg goes and the err is the one record. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 11 +++++++---- src/Messages.zig | 4 ++++ src/exec.zig | 10 ++++++++++ src/fs.zig | 10 ++++++++++ src/ninep/ctl.zig | 32 +++++++++++++++++++++++++++++++- src/ninep/events.zig | 38 ++++++++++++++++++++++++++++++++++++++ src/ninep/tree.zig | 7 +++++++ src/pardes.zig | 5 +++-- 8 files changed, 110 insertions(+), 7 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index e7c85681..ffee9124 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -720,10 +720,13 @@ mapping the serial it had to the one it has now, and `restoredcol for every line the editor says (with `verbose` on, that includes each builtin announcing itself as it runs, on purpose: the log says which ran -- unless the builtin then says something of its own that starts with its -name, `Kill: nothing running`, which takes the announcement's place; a -builtin that fails its write (`ctl`, `exec`, `/tagexec` or a column's -`exec`) is logged by that write's `err` alone, no announcement and no `msg`, so the same failure again is the same record -again; a line said again word for word is counted, `msg 3 Undo: nothing to +name, `Kill: nothing running`, which takes the announcement's place; an +announcement is logged only for a builtin that succeeds: one that fails, +as it runs or when the host could not do its work (a Save's write, a +Dump's), leaves none, from a click at the keyboard too. A builtin that +fails its write (`ctl`, `exec`, `/tagexec` or a column's `exec`, and an +open of `pane/new`) is logged by that write's `err` alone, no announcement +and no `msg`, so the same failure again is the same record again; a line said again word for word is counted, `msg 3 Undo: nothing to undo (x40)`, as `err` is (below); a text past 256 bytes is cut there, between words, and ends in an ellipsis, `…`, as an `err`'s reason is past 200; its serial is the pane it ran at, `-` when the keyboard was on a diff --git a/src/Messages.zig b/src/Messages.zig index eb2fa5e2..c0838fb2 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -485,6 +485,10 @@ pub fn clip(text: []const u8, max: usize) []const u8 { /// reportError with the words already chosen. pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { + p.fs.failures +%= 1; + // A failure said later, when the host could not do the work (a Save's + // write): that builtin's announcement goes from the log too. + ctlfs.events.dropFailedAnnouncement(p, text, false); // A builtin a ctl write runs: its first error is also the write's, cut // between words. const failing_write = p.fs.no_prompt or p.fs.capturing; diff --git a/src/exec.zig b/src/exec.zig index c2d1be21..aee2e1e5 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -789,12 +789,22 @@ pub fn runBuiltinFrom(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ? // A builtin says its own name before it runs, so a tagline click is // legible even when what it did is invisible. Whatever the builtin // then says for itself replaces the announcement. + // Its log record stands only if it does not fail (events.dropFailedAnnouncement). + var announced: ?u64 = null; if (p.announce and p.settings.verbose and builtins.registry.announces(b)) { p.setMessage(id, @tagName(b)); pane.msg_announcement = true; + announced = pardes.ctlfs.events.newestSaying(p, @tagName(b)); + p.fs.announced_seq = announced; + const word = @tagName(b)[0..@min(@tagName(b).len, p.fs.announced_word.len)]; + @memcpy(p.fs.announced_word[0..word.len], word); + p.fs.announced_word_len = @intCast(word.len); } + const failures = p.fs.failures; const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg, .from_body = from_body }; builtins.registry.dispatch(b, c); + if (announced != null and p.fs.failures != failures and p.fs.announced_seq == announced) + pardes.ctlfs.events.dropFailedAnnouncement(p, "", true); } pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[]const u8) void { diff --git a/src/fs.zig b/src/fs.zig index 71e2cbad..6a4c0a33 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1298,6 +1298,16 @@ pub const Namespace = struct { header_held: bool = false, late_failure: [256]u8 = undefined, late_failure_len: u16 = 0, + /// The log record of the last Verbose announcement (`msg + /// `) and its word: a failure of that builtin, now or when its + /// host work fails (a Save, a Dump), takes it back out of the log, so + /// an announcement stands only for a builtin that did what it said. + announced_seq: ?u64 = null, + /// Every failure said (Messages.reportFailure), counted: a builtin + /// that said one while it ran failed. + failures: u32 = 0, + announced_word: [32]u8 = undefined, + announced_word_len: u8 = 0, /// A refusal that quotes the message it refuses, as Plan 9's cmderror /// does (kernel/misc/parse.c:82); answered at once (src/9p_io.zig). ename: [320]u8 = undefined, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index de63c6aa..b6fefa01 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1486,6 +1486,36 @@ test "look and exec read back what the last command touched, a ctl write's too" try testing.expectEqualStrings("", rd(p, @intFromEnum(tree.TopFile.look), 0, 64).bytes); } +test "a builtin's Verbose announcement is logged only when it succeeds, its failure said now or by the host later" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + var want: [64]u8 = undefined; + const said_exit = try std.fmt.bufPrint(&want, "msg {d} Exit\n", .{serial}); + // Refused as it runs, through a click: the write fails, and no Exit. + const f = &p.panes[0].?.file.?; + f.saved_revision = f.revision -% 1; + f.saved_hash = 0; + try testing.expect(wr(p, Node.of(serial, .exec), "Exit\n").errno() != 0); + try testing.expect(!th.logHas(p, said_exit)); + // Refused at the keyboard (no write to fail), edited since: the same. + f.revision +%= 1; + _ = p.executeBuiltinLine(p.active, "Exit"); + try testing.expect(!th.logHas(p, said_exit)); + try testing.expect(!p.quit); + // A Save the host could not do, told a step later: the Save goes too. + var save_buf: [64]u8 = undefined; + const said_save = try std.fmt.bufPrint(&save_buf, "msg {d} Save\n", .{serial}); + _ = wr(p, Node.of(serial, .exec), "Save\n"); + p.saveFailed(@intCast(p.paneBySerial(serial).?), "/test.txt", error.AccessDenied); + try testing.expect(!th.logHas(p, said_save)); + // One that does what it says keeps its announcement. + _ = wr(p, Node.of(serial, .exec), "Undo\n"); + var undo_buf: [64]u8 = undefined; + try testing.expect(th.logHas(p, try std.fmt.bufPrint(&undo_buf, "msg {d} Undo", .{serial}))); +} + test "an error's words give the errno a mount reads: EINVAL for what is malformed, EIO for what failed" { // 9ns (cloud9's 9ns/src/nine.zig) maps an error to an errno by its // words, and EIO when none of them match: these words must not. @@ -1574,7 +1604,7 @@ test "a Restore of a file that is no dump fails the write before any warning, an p.fs.late_failure_len = 0; p.dumpFailed("/nowhere/pardes.dump.zon", error.FileNotFound); - try testing.expectEqualStrings("Dump /nowhere/pardes.dump.zon: FileNotFound", p.fs.late_failure[0..p.fs.late_failure_len]); + try testing.expectEqualStrings("Dump /nowhere/pardes.dump.zon: file not found", p.fs.late_failure[0..p.fs.late_failure_len]); } test "a setting this frontend cannot show says GUI-only, and DumpDir reads back the directory in effect" { diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 2b7c1c1d..44ad560e 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -232,6 +232,44 @@ pub fn dropAnnouncement(p: *Pardes, serial: u32, text: []const u8) void { p.fs.log.buf.shrinkRetainingCapacity(last.at); } +/// The sequence number of the newest log record when it is a msg that +/// ends in `word` alone: not one counted (`(x2)`) over an earlier say. +pub fn newestSaying(p: *Pardes, word: []const u8) ?u64 { + const last = newest(p) orelse return null; + if (!std.mem.startsWith(u8, last.text, "msg ") or !std.mem.endsWith(u8, last.text, word)) return null; + if (last.text[last.text.len - word.len - 1] != ' ') return null; + return last.seq; +} + +/// Takes record `seq` back out of the log, unless a follower has read it. +pub fn dropRecord(p: *Pardes, seq: u64) void { + if (followerRead(p, seq)) return; + const q = &p.fs.log; + var at = q.head; + var s = q.dropped; + while (at + 4 <= q.buf.items.len) : (s += 1) { + const size = 4 + std.mem.readInt(u32, q.buf.items[at..][0..4], .little); + if (s == seq) { + const items = q.buf.items; + std.mem.copyForwards(u8, items[at..], items[at + size ..]); + q.buf.shrinkRetainingCapacity(items.len - size); + return; + } + at += size; + } +} + +/// A builtin's failure: its Verbose announcement goes from the log, when +/// `text` is that builtin's (it starts with its word) or `any`, as for a +/// failure said while the builtin itself runs. +pub fn dropFailedAnnouncement(p: *Pardes, text: []const u8, any: bool) void { + const seq = p.fs.announced_seq orelse return; + const word = p.fs.announced_word[0..p.fs.announced_word_len]; + if (!any and !(std.mem.startsWith(u8, text, word) and text.len > word.len and (text[word.len] == ' ' or text[word.len] == ':'))) return; + p.fs.announced_seq = null; + dropRecord(p, seq); +} + /// Drops the newest record when it is a msg saying `text` (of any pane) /// that no follower has read: a failure its write's err record will say. pub fn dropMessage(p: *Pardes, text: []const u8) void { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 69b89f53..ed0e0352 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -717,7 +717,12 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { .new => { const slot = p.freeSlot() orelse return failText(req.tag, E.NOSPC, std.fmt.bufPrint(&p.fs.ename, "pane/new: " ++ pardes.Messages.no_pane_slots, .{pardes.MAX_PANES}) catch "no space for a pane"); p.fs.no_pane_slot = false; + // Refused, the open's err is the one record of it (the + // one rule): no msg besides. + p.fs.capturing = true; p.newScratchFor(p.active, .fs); + p.fs.capturing = false; + p.fs.failure_len = 0; const made = p.panes[slot] orelse return Reply.fail(req.tag, E.NFILE); // No room in its column: it closes at the step's end. if (p.unplaced.isSet(slot)) return failText(req.tag, E.NOSPC, p.fs.ename[0..p.fs.no_pane_slot_len]); @@ -1448,6 +1453,8 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e try testing.expectEqual(E.NOSPC, refused.errno()); try testing.expect(std.mem.endsWith(u8, refused.reply.ename, said)); try testing.expect(th.logHas(p, said)); + // Its err alone says it: no msg besides (the one rule). + try testing.expect(!th.logHas(p, "New: no space")); // A look that would open a pane fails its write, and says the same. var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); diff --git a/src/pardes.zig b/src/pardes.zig index 98b8819c..739d5bf2 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5219,8 +5219,9 @@ pub const Pardes = struct { var what: [limits.host_path_cap + 8]u8 = undefined; const operation = std.fmt.bufPrint(&what, "Dump {s}", .{path}) catch "Dump"; p.reportError(p.active, operation, err); - var buf: [256]u8 = undefined; - const said = std.fmt.bufPrint(&buf, "{s}: {s}", .{ operation, @errorName(err) }) catch "Dump failed"; + // In the words the message row has, so the write's err is the one + // record of it (its msg goes: 9p_io, dropMessage). + const said = if (p.panes[p.active]) |pane| pane.msg[0..pane.msg_len] else "Dump failed"; const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len); @memcpy(p.fs.late_failure[0..kept.len], kept); p.fs.late_failure_len = @intCast(kept.len); -- cgit v1.3 From 740effb5c9e18e7638fde196000030c899e8798e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 07:29:46 -0300 Subject: A root exec or look that fails logs its err against the pane it ran at `err - exec: ...` said nothing of where the line ran; the root's exec and look run at the keyboard's pane, and their err now names it, as a click there would. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 4 +++- src/fs.zig | 3 +++ src/ninep/ctl.zig | 18 +++++++++++++++++- src/ninep/events.zig | 8 +++++++- 4 files changed, 30 insertions(+), 3 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 7baac666..36fc7d7a 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -748,7 +748,9 @@ between words, and ends in an ellipsis, `…`, as an `err`'s reason is past 200; its serial is the pane it ran at, `-` when the keyboard was on a column or workspace tag, or the line came to the root's ctl, `/tagexec` or a column's ctl or exec), and `err -: ` for every write or truncation the tree refused or that +: ` (the serial the pane's whose file it is, and for the root's +`exec` and `look` the pane the line ran at, `err 3 exec: ...`; `-` for +another root file) for every write or truncation the tree refused or that failed -- through a mount a shell sees only the errno its kernel mapped the reply to, usually `Invalid argument`, and this is the reason (`err 3 addr: no match for regexp`). A record said again word for word, straight after diff --git a/src/fs.zig b/src/fs.zig index 6a4c0a33..4414c150 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1303,6 +1303,9 @@ pub const Namespace = struct { /// host work fails (a Save, a Dump), takes it back out of the log, so /// an announcement stands only for a builtin that did what it said. announced_seq: ?u64 = null, + /// The serial of the pane the root's exec or look last ran a line at + /// (the keyboard's), 0 before one: its err record names that pane. + ran_at: u32 = 0, /// Every failure said (Messages.reportFailure), counted: a builtin /// that said one while it ran failed. failures: u32 = 0, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 7c68210a..4f52d661 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -170,6 +170,7 @@ pub fn completeEnd(p: *Pardes, data: []const u8) usize { /// A null `serial` clicks at whichever pane is active as each line runs, /// which is what the root's own look and exec mean; a serial stays put. pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Reply { + p.fs.ran_at = 0; for ([2]bool{ false, true }) |apply| { if (apply) p.fs.results_len = 0; var it = Messages.init(p, req.data); @@ -181,6 +182,7 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep if (!apply) continue; const id = if (serial) |s| p.paneBySerial(s) orelse break else p.active; if (p.panes[id] == null) return Reply.fail(req.tag, E.NOENT); + p.fs.ran_at = p.panes[id].?.serial; p.fs.no_pane_slot = false; if (captured(p, req, id, exec, text, in_tag)) |refusal| return refusal; // A pane it would have opened had no slot: the write fails, and @@ -1728,6 +1730,17 @@ test "Mount dials its peer and fails, mounting nothing, when none answers; a loo try testing.expect(th.logHas(p, "look: /n/gone/f.txt: dial failed: no answer")); } +test "a root exec that fails logs its err against the pane it ran at" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const f = &p.panes[0].?.file.?; + f.saved_revision = f.revision -% 1; + f.saved_hash = 0; + try testing.expect(wr(p, root_exec, "Exit\n").errno() != 0); + var want: [32]u8 = undefined; + try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "err {d} exec: ", .{serialOf(p)}))); +} + test "size is monotonic: growing is never refused, and a size once taken is taken again" { const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 60 }); defer p.deinit(); @@ -1983,7 +1996,10 @@ test "a builtin that fails through exec, tagexec or a column's exec fails the wr const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; try testing.expect(std.mem.indexOf(u8, text, "msg ") == null); - try testing.expectEqual(@as(usize, 4), std.mem.count(u8, text, "Kill: no running command has that first word")); + // The root's exec ran at the pane, so its err and the pane's exec's are + // the same record, counted. + try testing.expectEqual(@as(usize, 3), std.mem.count(u8, text, "Kill: no running command has that first word")); + try testing.expect(std.mem.indexOf(u8, text, "first word (x2)") != null); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); // A control character is refused with its reason. try testing.expectEqualStrings(e_control, wr(p, root_exec, "Msg a\x01b\n").reply.ename); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index fb0141f4..98799774 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -187,7 +187,13 @@ pub fn noteError(p: *Pardes, req: Req, reply: Reply) void { if (req.node & tree.sources.archive_node != 0) file = "src"; if (req.node != pardes.filesystem.os_root and req.node & pardes.filesystem.os_node == 0 and req.node & tree.sources.archive_node == 0) { if (tree.Node.target(req.node)) |t| switch (t) { - .top => |f| file = f.fileName(), + .top => |f| { + file = f.fileName(); + // The root's exec or look ran at the keyboard's pane: its + // failure is that pane's, as a click there would be. + if ((f == .exec or f == .look) and p.fs.ran_at != 0) + serial = std.fmt.bufPrint(&name, "{d}", .{p.fs.ran_at}) catch "-"; + }, .col => |c| { serial = "-"; file = (if (c.file == .dir) -- cgit v1.3 From a550753fb60be3cdc040c521ddaab9022f5d3248 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 09:11:37 -0300 Subject: Every EINVAL a write gets says why; DEL in an exec or look line is a control character An empty name, a word written to log other than follow, a data, sel, dot or dirty write to a pane with no text, a truncate other than to zero, and a control character in a look line written through a held open were refused with no words, logged as `Invalid argument`. Each says its reason now; and DEL is refused in exec and look lines as in names. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 8 ++++++-- src/fs.zig | 4 ++-- src/ninep/cols.zig | 2 +- src/ninep/ctl.zig | 26 ++++++++++++++++++++++++-- src/ninep/events.zig | 4 ++-- src/ninep/pane.zig | 15 +++++++++------ src/ninep/tree.zig | 2 +- 7 files changed, 45 insertions(+), 16 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 0b255390..ffce848e 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -410,8 +410,8 @@ same tree without leaving the process. its whole line, `&` jobs included; a command line is at most 1024 bytes, and a longer one written to an exec fails the write (EINVAL, `invalid command line: a command line is at most 1024 bytes`, and one with a control - character but a tab, `invalid command line: it holds a control character - other than a tab`; the root's exec logs either against the pane it would + character (DEL too) but a tab, `invalid command line: it holds a control + character (or DEL) other than a tab`; the root's exec logs either against the pane it would have run at) before anything in it runs; a builtin's line (a long `Msg`, an Edit block) may be longer. To run a command again, execute its line again from its directory: `echo 'make test' > pane//exec` on @@ -818,6 +818,10 @@ acme's `errors` only takes text, and one record stream is simpler to watch than a file per pane. A `msg` said while a pane is being made can precede that pane's `new`; panes present at boot are recorded before anything else. +Every EINVAL a write gets says why, in its reply and in its `err` record +(`bad character in file name: an empty name`, `invalid write to log: it +takes \`follow\` or \`follow new\``, `invalid write: this pane has no +text`), never a bare `Invalid argument`. Control characters, DEL and C1 controls (U+0080-U+009F) in a record become spaces, and a byte that is not UTF-8 is written `\xNN`, so a record is one line of UTF-8. diff --git a/src/fs.zig b/src/fs.zig index 4414c150..352aa0c4 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -224,12 +224,12 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { if (fd < 0) return Reply.fail(req.tag, E.PERM); defer _ = libc.close(fd); if (req.op == .setattr) { - if (!req.truncate or req.off != 0 or libc.ftruncate(fd, 0) != 0) return Reply.fail(req.tag, E.INVAL); + if (!req.truncate or req.off != 0 or libc.ftruncate(fd, 0) != 0) return tree.failText(req.tag, E.INVAL, "invalid truncate: only to zero"); var truncated = attr; truncated.size = 0; return .{ .tag = req.tag, .attr = truncated }; } - if (req.off > std.math.maxInt(i64)) return Reply.fail(req.tag, E.INVAL); + if (req.off > std.math.maxInt(i64)) return tree.failText(req.tag, E.INVAL, "invalid offset: past what a file may hold"); if (libc.lseek(fd, @intCast(req.off), libc.SEEK.SET) < 0) return Reply.fail(req.tag, E.IO); if (req.op == .write) { const written = libc.write(fd, req.data.ptr, req.data.len); diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index 7f78522a..6fdcda07 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -166,7 +166,7 @@ pub fn writeExec(p: *Pardes, req: Req, serial: ?u32) Reply { while (lines.next()) |raw| { const line = std.mem.trim(u8, raw, " \t\r"); if (line.len == 0) continue; - for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, pardes.ctlfs.ctl.e_control); + for (line) |c| if ((c < ' ' and c != '\t') or c == 0x7f) return tree.failText(req.tag, E.INVAL, pardes.ctlfs.ctl.e_control); if (pardes.ctlfs.ctl.tooLong(req, line)) |refusal| return refusal; // A pane's word (Undo, Msg, Save) is no word of a tag no pane owns: // refused as the root's ctl refuses it, never done at whichever diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 2f94dd3c..ccba342e 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -179,7 +179,7 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep while (it.next()) |text| { if (text.len == 0) continue; // Only an Edit block holds newlines (Messages). - for (text) |c| if (c < ' ' and c != '\t' and c != '\n') return tree.failText(req.tag, E.INVAL, e_control); + for (text) |c| if ((c < ' ' and c != '\t' and c != '\n') or c == 0x7f) return tree.failText(req.tag, E.INVAL, e_control); if (exec) if (tooLong(req, text)) |refusal| return refusal; if (!apply) continue; const id = if (serial) |s| p.paneBySerial(s) orelse break else p.active; @@ -214,7 +214,7 @@ pub fn tooLong(req: Req, line: []const u8) ?Reply { return tree.failText(req.tag, E.INVAL, e_too_long); } -pub const e_control = "invalid command line: it holds a control character other than a tab"; +pub const e_control = "invalid command line: it holds a control character (or DEL) other than a tab"; /// Runs one click (`run`) as a 9P write's: a builtin that fails there fails /// the write, with its words and an err record, and no msg, as a ctl line @@ -1968,6 +1968,28 @@ test "pty/ctl exec in a directory that is gone fails ENOENT; a shell that cannot try testing.expectEqualStrings("shell: access denied", p.fs.late_failure[0..p.fs.late_failure_len]); } +test "every EINVAL a write gets says why, in its err record too; DEL is a control character in a line" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const log = @intFromEnum(tree.TopFile.log); + const h = call(p, .{ .tag = 1, .op = .open, .node = log, .omode = 2 }).reply.handle; + const Case = struct { node: u64, data: []const u8, words: []const u8, handle: u32 = 0 }; + for ([_]Case{ + .{ .node = root_exec, .data = "echo a\x7fb\n", .words = "control character" }, + .{ .node = root_look, .data = "a\x7fb\n", .words = "control character" }, + .{ .node = Node.of(serial, .name), .data = "\n", .words = "an empty name" }, + .{ .node = log, .data = "bogus\n", .words = "takes `follow`", .handle = h }, + }) |c| { + const refused = call(p, .{ .tag = 2, .op = .write, .node = c.node, .handle = c.handle, .data = c.data }); + try testing.expectEqual(E.INVAL, refused.errno()); + try testing.expect(std.mem.indexOf(u8, refused.reply.ename, c.words) != null); + } + _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); + try testing.expect(!th.logHas(p, "Invalid argument")); + try testing.expect(th.logHas(p, "an empty name")); +} + test "size is monotonic: growing is never refused, and a size once taken is taken again" { const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 60 }); defer p.deinit(); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index d7079c5e..f58d970e 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -101,7 +101,7 @@ pub const Queue = struct { /// One record per read; `.again` holds the read until a record arrives. pub fn readQueue(p: *Pardes, req: Req, q: *Queue) Reply { const record = q.peek() orelse return .{ .tag = req.tag, .status = .again }; - if (req.size < record.len) return Reply.fail(req.tag, E.INVAL); + if (req.size < record.len) return tree.failText(req.tag, E.INVAL, "invalid read: shorter than the record waiting"); const out = p.fs.stage(p.gpa); out.appendSlice(p.gpa, record) catch return Reply.fail(req.tag, E.NOMEM); q.pop(); @@ -477,7 +477,7 @@ pub fn writeLog(p: *Pardes, req: Req) Reply { // what was there and waits for what comes after, as tail -n0 -f does. if (std.mem.eql(u8, word, "follow new")) { slot.pos = slot.bytes.len; - } else if (!std.mem.eql(u8, word, "follow")) return Reply.fail(req.tag, E.INVAL); + } else if (!std.mem.eql(u8, word, "follow")) return tree.failText(req.tag, E.INVAL, "invalid write to log: it takes `follow` or `follow new`"); slot.follow = true; return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 66b3728c..4c967fc5 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -481,8 +481,11 @@ fn writeTag(req: Req, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } +/// A write only text takes, to a pane with none: said, as every EINVAL is. +pub const e_no_text = "invalid write: this pane has no text (a terminal, an image or a PDF)"; + fn writeData(p: *Pardes, req: Req, pane: *Pane) Reply { - if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); + if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text); const pf = &pane.fs; if (pf.addr_failed) return tree.failText(req.tag, E.INVAL, e_addr_failed); clampAddr(pf, bodyOf(pane).len); @@ -501,7 +504,7 @@ fn writeData(p: *Pardes, req: Req, pane: *Pane) Reply { } fn writeSel(p: *Pardes, req: Req, pane: *Pane) Reply { - if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); + if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text); const d = dotOf(pane); const q0: usize = d.q0; const q1: usize = @max(q0, @as(usize, d.q1)); @@ -558,7 +561,7 @@ fn writeRange(req: Req, pane: *Pane, file: PaneFile) Reply { .limit => pf.limit = range, // Setting dot scrolls to it, which is the whole of acme's `show`. .dot => { - if (fileOf(pane) == null) return Reply.fail(req.tag, E.INVAL); + if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text); setDot(pane, range); }, else => unreachable, @@ -573,7 +576,7 @@ fn writeFlag(p: *Pardes, req: Req, pane: *Pane, file: PaneFile) Reply { const pf = &pane.fs; switch (file) { .dirty => { - const f = fileOf(pane) orelse return Reply.fail(req.tag, E.INVAL); + const f = fileOf(pane) orelse return tree.failText(req.tag, E.INVAL, e_no_text); f.saved_revision = if (on) f.revision -% 1 else f.revision; }, // acme's nomark joins the writes after it into one undo step. The @@ -616,7 +619,7 @@ fn nameFault(name: []const u8) ?[]const u8 { fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // One name: its newline ends it, as `echo` writes it, and it is one. const name = if (std.mem.endsWith(u8, req.data, "\n")) req.data[0 .. req.data.len - 1] else req.data; - if (name.len == 0) return Reply.fail(req.tag, E.INVAL); + if (name.len == 0) return tree.failText(req.tag, E.INVAL, e_name_char ++ ": an empty name"); if (nameFault(name)) |why| return tree.failText(req.tag, E.INVAL, why); if (fileOf(pane) == null) return tree.failText(req.tag, E.PERM, if (pane.isTerminal()) "rename not allowed: a terminal is named by its shell's directory; cd there, or Tty in another" @@ -624,7 +627,7 @@ fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { "rename not allowed: an image or PDF is named by the file it shows"); const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ pardes.Pardes.paneDir(pane), name }) catch return Reply.fail(req.tag, E.NOMEM); - if (!std.fs.path.isAbsolute(full) or full.len >= 4096) return Reply.fail(req.tag, E.INVAL); + if (!std.fs.path.isAbsolute(full) or full.len >= 4096) return tree.failText(req.tag, E.INVAL, "invalid file name: longer than a path may be"); nameBuffer(p, id, full, false) catch |err| return Reply.fail(req.tag, switch (err) { error.OutOfMemory => E.NOMEM, else => E.INVAL, diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index ed0e0352..391847f5 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1007,7 +1007,7 @@ fn write(p: *Pardes, req: Req, target: Target) Reply { if (o.what != .lines and o.what != .ctl) return writeNow(p, req, target); // A clicked line holds no control character: refused at once, not held // to fail unseen at the close. - if (resultsFile(target)) for (req.data) |c| if (c < ' ' and c != '\t' and c != '\n' and c != '\r') return Reply.fail(req.tag, E.INVAL); + if (resultsFile(target)) for (req.data) |c| if ((c < ' ' and c != '\t' and c != '\n' and c != '\r') or c == 0x7f) return failText(req.tag, E.INVAL, ctl.e_control); o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); const end = ctl.completeEnd(p, o.pending.items); if (end == 0) { -- cgit v1.3 From 157df8cb547ba4cf900b1f9eb75df15384985708 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 09:45:38 -0300 Subject: A served-tree pane spoils no Grep, and `look .` from a gone directory is ENOENT A pane named `/virtual` gave Grep the root `/`, which swallowed every other pane's directory and ran out of walk before any file: every Grep missed. Grep passes over panes of the served tree. And `.` from a pane whose directory was gone resolved to the served tree's root (/virtual/), or through the jump list to another pane's directory: a dot path is the looking pane's own, and gone it fails, `look: : no such directory`. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 8 ++++++-- src/fs.zig | 12 +++++++++++- src/look.zig | 22 ++++++++++++++++++++-- src/ninep/ctl.zig | 25 +++++++++++++++++++++++++ 4 files changed, 62 insertions(+), 5 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index a45bff17..184f6131 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -719,8 +719,12 @@ column's `exec`, or to any other file -- with an errno that fits, EINVAL for malformed input (an unknown word, a control character, a command line over 1024 bytes, a `size` or `winsize` out of range, a bad address or event record), else EIO or the errno the words -name (ENOENT for a pane, file or directory gone and for a Find or Grep -that finds nothing, `grep: no match, not found`, ENOSPC for no room or +name (ENOENT for a pane, file or directory gone -- `look .` from a pane +whose directory is gone says `look: : no such directory` -- and for a +Find or Grep that finds nothing, `grep: no match, not found`; Grep walks +every pane's directory on this host, passing over panes of the served +tree (`/virtual/`, a peer's `/n//`) and directories not there, +so none of them spoils the rest, ENOSPC for no room or slot, EBUSY for a held lock) -- and logs its reason exactly once, as `err : `, with no `msg` for it. A builtin a click runs (Save, get's `Modified`, Tty with no room, Edit) is no exception. What is not a diff --git a/src/fs.zig b/src/fs.zig index 352aa0c4..de02e8e8 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -677,7 +677,9 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 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; - if (resolveVirtual(p, word, 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 }; @@ -685,6 +687,14 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 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. diff --git a/src/look.zig b/src/look.zig index fa86aee4..9a81a5c9 100644 --- a/src/look.zig +++ b/src/look.zig @@ -593,7 +593,11 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start var nroots: usize = 0; for (p.panes) |slot| { const pp = slot orelse continue; - const d = Pardes.paneDir(pp); + // A pane of the served tree (/virtual/, /n//) has no + // directory on this host to walk, and one that named `/` would + // swallow every other root: passed over. + const d = filesystem.localPath(Pardes.paneDir(pp)) orelse continue; + if (filesystem.isVirtual(if (pp.file) |f| f.path else d)) continue; var covered = false; var k: usize = 0; while (k < nroots) { @@ -1107,7 +1111,8 @@ fn resolveLookTarget(p: *Pardes, id: usize, txt: []const u8, realbuf: *[4096]u8) if (openPaneTarget(p, j, pl.at)) |target| return target; } found = resolve(p, txt, dir, realbuf); - if (found != .none or pl.path.len == 0 or pl.path[0] == '/') break; + // `.`, `..`, `./x` are this pane's directory's, not another's. + if (found != .none or pl.path.len == 0 or pl.path[0] == '/' or filesystem.dotRelative(pl.path)) break; } return found; } @@ -1407,6 +1412,13 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { } switch (found) { .none => { + // `.` or `..` from a pane whose directory is gone: said, ENOENT, + // not searched for as a word. + if (filesystem.dotRelative(trimmed)) { + const dir = Pardes.paneDir(pane); + var said: [4200]u8 = undefined; + return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch "look: no such directory"); + } // A raw terminal's clicks are its program's; a look written over // 9P is no keyboard input, and searches whatever the key mode. if (pane.image != null or (pane.body.mode == .tty and !p.fs.serving)) return; @@ -1439,6 +1451,12 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { }, .url => |u| if (u.len <= 256) p.emit(.{ .open_link = .from(u) }), .dir => |dir| { + // A directory that is not there (the pane's own, gone): said, + // ENOENT, no terminal made in it. + if (comptime pardes.hosted) if (filesystem.localPath(dir)) |local| if (!exec.isDirectory(local)) { + var said: [4200]u8 = undefined; + return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch "look: no such directory"); + }; for (p.panes, 0..) |slot, i| { if (slot) |tt| if (std.mem.eql(u8, tt.cwdSlice(), dir) and exec.takesCommandLine(p, i)) { clearNavigationSelection(p, tt); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index db37fa49..d9a479fe 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2001,6 +2001,31 @@ test "/index shows a name as the log does: a newline in it is \\n, controls spac try testing.expectEqual(@as(u64, index.len), call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(tree.TopFile.index) }).reply.attr.size); } +test "a served-tree pane spoils no Grep, and Look . from a gone directory is ENOENT, not /virtual/" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "hit.txt", .data = "needle here\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + var line: [4200]u8 = undefined; + _ = wr(p, Node.of(serialOf(p), .name), try std.fmt.bufPrint(&line, "{s}/other.txt\n", .{dir})); + // A pane of the served tree. + const virtual = try th.newPane(p); + _ = wr(p, Node.of(virtual, .name), "/virtual/index\n"); + // One named the served tree's root, whose directory is `/`. + const top = try th.newPane(p); + _ = wr(p, Node.of(top, .name), "/virtual\n"); + try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Grep needle\n").reply.status); + // `.` from a pane whose directory is gone. + const gone = try th.newPane(p); + _ = wr(p, Node.of(gone, .name), "/tmp/pardes-no-such-dir-zz/f.txt\n"); + const looked = wr(p, Node.of(gone, .look), ".\n"); + try testing.expectEqual(E.NOENT, looked.errno()); + try testing.expectStringStartsWith(looked.reply.ename, "look: /tmp/pardes-no-such-dir-zz: no such directory"); +} + test "size is monotonic: growing is never refused, and a size once taken is taken again" { const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 60 }); defer p.deinit(); -- cgit v1.3 From df6106af80e13cc4f0121b7f2caf5315a4453a9d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 10:03:10 -0300 Subject: Find and Grep share one +Search a directory, each run replacing the last Each Grep with a new pattern opened another +Search, until the column refused panes. Find and Grep now reuse their directory's one, as acme reuses +Errors, and the exec reads back the pane it filled; a plain word's LookWord list search keeps a pane a pattern as before. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 5 ++++- src/Output.zig | 17 +++++++++++++++-- src/fs.zig | 3 +++ src/ninep/ctl.zig | 9 ++++++++- test/snapshots/find.golden | 16 ++++++++++------ test/snapshots/stepgrain.golden | 32 +++++++++++++++++++------------- 6 files changed, 59 insertions(+), 23 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 9b5b9d64..a0b3dcf7 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -736,7 +736,10 @@ whose directory is gone says `look: : no such directory` -- and for a Find or Grep that finds nothing, `grep: no match, not found`; Grep walks every pane's directory on this host, passing over panes of the served tree (`/virtual/`, a peer's `/n//`) and directories not there, -so none of them spoils the rest, ENOSPC for no room or +so none of them spoils the rest; Find and Grep share one `+Search` a +directory, each run replacing what the last showed, as acme reuses a +directory's `+Errors` (the exec reads that pane back), while a plain +word's `LookWord list` search keeps a pane a pattern, ENOSPC for no room or slot, EBUSY for a held lock) -- and logs its reason exactly once, as `err : `, with no `msg` for it. A builtin a click runs (Save, get's `Modified`, Tty with no room, Edit) is no exception. What is not a diff --git a/src/Output.zig b/src/Output.zig index b32a40a2..37d25168 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -406,6 +406,16 @@ pub fn open(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u return pane; } +/// Find and Grep share one +Search a directory, each run replacing what +/// the last showed, as acme reuses a directory's +Errors; a pane's own +/// search (LookWord list) keeps a pane a pattern. +fn fileSearch(from: Origin) bool { + return switch (from) { + .cmd => |c| c == .Find or c == .Grep, + else => false, + }; +} + pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8, initial_anchor: ?usize) !void { var result_content = content; errdefer p.gpa.free(result_content); @@ -448,9 +458,12 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] const rp = slot orelse continue; const rf = if (rp.file) |*f| f else continue; const o = if (rf.output) |*x| x else continue; - if (!std.meta.eql(o.from, from)) continue; - if (by_arg and !std.mem.eql(u8, o.arg(), arg)) continue; + const shared = fileSearch(from) and fileSearch(o.from); + if (!shared and !std.meta.eql(o.from, from)) continue; + if (!shared and by_arg and !std.mem.eql(u8, o.arg(), arg)) continue; if (!std.mem.eql(u8, std.fs.path.dirname(rf.path) orelse "", dir)) continue; + o.from = from; + p.fs.refilled = rp.serial; try setArg(o, arg); if (std.mem.eql(u8, rf.content, result_content)) { p.gpa.free(result_content); diff --git a/src/fs.zig b/src/fs.zig index de02e8e8..6feaa972 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1316,6 +1316,9 @@ pub const Namespace = struct { /// The serial of the pane the root's exec or look last ran a line at /// (the keyboard's), 0 before one: its err record names that pane. ran_at: u32 = 0, + /// The output pane a search just filled again rather than made + /// (Output.fillResults): what an exec reads back. + refilled: ?u32 = null, /// Every failure said (Messages.reportFailure), counted: a builtin /// that said one while it ran failed. failures: u32 = 0, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index a474c781..fbda6113 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -73,6 +73,7 @@ pub fn run(p: *Pardes, id: usize, exec: bool, text: []const u8, in_tag: bool) vo // An exec answers the pane it went to: a command pane it reused, or // the terminal it typed into. p.look_missed = false; + p.fs.refilled = null; const went: ?usize = if (exec) pardes.exec.execute(p, id, text) else blk: { look.lookAt(p, id, text); break :blk null; @@ -88,6 +89,9 @@ pub fn run(p: *Pardes, id: usize, exec: bool, text: []const u8, in_tag: bool) vo created = true; }; if (created) return; + // A +Search it filled again (Find and Grep reuse one): that is what it + // touched. + if (p.fs.refilled) |serial| if (p.paneBySerial(serial) != null) return noteResult(p, serial); if (went) |dst| if (p.panes[dst]) |pane| return noteResult(p, pane.serial); noteResult(p, if (exec) context else (p.panes[p.active] orelse return).serial); } @@ -1841,7 +1845,8 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line: [4200]u8 = undefined; _ = wr(p, Node.of(serialOf(p), .name), try std.fmt.bufPrint(&line, "{s}/a.txt\n", .{dir})); - // A hit opens its +Search, a row a line: exec reads it back. + // A hit opens its +Search, a row a line: exec reads it back. Find and + // Grep share it, a directory's one +Search, each run replacing it. try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Grep bravo\n").reply.status); const grepped = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; try testing.expectEqual(@as(usize, 2), std.mem.count(u8, grepped.file.?.content, "other.txt:")); @@ -1850,6 +1855,8 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status); const found = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; try testing.expect(std.mem.indexOf(u8, found.file.?.content, "other.txt") != null); + try testing.expectEqual(grepped.serial, found.serial); + try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") == null); // A second pane in a directory that is not there. const other = try th.newPane(p); _ = wr(p, Node.of(other, .name), "/tmp/pardes-no-such-dir-zz/b.txt\n"); diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index dec8ed1d..a6eae9cf 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -75,13 +75,17 @@ |3: 1 Find Find / |4: |13: 1 gamma body Last -== snap nomatch grid=120x41 cursor=7,8 +== snap nomatch grid=120x41 cursor=7,3 |3: 1 Find +|6: 1 +|7: +|8: |13: 1 gamma body -|18: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del -|19: 1 == snap refit grid=120x41 cursor=7,3 +|6: 1 sub/ZQMARK-beta.txt +|7: 2 sub/nest/zqmark-gamma.txt +|8: 3 zqmark-alpha.txt == snap topbar grid=120x41 cursor=12,16 -|21: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del -|22: 1 zqmark-alpha.txt -|23: 2 +|6: 1 zqmark-alpha.txt +|7: 2 +|8: diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index ef3cc49b..7f18d246 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -51,17 +51,23 @@ |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 d,#0d1410, == snap step-row3 grid=150x31 cursor=7,10 == snap step-wrap grid=150x31 cursor=7,6 -== snap blank-in-path grid=150x31 cursor=7,13 -|12: /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del -|13: 1 two words.txt -|14: 2 +== snap blank-in-path grid=150x31 cursor=7,6 +|5: /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del +|6: 1 two words.txt +|7: 2 +|8: +|9: +|10: +|11: +|12: == style blank-in-path grid=150x31 -|5: 0-1 #ffffff,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-40 #d3b0d9,#1d2824, 41-78 #b2c3b8,#1d2824, 79-149 d,#1d2824, -|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-18 #f5f7ee,#3c614a, 19-149 d,#0d1410, -|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-19 #59675c,#0d1410, 20-149 d,#0d1410, -|11: 0-0 d,#152019, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #f7e4a5,#5e4923, 13-23 #e5eee5,#0d1410, 24-149 d,#0d1410, -|12: 0-1 #000000,#add38a, 2-2 d,#314738, 3-33 #becfc4,#314738, 34-40 #dfbce5,#314738, 41-62 #becfc4,#314738, 63-149 d,#314738, -|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 d,#0d1410, -== snap blank-opened grid=150x31 cursor=7,16 -|15: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del -|16: 1 +|5: 0-1 #000000,#add38a, 2-2 d,#314738, 3-33 #becfc4,#314738, 34-40 #dfbce5,#314738, 41-62 #becfc4,#314738, 63-149 d,#314738, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 d,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|9: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-149 d,#0d1410, +== snap blank-opened grid=150x31 cursor=7,9 +|8: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del +|9: 1 -- cgit v1.3 From 05118f216d524c96ffe936e494b8ecce26303de1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 11:36:01 -0300 Subject: A builtin's Verbose announcement is the message row's alone, never logged With Verbose on by default, /log filled with msg - DumpDir, msg 4 Grep and the like, with machinery to take an announcement back out when its builtin failed or said something itself. A msg record is now only something said; the take-back machinery goes with it. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 14 ++++------- src/Messages.zig | 9 ++----- src/exec.zig | 15 ++++-------- src/fs.zig | 7 ------ src/ninep/cols.zig | 11 ++++----- src/ninep/events.zig | 66 ++-------------------------------------------------- 6 files changed, 18 insertions(+), 104 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 68cc38a9..dfd888b5 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -814,16 +814,12 @@ new log after its panes' `new`s (a relative Restore path is looked for in last dump this session wrote), then `restored ` for each pane, mapping the serial it had to the one it has now, and `restoredcol ` for each column, and `msg ` -for every line the editor says (with `verbose` on, that includes each -builtin announcing itself as it runs, on purpose: the log says which ran -- -unless the builtin then says something of its own that starts with its -name, `Kill: nothing running`, which takes the announcement's place; an -announcement is logged only for a builtin that succeeds: one that fails, -as it runs or when the host could not do its work (a Save's write, a -Dump's), leaves none, from a click at the keyboard too. A builtin that +for every line the editor says (a builtin announcing its own name as it +runs, with `Verbose` on, is the message row's alone, never logged: a `msg` +is something said, `Kill: nothing running`). A builtin that fails its write (`ctl`, `exec`, `/tagexec` or a column's `exec`, and an -open of `pane/new`) is logged by that write's `err` alone, no announcement -and no `msg`, so the same failure again is the same record again; a line said again word for word is counted, `msg 3 Undo: nothing to +open of `pane/new`) is logged by that write's `err` alone, no `msg`, so +the same failure again is the same record again; a line said again word for word is counted, `msg 3 Undo: nothing to undo (x40)`, as `err` is (below); a text past 256 bytes is cut there, between words, and ends in an ellipsis, `…`, as an `err`'s reason is past 200; its serial is the pane it ran at -- a line written to the root's diff --git a/src/Messages.zig b/src/Messages.zig index ce7a2a8c..aebaff0c 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -503,9 +503,6 @@ pub fn clip(text: []const u8, max: usize) []const u8 { /// reportError with the words already chosen. pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { p.fs.failures +%= 1; - // A failure said later, when the host could not do the work (a Save's - // write): that builtin's announcement goes from the log too. - ctlfs.events.dropFailedAnnouncement(p, text, false); // A builtin a ctl write runs: its first error is also the write's, cut // between words. const failing_write = p.fs.no_prompt or p.fs.capturing; @@ -520,11 +517,9 @@ pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { p.fs.failure_len = @intCast(n); } // The write fails with it, and its err record says it: no msg for it, - // and no Verbose announcement before that, so the same failure again is - // the same record again, counted (events.pushCounting). + // so the same failure again is the same record again, counted + // (events.pushCounting). if (failing_write) { - const serial: u32 = if (p.fs.session_write) 0 else if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; - ctlfs.events.dropAnnouncement(p, serial, text); p.fs.unlogged = true; defer p.fs.unlogged = false; return setMessage(p, id, text); diff --git a/src/exec.zig b/src/exec.zig index 1fc38b9c..9e46b434 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -861,23 +861,16 @@ pub fn runBuiltinFrom(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ? const pane = p.panes[id] orelse return; // A builtin says its own name before it runs, so a tagline click is // legible even when what it did is invisible. Whatever the builtin - // then says for itself replaces the announcement. - // Its log record stands only if it does not fail (events.dropFailedAnnouncement). - var announced: ?u64 = null; + // then says for itself replaces the announcement. It is the message + // row's only, never /log's: a msg record is something said. if (p.announce and p.settings.verbose and builtins.registry.announces(b)) { + p.fs.unlogged = true; p.setMessage(id, @tagName(b)); + p.fs.unlogged = false; pane.msg_announcement = true; - announced = pardes.ctlfs.events.newestSaying(p, @tagName(b)); - p.fs.announced_seq = announced; - const word = @tagName(b)[0..@min(@tagName(b).len, p.fs.announced_word.len)]; - @memcpy(p.fs.announced_word[0..word.len], word); - p.fs.announced_word_len = @intCast(word.len); } - const failures = p.fs.failures; const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg, .from_body = from_body }; builtins.registry.dispatch(b, c); - if (announced != null and p.fs.failures != failures and p.fs.announced_seq == announced) - pardes.ctlfs.events.dropFailedAnnouncement(p, "", true); } pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[]const u8) void { diff --git a/src/fs.zig b/src/fs.zig index 6feaa972..5d7d68e8 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1308,11 +1308,6 @@ pub const Namespace = struct { header_held: bool = false, late_failure: [256]u8 = undefined, late_failure_len: u16 = 0, - /// The log record of the last Verbose announcement (`msg - /// `) and its word: a failure of that builtin, now or when its - /// host work fails (a Save, a Dump), takes it back out of the log, so - /// an announcement stands only for a builtin that did what it said. - announced_seq: ?u64 = null, /// The serial of the pane the root's exec or look last ran a line at /// (the keyboard's), 0 before one: its err record names that pane. ran_at: u32 = 0, @@ -1322,8 +1317,6 @@ pub const Namespace = struct { /// Every failure said (Messages.reportFailure), counted: a builtin /// that said one while it ran failed. failures: u32 = 0, - announced_word: [32]u8 = undefined, - announced_word_len: u8 = 0, /// A refusal that quotes the message it refuses, as Plan 9's cmderror /// does (kernel/misc/parse.c:82); answered at once (src/9p_io.zig). ename: [320]u8 = undefined, diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index aae6d364..6b59f9e5 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -401,19 +401,18 @@ test "tagexec runs a word as a click in the workspace tag; exec files read back try testing.expectEqual(tree.Status.ok, th.look_up(p, tree.root, "tagexec").reply.status); try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, "Newcol\n").reply.status); try testing.expectEqual(@as(usize, 2), p.ncol); - // What it says is the session's (Newcol announcing itself); a pane's - // word such as Msg is refused there. - try testing.expect(th.logHas(p, "msg - Newcol\n")); + // Its announcement is the message row's, never logged; a pane's word + // such as Msg is refused there. + try testing.expect(!th.logHas(p, "msg - Newcol\n")); try testing.expectEqual(E.INVAL, th.wr(p, tagexec, "Msg from the top\n").errno()); - // A column's exec makes a pane there, reads it back, and its Msg is - // the session's too. + // A column's exec makes a pane there and reads it back. const right = layout.columnSerial(p, 1); try testing.expectEqual(tree.Status.ok, th.wr(p, Node.ofCol(right, .exec), "New\n").reply.status); const made = p.panes[p.col_panes[1][0]].?.serial; var want: [16]u8 = undefined; try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), th.rd(p, Node.ofCol(right, .exec), 0, 64).bytes); try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), th.rd(p, tagexec, 0, 64).bytes); - try testing.expect(th.logHas(p, "msg - New\n")); + try testing.expect(!th.logHas(p, "msg - New\n")); // announced on the message row only } test "a word run from the workspace's or a column's tag runs in the session's directory, a pane's in its own" { diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 690efbe5..95b4926e 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -161,10 +161,6 @@ pub fn noteMessage(p: *Pardes, serial: u32, said: []const u8) void { var buf: [pardes.Messages.LoggedMessage.cap + 32]u8 = undefined; const kept = pardes.Messages.clip(said, pardes.Messages.LoggedMessage.cap); const cut = if (kept.len < said.len) "…" else ""; - // A builtin's own word for what it did stands in for its Verbose - // announcement just before (`Undo` then `Undo: nothing to undo`), so - // that 1000 Undos with nothing left are one line, counted, as err's are. - dropAnnouncement(p, serial, kept); pushCounting(p, (if (serial == 0) std.fmt.bufPrint(&buf, "msg - {s}{s}\n", .{ kept, cut }) else @@ -230,61 +226,6 @@ pub fn noteError(p: *Pardes, req: Req, reply: Reply) void { pushCounting(p, record); } -/// Drops the newest record when it is the Verbose announcement (`msg -/// `) of the builtin whose words `text` are (`Word: ...`): -/// what the builtin said, or the err its failure logs, takes its place. -/// Not one a follower has read. -pub fn dropAnnouncement(p: *Pardes, serial: u32, text: []const u8) void { - const last = newest(p) orelse return; - if (followerRead(p, last.seq) or !std.mem.startsWith(u8, last.text, "msg ")) return; - const rest = last.text["msg ".len..]; - const sp = std.mem.indexOfScalar(u8, rest, ' ') orelse rest.len; - const word = rest[@min(sp + 1, rest.len)..]; - var who: [16]u8 = undefined; - const mine = if (serial == 0) "-" else std.fmt.bufPrint(&who, "{d}", .{serial}) catch ""; - if (std.mem.eql(u8, rest[0..sp], mine) and word.len > 0 and std.mem.indexOfScalar(u8, word, ' ') == null and - text.len > word.len and std.mem.startsWith(u8, text, word) and text[word.len] == ':') - p.fs.log.buf.shrinkRetainingCapacity(last.at); -} - -/// The sequence number of the newest log record when it is a msg that -/// ends in `word` alone: not one counted (`(x2)`) over an earlier say. -pub fn newestSaying(p: *Pardes, word: []const u8) ?u64 { - const last = newest(p) orelse return null; - if (!std.mem.startsWith(u8, last.text, "msg ") or !std.mem.endsWith(u8, last.text, word)) return null; - if (last.text[last.text.len - word.len - 1] != ' ') return null; - return last.seq; -} - -/// Takes record `seq` back out of the log, unless a follower has read it. -pub fn dropRecord(p: *Pardes, seq: u64) void { - if (followerRead(p, seq)) return; - const q = &p.fs.log; - var at = q.head; - var s = q.dropped; - while (at + 4 <= q.buf.items.len) : (s += 1) { - const size = 4 + std.mem.readInt(u32, q.buf.items[at..][0..4], .little); - if (s == seq) { - const items = q.buf.items; - std.mem.copyForwards(u8, items[at..], items[at + size ..]); - q.buf.shrinkRetainingCapacity(items.len - size); - return; - } - at += size; - } -} - -/// A builtin's failure: its Verbose announcement goes from the log, when -/// `text` is that builtin's (it starts with its word) or `any`, as for a -/// failure said while the builtin itself runs. -pub fn dropFailedAnnouncement(p: *Pardes, text: []const u8, any: bool) void { - const seq = p.fs.announced_seq orelse return; - const word = p.fs.announced_word[0..p.fs.announced_word_len]; - if (!any and !(std.mem.startsWith(u8, text, word) and text.len > word.len and (text[word.len] == ' ' or text[word.len] == ':'))) return; - p.fs.announced_seq = null; - dropRecord(p, seq); -} - /// Drops the newest record when it is a msg saying `text` (of any pane) /// that no follower has read: a failure its write's err record will say. pub fn dropMessage(p: *Pardes, text: []const u8) void { @@ -1100,12 +1041,9 @@ test "the log records whether or not anyone reads, and an open that follows wait try std.fmt.bufPrint(&expected, "msg {d} save: two lines\n", .{serial}), rdf.next(p, log, fh, frozen).bytes, ); - // A builtin announces itself on the message row, so the log says which ran. + // A builtin announces itself on the message row only: the log has + // what it did. try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "Del\n").reply.status); - try testing.expectEqualStrings( - try std.fmt.bufPrint(&expected, "msg {d} Del\n", .{serial}), - rdf.next(p, log, fh, frozen).bytes, - ); try testing.expectEqualStrings( try std.fmt.bufPrint(&expected, "del {d} /tmp/logged.txt\n", .{serial}), rdf.next(p, log, fh, frozen).bytes, -- cgit v1.3 From 4f57043e39396bc958a103f87466870cf8dafe00 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 12:19:39 -0300 Subject: A language server question that finds nothing, cannot be answered or has no room fails, and so does a write to an image's or PDF's body Callers or Callees with nothing found, Hover or Lspwhy with no room for its pane, and a question asked of no file's pane said nothing, the 9P write succeeding; a body write to an image or PDF pane went nowhere. A write that asks a language server now waits for its answer (turn.lsp_answers), and what fails there -- nothing found, no answer, a backend's @none why, a placement with no room (ENOSPC) -- fails the write and logs its err. No diagnostics is said, not failed. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 8 ++++- src/fs.zig | 3 ++ src/ninep/ctl.zig | 36 +++++++++++++++++++ src/ninep/pane.zig | 2 ++ src/pardes.zig | 91 ++++++++++++++++++++++++++++++++++++++++++----- test/snapshots/lsp.golden | 1 + 6 files changed, 132 insertions(+), 9 deletions(-) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 72897979..96f91bc1 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -312,13 +312,19 @@ pub const Listener = struct { defer if (restoring) l.restore_writer.store(false, .release); core.fs.late_failure_len = 0; if (core.effects_len != 0) pardes.turn.awaitSettled(epoch); + if (core.fs.lsp_answer_at) |n| { + core.fs.lsp_answer_at = null; + pardes.turn.awaitLsp(n); + } // ponytail: one slot, so a failure of another client's effects that // settle in the same wait is told to this write too. if (l.core == core and core.fs.late_failure_len != 0) { const late = core.fs.late_failure[0..core.fs.late_failure_len]; // What is not there (`no such directory`) is ENOENT, as a // builtin's failure saying so is (ctl.failureErrno). - const errno = if (std.mem.indexOf(u8, late, "no such") != null or std.mem.indexOf(u8, late, "not found") != null) pardes.ctlfs.E.NOENT else pardes.ctlfs.E.IO; + const errno = if (std.mem.indexOf(u8, late, "no such") != null or std.mem.indexOf(u8, late, "not found") != null) + pardes.ctlfs.E.NOENT + else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else pardes.ctlfs.E.IO; const failed = pardes.ctlfs.failText(req.tag, errno, late); // Its err record says it (the path in it); the msg the failure // was also said as goes, as a builtin's failing a write does. diff --git a/src/fs.zig b/src/fs.zig index 5d7d68e8..5fd1fd4e 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1308,6 +1308,9 @@ pub const Namespace = struct { header_held: bool = false, late_failure: [256]u8 = undefined, late_failure_len: u16 = 0, + /// A 9P write asked a language server something: the answer count it + /// waits to change (`turn.lsp_answers`), so its failure is the write's. + lsp_answer_at: ?u64 = null, /// The serial of the pane the root's exec or look last ran a line at /// (the keyboard's), 0 before one: its err record names that pane. ran_at: u32 = 0, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index c2a78fb8..2c6d2010 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2079,6 +2079,42 @@ test "a script whose interpreter is not there: Tty refuses it up front, only an try testing.expect(!p.panes[id].?.shell_failed); } +test "a language server question that finds nothing, cannot be answered, or is asked of no file fails, and a write to an image's body is refused" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const id = p.active; + // Asked of a pane that is no file's: at once. + _ = wr(p, root_exec, "Recent\n"); + const listed = p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?; + p.lspRequest(listed, .incoming_calls, ""); + try testing.expect(std.mem.indexOf(u8, p.panes[listed].?.msg[0..p.panes[listed].?.msg_len], "Callers: only a file's pane asks") != null); + // Nothing found: Callers says so, and the waiting write hears it. + p.fs.late_failure_len = 0; + p.lspRequest(id, .incoming_calls, ""); + try testing.expect(p.lsp_wait != null); + p.lspResponse(p.lsp_wait.?.id, ""); + try testing.expectEqualStrings("Callers: no callers, not found", p.fs.late_failure[0..p.fs.late_failure_len]); + // A backend that cannot answer says why. + p.fs.late_failure_len = 0; + p.lspRequest(id, .outgoing_calls, ""); + p.lspResponse(p.lsp_wait.?.id, "@none zls does not answer call hierarchy\n"); + try testing.expectEqualStrings("Callees: zls does not answer call hierarchy", p.fs.late_failure[0..p.fs.late_failure_len]); + // No answer at all. + p.fs.late_failure_len = 0; + p.lspRequest(id, .hover, ""); + p.lspResponse(p.lsp_wait.?.id, null); + try testing.expectEqualStrings("Hover: the language server did not answer", p.fs.late_failure[0..p.fs.late_failure_len]); + // No diagnostics is no failure. + p.fs.late_failure_len = 0; + p.lspRequest(id, .diagnostics, ""); + p.lspResponse(p.lsp_wait.?.id, ""); + try testing.expectEqual(@as(u16, 0), p.fs.late_failure_len); + // An image's body takes no write. + const slot = p.freeSlot().?; + const img = try pardes.panes.Image.create(p, slot, "/tmp/pardes-no-such.png", try p.image_gpa.dupe(u8, "not a png")); + try testing.expectEqual(E.INVAL, wr(p, Node.of(img.serial, .body), "text\n").errno()); +} + test "every EINVAL a write gets says why, in its err record too; DEL is a control character in a line" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 5ed3f6f4..fe3312b4 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -449,6 +449,8 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; if (pane.file == null) { + // An image's or a PDF's body is no text a write goes into. + if (!pane.isTerminal()) return tree.failText(req.tag, E.INVAL, e_no_text); const take = wholeUtf8(req.data); p.emitWrite(id, req.data[0..take]); return .{ .tag = req.tag, .written = @intCast(take) }; diff --git a/src/pardes.zig b/src/pardes.zig index ba9a1f90..135823e4 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -117,7 +117,10 @@ pub const Turn = struct { /// (`takeRestore`), which lives after `pump` because it swaps the core /// out from under it; a request that asked for one waits for this. restores: u64 = 0, - /// Both of the above, and `out` reaching zero. + /// Bumped each time a language server's answer (or its lack) is taken + /// in (`lspResponse`): a write that asked one waits for this. + lsp_answers: u64 = 0, + /// All of the above, and `out` reaching zero. settled: std.Io.Condition = .init, /// The editor's thread takes the turn for good; it has it until `stop`. @@ -204,6 +207,16 @@ pub const Turn = struct { t.settled.broadcast(io); } + pub fn lspAnswered(t: *Turn) void { + const io = t.io orelse return; + t.lsp_answers +%= 1; + t.settled.broadcast(io); + } + + pub fn awaitLsp(t: *Turn, answers: u64) void { + while (t.lsp_answers == answers) t.settled.wait(t.io.?, &t.mutex) catch return; + } + pub fn awaitRestored(t: *Turn, restores: u64) void { while (t.restores == restores) t.settled.wait(t.io.?, &t.mutex) catch return; } @@ -5634,6 +5647,7 @@ pub const Pardes = struct { p.raw_hover_intent = false; look.cancelLookHover(p); p.fs.serving = true; + p.fs.lsp_answer_at = null; const reply = ctlfs.handle(p, req); p.fs.serving = false; if (reply.status == .err and (req.op == .write or req.op == .setattr or (req.op == .open and reply.errno == ctlfs.E.NOSPC) or (req.op == .release and req.remove))) ctlfs.events.noteError(p, req, reply); @@ -6310,23 +6324,30 @@ pub const Pardes = struct { pub fn lspRequest(p: *Pardes, id: usize, kind: lsp.Kind, arg: []const u8) void { if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary - if (!lsp.supports.contains(kind)) return; + var said: [128]u8 = undefined; + if (!lsp.supports.contains(kind)) + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no language server here answers it", .{lspWord(kind)}) catch "no language server answers it"); const pane = p.panes[id] orelse return; if (kind != .status) { - const f = pane.file orelse return; - if (f.output != null) return; + const f = pane.file orelse + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch "only a file's pane asks"); + if (f.output != null) + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch "only a file's pane asks"); } - if (arg.len > 128) return; // the effect's arg is a Buf(128) + if (arg.len > 128) return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: its argument is at most 128 bytes", .{lspWord(kind)}) catch "argument too long"); if (kind == .rename) { const zig_buf = if (pane.file) |f| std.mem.endsWith(u8, f.path, ".zig") else true; - if (zig_buf and (!std.zig.isValidId(arg) or std.zig.isUnderscore(arg))) return; - if (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null) return; + if ((zig_buf and (!std.zig.isValidId(arg) or std.zig.isUnderscore(arg))) or + (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null)) + return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name"); } const off = if (pane.file) |f| modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)), }) else 0; p.lsp_seq +%= 1; + // A 9P write that asked it is answered once the answer is in. + if (p.fs.serving) p.fs.lsp_answer_at = turn.lsp_answers; p.lsp_wait = .{ .id = p.lsp_seq, .kind = kind, @@ -6466,13 +6487,56 @@ pub const Pardes = struct { return true; } + /// The builtin word that asks `kind`, for what it says. + fn lspWord(kind: lsp.Kind) []const u8 { + return switch (kind) { + .hover => "Hover", + .explain => "Lspwhy", + .incoming_calls => "Callers", + .outgoing_calls => "Callees", + .document_symbols => "Symbols", + .workspace_symbols => "WsSymbols", + .diagnostics => "Diagnostics", + .workspace_diagnostics => "WsDiagnostics", + .code_action => "CodeAction", + .select_refs => "SelectRefs", + .supertypes => "Supertypes", + .subtypes => "Subtypes", + .rename => "Rename", + .format => "Format", + else => @tagName(kind), + }; + } + + /// What was said of a failure just now on pane `id` is also the waiting + /// 9P write's (9p_io, `fs.late_failure`). + pub fn noteLateFailure(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const said = pane.msg[0..pane.msg_len]; + const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len); + @memcpy(p.fs.late_failure[0..kept.len], kept); + p.fs.late_failure_len = @intCast(kept.len); + } + pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { + defer turn.lspAnswered(); const w = p.lsp_wait orelse return; if (w.id != id) return; // superseded by a newer press, or the pane died p.lsp_wait = null; - const rows = response orelse return; const pane = p.panes[w.pane] orelse return; if (pane.serial != w.serial) return; + // Whatever fails from here -- no answer, nothing found, no room for + // its pane -- fails a 9P write that asked it too. + const failures = p.fs.failures; + defer if (p.fs.failures != failures) p.noteLateFailure(w.pane); + var said: [256]u8 = undefined; + const rows = response orelse + return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: the language server did not answer", .{lspWord(w.kind)}) catch "no answer"); + // A backend that cannot answer it says why (`@none `). + if (std.mem.startsWith(u8, rows, "@none ")) { + const why = std.mem.trimEnd(u8, rows["@none ".len..], "\n"); + return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), why[0..@min(why.len, 200)] }) catch "no answer"); + } if (w.kind == .rename or w.kind == .format) { const fallback: ?[]const u8 = if (w.kind == .rename) w.arg.slice() else null; if (p.parseLspEdits(rows, fallback)) |edits| { @@ -6492,6 +6556,17 @@ pub const Pardes = struct { if (rows.len == 0) { if (w.kind == .completion and pane.body.mode == .insert and pane.body.nsel == 0 and pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p, &pane.body); + // Nothing found fails, but for a file with no diagnostics, + // which is no failure, and a completion's Tab. + const none: ?[]const u8 = switch (w.kind) { + .completion, .format, .rename => null, + .diagnostics, .workspace_diagnostics => return p.setMessage(w.pane, std.fmt.bufPrint(&said, "{s}: none", .{lspWord(w.kind)}) catch "none"), + .incoming_calls => "no callers, not found", + .outgoing_calls => "no callees, not found", + .hover => "nothing to show, not found", + else => "nothing found, not found", + }; + if (none) |text| p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), text }) catch "nothing found"); return; } diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index 984a7abf..2d3880f1 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -33,3 +33,4 @@ == snap step grid=120x41 cursor=15,3 |3: 1 const std = @import("std"); == snap nothing grid=120x41 cursor=7,5 +|3: 1 const std = @import("std"); definition: nothing found, not found -- cgit v1.3 From fea3f2c5abf14aada5d9187b82985e51eb5b7a98 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 13:36:33 -0300 Subject: A path with a part over 255 bytes is refused, never a panic std's statFile takes the kernel's ENAMETOOLONG for a bug (errnoBug), so a name, look, DumpDir or Save path with a part over 255 bytes panicked the editor (exec.kindOf via writeName, recentKeeps, dumpFailed). Every non-test statFile now goes through fs.statPath, which refuses such a name as NameTooLong first; fs.py drives long, looping, not-a-directory and not-ours paths through name, look, DumpDir, Dump and Save. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 2 +- src/exec.zig | 4 ++-- src/file_watch.zig | 4 ++-- src/fs.zig | 17 ++++++++++++++++- src/host_io.zig | 6 +++--- test/fs.py | 25 +++++++++++++++++++++++++ 6 files changed, 49 insertions(+), 9 deletions(-) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 96f91bc1..560c4ed6 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -865,7 +865,7 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: [ return null; }; _ = l.runner.listen(.{ .unix = p }, max_conns) catch |err| retry: { - const existing = std.Io.Dir.cwd().statFile(io, p, .{ .follow_symlinks = false }) catch null; + const existing = @import("fs.zig").statPath(io, p, .{ .follow_symlinks = false }) catch null; if (err != error.AddressInUse or existing == null or existing.?.kind != .unix_domain_socket or alive(p)) { log.warn("something is already listening on {s}", .{p}); l.deinit(gpa); diff --git a/src/exec.zig b/src/exec.zig index 88c0705d..4785e7a2 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -391,7 +391,7 @@ pub fn isDirectory(path: []const u8) bool { const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return false; pardes.turn.yield(); defer pardes.turn.back(); - const stat = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), z, .{}) catch return false; + const stat = @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), z, .{}) catch return false; return stat.kind == .directory; } @@ -407,7 +407,7 @@ pub fn kindOf(path: []const u8) ?std.Io.File.Kind { const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return null; pardes.turn.yield(); defer pardes.turn.back(); - const stat = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), z, .{}) catch return null; + const stat = @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), z, .{}) catch return null; return stat.kind; } diff --git a/src/file_watch.zig b/src/file_watch.zig index 8bd9de8b..81f4ba87 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -397,7 +397,7 @@ fn watchPath( // stat and a lookup out there: the turn goes out with them. pardes.turn.yield(); defer pardes.turn.back(); - const stat = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), watched_path, .{}) catch null; + const stat = @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), watched_path, .{}) catch null; const dir = if (stat != null and stat.?.kind == .directory) watched_path else std.fs.path.dirname(watched_path) orelse "."; var dir_buf: [4096:0]u8 = undefined; if (dir.len >= dir_buf.len) return; @@ -631,7 +631,7 @@ pub fn identify(io: std.Io, path: []const u8) !Identity { const native = filesystem.localPath(path) orelse return error.NonLocalPath; pardes.turn.yield(); defer pardes.turn.back(); - const stat = try std.Io.Dir.cwd().statFile(io, native, .{}); + const stat = try @import("fs.zig").statPath(io, native, .{}); if (stat.kind != .file) return error.NotFile; return .{ .inode = stat.inode, diff --git a/src/fs.zig b/src/fs.zig index 5fd1fd4e..753a4446 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -159,7 +159,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { const stat = stat: { pardes.turn.yield(); defer pardes.turn.back(); - break :stat std.Io.Dir.cwd().statFile(io, path, .{}) catch return Reply.fail(req.tag, E.NOENT); + break :stat statPath(io, path, .{}) catch return Reply.fail(req.tag, E.NOENT); }; const attr: Reply.Attr = .{ .name = if (req.node == os_root) "os" else std.fs.path.basename(path), .node = req.node, .dir = stat.kind == .directory, .size = stat.size, .mode = if (stat.kind == .directory) 0o755 else 0o644, .mtime = std.math.cast(u32, stat.mtime.toSeconds()) orelse 0 }; switch (req.op) { @@ -622,6 +622,21 @@ pub fn isVirtual(path: []const u8) bool { std.mem.eql(u8, path, "/n") or std.mem.startsWith(u8, path, "/n/"); } +/// 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 "a path with a part over 255 bytes is NameTooLong, never a panic" { + const long = "/tmp/" ++ "x" ** 300 ++ "/f"; + try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); +} + 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..]; diff --git a/src/host_io.zig b/src/host_io.zig index 8bbb0985..9d4b27c2 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -1048,7 +1048,7 @@ pub const Shell = struct { var buf: [2048]u8 = undefined; try std.testing.expectEqualStrings(bash_rc, readSmall(a_bash, &buf) orelse return error.ReadFailed); try std.testing.expectEqualStrings(fish_rc, readSmall(a.fishPath().?, &buf) orelse return error.ReadFailed); - const stat = try std.Io.Dir.cwd().statFile(std.testing.io, a_bash, .{}); + const stat = try @import("fs.zig").statPath(std.testing.io, a_bash, .{}); try std.testing.expectEqual(0, stat.permissions.toMode() & 0o077); var kept: [rc_path_capacity:0]u8 = @splat(0); @memcpy(kept[0..a_bash.len], a_bash); @@ -1202,7 +1202,7 @@ pub fn forkShell( // A shell's directory may be inside a mount this editor serves. pardes.turn.yield(); defer pardes.turn.back(); - const stat = try std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), path, .{}); + const stat = try @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), path, .{}); if (stat.kind != .directory) return error.NotDir; break :dir path; }; @@ -1440,7 +1440,7 @@ pub fn shellCwd(pid: libc.pid_t, buf: []u8) ?[]const u8 { // no directory to be named by, so the name it had stays, and a // restart works there once it is back. if (std.mem.endsWith(u8, link, " (deleted)")) { - _ = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), link, .{}) catch return null; + _ = @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), link, .{}) catch return null; } return link; }, diff --git a/test/fs.py b/test/fs.py index 75d03d40..a025ec47 100644 --- a/test/fs.py +++ b/test/fs.py @@ -814,6 +814,30 @@ def signal_cleans_up(binary): assert not address.exists() and not detached.exists(), (sig, list(root.iterdir())) +def odd_paths(binary): + """Long and odd paths written where a path goes -- name, look, DumpDir, + Dump, Save -- are refused or said, never a crash: a part over 255 bytes + (ENAMETOOLONG), a loop of links (ELOOP), a file taken for a directory + (ENOTDIR), one not ours (EACCES).""" + with tempfile.TemporaryDirectory(prefix='pardes-odd-') as directory: + root = Path(directory) + (root / 'loop').symlink_to(root / 'loop') + (root / 'plain').write_bytes(b'x\n') + odd = ['/tmp/' + 'x' * 300 + '/f.txt', str(root / ('y' * 300)), str(root / 'loop' / 'f'), + str(root / 'plain' / 'f'), '/root/nope/f', str(root / 'a' / '..' / 'b.txt')] + with session(binary, root, 'odd') as (client, _): + serial = new_pane(client, b'text\n') + for path in odd: + for where, line in ((f'/pane/{serial}/name', path), ('/look', path), + ('/ctl', f'DumpDir {path}'), ('/ctl', 'Dump'), (f'/pane/{serial}/ctl', 'Save')): + try: + client.write(where, (line + '\n').encode()) + except OSError: + pass + assert client.read('/index'), (where, line) + client.write('/ctl', b'DumpDir\n') + + def cut_writes(binary): """A write bigger than a 9P message comes as several, cut anywhere: each command line runs once, whole, an Edit block once it ends, and a last @@ -846,6 +870,7 @@ def cut_writes(binary): def test(binary, quic=False): started = time.monotonic() cut_writes(binary) + odd_paths(binary) run_file(binary) exit_answers(binary) unattended_messages_expire(binary) -- cgit v1.3 From c2e58c827bd8d2497c86b2eca23ac096cb972296 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 15:47:52 -0300 Subject: A ctl or exec line with no newline runs with its write and fails it, unless it needs more A last line with no newline was held to the close, so printf bogus > ctl answered 0 and failed only in the log, Edit ,s/zzz/y/ too. A write shorter than its Twrite is the whole of what was written (acme takes each write whole): its tail runs then and a failure is the write's. It is held only when the parser says it needs more -- an open { block, an a/c/i text -- or when the write filled its Twrite and may go on (the listener tells the core the room, msize less its header). Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 7 ++++--- docs/fs.md | 13 +++++++------ src/9p_io.zig | 2 ++ src/fs.zig | 4 ++++ src/ninep/pane.zig | 10 ++++++++-- src/ninep/tree.zig | 41 +++++++++++++++++++++++++++++++++++++-- 6 files changed, 64 insertions(+), 13 deletions(-) (limited to 'src/fs.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 16e90dc9..0de8820a 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -164,9 +164,10 @@ an open that never wrote, the session's last. With other clients about, write and read one open (`exec 3<>$m/look; echo x >&3; cat <&3; exec 3<&-`). A read is a stream: once read, a second read on the same fd gives EOF (on an open that wrote, until its next write); open again, or seek to 0, to read -it again. Each command line runs once whole, however a mount cuts a big write; a last -line with no newline runs when the open closes, and an Edit block still open -then fails there (an `err`: ``unmatched `{'``, or an a/c/i text with no `.` +it again. Each command line runs once whole, however a mount cuts a big write; a +write's last line with no newline runs with it (and fails it), unless the +write filled its 9P message and may go on; an Edit block still open when the +file closes fails there (an `err`: ``unmatched `{'``, or an a/c/i text with no `.` line), changing nothing. One rule: a builtin that fails, whether through a ctl (a pane's pty/ctl `exec` too), look, exec, tagexec or a column's exec, fails the write (EINVAL for a malformed line, ENOENT for what is not there -- diff --git a/docs/fs.md b/docs/fs.md index 83906d0a..7b1e47bf 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -518,12 +518,13 @@ A write of command lines -- to `look`, `exec`, `tagexec`, a `ctl` of the root, a pane or a column, or a column's `exec` -- runs each line once it is whole: a mount cuts a big write at its message size (4 KiB through the kernel's, 8 KiB from a client that asks), anywhere, and each piece comes as -a write of its own, so the open keeps a last line with no newline yet, or -an Edit block whose text has not ended, until its next write, and runs it -then; what is left when it closes runs at the close -- so a line written -with no newline (`printf Save > exec`) runs only as the file closes, after -the write has been answered, and its failure is in the log alone: end each -line with its newline to have the write itself fail -- where an Edit block +a write of its own. A write that fills its piece may go on in the next, so +the open keeps its last line with no newline until then; a write shorter +than a piece is the whole of what was written, as acme takes each write, so +its last line runs with it even with no newline (`printf Save > exec`), and +a failure is that write's. Only what needs more is held: an Edit block +whose `{` or `a`/`c`/`i` text has not ended waits for its next write, and +what is left when the file closes runs at the close -- where an Edit block whose `{` or `a`/`c`/`i` text never ended fails and changes nothing (``unmatched `{'``, or `a, c or i text not ended by a . line`, logged as an `err`): sam takes the end of input for a `.`, but a block that reaches Edit diff --git a/src/9p_io.zig b/src/9p_io.zig index 91240b57..7f490f81 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -261,6 +261,7 @@ pub const Listener = struct { return conn.reply(&later, ""); } const core = l.core; + core.fs.write_room = if (conn.engine.protocol.msize > 24) conn.engine.protocol.msize - 24 else 0; const epoch = pardes.turn.epoch; const restores = pardes.turn.restores; // Asked first: a release that runs a held line has none after. @@ -506,6 +507,7 @@ pub const Listener = struct { /// Answers one QUIC request, on the editor's thread. fn step(l: *Listener, srv: *Srv, req: pardes.ctlfs.Req) void { + l.core.fs.write_room = if (srv.protocol.msize > 24) srv.protocol.msize - 24 else 0; const reply = l.core.serveFs(req); srv.reply(&reply, l.core.fsPayload(reply)); if (req.op == .release) l.collectOs(); diff --git a/src/fs.zig b/src/fs.zig index 753a4446..845e6424 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1326,6 +1326,10 @@ pub const Namespace = struct { /// A 9P write asked a language server something: the answer count it /// waits to change (`turn.lsp_answers`), so its failure is the write's. lsp_answer_at: ?u64 = null, + /// The most a Twrite of the request being served can carry (msize less + /// its header), 0 when unknown: a write shorter than it is the whole of + /// what its client wrote, one that fills it may be cut and go on. + write_room: u32 = 0, /// The serial of the pane the root's exec or look last ran a line at /// (the keyboard's), 0 before one: its err record names that pane. ran_at: u32 = 0, diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 9f85a75f..d760bebd 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1153,13 +1153,19 @@ test "a name cut across writes is one name, applied once at its newline or its c const node = Node.of(serial, .name); const h = call(p, .{ .tag = 1, .op = .open, .node = node, .omode = 1 }).reply.handle; try testing.expect(h != 0); + // A piece that fills its Twrite goes on in the next. + p.fs.write_room = "/tmp/pardes-na".len; _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "/tmp/pardes-na" }); + p.fs.write_room = 0; try testing.expectEqualStrings("/test.txt", nameOf(p.panes[p.paneBySerial(serial).?].?)); _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "me.txt\n" }); try testing.expectEqualStrings("/tmp/pardes-name.txt", nameOf(p.panes[p.paneBySerial(serial).?].?)); - // No newline: the close applies it. - _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "/tmp/pardes-closed.txt" }); _ = call(p, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true }); + // No newline, the whole write: applied at once, on its own open. + const h3 = call(p, .{ .tag = 1, .op = .open, .node = node, .omode = 1 }).reply.handle; + _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h3, .data = "/tmp/pardes-closed.txt" }); + try testing.expectEqualStrings("/tmp/pardes-closed.txt", nameOf(p.panes[p.paneBySerial(serial).?].?)); + _ = call(p, .{ .tag = 3, .op = .release, .node = node, .handle = h3, .opened = true }); try testing.expectEqualStrings("/tmp/pardes-closed.txt", nameOf(p.panes[p.paneBySerial(serial).?].?)); } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index d6f4211b..0960f00b 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1073,7 +1073,18 @@ fn write(p: *Pardes, req: Req, target: Target) Reply { // to fail unseen at the close. if (resultsFile(target)) for (req.data) |c| if ((c < ' ' and c != '\t' and c != '\n' and c != '\r') or c == 0x7f) return failText(req.tag, E.INVAL, ctl.e_control); o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); - const end = ctl.completeEnd(p, o.pending.items); + var end = ctl.completeEnd(p, o.pending.items); + // A tail with no newline is a whole line when the write is the whole of + // what its client wrote (shorter than a Twrite can carry): it runs now, + // and its failure is this write's, as acme takes each write whole. Held + // only when it is not whole yet -- an open `{` block, an `a`/`c`/`i` + // text awaiting its `.` -- or the write filled its Twrite and may go on. + const cut = p.fs.write_room != 0 and req.data.len >= p.fs.write_room; + if (end < o.pending.items.len and !cut) { + o.pending.append(p.gpa, '\n') catch return Reply.fail(req.tag, E.NOMEM); + const whole = ctl.completeEnd(p, o.pending.items); + if (whole == o.pending.items.len) end = whole else o.pending.shrinkRetainingCapacity(o.pending.items.len - 1); + } if (end == 0) { if (o.pending.items.len <= pending_cap) return .{ .tag = req.tag, .written = @intCast(req.data.len) }; o.pending.clearRetainingCapacity(); @@ -1580,8 +1591,12 @@ test "a command line cut across writes runs once whole, and the last runs at rel const exec = @intFromEnum(TopFile.exec); const h = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 1 }).reply.handle; try testing.expect(h != 0); - for ([_][]const u8{ "Msg he", "llo\nMsg wor", "ld\nMsg tail" }) |piece| + // Each piece fills its Twrite (a client's one write cut at msize). + for ([_][]const u8{ "Msg he", "llo\nMsg wor", "ld\nMsg tail" }) |piece| { + p.fs.write_room = @intCast(piece.len); try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = piece }).reply.status); + } + p.fs.write_room = 0; try testing.expect(th.logHas(p, " hello\n") and th.logHas(p, " world\n")); try testing.expect(!th.logHas(p, " he\n") and !th.logHas(p, " tail\n")); _ = call(p, .{ .tag = 3, .op = .release, .node = exec, .handle = h, .opened = true }); @@ -1596,6 +1611,28 @@ test "a command line cut across writes runs once whole, and the last runs at rel try testing.expectEqualStrings("x\none\ntwo\n", p.panes[0].?.file.?.content); } +test "a write with no newline, whole in its Twrite, runs then and fails the write; one needing more waits" { + const p = try th.withFile(testing.allocator, "abc\n"); + defer p.deinit(); + const serial = serialOf(p); + const ctl_node = Node.of(serial, .ctl); + const c = call(p, .{ .tag = 1, .op = .open, .node = ctl_node, .omode = 1 }).reply.handle; + p.fs.write_room = 8192; + defer p.fs.write_room = 0; + try testing.expectEqual(Status.err, call(p, .{ .tag = 2, .op = .write, .node = ctl_node, .handle = c, .data = "bogus" }).reply.status); + try testing.expectEqual(Status.err, call(p, .{ .tag = 3, .op = .write, .node = ctl_node, .handle = c, .data = "Edit ,s/zzz/y/" }).reply.status); + // An `a` needs its text and `.`: held, not run, not failed. + try testing.expectEqual(Status.ok, call(p, .{ .tag = 4, .op = .write, .node = ctl_node, .handle = c, .data = "Edit $a" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 5, .op = .write, .node = ctl_node, .handle = c, .data = "\nmore\n.\n" }).reply.status); + try testing.expectEqualStrings("abc\nmore\n", p.panes[0].?.file.?.content); + _ = call(p, .{ .tag = 6, .op = .release, .node = ctl_node, .handle = c, .opened = true }); + // The root's ctl too. + const root_ctl = @intFromEnum(TopFile.ctl); + const r = call(p, .{ .tag = 7, .op = .open, .node = root_ctl, .omode = 1 }).reply.handle; + try testing.expectEqual(Status.err, call(p, .{ .tag = 8, .op = .write, .node = root_ctl, .handle = r, .data = "bogus" }).reply.status); + _ = call(p, .{ .tag = 9, .op = .release, .node = root_ctl, .handle = r, .opened = true }); +} + test "look and exec read back what their own open's write touched; a fresh open reads the session's last" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); -- cgit v1.3 From eb47ded95f43e50dc24b841289b68814105dcfb7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 16:17:26 -0300 Subject: An open's writes in a row to one place go in as one edit: a 10 MB body write is linear Each body or data write copied and hashed the whole buffer, so a write the mount cut in 8 KB pieces was quadratic: 10 MB took 50 s and a 1 MB insert into 10 MB 11 s, holding the editor's turn. An open's appends to body, or inserts going on at data's address, are now held and put in as one splice (one copy, one undo step, one line-starts pass) before any other request, the close, or the editor's step once the writes pause 20 ms. fs.py-driven: 2 MB 2.19 -> 0.16 s, 10 MB 50.17 -> 0.78 s, 1 MB data into 10 MB 11.49 -> 0.26 s. A body-2m case (2 MB in 256 KB writes on one open) joins the perf gate: 84023 -> 15785 us; baselines re-recorded. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 6 ++- src/fs.zig | 14 +++++ src/ninep/pane.zig | 96 ++++++++++++++++++++++++++++++++- src/ninep/tree.zig | 3 ++ src/pardes.zig | 5 ++ test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 20 +++++++ 9 files changed, 144 insertions(+), 6 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 5f3ef743..eab1b00d 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -768,7 +768,11 @@ shell writes it a line at a time), and the next open starts another. The pane has one history, so two opens writing at once take turns in it: each open's first write after the other's starts a step of its own; to make a loop's writes one step, write `1` (an undo point here), then `0`, -the writes, then `1` again. +the writes, then `1` again. An open's writes in a row to one place -- an +append to `body`, inserts going on at `data`'s address -- are held and go +in as one edit when anything else comes (another request, the close, or +the editor's step once they pause 20 ms), so a 10 MB write is one copy, not +one per 8 KB piece; any read sees them. One rule for what fails: a write fails whenever what it asked for fails, whether it came to a `ctl` (the root's, a pane's, a column's, a pane's diff --git a/src/fs.zig b/src/fs.zig index 845e6424..2487ffee 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1330,6 +1330,20 @@ pub const Namespace = struct { /// its header), 0 when unknown: a write shorter than it is the whole of /// what its client wrote, one that fills it may be cut and go on. write_room: u32 = 0, + /// Writes one open made in a row into one place of a pane's body (an + /// append to `body`, an insert at `data`'s address), held and put in + /// as one edit when anything else comes (ninep/pane.zig flushBatch): a + /// 10 MB write in 8 KB pieces is one copy and one undo step, not 1280. + batch: struct { + serial: u32 = 0, + node: u64 = 0, + handle: u32 = 0, + at: usize = 0, + bytes: std.ArrayList(u8) = .empty, + /// The editor's clock at the last write held: its step puts them in + /// once the writes have paused (`batch_pause_ns`). + last_ns: u64 = 0, + } = .{}, /// The serial of the pane the root's exec or look last ran a line at /// (the keyboard's), 0 before one: its err record names that pane. ran_at: u32 = 0, diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index d760bebd..ec6e8551 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -475,6 +475,55 @@ fn joinOnly(pane: *Pane, handle: u32) void { if (pane.fs.joined_by != 0 and pane.fs.joined_by != handle) pane.fs.joined = null; } +/// How long writes in a row may pause before the editor's own step puts +/// them in: long enough that a stream of 8 KB writes is one edit. +pub const batch_pause_ns: u64 = 20 * std.time.ns_per_ms; + +/// The editor's step: the held writes go in once they have paused. +pub fn flushPausedBatch(p: *Pardes) void { + const b = &p.fs.batch; + if (b.bytes.items.len == 0) return; + if (p.now_ns != 0 and p.now_ns -| b.last_ns < batch_pause_ns) return; + flushBatch(p); +} + +/// Puts the held writes (`fs.batch`) in as one edit: before any other +/// request, the open's release, or the editor's own step. +pub fn flushBatch(p: *Pardes) void { + const b = &p.fs.batch; + if (b.bytes.items.len == 0) return; + defer b.bytes.clearRetainingCapacity(); + const id = p.paneBySerial(b.serial) orelse return; + const pane = p.panes[id].?; + if (fileOf(pane) == null) return; + const before = dotOf(pane); + joinOnly(pane, b.handle); + const take = spliceBody(p, pane, b.at, b.at, b.bytes.items) orelse return; + pane.fs.joined = fileOf(pane).?.revision; + pane.fs.joined_by = b.handle; + setDot(pane, .{ + .q0 = shiftOne(before.q0, clip(b.at), 0, clip(take)), + .q1 = shiftOne(before.q1, clip(b.at), 0, clip(take)), + }); + if (!pane.fs.noscroll) showOffset(pane, b.at + take); +} + +/// The held bytes a write at `at` on this open can go on from: its own +/// batch, when it ends right at `at`; any other is put in first. +fn batchFor(p: *Pardes, req: Req, pane: *Pane, at: usize) ?*@TypeOf(p.fs.batch) { + const b = &p.fs.batch; + const mine = b.serial == pane.serial and b.node == req.node and b.handle == req.handle; + if (b.bytes.items.len > 0 and !(mine and b.at + b.bytes.items.len == at)) flushBatch(p); + // Only an open's writes are held: one with no record (a test's, handle + // 0) is put in at once. A hold past 64 MiB is put in first. + if (req.handle == 0 or b.bytes.items.len > 64 << 20) { + flushBatch(p); + return null; + } + if (b.bytes.items.len == 0) b.* = .{ .serial = pane.serial, .node = req.node, .handle = req.handle, .at = at, .bytes = b.bytes }; + return b; +} + fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; if (pane.file == null) { @@ -484,7 +533,14 @@ fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { p.emitWrite(id, req.data[0..take]); return .{ .tag = req.tag, .written = @intCast(take) }; } - const at = bodyOf(pane).len; + const held = if (p.fs.batch.serial == pane.serial and p.fs.batch.node == req.node and p.fs.batch.handle == req.handle) p.fs.batch.bytes.items.len else 0; + const at = bodyOf(pane).len + held; + if (batchFor(p, req, pane, at)) |b| { + const take = wholeUtf8(req.data); + b.bytes.appendSlice(p.gpa, req.data[0..take]) catch return Reply.fail(req.tag, E.NOMEM); + b.last_ns = p.now_ns; + return .{ .tag = req.tag, .written = @intCast(take) }; + } joinOnly(pane, req.handle); const take = spliceBody(p, pane, at, at, req.data) orelse return Reply.fail(req.tag, E.NOMEM); @@ -538,9 +594,19 @@ fn writeData(p: *Pardes, req: Req, pane: *Pane) Reply { if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text); const pf = &pane.fs; if (pf.addr_failed) return tree.failText(req.tag, E.INVAL, e_addr_failed); - clampAddr(pf, bodyOf(pane).len); + const held = if (p.fs.batch.serial == pane.serial and p.fs.batch.node == req.node and p.fs.batch.handle == req.handle) p.fs.batch.bytes.items.len else 0; + clampAddr(pf, bodyOf(pane).len + held); const q0: usize = pf.addr.q0; const q1: usize = @max(q0, @as(usize, pf.addr.q1)); + // An insert (an empty address) goes on from the open's held bytes. + if (q1 == q0) if (batchFor(p, req, pane, q0)) |b| { + const take = wholeUtf8(req.data); + b.bytes.appendSlice(p.gpa, req.data[0..take]) catch return Reply.fail(req.tag, E.NOMEM); + b.last_ns = p.now_ns; + pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }; + return .{ .tag = req.tag, .written = @intCast(take) }; + }; + flushBatch(p); const before = dotOf(pane); joinOnly(pane, req.handle); const take = spliceBody(p, pane, q0, q1, req.data) orelse @@ -1097,6 +1163,32 @@ test "the writes of one open are one undo step, as bash's line-buffered printf m } } +test "an open's writes in a row are held and go in as one edit, seen by the next request" { + const p = try withFile(testing.allocator, "one\n"); + defer p.deinit(); + const serial = serialOf(p); + const body = Node.of(serial, .body); + const h = call(p, .{ .tag = 1, .op = .open, .node = body, .omode = 1 }).reply.handle; + const revision = p.panes[0].?.file.?.revision; + for (0..100) |_| _ = call(p, .{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "0123456789\n" }); + // Held: nothing edited yet. + try testing.expectEqual(revision, p.panes[0].?.file.?.revision); + // Any other request puts them in, once. + try testing.expectEqual(@as(usize, 4 + 1100), rd(p, body, 0, 4096).bytes.len); + try testing.expectEqual(revision + 1, p.panes[0].?.file.?.revision); + _ = call(p, .{ .tag = 3, .op = .release, .node = body, .handle = h, .opened = true }); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status); + try testing.expectEqualStrings("one\n", rd(p, body, 0, 64).bytes); + // data inserts at its address go on the same way. + const data = Node.of(serial, .data); + _ = wr(p, Node.of(serial, .addr), "#0"); + const d = call(p, .{ .tag = 4, .op = .open, .node = data, .omode = 1 }).reply.handle; + _ = call(p, .{ .tag = 5, .op = .write, .node = data, .handle = d, .data = "a" }); + _ = call(p, .{ .tag = 5, .op = .write, .node = data, .handle = d, .data = "b" }); + _ = call(p, .{ .tag = 6, .op = .release, .node = data, .handle = d, .opened = true }); + try testing.expectEqualStrings("abone\n", rd(p, body, 0, 64).bytes); +} + test "two opens writing one body are two undo steps, however their writes interleave" { const p = try withFile(testing.allocator, "one\n"); defer p.deinit(); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 0960f00b..6d09b9a6 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -454,6 +454,9 @@ pub fn stagedReply(p: *Pardes, req: Req) Reply { // ---- dispatch ---- pub fn handle(p: *Pardes, req: Req) Reply { + // Held writes go in before anything but the next write of their open. + if (p.fs.batch.bytes.items.len > 0 and !(req.op == .write and req.node == p.fs.batch.node and req.handle == p.fs.batch.handle)) + pane.flushBatch(p); if (req.op == .open and req.create) { if (Node.target(req.node)) |t| if (t == .pane and p.paneBySerial(t.pane.serial) == null) return Reply.fail(req.tag, E.NOENT); diff --git a/src/pardes.zig b/src/pardes.zig index dc479909..391fa23d 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4792,6 +4792,7 @@ pub const Pardes = struct { for (p.panes) |slot| if (slot) |pane| p.noteClosed(pane); p.saveRecent(); p.recent.deinit(p.recentGpa()); + p.fs.batch.bytes.deinit(p.gpa); if (p.stand_in) |pane| p.teardownPane(pane); look.cancelLookHover(p); if (p.repl_ask) |ask| p.gpa.free(ask.text); @@ -5686,6 +5687,8 @@ pub const Pardes = struct { f(h.ctx, timeout); } if (v.now) |clock| p.advance(clock(h.ctx)); + // What a 9P open wrote in a row goes in once the writes pause. + ctlfs.pane.flushPausedBatch(p); while (p.nextQueued()) |ev| p.update(ev); while (p.nextEffect()) |e| p.perform(e); turn.settle(); @@ -7123,6 +7126,8 @@ pub const Pardes = struct { /// sleep exactly as long as nothing changes. pub fn nextWake(p: *const Pardes) ?u64 { const next = p.stepped_ns + animation.frame_ns; + // Held 9P writes go in when they pause: wake for it. + if (p.fs.batch.bytes.items.len > 0) return p.fs.batch.last_ns + ctlfs.pane.batch_pause_ns; if (p.chrome_animation.isActive() or p.presentation.animating()) return next; var frames: ?u64 = null; if (p.look_hover_wait) |waiting| { diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index 6bfe2c90..659e49d1 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"67f85bf9692f1778","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1887,"med_us":2147,"p90_us":2277,"max_us":2326},{"op":"render","fixture":"medium","min_us":73,"med_us":76,"p90_us":84,"max_us":96},{"op":"key-down","fixture":"medium","min_us":73,"med_us":81,"p90_us":84,"max_us":86},{"op":"key-right","fixture":"medium","min_us":73,"med_us":77,"p90_us":91,"max_us":173},{"op":"page-down","fixture":"medium","min_us":75,"med_us":78,"p90_us":80,"max_us":84},{"op":"wheel","fixture":"medium","min_us":72,"med_us":76,"p90_us":79,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1269,"med_us":1437,"p90_us":1680,"max_us":1697}]} +{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1841,"med_us":2197,"p90_us":2308,"max_us":2328},{"op":"render","fixture":"medium","min_us":72,"med_us":81,"p90_us":84,"max_us":86},{"op":"key-down","fixture":"medium","min_us":74,"med_us":74,"p90_us":80,"max_us":81},{"op":"key-right","fixture":"medium","min_us":74,"med_us":80,"p90_us":85,"max_us":100},{"op":"page-down","fixture":"medium","min_us":74,"med_us":81,"p90_us":84,"max_us":176},{"op":"wheel","fixture":"medium","min_us":71,"med_us":75,"p90_us":79,"max_us":93},{"op":"edit-char","fixture":"medium","min_us":1086,"med_us":1515,"p90_us":1692,"max_us":1822},{"op":"body-2m","fixture":"medium","min_us":9044,"med_us":16111,"p90_us":19782,"max_us":21405}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index 6ffd034c..bed59c8c 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"67f85bf9692f1778","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1907,"med_us":2037,"p90_us":2283,"max_us":2371},{"op":"render","fixture":"medium","min_us":72,"med_us":80,"p90_us":87,"max_us":87},{"op":"key-down","fixture":"medium","min_us":73,"med_us":78,"p90_us":82,"max_us":88},{"op":"key-right","fixture":"medium","min_us":72,"med_us":75,"p90_us":87,"max_us":87},{"op":"page-down","fixture":"medium","min_us":73,"med_us":81,"p90_us":93,"max_us":94},{"op":"wheel","fixture":"medium","min_us":73,"med_us":75,"p90_us":84,"max_us":88},{"op":"edit-char","fixture":"medium","min_us":1333,"med_us":1712,"p90_us":1956,"max_us":2636}]} +{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1800,"med_us":2113,"p90_us":2193,"max_us":2326},{"op":"render","fixture":"medium","min_us":71,"med_us":76,"p90_us":85,"max_us":97},{"op":"key-down","fixture":"medium","min_us":73,"med_us":76,"p90_us":82,"max_us":84},{"op":"key-right","fixture":"medium","min_us":72,"med_us":76,"p90_us":81,"max_us":95},{"op":"page-down","fixture":"medium","min_us":74,"med_us":78,"p90_us":83,"max_us":83},{"op":"wheel","fixture":"medium","min_us":72,"med_us":75,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1027,"med_us":1418,"p90_us":1699,"max_us":1834},{"op":"body-2m","fixture":"medium","min_us":8357,"med_us":17722,"p90_us":20080,"max_us":21699}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index 5d68e6b2..d13442a5 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"67f85bf9692f1778","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1771,"med_us":2022,"p90_us":2188,"max_us":2228},{"op":"render","fixture":"medium","min_us":75,"med_us":76,"p90_us":76,"max_us":86},{"op":"key-down","fixture":"medium","min_us":73,"med_us":79,"p90_us":80,"max_us":80},{"op":"key-right","fixture":"medium","min_us":72,"med_us":78,"p90_us":81,"max_us":82},{"op":"page-down","fixture":"medium","min_us":72,"med_us":76,"p90_us":80,"max_us":84},{"op":"wheel","fixture":"medium","min_us":75,"med_us":76,"p90_us":78,"max_us":79},{"op":"edit-char","fixture":"medium","min_us":1106,"med_us":1436,"p90_us":1692,"max_us":1721}]} +{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1819,"med_us":2002,"p90_us":2068,"max_us":2122},{"op":"render","fixture":"medium","min_us":71,"med_us":76,"p90_us":88,"max_us":89},{"op":"key-down","fixture":"medium","min_us":73,"med_us":75,"p90_us":76,"max_us":82},{"op":"key-right","fixture":"medium","min_us":73,"med_us":77,"p90_us":86,"max_us":126},{"op":"page-down","fixture":"medium","min_us":71,"med_us":75,"p90_us":81,"max_us":83},{"op":"wheel","fixture":"medium","min_us":71,"med_us":74,"p90_us":76,"max_us":97},{"op":"edit-char","fixture":"medium","min_us":1036,"med_us":1493,"p90_us":1805,"max_us":1967},{"op":"body-2m","fixture":"medium","min_us":8482,"med_us":17227,"p90_us":20296,"max_us":23040}]} diff --git a/test/perf.zig b/test/perf.zig index e244091c..c639178f 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -46,6 +46,9 @@ const Op = enum { page_down, wheel, edit_char, + /// 2 MB appended to the file through 9P, on one open, in 256 KB + /// writes: linear, not a copy of the whole buffer per write. + body_write, fn label(o: Op) []const u8 { return switch (o) { @@ -56,10 +59,25 @@ const Op = enum { .page_down => "page-down", .wheel => "wheel", .edit_char => "edit-char", + .body_write => "body-2m", }; } }; +var body_chunk: [256 * 1024]u8 = @splat('y'); + +/// The body_write gesture: an open of the pane's body, eight 256 KB writes, +/// a read (which the held writes go in before), the close. +fn bodyWrite(core: *pardes.Pardes, serial: u32) void { + const Node = pardes.ctlfs.Node; + const body = Node.of(serial, .body); + for (&body_chunk, 0..) |*c, i| c.* = if (i % 64 == 63) '\n' else 'y'; + const h = core.serveFs(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }).handle; + for (0..8) |_| _ = core.serveFs(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = &body_chunk }); + _ = core.serveFs(.{ .tag = 3, .op = .getattr, .node = body, .handle = h }); + _ = core.serveFs(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }); +} + const TermFixture = struct { name: []const u8, kb: usize, @@ -514,12 +532,14 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u .page_down => core.update(.{ .key = .{ .cp = pardes.Key.page_down } }), .wheel => core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = wheel_col, .row = wheel_row } }), .edit_char => core.update(.{ .key = .{ .cp = 'x', .text = "x" } }), + .body_write => bodyWrite(core, pane.serial), } pump(core); _ = try frame(core); const dt = nowNs() -| t0; switch (op) { .open => unreachable, + .body_write => if (pane.file.?.content.len != before.len + 8 * body_chunk.len) return error.BodyWriteWasNotAppended, .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or pane.file.?.content.len != before.len) return error.RenderChangedDocument, .key_down => if (pane.body.cur_row != before.row + 1) return error.DownDidNotMove, -- cgit v1.3 From d6445bb28bcb4a0d0e5f29c6308682737d253ebe Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 16:19:21 -0300 Subject: A failure said while a 9P write waits on it posts no msg, only the write's err A failure the editor said as it performed a write's work (a Save's disk write, a shell, a language server) was posted as a msg and taken back out when the write's err was logged, which it cannot be once a log follower has read it: a follower saw both. Such a failure is now posted without a msg in the first place (fs.write_waits), and nothing is taken back. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 8 +++++--- src/Messages.zig | 2 +- src/fs.zig | 4 ++++ src/ninep/ctl.zig | 10 ++++++++++ 4 files changed, 20 insertions(+), 4 deletions(-) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 7f490f81..6f05e3ab 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -312,11 +312,14 @@ pub const Listener = struct { if (restoring) l.restore_writer.store(true, .release); defer if (restoring) l.restore_writer.store(false, .release); core.fs.late_failure_len = 0; + // What fails while this waits is this write's err, never a msg too. + core.fs.write_waits = true; if (core.effects_len != 0) pardes.turn.awaitSettled(epoch); if (core.fs.lsp_answer_at) |n| { core.fs.lsp_answer_at = null; pardes.turn.awaitLsp(n); } + core.fs.write_waits = false; // ponytail: one slot, so a failure of another client's effects that // settle in the same wait is told to this write too. if (l.core == core and core.fs.late_failure_len != 0) { @@ -327,9 +330,8 @@ pub const Listener = struct { pardes.ctlfs.E.NOENT else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else pardes.ctlfs.E.IO; const failed = pardes.ctlfs.failText(req.tag, errno, late); - // Its err record says it (the path in it); the msg the failure - // was also said as goes, as a builtin's failing a write does. - pardes.ctlfs.events.dropMessage(core, core.fs.late_failure[0..core.fs.late_failure_len]); + // Its err record says it (the path in it), the one record: it + // was said with no msg while this waited (fs.write_waits). pardes.ctlfs.events.noteError(core, req, failed); return conn.reply(&failed, ""); } diff --git a/src/Messages.zig b/src/Messages.zig index aebaff0c..7342f726 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -505,7 +505,7 @@ pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { p.fs.failures +%= 1; // A builtin a ctl write runs: its first error is also the write's, cut // between words. - const failing_write = p.fs.no_prompt or p.fs.capturing; + const failing_write = p.fs.no_prompt or p.fs.capturing or p.fs.write_waits; if (failing_write and p.fs.failure_len == 0) { const kept = if (text.len > p.fs.failure.len) clip(text, p.fs.failure.len - 3) else text; @memcpy(p.fs.failure[0..kept.len], kept); diff --git a/src/fs.zig b/src/fs.zig index 2487ffee..edd8fcb8 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1330,6 +1330,10 @@ pub const Namespace = struct { /// its header), 0 when unknown: a write shorter than it is the whole of /// what its client wrote, one that fills it may be cut and go on. write_room: u32 = 0, + /// A 9P write waits on what the editor performs for it (a Save's disk + /// write, a shell, a language server): a failure said meanwhile is that + /// write's err, so it posts no msg (Messages.reportFailure). + write_waits: bool = false, /// Writes one open made in a row into one place of a pane's body (an /// append to `body`, an insert at `data`'s address), held and put in /// as one edit when anything else comes (ninep/pane.zig flushBatch): a diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 397f3339..63e7e76a 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2234,6 +2234,16 @@ test "a buffer whose file was deleted on disk is dirty, and Del asks first" { try testing.expect(p.paneBySerial(serial) == null); } +test "a failure said while a 9P write waits on it posts no msg, only the write's err" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + p.fs.write_waits = true; + p.saveFailed(@intCast(p.active), "/nowhere/zz.txt", error.FileNotFound); + p.fs.write_waits = false; + try testing.expect(!th.logHas(p, "msg ")); + try testing.expect(p.fs.late_failure_len > 0); +} + test "every EINVAL a write gets says why, in its err record too; DEL is a control character in a line" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); -- cgit v1.3 From 494dae826c3c567b0eea6e91936628a2952fb5c6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 16:33:12 -0300 Subject: A repeated log record is counted only when its whole text repeats, not just what was cut to fit (xN) compared records after msg and err cut long texts to fit, so two different long failures that agreed in their first 200-odd bytes were counted as one. The whole text of the newest counted record is now hashed, and a repeat needs it too. Co-Authored-By: Claude Opus 5.5 --- src/fs.zig | 3 +++ src/ninep/events.zig | 27 ++++++++++++++++++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index edd8fcb8..edead0ff 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1334,6 +1334,9 @@ pub const Namespace = struct { /// write, a shell, a language server): a failure said meanwhile is that /// write's err, so it posts no msg (Messages.reportFailure). write_waits: bool = false, + /// The whole text of the newest counted log record, hashed: its record + /// may be cut, and a repeat is only the same whole text again. + log_full_hash: u64 = 0, /// Writes one open made in a row into one place of a pane's body (an /// append to `body`, an insert at `data`'s address), held and put in /// as one edit when anything else comes (ninep/pane.zig flushBatch): a diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 570cae78..f76a5212 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -171,7 +171,7 @@ pub fn noteMessage(p: *Pardes, serial: u32, said: []const u8) void { pushCounting(p, (if (serial == 0) std.fmt.bufPrint(&buf, "msg - {s}{s}\n", .{ kept, cut }) else - std.fmt.bufPrint(&buf, "msg {d} {s}{s}\n", .{ serial, kept, cut })) catch return); + std.fmt.bufPrint(&buf, "msg {d} {s}{s}\n", .{ serial, kept, cut })) catch return, said); } /// Records `err : ` for a write or truncation that was @@ -186,7 +186,7 @@ pub fn noteMessage(p: *Pardes, serial: u32, said: []const u8) void { pub fn noteErrCounted(p: *Pardes, text: []const u8) void { bootFirst(p); var buf: [pardes.memory.limits.host_path_cap + 16]u8 = undefined; - pushCounting(p, std.fmt.bufPrint(&buf, "err {s}\n", .{text}) catch return); + pushCounting(p, std.fmt.bufPrint(&buf, "err {s}\n", .{text}) catch return, text); } pub fn notePath(p: *Pardes, what: []const u8, path: []const u8) void { @@ -239,7 +239,7 @@ pub fn noteError(p: *Pardes, req: Req, reply: Reply) void { for (record[0 .. record.len - 1]) |*c| if (c.* < ' ') { c.* = ' '; }; - pushCounting(p, record); + pushCounting(p, record, reason); } /// Drops the newest record when it is a msg saying `text` (of any pane) @@ -256,7 +256,11 @@ pub fn dropMessage(p: *Pardes, text: []const u8) void { /// counts that one instead: ` (x2)`, the count being every time it /// was said. One a follower has already read is not rewritten: the repeat /// is a new line carrying the running count, `(x3)`. -fn pushCounting(p: *Pardes, raw: []u8) void { +/// `full` is the text before any cut: two records that agree only in what +/// was cut to fit are no repeat (`fs.log_full_hash`). +fn pushCounting(p: *Pardes, raw: []u8, full: []const u8) void { + const full_hash = std.hash.Wyhash.hash(0, full); + defer p.fs.log_full_hash = full_hash; // A client retrying a write that fails the same way would fill the ring // with one line, so a repeat of the newest record is that record counted, // `(x3)`, as +Messages counts its repeats; unless a follower has read it @@ -272,7 +276,7 @@ fn pushCounting(p: *Pardes, raw: []u8) void { said = said[0..x]; } else |_| {} }; - if (!std.mem.eql(u8, said, record[0 .. record.len - 1])) return pushLog(p, record); + if (!std.mem.eql(u8, said, record[0 .. record.len - 1]) or p.fs.log_full_hash != full_hash) return pushLog(p, record); var counted: [pardes.Messages.LoggedMessage.cap + 64]u8 = undefined; const again = std.fmt.bufPrint(&counted, "{s} (x{d})\n", .{ said, times +| 1 }) catch return; if (!followerRead(p, last.seq)) p.fs.log.buf.shrinkRetainingCapacity(last.at); @@ -373,6 +377,8 @@ fn shownAs(text: []const u8, out: []u8, escape_newline: bool) []u8 { } fn pushLog(p: *Pardes, raw: []u8) void { + // A record not counted: the next one is no repeat of a counted one. + p.fs.log_full_hash = 0; var clean: [4 * 4096 + 256]u8 = undefined; const record = sanitize(raw, &clean); // One record larger than the ring would push every other out and then @@ -1295,3 +1301,14 @@ test "a long err record is cut between words, with an ellipsis" { try testing.expect(std.mem.endsWith(u8, record, "abcdefgh…\n")); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); } + +test "two failures that agree only in what their records cut are two records, not one counted" { + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + const long = "why " ** 80; + p.setMessage(0, long ++ "first"); + p.setMessage(0, long ++ "second"); + try testing.expect(!th.logHas(p, "(x2)")); + p.setMessage(0, long ++ "second"); + try testing.expect(th.logHas(p, "(x2)")); +} -- cgit v1.3 From 2b388888348860097967ae04d03f68c00a70472c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 20:25:28 -0300 Subject: Mini.zig is mini.zig: a file of functions and no fields takes a namespace's lowercase name The naming the split agreed on, deferred until now; panes.mini is its name at its importers. File.zig keeps its alias line (const Mini = panes.mini) so the file another agent is working in changes by that line alone. The served sources list and docs/design.typ name the new file. No behaviour changes; test/perf.zig's two references change, and since the perf harness is keyed by its own text, its three baselines are recorded again (under other agents' builds, so a little slower). Co-Authored-By: Claude Opus 5.5 --- docs/design.typ | 2 +- src/File.zig | 2 +- src/Mini.zig | 321 -------------------------------- src/builtins.zig | 2 +- src/fs.zig | 2 +- src/mini.zig | 321 ++++++++++++++++++++++++++++++++ src/panes.zig | 4 +- test/output.zig | 6 +- test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 10 +- 12 files changed, 338 insertions(+), 338 deletions(-) delete mode 100644 src/Mini.zig create mode 100644 src/mini.zig (limited to 'src/fs.zig') diff --git a/docs/design.typ b/docs/design.typ index ed2bbb94..20085706 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -526,7 +526,7 @@ verbatim by right-click and the delayed hover preview; that policy stays beside input because it also observes live pane selections and wrapped grid coordinates. Each pane kind keeps its storage and operations together in its own file -(`File.zig`, `Terminal.zig`, `Output.zig`, `Mini.zig`, `pdf_view.zig`, and the +(`File.zig`, `Terminal.zig`, `Output.zig`, `mini.zig`, `pdf_view.zig`, and the image pane in `image.zig`), reached through `panes.zig` beside `Pane`. `layout.zig` owns placement and presentation state. `pardes.zig` handles input and cross-pane state directly, without a pane vtable; the rest of the editor diff --git a/src/File.zig b/src/File.zig index 9f0f329c..c4040863 100644 --- a/src/File.zig +++ b/src/File.zig @@ -16,7 +16,7 @@ const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); const Pane = panes.Pane; const Output = panes.Output; -const Mini = panes.Mini; +const Mini = panes.mini; const Terminal = panes.Terminal; const Text = panes.Text; diff --git a/src/Mini.zig b/src/Mini.zig deleted file mode 100644 index a6aef15a..00000000 --- a/src/Mini.zig +++ /dev/null @@ -1,321 +0,0 @@ -//! The Mini minimap: a file drawn four rows to a cell in braille dots. -const panes = @import("panes.zig"); -const std = @import("std"); -const pardes = @import("pardes.zig"); -const exec = @import("exec.zig"); -const config = @import("config.zig"); -const Pardes = pardes.Pardes; -const modal = @import("modal.zig"); -const filesystem = @import("fs.zig"); -const syntax = @import("syntax.zig"); -const File = panes.File; -const Output = panes.Output; - -pub const max_input_bytes = 4 * 1024 * 1024; -pub const max_output_bytes = 4 * 1024 * 1024; - -pub const State = struct { - source: []u8, - colors: []u8, - - pub fn deinit(state: *State, gpa: std.mem.Allocator) void { - gpa.free(state.source); - gpa.free(state.colors); - state.* = undefined; - } -}; - -pub const Result = struct { - content: []u8, - colors: []u8, - - pub fn deinit(result: Result, gpa: std.mem.Allocator) void { - gpa.free(result.content); - gpa.free(result.colors); - } -}; - -const Row = struct { - text: []const u8 = "", - base: usize = 0, - at: usize = 0, - left: usize = 0, - ink: bool = false, - color: u8 = 0, - - fn dot(row: *Row, styles: []const u8) ?u8 { - if (row.left == 0) { - if (row.at == row.text.len) return null; - const end = modal.nextGrapheme(row.text, row.at); - const grapheme = row.text[row.at..end]; - row.left = File.graphemeDisplayWidth(grapheme); - // unreachable below: `generate` refuses a source that is no UTF-8 - const n = std.unicode.utf8ByteSequenceLength(grapheme[0]) catch unreachable; - const cp = std.unicode.utf8Decode(grapheme[0..n]) catch unreachable; - const blank = switch (cp) { - '\t'...'\r', ' ', 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true, - else => false, - }; - row.ink = !blank or grapheme.len != n; - row.color = if (styles.len == 0) 0 else styles[row.base + row.at]; - row.at = end; - } - row.left -= 1; - return if (row.ink) row.color else null; - } -}; - -fn render(output: ?Result, source: []const u8, styles: []const u8) !usize { - if (source.len == 0) return 0; - const end = source.len - @intFromBool(source[source.len - 1] == '\n'); - var lines = std.mem.splitScalar(u8, source[0..end], '\n'); - var offset: usize = 0; - while (lines.peek() != null) { - var rows: [4]Row = @splat(.{}); - for (&rows) |*row| { - const line = lines.next() orelse break; - row.text = std.mem.trimEnd(u8, line, "\r"); - row.base = @intFromPtr(line.ptr) - @intFromPtr(source.ptr); - } - var spaces: usize = 0; - while (true) { - var more = false; - for (rows) |row| more = more or row.at < row.text.len or row.left > 0; - if (!more) break; - const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; - var mask: u8 = 0; - var counts: [5]u8 = @splat(0); - for (&rows, 0..) |*row, y| { - for (0..2) |x| { - if (row.dot(styles)) |color| { - mask |= @as(u8, 1) << bits[y][x]; - counts[color] += 1; - } - } - } - if (mask == 0) { - spaces += 1; - continue; - } - if (spaces + 3 > max_output_bytes - offset) return error.MiniTooLarge; - var color: u8 = 0; - var most: u8 = 0; - for (counts[1..], 1..) |count, i| { - if (count > most) { - color = @intCast(i); - most = count; - } - } - if (output) |out| { - @memset(out.content[offset..][0..spaces], ' '); - @memset(out.colors[offset..][0..spaces], 0); - // unreachable: U+2800 plus a u8 mask is a braille codepoint, always three bytes - _ = std.unicode.utf8Encode(@as(u21, 0x2800) + mask, out.content[offset + spaces ..][0..3]) catch unreachable; - @memset(out.colors[offset + spaces ..][0..3], color); - } - offset += spaces + 3; - spaces = 0; - } - if (offset == max_output_bytes) return error.MiniTooLarge; - if (output) |out| { - out.content[offset] = '\n'; - out.colors[offset] = 0; - } - offset += 1; - } - return offset; -} - -pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) !Result { - if (source.len > max_input_bytes) return error.MiniTooLarge; - if (!std.unicode.utf8ValidateSlice(source)) return error.InvalidUtf8; - if (styles.len != 0 and styles.len != source.len) return error.InvalidMiniColors; - for (styles) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMiniColors; - const len = try render(null, source, styles); - const content = try gpa.alloc(u8, len); - errdefer gpa.free(content); - const colors = try gpa.alloc(u8, len); - errdefer gpa.free(colors); - const result: Result = .{ .content = content, .colors = colors }; - const written = try render(result, source, styles); - std.debug.assert(written == len); - return result; -} - -pub fn open(p: *Pardes, id: usize, argument: []const u8) !void { - const caller = p.panes[id] orelse return error.MissingPane; - const word = std.mem.trim(u8, argument, " \t\r\n"); - if (word.len == 0) return error.MissingPath; - var path_buf: [4096]u8 = undefined; - const target = filesystem.resolve(p, word, Pardes.paneDir(caller), &path_buf) orelse return error.FileNotFound; - if (target.dir) return error.NotAFile; - const source = try p.gpa.dupe(u8, target.path); - errdefer p.gpa.free(source); - const input = try filesystem.readLimit(p, source, max_input_bytes); - defer p.gpa.free(input); - const styles = try syntax.highlightFileRange(p.tree_sitter_gpa, source, input, 0, input.len); - defer p.tree_sitter_gpa.free(styles); - const result = try generate(p.gpa, input, styles); - errdefer result.deinit(p.gpa); - for (p.panes, 0..) |slot, i| { - const pane = slot orelse continue; - const file = if (pane.file) |*f| f else continue; - const old = file.mini orelse continue; - if (!std.mem.eql(u8, old.source, source)) continue; - if (std.mem.eql(u8, file.content, result.content) and std.mem.eql(u8, old.colors, result.colors)) { - p.gpa.free(source); - result.deinit(p.gpa); - } else { - File.setContent(p, file, result.content); - file.mini = .{ .source = source, .colors = result.colors }; - file.syntax_dirty = false; - Output.resetBody(p, pane); - } - p.active = i; - return; - } - const free = p.freeSlot() orelse return error.NoPaneSlots; - const dir = std.fs.path.dirname(source) orelse "/"; - const path = try std.fmt.allocPrint(p.gpa, "{s}/Mini {s}", .{ std.mem.trimEnd(u8, dir, "/"), std.fs.path.basename(source) }); - errdefer p.gpa.free(path); - const history = try File.History.create(p.gpa); - errdefer p.gpa.destroy(history); - const pane = try p.newDocPane(free); - pane.file = .{ - .path = path, - .content = result.content, - .output = .{ .from = .{ .cmd = .Mini } }, - .mini = .{ .source = source, .colors = result.colors }, - .history = history, - .syntax_dirty = false, - }; - pane.body.cur_pinned = true; - exec.placeNew(p, id, id, free, .doc); - p.active = free; -} - -test "Mini maps every braille dot and partial line group" { - const gpa = std.testing.allocator; - const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; - for (0..256) |mask| { - var source: [12]u8 = undefined; - for (0..4) |row| { - for (0..2) |col| source[row * 3 + col] = if (mask & (@as(usize, 1) << bits[row][col]) != 0) 'x' else ' '; - source[row * 3 + 2] = '\n'; - } - const result = try generate(gpa, &source, ""); - defer result.deinit(gpa); - var expected: [4]u8 = undefined; - const len: usize = if (mask == 0) 0 else try std.unicode.utf8Encode(@as(u21, 0x2800) + @as(u21, @intCast(mask)), &expected); - expected[len] = '\n'; - try std.testing.expectEqualStrings(expected[0 .. len + 1], result.content); - try std.testing.expectEqual(result.content.len, result.colors.len); - for (result.colors) |color| try std.testing.expectEqual(@as(u8, 0), color); - } - for ([_]struct { source: []const u8, expected: []const u8 }{ - .{ .source = "", .expected = "" }, - .{ .source = "x", .expected = "⠁\n" }, - .{ .source = "xx\n", .expected = "⠉\n" }, - .{ .source = "x \n", .expected = "⠁\n" }, - .{ .source = "\n\n\n\nx", .expected = "\n⠁\n" }, - .{ .source = "x\r\nx\r\n", .expected = "⠃\n" }, - }) |case| { - const result = try generate(gpa, case.source, ""); - defer result.deinit(gpa); - try std.testing.expectEqualStrings(case.expected, result.content); - } -} - -test "Mini uses display cells for tabs combining text and wide characters" { - const gpa = std.testing.allocator; - for ([_]struct { source: []const u8, expected: []const u8 }{ - .{ .source = "e\u{301}界\n", .expected = "⠉⠁\n" }, - .{ .source = " x\n", .expected = " ⠁\n" }, - .{ .source = "\u{a0}x\n", .expected = "⠈\n" }, - }) |case| { - const result = try generate(gpa, case.source, ""); - defer result.deinit(gpa); - try std.testing.expectEqualStrings(case.expected, result.content); - } - const tabs = try generate(gpa, "\tx\n", ""); - defer tabs.deinit(gpa); - const spaces = config.tab_width / 2; - for (tabs.content[0..spaces]) |byte| try std.testing.expectEqual(@as(u8, ' '), byte); - try std.testing.expectEqualStrings(if (config.tab_width % 2 == 0) "⠁\n" else "⠈\n", tabs.content[spaces..]); -} - -test "Mini chooses highlighted dots over plain ink with stable color ties" { - const gpa = std.testing.allocator; - const source = "xx\nxx\nxx\nxx\n"; - var styles: [source.len]u8 = @splat(0); - styles[0] = @intFromEnum(syntax.Syn.keyword); - const rare = try generate(gpa, source, &styles); - defer rare.deinit(gpa); - try std.testing.expectEqualStrings("⣿\n", rare.content); - try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1, 0 }, rare.colors); - styles[0] = @intFromEnum(syntax.Syn.string); - styles[1] = @intFromEnum(syntax.Syn.number); - const tied = try generate(gpa, source, &styles); - defer tied.deinit(gpa); - try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2, 0 }, tied.colors); - styles[3] = @intFromEnum(syntax.Syn.number); - const majority = try generate(gpa, source, &styles); - defer majority.deinit(gpa); - try std.testing.expectEqualSlices(u8, &.{ 3, 3, 3, 0 }, majority.colors); -} - -test "Mini generation bounds and allocation failures leave no partial result" { - const Case = struct { - fn run(gpa: std.mem.Allocator) !void { - const result = try generate(gpa, "alpha\nbeta\ngamma\ndelta\nepsilon\n", ""); - defer result.deinit(gpa); - } - }; - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{}); - try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "x", &.{5})); - try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "xx", &.{0})); - var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); - const source = try std.testing.allocator.alloc(u8, max_input_bytes + 1); - defer std.testing.allocator.free(source); - try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source, "")); - for (source[0..max_input_bytes], 0..) |*byte, i| byte.* = if (i % 2 == 0) 'x' else ' '; - try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source[0..max_input_bytes], "")); - try std.testing.expect(!allocator.has_induced_failure); -} - -test "Mini publishes only complete snapshots and content replacement drops metadata" { - const Case = struct { - fn run(gpa: std.mem.Allocator, path: []const u8) !void { - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const source = try p.setTestFile("untouched\n"); - const free = p.freeSlot(); - open(p, 0, path) catch |err| { - try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(free, p.freeSlot()); - try std.testing.expectEqual(source, p.panes[0].?); - try std.testing.expectEqualStrings("untouched\n", source.file.?.content); - return err; - }; - const file = &p.panes[p.active].?.file.?; - try std.testing.expectEqualStrings("⠉\n", file.content); - try std.testing.expectEqualStrings(path, file.mini.?.source); - const replacement = try gpa.dupe(u8, "plain\n"); - File.setContent(p, file, replacement); - try std.testing.expect(file.mini == null); - try std.testing.expectEqualStrings("plain\n", file.content); - } - }; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mini.txt", .data = "xx\n" }); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - var path_buf: [4096]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); -} - -test "Mini refuses a file that is no UTF-8, before its decoding could panic" { - try std.testing.expectError(error.InvalidUtf8, generate(std.testing.allocator, "ok \xff\xfe bad\n\xc3", "")); -} diff --git a/src/builtins.zig b/src/builtins.zig index 8a01b3d6..cc86067e 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1379,7 +1379,7 @@ pub const Mini = struct { pub const output: OutputTraits = .{ .name = "Mini", .doc = true }; pub fn run(c: Ctx) void { - panes.Mini.open(c.p, c.id, c.arg orelse "") catch |err| + panes.mini.open(c.p, c.id, c.arg orelse "") catch |err| c.p.reportError(c.id, "Mini", err); } }; diff --git a/src/fs.zig b/src/fs.zig index edead0ff..a2e8daf8 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -55,7 +55,7 @@ const source_files = [_]Source{ .{ .path = "src/Pipe.zig", .contents = @embedFile("Pipe.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, - .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, + .{ .path = "src/mini.zig", .contents = @embedFile("mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, .{ .path = "src/Terminal.zig", .contents = @embedFile("Terminal.zig") }, .{ .path = "src/pdf_view.zig", .contents = @embedFile("pdf_view.zig") }, diff --git a/src/mini.zig b/src/mini.zig new file mode 100644 index 00000000..a6aef15a --- /dev/null +++ b/src/mini.zig @@ -0,0 +1,321 @@ +//! The Mini minimap: a file drawn four rows to a cell in braille dots. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const modal = @import("modal.zig"); +const filesystem = @import("fs.zig"); +const syntax = @import("syntax.zig"); +const File = panes.File; +const Output = panes.Output; + +pub const max_input_bytes = 4 * 1024 * 1024; +pub const max_output_bytes = 4 * 1024 * 1024; + +pub const State = struct { + source: []u8, + colors: []u8, + + pub fn deinit(state: *State, gpa: std.mem.Allocator) void { + gpa.free(state.source); + gpa.free(state.colors); + state.* = undefined; + } +}; + +pub const Result = struct { + content: []u8, + colors: []u8, + + pub fn deinit(result: Result, gpa: std.mem.Allocator) void { + gpa.free(result.content); + gpa.free(result.colors); + } +}; + +const Row = struct { + text: []const u8 = "", + base: usize = 0, + at: usize = 0, + left: usize = 0, + ink: bool = false, + color: u8 = 0, + + fn dot(row: *Row, styles: []const u8) ?u8 { + if (row.left == 0) { + if (row.at == row.text.len) return null; + const end = modal.nextGrapheme(row.text, row.at); + const grapheme = row.text[row.at..end]; + row.left = File.graphemeDisplayWidth(grapheme); + // unreachable below: `generate` refuses a source that is no UTF-8 + const n = std.unicode.utf8ByteSequenceLength(grapheme[0]) catch unreachable; + const cp = std.unicode.utf8Decode(grapheme[0..n]) catch unreachable; + const blank = switch (cp) { + '\t'...'\r', ' ', 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true, + else => false, + }; + row.ink = !blank or grapheme.len != n; + row.color = if (styles.len == 0) 0 else styles[row.base + row.at]; + row.at = end; + } + row.left -= 1; + return if (row.ink) row.color else null; + } +}; + +fn render(output: ?Result, source: []const u8, styles: []const u8) !usize { + if (source.len == 0) return 0; + const end = source.len - @intFromBool(source[source.len - 1] == '\n'); + var lines = std.mem.splitScalar(u8, source[0..end], '\n'); + var offset: usize = 0; + while (lines.peek() != null) { + var rows: [4]Row = @splat(.{}); + for (&rows) |*row| { + const line = lines.next() orelse break; + row.text = std.mem.trimEnd(u8, line, "\r"); + row.base = @intFromPtr(line.ptr) - @intFromPtr(source.ptr); + } + var spaces: usize = 0; + while (true) { + var more = false; + for (rows) |row| more = more or row.at < row.text.len or row.left > 0; + if (!more) break; + const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; + var mask: u8 = 0; + var counts: [5]u8 = @splat(0); + for (&rows, 0..) |*row, y| { + for (0..2) |x| { + if (row.dot(styles)) |color| { + mask |= @as(u8, 1) << bits[y][x]; + counts[color] += 1; + } + } + } + if (mask == 0) { + spaces += 1; + continue; + } + if (spaces + 3 > max_output_bytes - offset) return error.MiniTooLarge; + var color: u8 = 0; + var most: u8 = 0; + for (counts[1..], 1..) |count, i| { + if (count > most) { + color = @intCast(i); + most = count; + } + } + if (output) |out| { + @memset(out.content[offset..][0..spaces], ' '); + @memset(out.colors[offset..][0..spaces], 0); + // unreachable: U+2800 plus a u8 mask is a braille codepoint, always three bytes + _ = std.unicode.utf8Encode(@as(u21, 0x2800) + mask, out.content[offset + spaces ..][0..3]) catch unreachable; + @memset(out.colors[offset + spaces ..][0..3], color); + } + offset += spaces + 3; + spaces = 0; + } + if (offset == max_output_bytes) return error.MiniTooLarge; + if (output) |out| { + out.content[offset] = '\n'; + out.colors[offset] = 0; + } + offset += 1; + } + return offset; +} + +pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) !Result { + if (source.len > max_input_bytes) return error.MiniTooLarge; + if (!std.unicode.utf8ValidateSlice(source)) return error.InvalidUtf8; + if (styles.len != 0 and styles.len != source.len) return error.InvalidMiniColors; + for (styles) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMiniColors; + const len = try render(null, source, styles); + const content = try gpa.alloc(u8, len); + errdefer gpa.free(content); + const colors = try gpa.alloc(u8, len); + errdefer gpa.free(colors); + const result: Result = .{ .content = content, .colors = colors }; + const written = try render(result, source, styles); + std.debug.assert(written == len); + return result; +} + +pub fn open(p: *Pardes, id: usize, argument: []const u8) !void { + const caller = p.panes[id] orelse return error.MissingPane; + const word = std.mem.trim(u8, argument, " \t\r\n"); + if (word.len == 0) return error.MissingPath; + var path_buf: [4096]u8 = undefined; + const target = filesystem.resolve(p, word, Pardes.paneDir(caller), &path_buf) orelse return error.FileNotFound; + if (target.dir) return error.NotAFile; + const source = try p.gpa.dupe(u8, target.path); + errdefer p.gpa.free(source); + const input = try filesystem.readLimit(p, source, max_input_bytes); + defer p.gpa.free(input); + const styles = try syntax.highlightFileRange(p.tree_sitter_gpa, source, input, 0, input.len); + defer p.tree_sitter_gpa.free(styles); + const result = try generate(p.gpa, input, styles); + errdefer result.deinit(p.gpa); + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const file = if (pane.file) |*f| f else continue; + const old = file.mini orelse continue; + if (!std.mem.eql(u8, old.source, source)) continue; + if (std.mem.eql(u8, file.content, result.content) and std.mem.eql(u8, old.colors, result.colors)) { + p.gpa.free(source); + result.deinit(p.gpa); + } else { + File.setContent(p, file, result.content); + file.mini = .{ .source = source, .colors = result.colors }; + file.syntax_dirty = false; + Output.resetBody(p, pane); + } + p.active = i; + return; + } + const free = p.freeSlot() orelse return error.NoPaneSlots; + const dir = std.fs.path.dirname(source) orelse "/"; + const path = try std.fmt.allocPrint(p.gpa, "{s}/Mini {s}", .{ std.mem.trimEnd(u8, dir, "/"), std.fs.path.basename(source) }); + errdefer p.gpa.free(path); + const history = try File.History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(free); + pane.file = .{ + .path = path, + .content = result.content, + .output = .{ .from = .{ .cmd = .Mini } }, + .mini = .{ .source = source, .colors = result.colors }, + .history = history, + .syntax_dirty = false, + }; + pane.body.cur_pinned = true; + exec.placeNew(p, id, id, free, .doc); + p.active = free; +} + +test "Mini maps every braille dot and partial line group" { + const gpa = std.testing.allocator; + const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; + for (0..256) |mask| { + var source: [12]u8 = undefined; + for (0..4) |row| { + for (0..2) |col| source[row * 3 + col] = if (mask & (@as(usize, 1) << bits[row][col]) != 0) 'x' else ' '; + source[row * 3 + 2] = '\n'; + } + const result = try generate(gpa, &source, ""); + defer result.deinit(gpa); + var expected: [4]u8 = undefined; + const len: usize = if (mask == 0) 0 else try std.unicode.utf8Encode(@as(u21, 0x2800) + @as(u21, @intCast(mask)), &expected); + expected[len] = '\n'; + try std.testing.expectEqualStrings(expected[0 .. len + 1], result.content); + try std.testing.expectEqual(result.content.len, result.colors.len); + for (result.colors) |color| try std.testing.expectEqual(@as(u8, 0), color); + } + for ([_]struct { source: []const u8, expected: []const u8 }{ + .{ .source = "", .expected = "" }, + .{ .source = "x", .expected = "⠁\n" }, + .{ .source = "xx\n", .expected = "⠉\n" }, + .{ .source = "x \n", .expected = "⠁\n" }, + .{ .source = "\n\n\n\nx", .expected = "\n⠁\n" }, + .{ .source = "x\r\nx\r\n", .expected = "⠃\n" }, + }) |case| { + const result = try generate(gpa, case.source, ""); + defer result.deinit(gpa); + try std.testing.expectEqualStrings(case.expected, result.content); + } +} + +test "Mini uses display cells for tabs combining text and wide characters" { + const gpa = std.testing.allocator; + for ([_]struct { source: []const u8, expected: []const u8 }{ + .{ .source = "e\u{301}界\n", .expected = "⠉⠁\n" }, + .{ .source = " x\n", .expected = " ⠁\n" }, + .{ .source = "\u{a0}x\n", .expected = "⠈\n" }, + }) |case| { + const result = try generate(gpa, case.source, ""); + defer result.deinit(gpa); + try std.testing.expectEqualStrings(case.expected, result.content); + } + const tabs = try generate(gpa, "\tx\n", ""); + defer tabs.deinit(gpa); + const spaces = config.tab_width / 2; + for (tabs.content[0..spaces]) |byte| try std.testing.expectEqual(@as(u8, ' '), byte); + try std.testing.expectEqualStrings(if (config.tab_width % 2 == 0) "⠁\n" else "⠈\n", tabs.content[spaces..]); +} + +test "Mini chooses highlighted dots over plain ink with stable color ties" { + const gpa = std.testing.allocator; + const source = "xx\nxx\nxx\nxx\n"; + var styles: [source.len]u8 = @splat(0); + styles[0] = @intFromEnum(syntax.Syn.keyword); + const rare = try generate(gpa, source, &styles); + defer rare.deinit(gpa); + try std.testing.expectEqualStrings("⣿\n", rare.content); + try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1, 0 }, rare.colors); + styles[0] = @intFromEnum(syntax.Syn.string); + styles[1] = @intFromEnum(syntax.Syn.number); + const tied = try generate(gpa, source, &styles); + defer tied.deinit(gpa); + try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2, 0 }, tied.colors); + styles[3] = @intFromEnum(syntax.Syn.number); + const majority = try generate(gpa, source, &styles); + defer majority.deinit(gpa); + try std.testing.expectEqualSlices(u8, &.{ 3, 3, 3, 0 }, majority.colors); +} + +test "Mini generation bounds and allocation failures leave no partial result" { + const Case = struct { + fn run(gpa: std.mem.Allocator) !void { + const result = try generate(gpa, "alpha\nbeta\ngamma\ndelta\nepsilon\n", ""); + defer result.deinit(gpa); + } + }; + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{}); + try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "x", &.{5})); + try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "xx", &.{0})); + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); + const source = try std.testing.allocator.alloc(u8, max_input_bytes + 1); + defer std.testing.allocator.free(source); + try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source, "")); + for (source[0..max_input_bytes], 0..) |*byte, i| byte.* = if (i % 2 == 0) 'x' else ' '; + try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source[0..max_input_bytes], "")); + try std.testing.expect(!allocator.has_induced_failure); +} + +test "Mini publishes only complete snapshots and content replacement drops metadata" { + const Case = struct { + fn run(gpa: std.mem.Allocator, path: []const u8) !void { + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const source = try p.setTestFile("untouched\n"); + const free = p.freeSlot(); + open(p, 0, path) catch |err| { + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(free, p.freeSlot()); + try std.testing.expectEqual(source, p.panes[0].?); + try std.testing.expectEqualStrings("untouched\n", source.file.?.content); + return err; + }; + const file = &p.panes[p.active].?.file.?; + try std.testing.expectEqualStrings("⠉\n", file.content); + try std.testing.expectEqualStrings(path, file.mini.?.source); + const replacement = try gpa.dupe(u8, "plain\n"); + File.setContent(p, file, replacement); + try std.testing.expect(file.mini == null); + try std.testing.expectEqualStrings("plain\n", file.content); + } + }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mini.txt", .data = "xx\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path_buf: [4096]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); +} + +test "Mini refuses a file that is no UTF-8, before its decoding could panic" { + try std.testing.expectError(error.InvalidUtf8, generate(std.testing.allocator, "ok \xff\xfe bad\n\xc3", "")); +} diff --git a/src/panes.zig b/src/panes.zig index 32ad7b6b..b6fdc31a 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -636,7 +636,7 @@ pub const File = @import("File.zig"); pub const Output = @import("Output.zig"); -pub const Mini = @import("Mini.zig"); +pub const mini = @import("mini.zig"); pub const Image = @import("image.zig"); @@ -649,7 +649,7 @@ test { _ = Text; _ = File; _ = Output; - _ = Mini; + _ = mini; _ = Image; _ = Pdf; _ = Terminal; diff --git a/test/output.zig b/test/output.zig index e5f87fb7..1b1b80c9 100644 --- a/test/output.zig +++ b/test/output.zig @@ -472,7 +472,7 @@ test "Mini syntax colors survive toggles themes and rendering without source acc defer p.deinit(); try p.panes[0].?.setOwnedCwd(dir); p.settings.colors = false; - try panes.Mini.open(p, 0, "demo.zig"); + try panes.mini.open(p, 0, "demo.zig"); const id = p.active; const mini = p.panes[id].?; const keyword = std.mem.indexOfScalar(u8, mini.file.?.mini.?.colors, @intFromEnum(pardes.syntax.Syn.keyword)) orelse return error.MissingKeywordColor; @@ -522,12 +522,12 @@ test "Mini failures leave its existing snapshot and focus unchanged" { const source = try p.setTestFile("abc\n"); var path_buf: [128]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{source.serial}); - try panes.Mini.open(p, 0, path); + try panes.mini.open(p, 0, path); const id = p.active; const mini = p.panes[id].?; const body = mini.file.?.content.ptr; const next = p.freeSlot(); - try std.testing.expectError(error.FileNotFound, panes.Mini.open(p, 0, "/virtual/does-not-exist")); + try std.testing.expectError(error.FileNotFound, panes.mini.open(p, 0, "/virtual/does-not-exist")); try std.testing.expectEqual(id, p.active); try std.testing.expectEqual(body, mini.file.?.content.ptr); try std.testing.expectEqual(next, p.freeSlot()); diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index 659e49d1..56a5da91 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1841,"med_us":2197,"p90_us":2308,"max_us":2328},{"op":"render","fixture":"medium","min_us":72,"med_us":81,"p90_us":84,"max_us":86},{"op":"key-down","fixture":"medium","min_us":74,"med_us":74,"p90_us":80,"max_us":81},{"op":"key-right","fixture":"medium","min_us":74,"med_us":80,"p90_us":85,"max_us":100},{"op":"page-down","fixture":"medium","min_us":74,"med_us":81,"p90_us":84,"max_us":176},{"op":"wheel","fixture":"medium","min_us":71,"med_us":75,"p90_us":79,"max_us":93},{"op":"edit-char","fixture":"medium","min_us":1086,"med_us":1515,"p90_us":1692,"max_us":1822},{"op":"body-2m","fixture":"medium","min_us":9044,"med_us":16111,"p90_us":19782,"max_us":21405}]} +{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2022,"med_us":2284,"p90_us":2363,"max_us":2431},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":90,"max_us":94},{"op":"key-down","fixture":"medium","min_us":79,"med_us":82,"p90_us":87,"max_us":97},{"op":"key-right","fixture":"medium","min_us":82,"med_us":83,"p90_us":91,"max_us":95},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":86},{"op":"wheel","fixture":"medium","min_us":79,"med_us":82,"p90_us":85,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1190,"med_us":1621,"p90_us":1843,"max_us":2008},{"op":"body-2m","fixture":"medium","min_us":9178,"med_us":16872,"p90_us":20886,"max_us":22596}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index bed59c8c..9c4b5ebe 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1800,"med_us":2113,"p90_us":2193,"max_us":2326},{"op":"render","fixture":"medium","min_us":71,"med_us":76,"p90_us":85,"max_us":97},{"op":"key-down","fixture":"medium","min_us":73,"med_us":76,"p90_us":82,"max_us":84},{"op":"key-right","fixture":"medium","min_us":72,"med_us":76,"p90_us":81,"max_us":95},{"op":"page-down","fixture":"medium","min_us":74,"med_us":78,"p90_us":83,"max_us":83},{"op":"wheel","fixture":"medium","min_us":72,"med_us":75,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1027,"med_us":1418,"p90_us":1699,"max_us":1834},{"op":"body-2m","fixture":"medium","min_us":8357,"med_us":17722,"p90_us":20080,"max_us":21699}]} +{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1902,"med_us":2386,"p90_us":2484,"max_us":2686},{"op":"render","fixture":"medium","min_us":83,"med_us":87,"p90_us":93,"max_us":118},{"op":"key-down","fixture":"medium","min_us":88,"med_us":94,"p90_us":100,"max_us":156},{"op":"key-right","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":92},{"op":"page-down","fixture":"medium","min_us":78,"med_us":84,"p90_us":89,"max_us":101},{"op":"wheel","fixture":"medium","min_us":77,"med_us":84,"p90_us":89,"max_us":132},{"op":"edit-char","fixture":"medium","min_us":1177,"med_us":1519,"p90_us":1721,"max_us":1909},{"op":"body-2m","fixture":"medium","min_us":8533,"med_us":15772,"p90_us":21361,"max_us":23276}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index d13442a5..984d480a 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1819,"med_us":2002,"p90_us":2068,"max_us":2122},{"op":"render","fixture":"medium","min_us":71,"med_us":76,"p90_us":88,"max_us":89},{"op":"key-down","fixture":"medium","min_us":73,"med_us":75,"p90_us":76,"max_us":82},{"op":"key-right","fixture":"medium","min_us":73,"med_us":77,"p90_us":86,"max_us":126},{"op":"page-down","fixture":"medium","min_us":71,"med_us":75,"p90_us":81,"max_us":83},{"op":"wheel","fixture":"medium","min_us":71,"med_us":74,"p90_us":76,"max_us":97},{"op":"edit-char","fixture":"medium","min_us":1036,"med_us":1493,"p90_us":1805,"max_us":1967},{"op":"body-2m","fixture":"medium","min_us":8482,"med_us":17227,"p90_us":20296,"max_us":23040}]} +{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2061,"med_us":2326,"p90_us":2462,"max_us":2503},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":86,"max_us":98},{"op":"key-down","fixture":"medium","min_us":78,"med_us":83,"p90_us":91,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":86,"max_us":90},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":90},{"op":"wheel","fixture":"medium","min_us":75,"med_us":82,"p90_us":87,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":1277,"med_us":1713,"p90_us":1948,"max_us":2063},{"op":"body-2m","fixture":"medium","min_us":9261,"med_us":17043,"p90_us":23512,"max_us":23722}]} diff --git a/test/perf.zig b/test/perf.zig index c639178f..38c640b4 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -1023,12 +1023,12 @@ const MiniMeasurement = struct { live_after_deinit: usize = 0, }; -fn checkMini(actual: pardes.panes.Mini.Result, expected: pardes.panes.Mini.Result) !void { +fn checkMini(actual: pardes.panes.mini.Result, expected: pardes.panes.mini.Result) !void { if (!std.mem.eql(u8, actual.content, expected.content) or !std.mem.eql(u8, actual.colors, expected.colors)) return error.MiniOutputMismatch; } -fn miniMeasurement(fallback: std.mem.Allocator, probe: MiniProbe, path: []const u8, source: []const u8, styles: []const u8, expected: pardes.panes.Mini.Result, reps: usize) !MiniMeasurement { +fn miniMeasurement(fallback: std.mem.Allocator, probe: MiniProbe, path: []const u8, source: []const u8, styles: []const u8, expected: pardes.panes.mini.Result, reps: usize) !MiniMeasurement { const samples = try gpa.alloc(u64, reps); defer gpa.free(samples); const allocators = pardes.memory.init(fallback); @@ -1059,7 +1059,7 @@ fn miniMeasurement(fallback: std.mem.Allocator, probe: MiniProbe, path: []const defer arena.deinit(); if (core) |p| { pump(p); - try pardes.panes.Mini.open(p, 0, path); + try pardes.panes.mini.open(p, 0, path); for (p.panes, 0..) |slot, id| if (slot != null and id != p.active) try p.removePane(id, null); pump(p); p.settings.colors = true; @@ -1095,7 +1095,7 @@ fn miniMeasurement(fallback: std.mem.Allocator, probe: MiniProbe, path: []const else styles; defer if (probe == .highlight_generate) syntax_allocator.free(highlighted); - const converted = try pardes.panes.Mini.generate(allocator, source, highlighted); + const converted = try pardes.panes.mini.generate(allocator, source, highlighted); const elapsed = nowNs() - begin; defer converted.deinit(allocator); if (index == 0) result.cold_ns = elapsed else samples[index - 1] = elapsed; @@ -1151,7 +1151,7 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool) defer gpa.free(styles); if (styles.len != source.len or std.mem.indexOfScalar(u8, styles, @intFromEnum(pardes.syntax.Syn.comment)) == null) return error.MiniSyntaxUnavailable; - const expected = try pardes.panes.Mini.generate(gpa, source, styles); + const expected = try pardes.panes.mini.generate(gpa, source, styles); defer expected.deinit(gpa); if (expected.content.len == 0 or expected.content.len != expected.colors.len or !std.unicode.utf8ValidateSlice(expected.content)) return error.InvalidMiniOutput; -- cgit v1.3 From 04b047fb366ea2c595708fb62467f690fce4b9ec Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 20:56:14 -0300 Subject: Terminal.zig is terminal.zig: a file of functions and no fields takes a namespace's lowercase name The last of the deferred renames, now that the tty and theme agents have landed: panes.terminal at its importers, the alias lines in Text.zig and File.zig and panes.zig's own uses following. dump.zig's Terminal struct, a dump record, is not this. The served sources list and docs/design.typ name the new file. test/perf.zig's references change, so the three perf baselines take its new harness id with their numbers as recorded. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- docs/design.typ | 2 +- src/File.zig | 6 +- src/Terminal.zig | 2670 ------------------------------- src/Text.zig | 18 +- src/body_layer.zig | 16 +- src/builtins.zig | 2 +- src/draw.zig | 8 +- src/dump.zig | 4 +- src/edit.zig | 26 +- src/exec.zig | 34 +- src/fs.zig | 2 +- src/host_io.zig | 2 +- src/layout.zig | 4 +- src/mouse.zig | 6 +- src/ninep/ctl.zig | 2 +- src/ninep/pane.zig | 4 +- src/ninep/pty.zig | 24 +- src/ninep/screen.zig | 4 +- src/panes.zig | 20 +- src/pardes.zig | 106 +- src/terminal.zig | 2670 +++++++++++++++++++++++++++++++ src/tty/tty.zig | 2 +- test/mode.zig | 2 +- test/panes.zig | 60 +- test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 16 +- 28 files changed, 2858 insertions(+), 2858 deletions(-) delete mode 100644 src/Terminal.zig create mode 100644 src/terminal.zig (limited to 'src/fs.zig') diff --git a/docs/design.typ b/docs/design.typ index ebbf213a..ec9bd5c4 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -526,7 +526,7 @@ verbatim by right-click and the delayed hover preview; that policy stays beside input because it also observes live pane selections and wrapped grid coordinates. Each pane kind keeps its storage and operations together in its own file -(`File.zig`, `Terminal.zig`, `Output.zig`, `mini.zig`, `pdf_view.zig`, and the +(`File.zig`, `terminal.zig`, `Output.zig`, `mini.zig`, `pdf_view.zig`, and the image pane in `image.zig`), reached through `panes.zig` beside `Pane`. `layout.zig` owns placement and presentation state. `pardes.zig` handles input and cross-pane state directly, without a pane vtable; the rest of the editor diff --git a/src/File.zig b/src/File.zig index c4040863..8babb27d 100644 --- a/src/File.zig +++ b/src/File.zig @@ -17,7 +17,7 @@ const locations = @import("locations.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; -const Terminal = panes.Terminal; +const terminal = panes.terminal; const Text = panes.Text; const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; @@ -782,7 +782,7 @@ pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { std.debug.assert(p.panes[id] == null and !p.reserved_slots[id]); const path_copy = try p.gpa.dupe(u8, path); errdefer p.gpa.free(path_copy); - const pane = try Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try terminal.createDoc(p.gpa, p.screen_w, p.screen_h); errdefer p.gpa.destroy(pane); const history = try History.create(p.gpa); errdefer p.gpa.destroy(history); @@ -1239,7 +1239,7 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) pub fn drawGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { const prefix_width = gutterWidth(pane); const goff = pane.scroll(); - const gcur = Terminal.gridCursor(pane); + const gcur = terminal.gridCursor(pane); const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice); const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); diff --git a/src/Terminal.zig b/src/Terminal.zig deleted file mode 100644 index c99a92a6..00000000 --- a/src/Terminal.zig +++ /dev/null @@ -1,2670 +0,0 @@ -//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay -//! typed over shell rows, and the Filter that recolours output to the theme. -const panes = @import("panes.zig"); -const std = @import("std"); -const pardes = @import("pardes.zig"); -const config = @import("config.zig"); -const Pardes = pardes.Pardes; -const Surface = pardes.Surface; -const modal = @import("modal.zig"); -const tracy = @import("tracy.zig"); -const dump = @import("dump.zig"); -const Key = pardes.Key; -const Pane = panes.Pane; -const EditText = panes.EditText; -const File = panes.File; - -pub const enabled = pardes.terminal_panes; -const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; - -pub const history_max = if (enabled) 64 else 8; - -pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; -pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; - -/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). -pub const prompt_aid = "pardes"; - -/// ghostty's handler, plus where the shell is in its command cycle as -/// its OSC 133 marks tell it: ghostty parses D's exit status and drops -/// it, and /pane//pty/run waits on exactly that. Only marks carrying -/// pardes's own `aid` move it, so fish's native marks, a nested shell's -/// and a stray `133;D` in some file being printed all pass it by. -pub const MarkedHandler = if (enabled) struct { - inner: ghostty_vt.TerminalStream.Handler, - phase: enum { none, prompt, input, running } = .none, - /// Counts commands started (C at the input phase). - started: u32 = 0, - /// Counts prompts drawn (B), so a line the shell refused without - /// running (a fish syntax error: no C, no D, a new prompt) shows. - prompts: u32 = 0, - /// D marks outside a running command: the shell handled a line - /// without starting it (bash on a syntax error prints no C). - declined: u32 = 0, - /// The newest prompt continues an unfinished line (bash's PS2, marked - /// `k=c`): the shell still holds the start of the command. - continuation: bool = false, - /// Where the newest command's output began (its C) and ended (its - /// D) on the primary screen, pinned so scrolling keeps them. - out_start: ?*ghostty_vt.Pin = null, - out_end: ?*ghostty_vt.Pin = null, - /// The running command's output was erased under it -- a clear, ED 3, - /// a reset -- so the pins no longer span what it printed: ED 3 moves - /// a pin to the next page without flagging it `garbage` - /// (PageList.erasePage). - lost: bool = false, - - /// The newest command to end: which one, and its status if given. - finished: ?struct { seq: u32, status: ?i32 } = null, - - const Action = ghostty_vt.TerminalStream.Action; - - /// Move one of the output pins to the cursor. Only the primary screen - /// is pinned: a command's own full-screen display is not its output. - fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { - const screen = self.inner.terminal.screens.get(.primary) orelse return; - if (slot.*) |old| screen.pages.untrackPin(old); - slot.* = null; - if (!now or self.inner.terminal.screens.active_key != .primary) return; - slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; - } - - pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { - if (comptime action == .semantic_prompt) mark: { - const aid = value.readOption(.aid) orelse break :mark; - if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; - switch (value.action) { - .fresh_line_new_prompt => { - self.phase = .prompt; - self.continuation = value.readOption(.prompt_kind) == .continuation; - }, - .end_prompt_start_input => { - self.phase = .input; - self.prompts +%= 1; - }, - // bash's DEBUG trap also fires on its own PROMPT_COMMAND, - // outside the input phase; only a C that ends input counts - .end_input_start_output => if (self.phase == .input) { - self.phase = .running; - self.started +%= 1; - self.lost = false; - self.pinCursor(&self.out_start, true); - self.pinCursor(&self.out_end, false); - }, - .end_command => if (self.phase == .running) { - self.phase = .none; - self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; - self.pinCursor(&self.out_end, true); - } else { - self.declined +%= 1; - }, - else => {}, - } - } - if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .full_reset) { - if (self.phase == .running) self.lost = true; - } - self.inner.vt(action, value); - } - - pub fn deinit(self: *@This()) void { - self.inner.deinit(); - } -} else void; - -pub const Replay = struct { - bytes: [1024 * 1024]u8 = undefined, - head: usize = 0, - len: usize = 0, -}; - -pub const State = struct { - vt: VtSlot, - stream: StreamSlot, - replay: Replay, - reply: [256]u8 = undefined, - reply_len: u16 = 0, -}; - -const GColor = ghostty_vt.color; - -const FilterPaletteKey = struct { - bg: GColor.RGB, - fg: GColor.RGB, - base: [16]GColor.RGB, -}; - -pub const FilterPalette = if (enabled) LivePalette else struct {}; - -const LivePalette = struct { - key: ?FilterPaletteKey = null, - colors: GColor.Palette = GColor.default, - - fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { - const bg = asGhostRgb(theme.bg orelse theme.tag_bg); - const fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var base: [16]GColor.RGB = undefined; - if (theme.palette) |palette| { - for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); - } else { - const synthesized = [16][3]u8{ - theme.bg orelse theme.tag_bg, - theme.kw, - theme.str, - theme.num, - theme.box, - theme.sel_bg, - theme.comment, - theme.fg orelse theme.tag_fg, - theme.lineno, - theme.kw, - theme.str, - theme.num, - theme.scroll_thumb, - theme.sel_fg, - theme.tag_fg, - theme.fg orelse theme.tag_fg, - }; - for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); - } - - const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; - if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; - - var seed = GColor.default; - for (base, 0..) |rgb, i| seed[i] = rgb; - self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); - self.key = key; - return &self.colors; - } -}; - -fn asGhostRgb(rgb: [3]u8) GColor.RGB { - return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; -} - -fn asPardesColor(rgb: GColor.RGB) pardes.Color { - return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; -} - -/// The owned text standing in for `rows` live terminal rows, beginning at -/// absolute surface row `row`. The emulator grid remains untouched underneath. -pub const EditBuffer = struct { - row: i32 = 0, - rows: i32 = 1, - text: []u8 = &.{}, -}; - -/// One whole-state terminal edit boundary. Null means the pane has not yet -/// materialized an edit buffer; non-null snapshots own their text. -pub const Snapshot = struct { - ovl: ?EditBuffer, - cur_row: i32, - cur_col: i32, - vsel: panes.Text.CharSel, -}; - -pub const PendingCommand = struct { - bytes: []u8 = &.{}, - wait: enum { none, spawn, input } = .none, -}; - -pub fn armShellSpawn(pane: *Pane) void { - if (comptime !enabled) return; - std.debug.assert(pane.pending_command.bytes.len == 0); - pane.pending_command.wait = .spawn; -} - -/// Remembers a line pardes types into this terminal as the command it -/// started, for Kill: it runs from the shell's next C mark to its D. -/// ponytail: of several lines queued for a shell not up yet, only the last -/// is remembered, as the first of them. -pub fn noteCommand(pane: *Pane, line: []const u8) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const word = std.mem.trim(u8, line, " \t")[0 .. std.mem.indexOfAny(u8, std.mem.trim(u8, line, " \t"), " \t") orelse std.mem.trim(u8, line, " \t").len]; - var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = state.stream.handler.started +% 1 }; - sent.len = @intCast(@min(word.len, sent.word.len)); - @memcpy(sent.word[0..sent.len], word[0..sent.len]); - pane.sent_command = sent; -} - -/// Whether the command pardes last typed here is running now. -pub fn commandRunning(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - const sent = pane.sent_command orelse return false; - const marks = &state.stream.handler; - return marks.phase == .running and marks.started == sent.seq; -} - -pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { - if (pane.pending_command.wait == .none) return false; - const old_len = pane.pending_command.bytes.len; - const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); - const bytes = if (old_len == 0) - try pane.gpa.alloc(u8, new_len) - else - try pane.gpa.realloc(pane.pending_command.bytes, new_len); - @memcpy(bytes[old_len..][0..command.len], command); - bytes[new_len - 1] = '\r'; - pane.pending_command.bytes = bytes; - pane.greet = false; - return true; -} - -pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { - const pane = p.panes[id] orelse return; - if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; - if (prompt_marks) { - pane.pending_command.wait = .input; - releasePendingCommand(p, id, pane, false); - } else { - pane.greet = false; - releasePendingCommand(p, id, pane, true); - } -} - -pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { - if (pane.pending_command.wait == .input) - releasePendingCommand(p, id, pane, promptInputReady(pane)); -} - -fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { - if (!ready) return; - const bytes = pane.pending_command.bytes; - pane.pending_command = .{}; - if (bytes.len > 0) { - p.emitWrite(id, bytes); - pane.gpa.free(bytes); - } -} - -pub fn deinitPendingCommand(pane: *Pane) void { - if (pane.pending_command.bytes.len > 0) - pane.gpa.free(pane.pending_command.bytes); - pane.pending_command = .{}; -} - -pub fn terminalIo() std.Io { - return if (comptime !pardes.hosted) - std.Io.failing - else - std.Io.Threaded.global_single_threaded.io(); -} - -/// The three numbers ghostty's scrollbar reports; all zero without an emulator. -pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; - -pub fn scrollbar(pane: *const Pane) Scrollbar { - if (comptime !enabled) return .{}; - const state = pane.terminal orelse return .{}; - const sb = state.vt.screens.active.pages.scrollbar(); - return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; -} - -/// The emulator's viewport offset, in SHELL rows: the top of what it shows. -pub fn gridOffset(pane: *const Pane) i32 { - return @intCast(scrollbar(pane).offset); -} - -/// Where the emulator itself puts the cursor, in active-area cells — the origin -/// without one, which is where an empty pane's cursor belongs anyway. -pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; - -pub fn gridCursor(pane: *const Pane) GridCursor { - if (comptime !enabled) return .{}; - const state = pane.terminal orelse return .{}; - const cur = state.vt.screens.active.cursor; - return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; -} - -pub fn visibleCursor(pane: *const Pane) ?GridCursor { - if (comptime !enabled) return null; - const state = pane.terminal orelse return null; - if (!state.vt.modes.get(.cursor_visible)) return null; - const cur = state.vt.screens.active.cursor; - const sb = scrollbar(pane); - const row = sb.total - sb.len + cur.y; - if (row < sb.offset or row - sb.offset >= sb.len) return null; - return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; -} - -/// Move the emulator's viewport by `delta` shell rows (negative scrolls back). -pub fn scrollGrid(pane: *Pane, delta: i32) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.vt.screens.active.scroll(.{ .delta_row = delta }); -} - -/// Is the viewport already showing the last row of output? -pub fn atBottom(pane: *const Pane) bool { - if (comptime !enabled) return true; - const sb = scrollbar(pane); - return sb.offset + sb.len >= sb.total; -} - -/// Snap the viewport back onto live output. -pub fn followOutput(pane: *Pane) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.vt.screens.active.scroll(.active); -} - -/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping -/// a scrollback; the next resize retries with the same numbers. -pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - if (cols != pane.cols) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; -} - -/// DECSET 2004: the program wants its pastes bracketed. -pub fn bracketedPaste(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.modes.get(.bracketed_paste); -} - -/// The program tracks the mouse itself, so a click in its body is its event. -pub fn reportsMouse(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - const m = &state.vt.modes; - return m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any); -} - -/// ...and wants them in SGR (1006) rather than the legacy X10 bytes. -pub fn mouseFormatSgr(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.modes.get(.mouse_format_sgr); -} - -/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body -/// reads and `Save` writes out. Logical lines: rows the terminal wrapped -/// are joined again (ghostty's wrap flags, as pty/run's output is), and -/// the last line ends with a newline. -pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { - if (comptime !enabled) return &.{}; - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - try writeScreenText(pane, &out.writer); - return out.toOwnedSlice(); -} - -fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const screen = state.vt.screens.active; - const br = screen.pages.getBottomRight(.screen) orelse return; - var both: TeeWriter = .{ .a = w }; - try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); - if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); -} - -/// Passes bytes through, remembering how many and the last one. -const TeeWriter = struct { - a: *std.Io.Writer, - count: usize = 0, - final: u8 = 0, - writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, - - fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { - const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); - var n: usize = 0; - for (data[0 .. data.len - 1]) |bytes| { - try t.a.writeAll(bytes); - t.note(bytes); - n += bytes.len; - } - const pattern = data[data.len - 1]; - for (0..splat) |_| { - try t.a.writeAll(pattern); - t.note(pattern); - n += pattern.len; - } - return n; - } - - fn note(t: *TeeWriter, bytes: []const u8) void { - if (bytes.len == 0) return; - t.count += bytes.len; - t.final = bytes[bytes.len - 1]; - } -}; - -/// How long `screenTextAlloc` would be, counted without keeping it: the -/// length a terminal's body reads as, which its ctl line reports. -pub fn screenTextLen(pane: *Pane) usize { - if (comptime !enabled) return 0; - var buf: [256]u8 = undefined; - var counting: std.Io.Writer.Discarding = .init(&buf); - writeScreenText(pane, &counting.writer) catch return 0; - return @intCast(counting.fullCount()); -} - -/// Release the emulator's heap. The Pane allocation itself is the core's. -pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.stream.deinit(); - state.vt.deinit(gpa); - gpa.destroy(state); - pane.terminal = null; -} - -/// Allocate the live emulator half of a terminal pane. Slot ownership, serial -/// assignment, and spawn effects remain core lifecycle invariants. -pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try createDoc(gpa, cols, rows); - errdefer gpa.destroy(pane); - if (comptime !enabled) return pane; - const state = try gpa.create(State); - errdefer gpa.destroy(state); - state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ - .cols = cols, - .rows = rows, - .max_scrollback = 16 * 1024 * 1024, - }); - state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); - state.replay.head = 0; - state.replay.len = 0; - state.reply_len = 0; - state.stream.handler.inner.effects.write_pty = ptyReport; - state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; - pane.terminal = state; - pane.tty_filter = true; - return pane; -} - -pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try gpa.create(Pane); - pane.* = .{ - .gpa = gpa, - .cols = cols, - .rows = rows, - }; - return pane; -} - -/// Where a restored terminal's history ends and its new shell begins. -pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; - -/// Rebuild a dump's terminal emulator from its recorded output. `live`: a -/// shell will be spawned into it, so the history is marked off from what -/// that shell prints and the pane waits for it like any new terminal. -/// Registration and tag/cwd policy stay with the core; raw VT replay and -/// viewport restoration belong here. -pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { - const terminal = src.terminal.?; - if (comptime !enabled) { - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - errdefer p.gpa.destroy(pane); - if (terminal.stream.len > 0) - pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; - return pane; - } - // An older dump's raw output tail cannot come back live: cut off mid - // redraw, or written at sizes the pane no longer has, it replays as - // garbage. Its rendered text can. - const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; - const bytes = if (legacy_text) - try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") - else if (terminal.stream_b64.len > 0) - try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) - else - &.{}; - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - if (live) { - if (bytes.len > 0) { - ingest(pane, bytes); - ingest(pane, restored_banner); - } - followOutput(pane); - // A view left scrolled back stays on what it was showing: the - // banner's line breaks scrolled a full screen by that many more. - if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); - armShellSpawn(pane); - } else if (bytes.len > 0) { - ingest(pane, bytes); - followOutput(pane); - if (src.scroll > 0) - scrollGrid(pane, -@as(i32, @intCast(src.scroll))); - } - return pane; -} - -/// Feed the emulator and retain the bounded suffix a dump can replay. Live -/// output and restoration share this byte path, then apply different views. -fn ingest(pane: *Pane, bytes: []const u8) void { - const state = pane.terminal.?; - const replay = &state.replay; - if (bytes.len >= replay.bytes.len) { - const kept = bytes[bytes.len - replay.bytes.len ..]; - @memcpy(&replay.bytes, kept); - replay.head = 0; - replay.len = replay.bytes.len; - } else { - const overflow = bytes.len -| (replay.bytes.len - replay.len); - replay.head = (replay.head + overflow) % replay.bytes.len; - replay.len -= overflow; - const tail = (replay.head + replay.len) % replay.bytes.len; - const first = @min(bytes.len, replay.bytes.len - tail); - @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); - @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); - replay.len += bytes.len; - } - state.stream.nextSlice(bytes); -} - -/// Return the replay ring in chronological order. Wrapped records are copied -/// into `allocator`; contiguous records remain a borrowed slice of the pane. -fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { - const state = pane.terminal orelse return &.{}; - const replay = &state.replay; - if (replay.len == 0) return &.{}; - if (replay.head + replay.len <= replay.bytes.len) - return replay.bytes[replay.head..][0..replay.len]; - const out = try allocator.alloc(u8, replay.len); - const first = replay.bytes.len - replay.head; - @memcpy(out[0..first], replay.bytes[replay.head..]); - @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); - 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 and enabled, 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 "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(!mouseFormatSgr(pane)); - try std.testing.expect(!promptInputReady(pane)); - scrollGrid(pane, 100); - followOutput(pane); - resizeGrid(pane, allocator, 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.expectEqualStrings("", try replayBytes(pane, allocator)); - try std.testing.expect(!failing.has_induced_failure); -} - -test "terminal state keeps parser fragments and sends emulator replies through its owner" { - if (comptime !enabled) return error.SkipZigTest; - 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); - try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); -} - -test "replay keeps a bounded chronological suffix across large writes and wrapping" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); - ingest(pane, "hello"); - const small = try replayBytes(pane, gpa); - try std.testing.expectEqualStrings("hello", small); - try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); - - const capacity = pane.terminal.?.replay.bytes.len; - const input = try gpa.alloc(u8, capacity + 7); - defer gpa.free(input); - @memset(input, 0); - const ending = "\x1b[31mred\x1b[0m\r\n"; - @memcpy(input[input.len - ending.len ..], ending); - ingest(pane, input); - try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); - ingest(pane, "next\r\n"); - const wrapped = try replayBytes(pane, gpa); - defer gpa.free(wrapped); - try std.testing.expectEqual(capacity, wrapped.len); - try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); - try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); -} - -test "replay restores terminal cells from the retained stream" { - if (comptime !enabled) 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, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); - defer gpa.free(encoded); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = pane.cols, - .rows = pane.rows, - .terminal = .{ .stream_b64 = encoded }, - }, false); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - const before = try screenTextAlloc(pane, gpa); - defer gpa.free(before); - const after = try screenTextAlloc(restored, gpa); - defer gpa.free(after); - try std.testing.expectEqualStrings(before, after); - try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); -} - -test "a restored command pane comes back finished, its command not run again" { - if (comptime !enabled or 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 p.newCommand(cmd, "/tmp", "make test"); - feedOutput(p, p.panes[cmd].?, "ok\r\n"); - p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); - try dump.dumpState(p); - const restored = try 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 !enabled or 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"); // `Tty bash`: it comes back as bash - try dump.dumpState(p); - const restored = try 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 "an older dump comes back live from its rendered text, not its raw output tail" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - // A tail cut mid-redraw: relative moves from a cursor it never set. - const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); - defer gpa.free(tail); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = 40, - .rows = 12, - .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, - }, true); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - defer deinitPendingCommand(restored); - const text = try screenTextAlloc(restored, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); -} - -/// Record and parse one live pty read, invalidate its motion surface, and -/// follow it only when the body (possibly parked under a tag edit) is raw. -pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { - // There are no pty reads at all without an emulator to parse them into. - if (comptime !enabled) return; - if (pane.terminal == null) return; - const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or - pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or - pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; - // Sticky bottom, as every other terminal does it: output drags the - // viewport down only when the viewport was already on the last row, so - // a reader scrolled back into the scrollback stays where they scrolled. - const at_bottom = atBottom(pane); - if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); - p.shell_rows.markStale(pane); - if (pane.body.mode == .tty and at_bottom) followOutput(pane); -} - -const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; -const PositionPin = struct { - target: *i32, - row: RowPin, - overlay: ?*EditBuffer, - edit_row: ?i32 = null, -}; - -fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { - if (row < 0) return .{ .offset = row }; - const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); - var left = pages.total_rows - 1 - bounded; - var node = pages.pages.last.?; - while (left >= node.rows()) { - left -= node.rows(); - node = node.prev.?; - } - const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { - failed.* = true; - return .{}; - }; - return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; -} - -fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { - const pin = row.pin orelse return row.offset; - const alive = pages orelse return 0; - if (pin.garbage) return 0; - var after: usize = 0; - var node = alive.pages.last; - while (node) |item| : (node = item.prev) { - if (item == pin.node) - return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; - after += item.rows(); - } - return 0; -} - -fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { - var grid = target.*; - if (overlay) |edit| { - const lines: i32 = @intCast(modal.lineCount(edit.text)); - if (grid >= edit.row and grid < edit.row +| lines) - return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; - if (grid > edit.row) grid = grid -| lines +| edit.rows; - } - return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; -} - -fn pointerRowCount(pane: *const Pane) usize { - var count: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - count += rows.len; - }; - return count; -} - -fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { - const screens = &pane.terminal.?.vt.screens; - const key = screens.active_key; - const generation = screens.generation(key); - const pages = &screens.active.pages; - const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; - var groups: [history_max * 2 + 1]Group = undefined; - groups[0] = .{ - .overlay = if (pane.ovl) |*overlay| overlay else null, - .cursor = &pane.body.cur_row, - .selection = &pane.body.vsel, - }; - var ngroups: usize = 1; - for ([_][]Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { - for (history) |*snapshot| { - groups[ngroups] = .{ - .overlay = if (snapshot.ovl) |*overlay| overlay else null, - .cursor = &snapshot.cur_row, - .selection = &snapshot.vsel, - }; - ngroups += 1; - } - } - const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; - var spans: [groups.len]Span = undefined; - var nspans: usize = 0; - var positions: [groups.len * 2 + panes.Text.max_selections * 2 + 4]PositionPin = undefined; - var npositions: usize = 0; - var failed = false; - for (groups[0..ngroups]) |group| { - if (group.overlay) |overlay| { - spans[nspans] = .{ - .overlay = overlay, - .start = trackRow(pages, overlay.row, &failed), - .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), - }; - nspans += 1; - } - positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); - npositions += 1; - if (group.selection.active) { - positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); - npositions += 1; - } - } - const overlay = groups[0].overlay; - var extra: [panes.Text.max_selections * 2 + 4]*i32 = undefined; - var nextra: usize = 0; - if (pane.body.msel.active) { - extra[nextra] = &pane.body.msel.r0; - extra[nextra + 1] = &pane.body.msel.r1; - nextra += 2; - } - for (pane.body.sels[0..pane.body.nsel]) |*selection| { - extra[nextra] = &selection.row; - extra[nextra + 1] = &selection.arow; - nextra += 2; - } - if (pane.body.last_edit) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - if (pane.look_at) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - for (extra[0..nextra]) |target| { - positions[npositions] = trackPosition(pages, target, overlay, &failed); - npositions += 1; - } - const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; - defer if (pointer_positions) |pins| pane.gpa.free(pins); - if (pointer_positions) |pins| { - var index: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - for (rows) |*row| { - pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); - index += 1; - } - }; - } else failed = true; - ingest(pane, bytes); - // RIS can destroy the alternate screen and every pin it owned. - const alive = if (screens.generation(key) == generation) pages else null; - var moved = false; - var pointer_rows_lost = alive == null or pointer_positions == null; - if (pointer_positions) |pins| for (pins) |position| { - if (alive != null) if (position.row.pin) |pin| { - if (pin.garbage) pointer_rows_lost = true; - }; - }; - for (spans[0..nspans]) |span| { - const start = pinnedRow(alive, span.start); - const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); - moved = moved or start != span.overlay.row or rows != span.overlay.rows; - span.overlay.row = start; - span.overlay.rows = rows; - if (alive) |owner| { - if (span.start.pin) |pin| owner.untrackPin(pin); - if (span.end.pin) |pin| owner.untrackPin(pin); - } - } - for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { - var row = pinnedRow(alive, position.row); - if (position.overlay) |edit| { - if (position.edit_row) |relative| { - row = edit.row +| relative; - } else if (row > edit.row) { - row = if (row < edit.row +| edit.rows) - edit.row - else - row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); - } - } - moved = moved or row != position.target.*; - position.target.* = row; - if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); - }; - if (pointer_rows_lost) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. - if (failed) { - const message = "terminal edit position reset: out of memory"; - @memcpy(pane.msg[0..message.len], message); - pane.msg_len = message.len; - } -} - -test "raw terminal output needs no position tracking allocations" { - if (comptime !enabled) return error.SkipZigTest; - 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 { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active_key == .alternate; -} - -/// Whether a new terminal's greeting may be typed now: only at the shell's -/// first prompt (pardes's own marks: no command started; a prompt drawn -/// again for a resize is the same first prompt), with nothing -/// typed at it and no program on the alternate screen. Any later moment is `.never`, for good: something has run or -/// been typed first, and an `ls` then would go into it. A shell pardes -/// cannot mark has no first prompt to find, and is never greeted. -pub fn greeting(pane: *const Pane) enum { wait, now, never } { - if (comptime !enabled) return .never; - if (pane.fs.unmarked) return .never; - // Text typed into the edit buffer that stands in for the prompt row. - if (pane.ovl) |o| if (o.text.len > 0) return .never; - const state = pane.terminal orelse return .wait; - const marks = &state.stream.handler; - // (Not `declined`: bash's first prompt comes after a D of its own.) - if (marks.started > 0) return .never; - // At a prompt's input (ghostty's semantic marks, pardes's or the - // shell's own), before any command pardes's marks saw run. - if (!promptInputReady(pane)) return .wait; - return if (promptInputEmpty(pane)) .now else .never; -} - -pub fn promptInputReady(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active_key != .alternate and - state.vt.screens.active.cursor.semantic_content == .input; -} - -pub const CommandOutput = struct { - /// Owned by the caller. - text: [:0]const u8, - /// Whether `text` starts where the command did. It does not when that - /// start is not there to read: cut off by `max_rows`, scrolled out of - /// the history (ghostty moved the pin to the oldest row it kept and - /// flagged it `garbage`), erased under it (`MarkedHandler.lost`), or - /// never pinned (a C or D that came on the alternate screen). - whole: bool, -}; - -/// What the newest finished command printed: the screen text between its -/// C and D marks, read from at most `max_rows` rows above its end, so a -/// command that printed the whole history costs no more than its tail. -/// The shell exited in the middle of a command (its `exit 3`): no end mark -/// will come, so the command's output ends where the cursor is. -pub fn endOutputHere(pane: *Pane) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const marks = &state.stream.handler; - if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); -} - -pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { - // Unless there is text to read, whether the nothing it printed is the - // whole of it. - const whole = if (comptime enabled) printed: { - const state = pane.terminal orelse break :printed true; - const marks = &state.stream.handler; - const start = marks.out_start orelse break :printed false; - const end = marks.out_end orelse break :printed false; - const screen = state.vt.screens.get(.primary) orelse break :printed false; - if (end.garbage) break :printed false; - var whole = !marks.lost and !start.garbage; - // D is where the next prompt begins: the output ends a cell before. - const last = end.leftWrap(1) orelse break :printed whole; - if (start.eql(end.*) or last.before(start.*)) break :printed whole; - var from = start.*; - if (last.up(max_rows)) |floor| if (from.before(floor)) { - from = floor; - from.x = 0; - whole = false; - }; - return .{ - .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), - .whole = whole, - }; - } else true; - return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; -} - -/// At a prompt with nothing typed on its line: no input left of the -/// cursor and none under it (text typed and then Ctrl-A'd starts at the -/// cursor). Nothing further right counts: that is where fish draws a -/// right prompt, and fish suggests nothing on an empty line. -pub fn promptInputEmpty(pane: *const Pane) bool { - if (comptime !enabled) return false; - if (!promptInputReady(pane)) return false; - const cursor = &pane.terminal.?.vt.screens.active.cursor; - const row = cursor.page_pin.cells(.all); - for (row[0..@min(cursor.x + 1, row.len)]) |cell| - if (cell.semantic_content == .input and !cell.isEmpty()) return false; - return true; -} - -/// Encode one key for the program that owns a raw terminal and queue its pty -/// write, respecting the application's keyboard protocol and terminal modes. -pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { - if (comptime enabled) { - const pane = p.panes[id] orelse return; - const state = pane.terminal orelse return; - const input = ghostty_vt.input; - const function_keys = comptime keys: { - var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; - for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); - break :keys keys; - }; - const physical: input.Key = switch (key.cp) { - Key.enter => .enter, - Key.backspace => .backspace, - Key.tab => .tab, - Key.escape => .escape, - Key.up => .arrow_up, - Key.down => .arrow_down, - Key.left => .arrow_left, - Key.right => .arrow_right, - Key.home => .home, - Key.end => .end, - Key.page_up => .page_up, - Key.page_down => .page_down, - Key.delete => .delete, - Key.insert => .insert, - Key.print_screen => .print_screen, - Key.scroll_lock => .scroll_lock, - Key.pause => .pause, - Key.menu => .context_menu, - Key.f1...Key.f25 => function_keys[key.cp - Key.f1], - else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, - }; - var utf8: [4]u8 = undefined; - const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; - // A key with no text of its own types its code point only when that - // is a character: the kitty keyboard protocol numbers function and - // modifier keys in the private use area (F3 is U+E016), and a shell - // was typed those as junk. - const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) - utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] - else - ""; - var buffer: [256]u8 = undefined; - var writer = std.Io.Writer.fixed(&buffer); - input.encodeKey(&writer, .{ - .key = physical, - .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, - .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, - .utf8 = text, - .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, - }, options: { - var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); - // fromTerminal cannot know this one and says so, defaulting to - // "option is not alt" — right for an app that lets macOS do the - // unicode translation and hands the encoder the composed text. - // Every pardes shell resolves the modifier itself and hands the - // core the BASE key with the alt bit and no text at all (see - // PardesView.keyDown, and app.mjs doing the same with the same - // two bits), so by the time this runs alt already means alt. - // Left at the default, a macOS build drops the ESC prefix on - // the floor and forwards Alt-n to the child as a bare `n`. - opts.macos_option_as_alt = .true; - break :options opts; - }) catch return; - if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); - return; - } - var control: [1]u8 = undefined; - const bytes: ?[]const u8 = blk: { - if (key.ctrl) { - if (key.cp >= 'a' and key.cp <= 'z') { - control[0] = @intCast(key.cp - 0x60); - break :blk control[0..1]; - } - // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. - if (key.cp >= '@' and key.cp <= '_') { - control[0] = @intCast(key.cp - 0x40); - break :blk control[0..1]; - } - } - if (key.text.len > 0) break :blk key.text; - break :blk switch (key.cp) { - Key.enter => "\r", - Key.backspace => "\x7f", - Key.tab => "\t", - Key.escape => "\x1b", - Key.up => "\x1b[A", - Key.down => "\x1b[B", - Key.right => "\x1b[C", - Key.left => "\x1b[D", - Key.delete => "\x1b[3~", - else => null, - }; - }; - if (bytes) |encoded| - p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); -} - -pub fn enterTty(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; - if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { - const screen = pane.terminal.?.vt.screens.active; - const goff: i32 = @intCast(screen.pages.scrollbar().offset); - const vp_row = pane.gridRow(pane.body.cur_row) - goff; - if (vp_row < 0) break :handoff; - - var grid_col: i32 = @max(0, pane.body.cur_col); - if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { - if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { - .cut => |cols| grid_col += @intCast(cols), - .keep, .blank => {}, - }; - } - const click_pin = screen.pages.pin(.{ - .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, - }) orelse break :handoff; - const cursor_pin = screen.cursor.page_pin.*; - var prompts = cursor_pin.promptIterator(.left_up, null); - const prompt_pin = prompts.next() orelse break :handoff; - if (click_pin.before(prompt_pin)) break :handoff; - const moves = screen.promptClickMove(click_pin); - for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); - for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); - }; - - pane.body.mode = .tty; - followOutput(pane); // entering raw mode is a request for the live shell - pane.body.msel.active = false; - pane.body.vsel.active = false; - pane.body.nsel = 0; - // The raw renderer follows the live cursor. A captured mouse selection - // keeps its modal endpoint for the next return to editor mode. - pane.body.cur_pinned = selected; - pane.body.select = false; - pane.body.restore_cursor = false; - pane.body.sticky_col = -1; - pane.body.normal.clear(); -} - -// Returned slices remain valid until the next cache rebuild or reset. -pub const RowsCache = struct { - /// whose grid this describes; null = the slot is free - pane: ?*const Pane = null, - /// the rows joined by '\n' — `flatSurface` hands this back verbatim - /// instead of rebuilding the join on every keystroke - text: []const u8 = &.{}, - /// slices INTO `text`, absolute grid rows from 0 - rows: [][]const u8 = &.{}, - /// `text` is a prefix of this: blanking a prompt row shortens the join, - /// and the slack is not worth a second allocation to reclaim - text_alloc: []u8 = &.{}, - stale: bool = false, - - pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.text_alloc.len > 0) gpa.free(c.text_alloc); - if (c.rows.len > 0) gpa.free(c.rows); - c.* = .{}; - } - - /// Free a stale entry. Called at the top of `update`, and nowhere else. - pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.stale) c.reset(gpa); - } - - /// `pane`'s grid moved: the entry no longer describes it. - pub fn markStale(c: *RowsCache, pane: *const Pane) void { - if (c.pane == pane) c.stale = true; - } - - pub fn dropPane(c: *RowsCache, pane: *const Pane) void { - if (c.pane != pane) return; - c.pane = null; - c.stale = true; - } -}; - -const Rows = struct { - text_alloc: []u8, - text: []const u8, - rows: [][]const u8, -}; - -const empty_grid = [1][]const u8{""}; - -/// What LEAVING raw tty mode does to one prompt row, decided from its cells -/// alone. See config.tty_blank for why any of this happens. -const PromptCut = union(enum) { - /// show the row exactly as ghostty dumped it - keep, - /// show nothing at all - blank, - /// drop this many leading COLUMNS — the prompt — and keep the rest, which - /// is what was typed at it - cut: usize, -}; - -fn promptCut(pin: ghostty_vt.Pin) PromptCut { - if (config.tty_blank == .prompt_and_input) return .blank; - const cells = pin.cells(.all); - var cols: usize = 0; - while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; - // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or - // a repaint that has moved on. Nothing here is the prompt, so hide nothing. - if (cols == 0) return .keep; - // ...and all prompt, nothing typed yet: the row is chrome end to end. - if (cols >= cells.len) return .blank; - return .{ .cut = cols }; -} - -pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { - if (comptime !enabled) return 0; - if (row < 0) return 0; - const state = pane.terminal orelse return 0; - const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; - if (pin.rowAndCell().row.semantic_prompt == .none) return 0; - return switch (promptCut(pin)) { - .keep => 0, - .blank => raw.len, - .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), - }; -} - -fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { - const cols = switch (promptCut(pin)) { - .keep => return raw, - .blank => return "", - .cut => |n| n, - }; - const cells = pin.cells(.all); - var at: usize = 0; - var col: usize = 0; - while (col < cols and at < raw.len) { - const cell = &cells[col]; - at = @min(raw.len, at + dumpedBytes(pin, cell)); - // the tail cell of a wide glyph spells nothing of its own - col += if (cell.wide == .wide) @as(usize, 2) else 1; - } - return std.mem.trimEnd(u8, raw[at..], " \t"); -} - -fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { - switch (cell.wide) { - .spacer_head, .spacer_tail => return 0, - .narrow, .wide => {}, - } - var n: usize = switch (cell.content_tag) { - .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( - cell.codepoint(), - ) catch 1, - // A cell carrying only a colour still spells one blank in the dump. - else => 1, - }; - if (cell.content_tag == .codepoint_grapheme) { - if (pin.grapheme(cell)) |extra| for (extra) |cp| { - n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; - }; - } - return n; -} - -pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { - if (comptime !enabled) return &empty_grid; - if (pane.terminal == null) return &empty_grid; - const c = &p.shell_rows; - if (!c.stale and c.pane == pane) return c.rows; - if (c.pane != null) { - c.stale = true; - return (try buildRows(p.scratch.allocator(), p, pane)).rows; - } - const built = try buildRows(p.gpa, p, pane); - c.* = .{ - .pane = pane, - .text = built.text, - .rows = built.rows, - .text_alloc = built.text_alloc, - }; - return c.rows; -} - -/// 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 { - const rows = try shellRows(p, pane); - if (pane.ovl == null) return rows; - var last = rows.len; - if (pane.ovl) |overlay| - last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); - var count = last; - if (pane.ovl) |overlay| { - if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) - count = count - @min( - @as(usize, @intCast(overlay.rows)), - last - @as(usize, @intCast(overlay.row)), - ) + @max(1, modal.lineCount(overlay.text)); - } - const lines = try p.scratch.allocator().alloc([]const u8, count); - var n: usize = 0; - var grid_row: usize = 0; - while (grid_row < last) : (grid_row += 1) { - if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { - var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); - while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; - grid_row += @intCast(overlay.rows - 1); - continue; - }; - lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; - n += 1; - } - return lines[0..n]; -} - -/// Flatten `cursorLines` without rebuilding the common cached/no-overlay -/// case. Scratch-owned when a join is required. -pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { - const cache = &p.shell_rows; - if (!cache.stale and cache.pane == pane and - lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; - var total: usize = if (lines.len > 0) lines.len - 1 else 0; - for (lines) |line| total += line.len; - const text = try p.scratch.allocator().alloc(u8, total); - var at: usize = 0; - for (lines, 0..) |line, i| { - if (i > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..line.len], line); - at += line.len; - } - return text; -} - -/// Materialize or extend the terminal edit overlay with one exact allocation. -/// Row slices are scratch-owned/borrowed; only the joined text is installed. -pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { - const want_lo = @max(0, @min(lo, hi)); - const want_hi = @max(want_lo, @max(lo, hi)); - const fresh = pane.ovl == null; - const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; - const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); - const up = old.row - want_lo; - const down = want_hi - (old.row + lines - 1); - const extending = fresh or up > 0 or down > 0; - var row0 = old.row; - var covered = old.rows; - var text = old.text; - var owned = false; - if (extending) { - const rows = shellRows(p, pane) catch return null; - row0 = old.row - @max(0, up); - covered = old.rows + @max(0, up) + @max(0, down); - const up_len: usize = @intCast(@max(0, up)); - const down_len: usize = @intCast(@max(0, down)); - const parts = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; - for (parts[0..up_len], 0..) |*part, i| { - const src = @as(usize, @intCast(row0)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - const middle: usize = @intCast(old.row); - parts[up_len] = if (fresh) - (if (middle < rows.len) rows[middle] else "") - else - old.text; - for (parts[up_len + 1 ..], 0..) |*part, i| { - const src = @as(usize, @intCast(old.row + old.rows)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - text = std.mem.join(p.gpa, "\n", parts) catch return null; - owned = true; - } - - const row: usize = @intCast(@max(0, want_lo - row0)); - const line_len: i32 = @intCast(modal.lineSlice(text, row).len); - if (col > line_len) { - const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { - if (owned) p.gpa.free(text); - return null; - }; - @memset(spaces, ' '); - const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { - if (owned) p.gpa.free(text); - return null; - }; - if (owned) p.gpa.free(text); - text = padded; - owned = true; - } - if (owned) { - if (pane.ovl) |overlay| p.gpa.free(overlay.text); - pane.ovl = .{ .row = row0, .rows = covered, .text = text }; - } - return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; -} - -/// Consume a rewritten overlay, freeing the terminal edit text it replaces. -pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { - const overlay = if (pane.ovl) |*value| value else return pardes.edit.retireEditText(p, new); - for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - } - p.gpa.free(overlay.text); - overlay.text = new; -} - -/// The shell's screen and scrollback (the primary screen, even under a -/// full-screen program) as VT that replays to what was shown: styled -/// text, soft-wrapped lines rejoined so they reflow at another width. -fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { - const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; - var out: std.Io.Writer.Allocating = .init(arena); - try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); - return out.written(); -} - -/// Serialize terminal-only state; the core supplies shared pane metadata. -pub fn dumpPane( - pane: *Pane, - arena: std.mem.Allocator, - tag: []const u8, - body: []const u8, - scroll: usize, -) !dump.Pane { - if (!enabled or pane.terminal == null) { - const text = if (pane.ovl) |overlay| overlay.text else ""; - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .shell = try arena.dupe(u8, pane.shell orelse ""), - .command = try arena.dupe(u8, pane.command orelse ""), - .status = pane.command_status, - .stream = try arena.dupe(u8, text), - .stream_b64 = &.{}, - .cursor = .{ .col = 0, .row = 0 }, - }, - }; - } - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); - const extra = if (pane.ovl) |overlay| overlay.text.len else 0; - const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); - var len: usize = 0; - var lines = std.mem.splitAny(u8, full, "\n"); - var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - var row: i32 = 0; - var skip: i32 = 0; - while (lines.next()) |raw| : (row += 1) { - // Hidden overlay rows still consume prompt pins to keep them aligned. - const prompt = if (pane.body.mode != .tty) prompts.next() else null; - if (skip > 0) { - skip -= 1; - continue; - } - if (row > 0) { - stream[len] = '\n'; - len += 1; - } - if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { - @memcpy(stream[len..][0..overlay.text.len], overlay.text); - len += overlay.text.len; - skip = overlay.rows - 1; - continue; - }; - const shown = if (prompt) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - @memcpy(stream[len..][0..shown.len], shown); - len += shown.len; - } - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .shell = try arena.dupe(u8, pane.shell orelse ""), - .command = try arena.dupe(u8, pane.command orelse ""), - .status = pane.command_status, - .stream = stream[0..len], - .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), - .stream_is_screen = true, - .cursor = .{ - .col = pane.terminal.?.vt.screens.active.cursor.x, - .row = pane.terminal.?.vt.screens.active.cursor.y, - }, - }, - }; -} - -fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); - var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - // split yields one more item than delimiters; the extra final slot is the - // cursor row retained below. - const n_rows = std.mem.count(u8, full, "\n") + 2; - const rows = try alloc.alloc([]const u8, n_rows); - errdefer alloc.free(rows); - // Blanking a prompt row only ever SHORTENS it and the retained cursor row - // adds one separator, so the dump's length plus one bounds the join. - const text = try alloc.alloc(u8, full.len + 1); - errdefer alloc.free(text); - var at: usize = 0; - var n: usize = 0; - var it = std.mem.splitScalar(u8, full, '\n'); - while (it.next()) |raw| { - const shown = if (pit.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - if (n > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..shown.len], shown); - rows[n] = text[at..][0..shown.len]; - at += shown.len; - n += 1; - } - text[at] = '\n'; - at += 1; - rows[n] = text[at..][0..0]; - n += 1; - std.debug.assert(n == n_rows); - return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; -} - -pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { - const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { - const state = pane.terminal orelse break :vp &.{}; - const screen = state.vt.screens.active; - var tl = screen.pages.getTopLeft(.viewport); - tl.x = 0; - const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; - var rows_out: std.Io.Writer.Allocating = .init(arena); - try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); - const raw = try rows_out.toOwnedSlice(); - var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); - const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); - var lines = std.mem.splitScalar(u8, raw, '\n'); - var n: usize = 0; - while (lines.next()) |ln| { - vp[n] = if (pane.body.mode != .tty) - if (prompts.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln - else - ln - else - ln; - n += 1; - } - std.debug.assert(n == vp.len); - break :vp vp; - }; - - const len = fillBody(null, pane, vp); - const out = try arena.alloc(u8, len); - const filled = fillBody(out, pane, vp); - std.debug.assert(filled == out.len); - return out; -} - -pub const BodyRow = union(enum) { - grid: i32, - edit: struct { line: []const u8, idx: usize }, -}; - -const BodyWalk = struct { - pane: *Pane, - goff: i32, - g: i32, - /// the buffer can start above the viewport: drop the lines scrolled past - skip: usize, - n: usize = 0, - lines: ?std.mem.SplitIterator(u8, .scalar) = null, - covered: i32 = 0, - line_idx: usize = 0, - - fn init(pane: *Pane) BodyWalk { - const off = pane.scroll(); - const goff = gridOffset(pane); - return .{ - .pane = pane, - .goff = goff, - .g = if (pane.body.mode == .tty) goff else pane.gridRow(off), - .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, - }; - } - - fn next(w: *BodyWalk) ?BodyRow { - while (w.n < w.pane.rows) { - if (w.lines) |*it| { - if (it.next()) |line| { - const idx = w.line_idx; - w.line_idx += 1; - // Lines scrolled off the top still count: the index names a - // line of the BUFFER, not of the visible body. - if (w.skip > 0) { - w.skip -= 1; - continue; - } - w.n += 1; - return .{ .edit = .{ .line = line, .idx = idx } }; - } - // The buffer stands in for `rows` shell rows however many lines - // it actually spelled, which is the whole slide. - w.g += w.covered; - w.skip = 0; - w.lines = null; - continue; - } - if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { - w.lines = std.mem.splitScalar(u8, o.text, '\n'); - w.covered = o.rows; - w.line_idx = 0; - continue; - }; - const vi = w.g - w.goff; - w.g += 1; - w.n += 1; - return .{ .grid = vi }; - } - return null; - } -}; - -/// Run the terminal body row walk. A null destination counts bytes; a slice -/// fills the exact allocation made from that count. -fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { - var walk: BodyWalk = .init(pane); - var written: usize = 0; - var first = true; - while (walk.next()) |row| { - if (!first) { - if (dst) |out| out[written] = '\n'; - written += 1; - } - first = false; - const bytes = switch (row) { - .edit => |e| e.line, - .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) - viewport[@intCast(vi)] - else - "", - }; - if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); - written += bytes.len; - } - return written; -} - -// Match surviving edit-buffer rows to their original terminal styles. -const EditAnchors = struct { - /// the buffer's own text, walked in order: a line the VIEWPORT skipped still - /// consumes the row it came from, so the lines below it stay aligned - text: []const u8 = &.{}, - at: usize = 0, - shell: []const []const u8 = &.{}, - /// the covered span, absolute grid rows, as `[first, end)` - first: usize = 0, - end: usize = 0, - lines: usize = 0, - /// the line `at` names, and the first row still unclaimed - idx: usize = 0, - cursor: usize = 0, - budget: usize = 0, - active: bool = false, - - fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { - if (o.rows <= 0 or o.row < 0) return .{}; - const first: usize = @intCast(o.row); - const screen = pane.terminal.?.vt.screens.active; - const total = screen.pages.scrollbar().total; - if (first >= total) return .{}; - const covered: usize = @intCast(o.rows); - const count = @min(covered, total - first); - const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; - const br = screen.pages.pin(.{ .screen = .{ - .x = screen.pages.cols - 1, - .y = @intCast(first + count - 1), - } }) orelse return .{}; - const arena = p.scratch.allocator(); - var output: std.Io.Writer.Allocating = .init(arena); - screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; - const shell = arena.alloc([]const u8, count) catch return .{}; - var raw = std.mem.splitScalar(u8, output.written(), '\n'); - var pins = tl.rowIterator(.right_down, br); - for (shell) |*row| { - const text = raw.next() orelse ""; - row.* = if (pins.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text - else - text; - } - const lines = std.mem.count(u8, o.text, "\n") + 1; - return .{ - .text = o.text, - .shell = shell, - .first = first, - .end = first + count, - .lines = lines, - .cursor = first, - .budget = covered + 4 * lines, - .active = true, - }; - } - - fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { - if (!a.active or idx >= a.lines) return null; - var found: ?Anchor = null; - while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); - return found; - } - - fn nextLine(a: *EditAnchors) ?[]const u8 { - if (a.at > a.text.len) return null; - const rest = a.text[a.at..]; - if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { - a.at += n + 1; - return rest[0..n]; - } - // The last line has no terminator; one past the end ends the walk. - a.at = a.text.len + 1; - return rest; - } - - /// Where this line still stands over the grid, if anywhere. - fn claim(a: *EditAnchors, line: []const u8) ?Anchor { - const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; - var k = a.cursor; - while (k < end) : (k += 1) { - if (a.budget == 0) return null; - a.budget -= 1; - if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; - a.cursor = k + 1; - return .{ .row = @intCast(k) }; - } - if (a.cursor >= a.end) return null; - const shell = a.shell[a.cursor - a.first]; - var p: usize = 0; - while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; - var s: usize = 0; - const room = @min(line.len, shell.len) - p; - while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; - if (p + s == 0) return null; - if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; - const row = a.cursor; - if (s > 0 or p >= shell.len) a.cursor += 1; - return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; - } -}; - -const Anchor = struct { - /// the row, absolute while it comes from `EditAnchors`, viewport once - /// `recolorAnsi` has subtracted the walk's offset - row: i32, - prefix: usize = std.math.maxInt(usize), - suffix: usize = 0, - /// the row's own dumped length — what the suffix is measured from on the - /// GRID side, where the edit may have changed the byte count - shell_len: usize = 0, - - fn whole(an: Anchor) bool { - return an.prefix == std.math.maxInt(usize); - } -}; - -pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { - // No emulator, no ANSI cells: the whole pass — and the 256-colour theme - // projection behind it — is compiled out. - if (comptime !enabled) return; - if (pane.terminal == null) return; - const body_y = p.bodyTop(pane, r); - var filtered_storage: FilteredColors = undefined; - const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { - const tz_filter = tracy.zone(@src(), "filterInit"); - defer tz_filter.end(); - filtered_storage = FilteredColors.init(p, pane); - break :blk &filtered_storage; - } else null; - // DECSCNM, read once: the filtered palette folds it in itself, the raw - // path needs it per cell. - const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); - const pages = &pane.terminal.?.vt.screens.active.pages; - const vp_rows: i32 = @intCast(scrollbar(pane).len); - // Which buffer lines the user has not actually changed, so a row swallowed - // by a growing buffer keeps the colour it still stands over. - var anchors: ?EditAnchors = null; - var walk: BodyWalk = .init(pane); - var lines = std.mem.splitScalar(u8, body, '\n'); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - // Before any early exit below, or the lines fall out of step with rows. - const text = lines.next() orelse ""; - const anchor: Anchor = switch (row) { - .edit => |e| blk: { - if (anchors == null) anchors = .init(p, pane, pane.ovl.?); - var an = anchors.?.shellRow(e.idx) orelse continue; - an.row -= walk.goff; - break :blk an; - }, - .grid => |v| .{ .row = v }, - }; - const vi = anchor.row; - if (vi < 0 or vi >= vp_rows) continue; - const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { - if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; - break :cut switch (promptCut(row_pin)) { - .keep => 0, - // Blanked end to end: the row shows nothing of the grid, so - // projecting the prompt's own colours onto it would be a lie. - .blank => continue, - .cut => |n| std.math.cast(u16, n) orelse continue, - }; - }; - if (cut > 0 and text.len == 0) continue; - var at: usize = 0; - var sc: u16 = 0; - var gc: u16 = cut; - var sb: usize = 0; - const mine_from = @min(anchor.prefix, text.len); - const mine_to = text.len - @min(anchor.suffix, text.len); - var crossed = false; - while (at < text.len and sc < tw) { - const stop = modal.nextGrapheme(text, at); - if (stop <= at) break; - const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; - if (at >= mine_from and at < mine_to) { - sc += span; - at = stop; - continue; - } - if (at >= mine_to and !crossed) { - crossed = true; - const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); - while (sb < upto) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - sb += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - } - } - const want = stop - at; - // Consume every cell that contributed to this grapheme. A cluster - // ghostty split across several cells is still ONE printed glyph. - var covered: usize = 0; - var style: ?pardes.CellStyle = null; - while (covered < want) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) - style = cellStyle(p, ci, filtered, scnm); - covered += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - // A spacer contributes no bytes; without this the loop would - // spin on a row that ends in one. - if (covered == 0 and gc >= pane.cols) break; - } - while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| { - if (t.cell.wide != .spacer_tail) break; - gc = std.math.add(u16, gc, 1) catch break; - } - if (style) |st| for (0..span) |k| { - const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = st; - }; - sb += covered; - sc += span; - at = stop; - } - var tail: ?pardes.CellStyle = null; - if (anchor.whole() or anchor.suffix > 0) { - while (sc < tw) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - gc = std.math.add(u16, gc, 1) catch break; - if (ci.cell.wide == .spacer_tail) continue; - const cell = s.at(tx + sc, body_y + vr); - sc += 1; - const style = cellStyle(p, ci, filtered, scnm); - tail = style; - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - } - if (tail) |style| while (sc < tw) : (sc += 1) { - const cell = s.at(tx + sc, body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - }; - } - } -} - -fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { - const style = ci.style(); - var cs: pardes.CellStyle = .{ - .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), - .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), - .bold = style.flags.bold, - .dim = style.flags.faint, - .italic = style.flags.italic, - .blink = style.flags.blink, - .reverse = style.flags.inverse, - .invisible = style.flags.invisible, - .strikethrough = style.flags.strikethrough, - .ul = switch (style.flags.underline) { - .none => .off, - .single => .single, - .double => .double, - .curly => .curly, - .dotted => .dotted, - .dashed => .dashed, - }, - }; - if (filtered == null) switch (ci.cell.content_tag) { - .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), - .bg_color_rgb => { - const rgb = ci.cell.content.color_rgb; - cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; - }, - else => {}, - }; - return cs; -} - -const FilteredColors = struct { - source: GColor.Palette, - target: *const GColor.Palette, - theme_bg: GColor.RGB, - theme_fg: GColor.RGB, - dynamic_bg: ?GColor.RGB, - dynamic_fg: ?GColor.RGB, - default_bg: GColor.RGB, - /// What a foreground too near `default_bg` becomes instead. - fallback_fg: GColor.RGB, - default_bg_luminance: f64, - fg_for_palette: [256]pardes.Color = undefined, - bg_for_palette: [256]pardes.Color = undefined, - /// The two answers for a cell that names no colour of its own. - fg_default: pardes.Color = undefined, - bg_default: pardes.Color = undefined, - cache_rgb: [256]GColor.RGB = undefined, - cache_key: [256]u8 = undefined, - cache_valid: [256]bool = @splat(false), - - fn init(p: *Pardes, pane: *const Pane) FilteredColors { - var source = GColor.default; - for (&source, 0..) |*rgb, i| - rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; - const theme = p.theme(); - var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); - var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); - var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); - if (pane.terminal.?.vt.modes.get(.reverse_colors)) { - std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); - std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); - } - var self: FilteredColors = .{ - .source = source, - .target = p.tty_filter_palette.get(theme), - .theme_bg = theme_bg, - .theme_fg = theme_fg, - .dynamic_bg = dynamic_bg, - .dynamic_fg = dynamic_fg, - .default_bg = theme_bg, - .fallback_fg = theme_fg, - .default_bg_luminance = luminanceOf(theme_bg), - }; - if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); - self.default_bg_luminance = luminanceOf(self.default_bg); - if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) - self.fallback_fg = self.theme_bg; - - self.fg_default = asPardesColor(self.legible( - if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, - )); - self.bg_default = asPardesColor(self.default_bg); - for (&self.source, 0..) |current, i| { - const idx: u8 = @intCast(i); - const mapped = self.paletteRgb(idx, current); - self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); - self.bg_for_palette[idx] = asPardesColor(mapped); - } - return self; - } - - fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { - return switch (style.fg_color) { - .none => self.fg_default, - .palette => |idx| self.fg_for_palette[idx], - .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ - .default = self.dynamic_fg orelse self.theme_fg, - .palette = &self.source, - .bold = null, - })))), - }; - } - - fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { - switch (cell.content_tag) { - .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], - .bg_color_rgb => {}, - else => switch (style.bg_color) { - .none => return self.bg_default, - .palette => |idx| return self.bg_for_palette[idx], - .rgb => {}, - }, - } - // Truecolour, from either the cell or its style. - return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); - } - - fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { - if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= - config.tty_filter_min_contrast) return rgb; - return self.fallback_fg; - } - - fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { - if (current.eql(GColor.default[idx])) return self.target[idx]; - return self.keyedRgb(current); - } - - fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { - return self.target[self.nearestKey(rgb)]; - } - - fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { - const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; - const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); - if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) - return self.cache_key[slot]; - - var best: u8 = 0; - var best_distance: u32 = std.math.maxInt(u32); - for (GColor.default, 0..) |candidate, i| { - const distance = colorDistance(rgb, candidate); - // Strict comparison makes duplicate-colour ties stable at the - // lowest canonical xterm key. - if (distance < best_distance) { - best_distance = distance; - best = @intCast(i); - } - } - self.cache_rgb[slot] = rgb; - self.cache_key[slot] = best; - self.cache_valid[slot] = true; - return best; - } -}; - -const channel_luminance: [256]f64 = blk: { - @setEvalBranchQuota(20000); - var table: [256]f64 = undefined; - for (&table, 0..) |*slot, c| { - const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; - slot.* = if (normalized <= 0.03928) - normalized / 12.92 - else - std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); - } - break :blk table; -}; - -fn luminanceOf(rgb: GColor.RGB) f64 { - return 0.2126 * channel_luminance[rgb.r] + - 0.7152 * channel_luminance[rgb.g] + - 0.0722 * channel_luminance[rgb.b]; -} - -/// ghostty's `RGB.contrast` with both luminances already in hand. -fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { - const lighter = @max(a_luminance, b_luminance); - const darker = @min(a_luminance, b_luminance); - return (lighter + 0.05) / (darker + 0.05); -} - -fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { - const dr = @as(i32, a.r) - @as(i32, b.r); - const dg = @as(i32, a.g) - @as(i32, b.g); - const db = @as(i32, a.b) - @as(i32, b.b); - 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)), - ); - } - } -} - -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(); - try testing.expect(pane.tty_filter); - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ - "\x1b[38;5;196mB" ++ - "\x1b[38;2;255;0;0mC" ++ - "\x1b[0;48;5;25mD" ++ - "\x1b[0;48;2;0;95;175mE" ++ - "\x1b[0;1;2;3;4;5;7;8;9mF" ++ - "\x1b[0;48;5;25m\x1b[K" ++ - "\r\n\x1b[0;38;5;2m界" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - const raw = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); - - pane.tty_filter = true; - _ = frame.reset(.retain_capacity); - const filtered = try p.render(frame.allocator()); - var expected_cache: FilterPalette = .{}; - const expected = expected_cache.get(p.theme()); - try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); - try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); - try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); - - const attrs = filtered.at(tx + 5, body_y).style; - try testing.expect(attrs.bold); - try testing.expect(attrs.dim); - try testing.expect(attrs.italic); - try testing.expect(attrs.blink); - try testing.expect(attrs.reverse); - try testing.expect(attrs.invisible); - try testing.expect(attrs.strikethrough); - try testing.expectEqual(.single, attrs.ul); - - const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; - try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); - try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); - try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); - // A filtered terminal never delegates either colour to a backend palette, - // including cells which were empty/default before the pass. - for (0..r.w - config.GUTTER) |col| { - const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); - try testing.expect(!cell.default); - switch (cell.style.fg) { - .rgb => {}, - else => return error.FilteredForegroundWasNotRgb, - } - switch (cell.style.bg) { - .rgb => {}, - else => return error.FilteredBackgroundWasNotRgb, - } - } - - // Colors remains the global master gate. The pane remembers Filter while - // ANSI projection is dormant, and resumes it without replaying VT bytes. - p.settings.colors = false; - _ = frame.reset(.retain_capacity); - const plain = try p.render(frame.allocator()); - try testing.expect(pane.tty_filter); - try testing.expectEqual(asPardesColor(asGhostRgb(p.theme().fg.?)), plain.at(tx, body_y).style.fg); - p.settings.colors = true; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); - const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; - try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); - pane.tty_filter = false; - pane.tty_filter = true; - try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); - _ = frame.reset(.retain_capacity); - const osc_palette = try p.render(frame.allocator()); - try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); - - // Dynamic default foreground/background colours key every default cell, - // including the otherwise blank end of the row. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ - "\x1b]11;#5f5f5f\x1b\\" } }); - const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; - const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; - try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); - try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); - _ = frame.reset(.retain_capacity); - const dynamic = try p.render(frame.allocator()); - const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), blank.bg); - - const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; - try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); - const reversed_explicit = reversed.at(tx, body_y).style; - try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); - try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); - try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); - _ = frame.reset(.retain_capacity); - const unreversed = try p.render(frame.allocator()); - const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); - - // The cache is keyed by values, not a theme name. Replacing a custom - // theme in place immediately recolours already-rendered indexed cells. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); - var custom = p.theme().*; - custom.name = try p.gpa.dupe(u8, "same-name"); - custom.palette = null; - custom.kw = .{ 1, 2, 3 }; - p.custom_theme = custom; - _ = frame.reset(.retain_capacity); - const custom_first = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); - if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; - _ = frame.reset(.retain_capacity); - const custom_second = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); -} - -test "terminal Filter keeps extended keys dark-to-light on a light theme" { - const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); - defer p.deinit(); - try std.testing.expectEqualStrings("acme", p.theme().name); - var cache: FilterPalette = .{}; - const palette = cache.get(p.theme()); - try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); - try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); -} - -test "terminal Filter preserves exact palette-null light theme default roles" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - var light = p.theme().*; - light.name = try p.gpa.dupe(u8, "filter-light-defaults"); - light.bg = .{ 0xf8, 0xf8, 0xf8 }; - light.fg = .{ 0x38, 0x38, 0x38 }; - light.palette = null; - p.custom_theme = light; - - const pane = p.panes[0].?; - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); - pane.tty_filter = true; - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const ordinary = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); -} - -test "terminal Filter maps the default roles before it maps anything else" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - // Native dark/light palettes plus legacy helix/dark/acme, including - // the null-page fallback that only the legacy dark theme exercises. - for (0..9) |t| { - p.settings.theme = @intCast(t); - const stage_one = FilteredColors.init(p, pane); - // `dark` declares no background of its own, which is exactly why the - // resolver reads the tag colours as the fallback rather than `.?`. - const theme = p.theme(); - try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); - try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); - // With no OSC 11 in play the mapped page IS that anchor, and the - // fallback is the other one: a background never contrasts with itself. - try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); - try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); - } - - p.settings.theme = 0; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, pane); - try testing.expect(!moved.default_bg.eql(moved.theme_bg)); - try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); -} - -test "terminal Filter refuses a foreground that would collapse onto the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ - "\x1b[0;30mB" ++ - "\x1b[0;31mR" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); - const page = asPardesColor(fc.default_bg); - const rescued = asPardesColor(fc.fallback_fg); - _ = frame.reset(.retain_capacity); - const g = try p.render(frame.allocator()); - - // The colour each of the three would have been given with no floor. - const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); - const raw_black = fc.paletteRgb(0, GColor.default[0]); - const raw_red = fc.paletteRgb(1, GColor.default[1]); - - for ([_]struct { at: u16, raw: GColor.RGB }{ - .{ .at = 0, .raw = raw_white }, - .{ .at = 1, .raw = raw_black }, - .{ .at = 2, .raw = raw_red }, - }) |case| { - const cell = g.at(tx + case.at, body_y).style; - try testing.expectEqual(page, cell.bg); - if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { - // Refused: the projection's answer is not painted, the anchor is. - try testing.expectEqual(rescued, cell.fg); - try testing.expect(!std.meta.eql(cell.fg, cell.bg)); - } else { - // Cleared the floor, so stage two leaves it exactly alone. - try testing.expectEqual(asPardesColor(case.raw), cell.fg); - } - // Either way a filtered cell delegates neither colour to a backend. - switch (cell.fg) { - .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= - config.tty_filter_min_contrast), - else => return error.FilteredForegroundWasNotRgb, - } - } - - // At least one of the three has to have been a real collapse, or this - // theme proved nothing: white on the light theme, black on the dark. - try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or - raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); - // A saturated red is never the page on any curated theme. - try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - } -} - -test "terminal Filter holds every projected foreground off the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); - var refused: usize = 0; - for (fc.target, 0..) |projected, key| { - const ink = fc.legible(projected); - try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - if (!ink.eql(projected)) { - refused += 1; - try testing.expect(ink.eql(fc.fallback_fg)); - // Only ever refused for being too near the page. - try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); - } - // The key a background asks for is handed back untouched, including - // the one whose value is the page itself. - try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); - } - // Every curated theme owns at least one collapsing key — that is why - // the floor exists — and the floor must not be flattening the palette. - try testing.expect(refused > 0); - try testing.expect(refused < fc.target.len / 8); - } -} - -test "tty ansi colors follow the prompt hug into normal mode" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; - const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; - - // tty mode projects the emulator's ansi colours cell for cell. - pane.body.mode = .tty; - p.shell_rows.stale = true; - const tty = try p.render(frame.allocator()); - try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); - try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); - - pane.body.mode = .normal; - p.shell_rows.stale = true; - _ = frame.reset(.retain_capacity); - const norm = try p.render(frame.allocator()); - try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); - try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); - try testing.expectEqual(red, norm.at(tx, body_y).style.fg); - try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); -} - -test "a prompt row hidden end to end paints nothing at all" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a 12x8 screen: the body, not the tag - p.sync(); - pane.tty_filter = false; - pane.body.mode = .normal; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - p.shell_rows.stale = true; - const s = try p.render(frame.allocator()); - - try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); - 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 }; -} - -pub 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. - if (comptime !enabled) return; - 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); -} - -pub fn undo(p: *Pardes, pane: *Pane) void { - const back_to = pane.body.step(p.gpa, pane.ovl, true) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = back_to.ovl; - pane.ensureCursorVisible(); -} - -pub fn redo(p: *Pardes, pane: *Pane) void { - const forward_to = pane.body.step(p.gpa, pane.ovl, false) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = forward_to.ovl; - pane.ensureCursorVisible(); -} - -pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { - const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); - const room = state.reply.len - state.reply_len; - const n = @min(room, data.len); - @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); - state.reply_len += @intCast(n); -} - -const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( - @FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"), -).optional.child).pointer.child).@"fn".return_type.?; -pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs { - return .{}; -} diff --git a/src/Text.zig b/src/Text.zig index ab23bf8e..cef76b3b 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -14,7 +14,7 @@ const config = @import("config.zig"); const memory = @import("memory.zig"); const Pane = panes.Pane; const File = panes.File; -const Terminal = panes.Terminal; +const terminal = panes.terminal; const Text = @This(); pub const Mode = enum { normal, insert, tty }; @@ -84,9 +84,9 @@ normal: modal.Normal.State = .{}, /// last f/F/t/T motion, for Alt-. repeat find_op: u8 = 0, find_ch: u21 = 0, -ed_undo: [Terminal.history_max]Terminal.Snapshot = undefined, +ed_undo: [terminal.history_max]terminal.Snapshot = undefined, ed_undo_len: usize = 0, -ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, +ed_redo: [terminal.history_max]terminal.Snapshot = undefined, ed_redo_len: usize = 0, /// Set when an edit would have changed characters this text does not own /// (a tag's computed prefix) and was refused; the key that tried it puts @@ -706,10 +706,10 @@ pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void { t.show(); } -fn pushHistory(gpa: std.mem.Allocator, slots: []Terminal.Snapshot, len: *usize, value: Terminal.Snapshot) void { +fn pushHistory(gpa: std.mem.Allocator, slots: []terminal.Snapshot, len: *usize, value: terminal.Snapshot) void { if (len.* == slots.len) { if (slots[0].ovl) |overlay| gpa.free(overlay.text); - std.mem.copyForwards(Terminal.Snapshot, slots[0 .. slots.len - 1], slots[1..]); + std.mem.copyForwards(terminal.Snapshot, slots[0 .. slots.len - 1], slots[1..]); len.* -= 1; } slots[len.*] = value; @@ -719,14 +719,14 @@ fn pushHistory(gpa: std.mem.Allocator, slots: []Terminal.Snapshot, len: *usize, /// Record an edit buffer (a terminal's overlay, a tag's own text) as it /// stands before an edit, once per change of it, and forget what could have /// been redone. Null is a buffer not made yet. -pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer) void { +pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer) void { if (t.ed_undo_len > 0) { const top = t.ed_undo[t.ed_undo_len - 1]; const same = if (top.ovl) |overlay| if (current) |now| overlay.row == now.row and overlay.rows == now.rows and std.mem.eql(u8, overlay.text, now.text) else false else current == null; if (same) return; } - const copy: ?Terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return } else null; + const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return } else null; pushHistory(gpa, &t.ed_undo, &t.ed_undo_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel }); for (t.ed_redo[0..t.ed_redo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text); t.ed_redo_len = 0; @@ -736,13 +736,13 @@ pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer) /// other history and the state to return to comes back, its cursor and /// selection already restored here. The caller installs its buffer, which /// it then owns. Null when there is nothing to step to. -pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer, back: bool) ?Terminal.Snapshot { +pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer, back: bool) ?terminal.Snapshot { const from, const from_len, const to, const to_len = if (back) .{ &t.ed_undo, &t.ed_undo_len, &t.ed_redo, &t.ed_redo_len } else .{ &t.ed_redo, &t.ed_redo_len, &t.ed_undo, &t.ed_undo_len }; if (from_len.* == 0) return null; - const copy: ?Terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return null } else null; + const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return null } else null; pushHistory(gpa, to, to_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel }); from_len.* -= 1; const back_to = from[from_len.*]; diff --git a/src/body_layer.zig b/src/body_layer.zig index 6e1fe8f1..cb26c1f2 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -51,7 +51,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ var visible: i32 = 0; while (lines.next()) |line| : (visible += 1) { if (visible >= r.h -| pane.tag_rows) break; - const source_row = if (raw) panes.Terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; + const source_row = if (raw) panes.terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; for (rows) |row| { const target = if (row.raw_terminal) (if (raw) row.row else pane.surfRow(row.row)) @@ -64,7 +64,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ lo -|= row.prompt_bytes; hi -|= row.prompt_bytes; } else if (!row.raw_terminal and raw) { - const prefix = panes.Terminal.promptPrefixBytes(pane, source_row, line); + const prefix = panes.terminal.promptPrefixBytes(pane, source_row, line); lo += prefix; hi += prefix; } @@ -85,7 +85,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { if (pane.isTerminal()) return paintTerminalSelection(p, s, pane, r, rows, bg, fg); - const terminal_lines = if (pane.file == null) panes.Terminal.cursorLines(p, pane) catch return else &.{}; + const terminal_lines = if (pane.file == null) panes.terminal.cursorLines(p, pane) catch return else &.{}; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; const body_y = p.bodyTop(pane, r); @@ -291,7 +291,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); } else if (pane.isTerminal() and p.settings.colors) { - panes.Terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); + panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); } tz_color.end(); @@ -440,8 +440,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // (the tag's or a prompt's cursor wins while that is being typed into) if (active and pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice)) { if (pane.body.mode != .tty) { - const cur = panes.Terminal.gridCursor(pane); - const goff = panes.Terminal.gridOffset(pane); + const cur = panes.terminal.gridCursor(pane); + const goff = panes.terminal.gridOffset(pane); const crow = if (pane.body.cur_pinned) pane.body.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); const ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, @intCast(cur.x)); const cwp = pane.wrapRow(crow, ccol); @@ -460,7 +460,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane ccol; if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; - } else if (panes.Terminal.visibleCursor(pane)) |cur| { + } else if (panes.terminal.visibleCursor(pane)) |cur| { if (cur.y + pane.tag_rows < body_bottom and cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; } @@ -492,5 +492,5 @@ pub fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { unreachable; } if (pane.file) |*f| return panes.File.bodyText(arena, pane, f, p.settings.wrap); - return panes.Terminal.bodyText(arena, pane); + return panes.terminal.bodyText(arena, pane); } diff --git a/src/builtins.zig b/src/builtins.zig index cc86067e..c549b17f 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -625,7 +625,7 @@ pub const Kill = struct { stopped = true; continue; }; - if (!panes.Terminal.commandRunning(pane)) continue; + if (!panes.terminal.commandRunning(pane)) continue; const sent = pane.sent_command.?; if (names.len > 0) { var words = std.mem.tokenizeAny(u8, names, " \t"); diff --git a/src/draw.zig b/src/draw.zig index 10303117..ad24153f 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -63,7 +63,7 @@ pub fn place(p: *Pardes, s: *Surface) void { // A folded pane is its tag rows and nothing else. if (pane.collapsed) continue; const body_h = r.h -| pane.tag_rows; - const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) panes.Terminal.gridOffset(pane) else 0; + const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) panes.terminal.gridOffset(pane) else 0; s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } }; // An image's rail has no thumb; a native PDF's is measured as its @@ -78,7 +78,7 @@ pub fn place(p: *Pardes, s: *Surface) void { .offset = page, .len = 1, } else blk: { - const gsb = panes.Terminal.scrollbar(pane); + const gsb = panes.terminal.scrollbar(pane); break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len }; }; const track_h: usize = body_h; @@ -241,7 +241,7 @@ fn glideCursor(p: *Pardes, s: *Surface) void { if (inside) frame = paneFrame(s, pane.serial, rect); const origin: [2]f32 = .{ @floatFromInt(rect.x), @floatFromInt(rect.y) }; const view = p.cursor_view; - const line: i64 = if (pane.file) |f| @intCast(f.scroll) else if (pane.isTerminal()) panes.Terminal.gridOffset(pane) else 0; + const line: i64 = if (pane.file) |f| @intCast(f.scroll) else if (pane.isTerminal()) panes.terminal.gridOffset(pane) else 0; if (view.serial == pane.serial and view.inside == inside) { // The pane moved in the layout: the springs move with it (its // own cursor's; one in a column's tag stays). @@ -719,7 +719,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { sb_off = page; sb_total = if (comptime pdf_enabled) at.pdf.?.page_count else 0; } else { - const sb = panes.Terminal.scrollbar(at); + const sb = panes.terminal.scrollbar(at); sb_off = sb.offset; sb_total = sb.total; } diff --git a/src/dump.zig b/src/dump.zig index 1eabdae8..73d4e4ed 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -731,7 +731,7 @@ pub fn dumpState(p: *Pardes) !void { } else if (pane.image) |iv| try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) else - try pardes.panes.Terminal.dumpPane(pane, arena, tag, body, scroll); + try pardes.panes.terminal.dumpPane(pane, arena, tag, body, scroll); dp.tag_tail = pane.tag.own; if (dp.file) |*df| { const dot = ctlfs.pane.dotOf(pane); @@ -914,7 +914,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo // and how it ended: its command is not run again. const live = comptime (terminal_panes and platform != .web and !isolated); const revive = live and t.cwd.len <= effect_path_cap and t.command.len == 0; - const restored = try pardes.panes.Terminal.restore(p, src, revive); + const restored = try pardes.panes.terminal.restore(p, src, revive); p.installPane(i, restored); try restored.setOwnedCwd(t.cwd); if (t.shell.len > 0) restored.shell = try gpa.dupe(u8, t.shell); diff --git a/src/edit.zig b/src/edit.zig index 26062029..98c60efb 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -113,7 +113,7 @@ pub fn clipRequest(p: *Pardes, id: usize, mode: @FieldType(ClipRequest, "mode")) pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) void { if (text.len == 0) return; - if (panes.Terminal.bracketedPaste(pane)) { + if (panes.terminal.bracketedPaste(pane)) { p.emitWrite(id, "\x1b[200~"); p.emitWrite(id, text); p.emitWrite(id, "\x1b[201~"); @@ -225,7 +225,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { // Refresh the source map before translating the rendered rectangle. const raw = pane.isTerminal() and pane.body.mode == .tty; const body = try body_layer.bodyText(p, p.scratch.allocator(), pane); - const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null and !raw) try panes.terminal.cursorLines(p, pane) else &.{}; const first = @max(0, @min(gesture.r0, gesture.r1) - pane.tag_rows); const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - pane.tag_rows); @@ -242,7 +242,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { const left: i32 = if (cols.first) cols.lo else prefix; const right: i32 = cols.hi orelse std.math.maxInt(i32) / 2; var source = pane.wrapAt(visible); - if (raw) source = .{ .line = panes.Terminal.gridOffset(pane) + visible, .at = 0 }; + if (raw) source = .{ .line = panes.terminal.gridOffset(pane) + visible, .at = 0 }; const line = if (raw) modal.lineSlice(body, @intCast(visible)) else pointerSourceLine(pane, terminal_lines, source.line); var next = pane.wrapAt(visible + 1); if (raw) next = .{ .line = source.line + 1, .at = 0 }; @@ -256,7 +256,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { .hi = if (right < prefix) lo else if (cols.hi == null) end else @min(end, modal.nextGrapheme(line, at)), .to_edge = cols.hi == null, .raw_terminal = raw, - .prompt_bytes = if (raw) panes.Terminal.promptPrefixBytes(pane, source.line, line) else 0, + .prompt_bytes = if (raw) panes.terminal.promptPrefixBytes(pane, source.line, line) else 0, }; const rendered = modal.lineSlice(body, @intCast(visible)); const prefix_end = @min(rendered.len, @as(usize, @intCast(@min(prefix, right + 1)))); @@ -276,7 +276,7 @@ pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { const arena = p.scratch.allocator(); if (pane.rawPointerText(sl)) |text| return arena.dupe(u8, text); if (pane.pointerSelection(sl)) |rows| { - const terminal_lines = if (pane.file == null) try panes.Terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null) try panes.terminal.cursorLines(p, pane) else &.{}; var total: usize = rows.len -| 1; for (rows) |row| { const line = pointerSourceLine(pane, terminal_lines, row.row); @@ -402,7 +402,7 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); unreachable; } - return panes.Terminal.cursorLines(p, pane); + return panes.terminal.cursorLines(p, pane); } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { @@ -448,8 +448,8 @@ pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa); unreachable; } - const lines = try panes.Terminal.cursorLines(p, pane); - return panes.Terminal.flatSurface(p, pane, lines); + const lines = try panes.terminal.cursorLines(p, pane); + return panes.terminal.flatSurface(p, pane, lines); } pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { @@ -474,7 +474,7 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.image != null or pane.hasPdf()) return null; - return panes.Terminal.editText(p, pane, lo, hi, col); + return panes.terminal.editText(p, pane, lo, hi, col); } fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { @@ -535,7 +535,7 @@ pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) }; t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; if (pane.file) |*f| return panes.File.setContent(p, f, new); - panes.Terminal.setEditText(p, pane, new); + panes.terminal.setEditText(p, pane, new); } /// Take a text an edit made that nothing keeps, holding it until the next @@ -2057,7 +2057,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { } const pane = t.pane() orelse return; if (pane.file != null) return panes.File.pushUndo(p, pane); - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); } pub fn doUndo(p: *Pardes, t: *Text) void { @@ -2065,7 +2065,7 @@ pub fn doUndo(p: *Pardes, t: *Text) void { if (t.what != .body) return; const pane = t.pane() orelse return; if (pane.file != null) return panes.File.undo(p, pane); - panes.Terminal.undo(p, pane); + panes.terminal.undo(p, pane); } pub fn doRedo(p: *Pardes, t: *Text) void { @@ -2073,7 +2073,7 @@ pub fn doRedo(p: *Pardes, t: *Text) void { if (t.what != .body) return; const pane = t.pane() orelse return; if (pane.file != null) return panes.File.redo(p, pane); - panes.Terminal.redo(p, pane); + panes.terminal.redo(p, pane); } /// Undo or redo an edit of a text's own characters; stepping back past its diff --git a/src/exec.zig b/src/exec.zig index 2c42389c..221de105 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -42,11 +42,11 @@ pub fn takesCommandLine(p: *const Pardes, id: usize) bool { // idle, EMPTY prompt is typed at; otherwise a new pane runs the line. // (Text in pardes's own edit buffer is not the shell's yet: an exec of // it, or of anything, types only what it runs.) - if (panes.Terminal.promptInputReady(pane) and !panes.Terminal.promptInputEmpty(pane)) return false; + if (panes.terminal.promptInputReady(pane) and !panes.terminal.promptInputEmpty(pane)) return false; // A mounted shell sits behind sudo's process supervisor. Its OSC 133 // prompt marks identify input readiness; the launcher's executable is // not the shell executable used by the ordinary process heuristic. - if (pane.v9fs_on_spawn) return panes.Terminal.promptInputReady(pane); + if (pane.v9fs_on_spawn) return panes.terminal.promptInputReady(pane); return !p.hostTtyTaken(id); } @@ -111,7 +111,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand const visible = clicked.r0 - @as(i32, pane.tag_rows); const wrapped = pane.wrapAt(visible); const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= pane.tag_rows; - const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line; + const row = if (raw) panes.terminal.gridOffset(pane) + visible else wrapped.line; const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; const col = if (raw) @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) @@ -143,7 +143,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand lo -|= span.prompt_bytes; hi -|= span.prompt_bytes; } else if (!span.raw_terminal and raw) { - const prefix = panes.Terminal.promptPrefixBytes(pane, row, raw_line); + const prefix = panes.terminal.promptPrefixBytes(pane, row, raw_line); lo += prefix; hi += prefix; } @@ -429,8 +429,8 @@ pub fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void { const tt = p.panes[tty_id] orelse return; // No typing, cursor on the first prompt line, no scrollback: this is // the throwaway boot placeholder a document may replace. - if (tt.ovl != null or panes.Terminal.gridCursor(tt).y != 0 or - panes.Terminal.scrollbar(tt).total > tt.rows) return; + if (tt.ovl != null or panes.terminal.gridCursor(tt).y != 0 or + panes.terminal.scrollbar(tt).total > tt.rows) return; p.deinitPane(tt) catch |err| return p.reportError(tty_id, "close", err); layout.compute(p); // a just-stacked doc has no rect yet; absorb snaps to rows _ = layout.absorbVWeight(p, tty_id, null); @@ -588,7 +588,7 @@ pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { var said: [128]u8 = undefined; return p.setMessage(from, std.fmt.bufPrint(&said, "Repl: {d} bytes is more than can be sent at once; send less", .{n}) catch "Repl: too long to send"); } - const pasted = panes.Terminal.bracketedPaste(dst); + const pasted = panes.terminal.bracketedPaste(dst); edit.typeToTty(p, to, dst, clean[0..n]); // A Python block whose last line is indented, or a bare header, is not // over at one Enter, pasted into 3.13's REPL or typed into the old one: @@ -611,7 +611,7 @@ pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { dst.repl_enter_due_ns = clockNow(p) + repl_enter_wait_ns; } else for (0..enters) |_| p.emitWrite(to, "\r"); // Line by line, a blank line inside a Python block ends the block. - if (!panes.Terminal.bracketedPaste(dst) and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and + if (!panes.terminal.bracketedPaste(dst) and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and std.mem.indexOfScalar(u8, text, '\n') != null) { dst.repl_warned = true; @@ -671,9 +671,9 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi return null; } if (!takesCommandLine(p, id)) return runCommand(p, id, cmd); - panes.Terminal.padOutputBelowEdits(p, id); - panes.Terminal.noteCommand(pane, cmd); - if (panes.Terminal.queuePendingCommand(pane, cmd) catch |err| { + panes.terminal.padOutputBelowEdits(p, id); + panes.terminal.noteCommand(pane, cmd); + if (panes.terminal.queuePendingCommand(pane, cmd) catch |err| { p.reportError(id, "queue command", err); return id; }) return id; @@ -733,8 +733,8 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { // saved cursor), mouse reports and bracketed paste off, the cursor // shown, colours reset. (Not DECSTR: ghostty's stream does not // implement it.) - if (panes.Terminal.onAlternateScreen(pane)) panes.Terminal.feedOutput(p, pane, "\x1b[?1049l"); - panes.Terminal.feedOutput(p, pane, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); + if (panes.terminal.onAlternateScreen(pane)) panes.terminal.feedOutput(p, pane, "\x1b[?1049l"); + panes.terminal.feedOutput(p, pane, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); echoCommand(p, pane, line); p.emitSpawn(id, pane.serial, pane.cwdSlice()); noteRun(p, pane, "run", line); @@ -760,10 +760,10 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { fn echoCommand(p: *Pardes, pane: *Pane, line: []const u8) void { var buf: [2 * command_max + 8]u8 = undefined; var w = std.Io.Writer.fixed(&buf); - w.writeAll(if (panes.Terminal.gridCursor(pane).x != 0) "\r\n% " else "% ") catch {}; + w.writeAll(if (panes.terminal.gridCursor(pane).x != 0) "\r\n% " else "% ") catch {}; for (line) |c| (if (c == '\n') w.writeAll("\r\n") else w.writeByte(c)) catch {}; w.writeAll("\r\n") catch {}; - panes.Terminal.feedOutput(p, pane, w.buffered()); + panes.terminal.feedOutput(p, pane, w.buffered()); } /// `run ` or `exit ` in the log. @@ -788,8 +788,8 @@ pub fn commandDone(p: *Pardes, id: usize, status: ?u8) void { var buf: [16]u8 = undefined; const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch "?" else "?"; var said: [32]u8 = undefined; - const lead = if (panes.Terminal.gridCursor(pane).x != 0) "\r\n" else ""; - panes.Terminal.feedOutput(p, pane, std.fmt.bufPrint(&said, "{s}exit {s}\r\n", .{ lead, code }) catch "exit ?\r\n"); + const lead = if (panes.terminal.gridCursor(pane).x != 0) "\r\n" else ""; + panes.terminal.feedOutput(p, pane, std.fmt.bufPrint(&said, "{s}exit {s}\r\n", .{ lead, code }) catch "exit ?\r\n"); noteRun(p, pane, "exit", code); p.needs_frame = true; } diff --git a/src/fs.zig b/src/fs.zig index a2e8daf8..fc3eb98f 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -57,7 +57,7 @@ const source_files = [_]Source{ .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/mini.zig", .contents = @embedFile("mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, - .{ .path = "src/Terminal.zig", .contents = @embedFile("Terminal.zig") }, + .{ .path = "src/terminal.zig", .contents = @embedFile("terminal.zig") }, .{ .path = "src/pdf_view.zig", .contents = @embedFile("pdf_view.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, diff --git a/src/host_io.zig b/src/host_io.zig index 9e3fbf79..e7be28cd 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -1293,7 +1293,7 @@ pub fn forkShell( var command: std.Io.Writer.Allocating = .init(c.gpa); defer command.deinit(); try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, std.mem.span(socket), &spawn.argv); - if (!try pardes.panes.Terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; + if (!try pardes.panes.terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; } // Built here and not after the fork: between fork and exec the child may // not call setenv, whose malloc can deadlock against a pty reader thread diff --git a/src/layout.zig b/src/layout.zig index 28f567bc..28f3d270 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -607,7 +607,7 @@ fn blankRows(p: *const Pardes, id: usize) u16 { // The empty line after a final newline shows nothing. (panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) -| f.scroll else if (pane.isTerminal()) - @as(usize, panes.Terminal.gridCursor(pane).y) + 1 + @as(usize, panes.terminal.gridCursor(pane).y) + 1 else rows; return rows -| @as(u16, @intCast(@min(used, rows))); @@ -742,7 +742,7 @@ pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void { // Its tag may wrap to more than one row: the rows under it are its body. const tag_h = @max(BOX_H, src.tag_rows); const body: u16 = if (src_h > tag_h) src_h - tag_h else 1; - const cur: u16 = if (!src.isTerminal()) body / 2 else panes.Terminal.gridCursor(src).y + 1; + const cur: u16 = if (!src.isTerminal()) body / 2 else panes.terminal.gridCursor(src).y + 1; // cap keep so a content-full source still leaves the new pane a tag + // a few body rows (an Alt-n from a full shell was born 0 rows tall) // ...and the source min_body_rows of its own (exec.placeNew), when it diff --git a/src/mouse.zig b/src/mouse.zig index 1f2648b0..cb0378de 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -821,7 +821,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { const forward = gesture.r1 > gesture.r0 or (gesture.r1 == gesture.r0 and gesture.c1 >= gesture.c0); const endpoint = rows[if (forward) rows.len - 1 else 0]; const body = body_layer.bodyText(p, p.scratch.allocator(), pane) catch return; - const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.Terminal.gridOffset(pane)))); + const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.terminal.gridOffset(pane)))); const byte = if (forward) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; pane.body.cur_row = pane.surfRow(endpoint.row); var shown = std.mem.trimEnd(u8, line[@min(endpoint.prompt_bytes, line.len)..], " \t"); @@ -1137,11 +1137,11 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut) return; const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; if (y.len == 0) return; - if (panes.Terminal.reportsMouse(pane)) { + if (panes.terminal.reportsMouse(pane)) { const col: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].c1 + 1, 1, 9999)); const row: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows) + 1, 1, 9999)); var mb: [32]u8 = undefined; - if (panes.Terminal.mouseFormatSgr(pane)) { + if (panes.terminal.mouseFormatSgr(pane)) { p.emitWrite(s.id, std.fmt.bufPrint(&mb, "\x1b[<0;{d};{d}M\x1b[<0;{d};{d}m", .{ col, row, col, row }) catch return); } else { // ponytail: legacy X10 bytes; add utf8/urxvt formats if an app ever wants them diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 5bf354eb..060e0d6c 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -344,7 +344,7 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { pane.serial, pane_files.tagOf(p, pane).len, // A terminal's body is its history, read whole on an open's first read. - if (pane.isTerminal()) panes.Terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, + if (pane.isTerminal()) panes.terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, @as(u32, 0), @intFromBool(pane_files.dirtyOf(pane)), pane.cols, diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3c1e181e..3fad1fae 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -258,7 +258,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pf = &pane.fs; return switch (f) { // A terminal's body reads its screen and history, as text. - .body => if (pane.file == null and pane.isTerminal()) panes.Terminal.screenTextLen(pane) else if (pdfText(p, pane)) |t| t.len else bodyOf(pane).len, + .body => if (pane.file == null and pane.isTerminal()) panes.terminal.screenTextLen(pane) else if (pdfText(p, pane)) |t| t.len else bodyOf(pane).len, .data, .xdata => bodyOf(pane).len, .tag => tagOf(p, pane).len, .name => nameOf(pane).len + 1, @@ -399,7 +399,7 @@ fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return tree.stagedReply(p, req); } if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane); - const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch + const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); defer p.gpa.free(text); const out = p.fs.stage(p.gpa); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 8ba9f4df..0f5202cc 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -139,9 +139,9 @@ pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // or a line is typed at the prompt. Before the shell's first prompt a // run waits for it rather than answer busy, so that is not busy. // A build with no terminal panes (the board) has no marks to read. - const marks = if (comptime !pardes.panes.Terminal.enabled) null else if (pane.terminal) |state| &state.stream.handler else null; + const marks = if (comptime !pardes.panes.terminal.enabled) null else if (pane.terminal) |state| &state.stream.handler else null; const busy = p.hostTtyTaken(id) or (!pane.fs.unmarked and (waitingRun(p, pane) != null or - (if (marks) |m| m.prompts > 0 and (m.phase != .input or !pardes.panes.Terminal.promptInputEmpty(pane)) else false))); + (if (marks) |m| m.prompts > 0 and (m.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane)) else false))); const out = p.fs.stage(p.gpa); const size = winsize(pane); out.print(p.gpa, "{d:>11} {d:>11} {d:>11}\n", .{ size[0], size[1], @intFromBool(busy) }) catch {}; @@ -222,7 +222,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); if (line.len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); - if (comptime !pardes.panes.Terminal.enabled) return tree.failText(req.tag, E.INVAL, e_bad_line); + if (comptime !pardes.panes.terminal.enabled) return tree.failText(req.tag, E.INVAL, e_bad_line); const pf = &pane.fs; const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); const marks = &state.stream.handler; @@ -235,7 +235,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { } else if (pf.unmarked) { answer(p, slot, "error no prompt marks", .{}); } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and (marks.phase != .input or - !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)))) + !pardes.panes.terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)))) { // Something is running or someone has typed at the prompt: sending // now would type into the middle of it. The phase is pardes's own @@ -288,7 +288,7 @@ pub fn readRun(p: *Pardes, req: Req) Reply { /// for the prompt means whoever reads the answer can send the next command /// at once instead of finding the shell still drawing it. pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { - if (comptime !pardes.panes.Terminal.enabled) return; + if (comptime !pardes.panes.terminal.enabled) return; const state = pane.terminal orelse return; const pf = &pane.fs; const slot = waitingRun(p, pane) orelse return; @@ -299,13 +299,13 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { pf.run = null; return; } - if (marks.phase != .input or !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) return; + if (marks.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) return; slot.want = marks.started +% 1; slot.prompts = marks.prompts; slot.declined = marks.declined; p.emitWrite(id, slot.line); p.emitWrite(id, "\r"); - pardes.panes.Terminal.noteCommand(pane, slot.line); + pardes.panes.terminal.noteCommand(pane, slot.line); slot.phase = .sent; return; } @@ -319,7 +319,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { // typed into an empty prompt, so throw it away with Ctrl-C, which // drops the whole pending command, and answer at the prompt after // that, so the next line finds the shell clear. - const empty = pardes.panes.Terminal.promptInputEmpty(pane); + const empty = pardes.panes.terminal.promptInputEmpty(pane); switch (slot.cleared) { .no => { if (marks.continuation) { @@ -360,7 +360,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { /// Answers a run whose command ended with `status`: the header and the /// output it printed. fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void { - const printed = pardes.panes.Terminal.commandOutput(pane, p.gpa, output_rows) catch + const printed = pardes.panes.terminal.commandOutput(pane, p.gpa, output_rows) catch return answer(p, slot, "error out of memory", .{}); defer p.gpa.free(printed.text); // Keep the tail, cut at a line start so the first line kept is whole. @@ -400,7 +400,7 @@ pub fn shellExited(p: *Pardes, pane: *Pane, status: ?u8) void { const code = status orelse return; if (waitingRun(p, pane)) |slot| if (slot.phase == .sent) { pane.fs.run = null; - pardes.panes.Terminal.endOutputHere(pane); + pardes.panes.terminal.endOutputHere(pane); finish(p, slot, pane, code); }; var buf: [4]u8 = undefined; @@ -963,10 +963,10 @@ test "a run's answer says cut when its output's start is gone, and reads a bound // A resize between its start and end reflows the pins with the text. h = sh.send(p, node); sh.put(p, c ++ "one\r\ntwo\r\n"); - pardes.panes.Terminal.resizeGrid(pane, gpa, 50, 20); + pardes.panes.terminal.resizeGrid(pane, gpa, 50, 20); sh.put(p, d ++ prompt); try testing.expectEqualStrings("exit 0\none\ntwo\n", sh.answered(p, node, h, into)); - pardes.panes.Terminal.resizeGrid(pane, gpa, pane.cols, pane.rows); + pardes.panes.terminal.resizeGrid(pane, gpa, pane.cols, pane.rows); // A full-screen program leaves nothing on the primary screen, and a D // with no status is not a success. diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index f496da03..b991c3e4 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -47,7 +47,7 @@ pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { const snapshot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.snapshot; if (snapshot.* == null) { const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); - snapshot.* = panes.Terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); + snapshot.* = panes.terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); } const bytes = snapshot.*.?; const off = @min(req.off, bytes.len); @@ -129,7 +129,7 @@ test "terminal body handles keep one history snapshot across fragmented reads" { const node = Node.of(serialOf(p), .body); p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } }); while (p.nextEffect()) |_| {} - const original = try panes.Terminal.screenTextAlloc(p.panes[0].?, gpa); + const original = try panes.terminal.screenTextAlloc(p.panes[0].?, gpa); defer gpa.free(original); const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); try testing.expectEqual(Status.ok, opened.reply.status); diff --git a/src/panes.zig b/src/panes.zig index b6fdc31a..0380f89f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -89,7 +89,7 @@ pub const Pane = struct { pub const Cwd = union(enum) { none, inherited: *Pane, owned: []u8 }; pub const Focus = enum { body, tag }; - terminal: ?*Terminal.State = null, + terminal: ?*terminal.State = null, gpa: std.mem.Allocator, serial: u32 = 0, /// What the control filesystem keeps of this pane -- addr and limit, the @@ -116,7 +116,7 @@ pub const Pane = struct { /// A shell has run in it (Pardes.acknowledgeShell): a Tty whose first /// shell fails to start closes, one started again keeps its pane. had_shell: bool = false, - pending_command: Terminal.PendingCommand = .{}, + pending_command: terminal.PendingCommand = .{}, /// The last command line pardes typed into this terminal (an exec, a /// middle click, a pty/run): its first word, which Kill matches, and /// the shell's command count its start (C mark) reaches. @@ -227,7 +227,7 @@ pub const Pane = struct { next_pointer_selection: u64 = 0, /// terminals only: the typed-text buffer standing in for shell rows - ovl: ?Terminal.EditBuffer = null, + ovl: ?terminal.EditBuffer = null, tty_filter: bool = false, msg: [256]u8 = undefined, msg_len: u16 = 0, @@ -486,7 +486,7 @@ pub const Pane = struct { pub fn scroll(pane: *Pane) i32 { if (pane.file) |f| return @intCast(f.scroll); if (comptime Pdf.enabled) if (pane.pdf) |pv| return @intCast(pv.text_scroll); - return pane.surfRow(Terminal.gridOffset(pane)); + return pane.surfRow(terminal.gridOffset(pane)); } pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32 } { @@ -531,8 +531,8 @@ pub const Pane = struct { } } else { // the vt scrolls in SHELL rows; convert through the edit buffer - const off = Terminal.gridOffset(pane); - Terminal.scrollGrid(pane, pane.gridRow(pane.surfRow(off) + delta) - off); + const off = terminal.gridOffset(pane); + terminal.scrollGrid(pane, pane.gridRow(pane.surfRow(off) + delta) - off); } } @@ -611,8 +611,8 @@ pub const Pane = struct { pane.body.cur_row = pane.scroll(); pane.body.cur_col = 0; } else { - const cur = Terminal.gridCursor(pane); - pane.body.cur_row = pane.surfRow(@as(i32, cur.y) + Terminal.gridOffset(pane)); + const cur = terminal.gridCursor(pane); + pane.body.cur_row = pane.surfRow(@as(i32, cur.y) + terminal.gridOffset(pane)); pane.body.cur_col = @intCast(cur.x); } pane.body.cur_pinned = true; @@ -642,7 +642,7 @@ pub const Image = @import("image.zig"); pub const Pdf = @import("pdf_view.zig"); -pub const Terminal = @import("Terminal.zig"); +pub const terminal = @import("terminal.zig"); test { _ = Pane; @@ -652,5 +652,5 @@ test { _ = mini; _ = Image; _ = Pdf; - _ = Terminal; + _ = terminal; } diff --git a/src/pardes.zig b/src/pardes.zig index 141b214e..623af3c9 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1195,9 +1195,9 @@ test "Tty9p marks only the new Linux terminal for a mounted shell" { try std.testing.expect(pane.v9fs_on_spawn); try std.testing.expect(!pane.greet); try std.testing.expect(!exec.takesCommandLine(p, p.active)); - panes.Terminal.feedOutput(p, pane, "\x1b]133;A\x07$ \x1b]133;B\x07"); + panes.terminal.feedOutput(p, pane, "\x1b]133;A\x07$ \x1b]133;B\x07"); try std.testing.expect(exec.takesCommandLine(p, p.active)); - panes.Terminal.feedOutput(p, pane, "\x1b]133;C\x07"); + panes.terminal.feedOutput(p, pane, "\x1b]133;C\x07"); try std.testing.expect(!exec.takesCommandLine(p, p.active)); } @@ -1558,7 +1558,7 @@ test "a command of several lines keeps its tag one row, and its echo does not st _ = exec.execute(p, 1, two); while (p.nextEffect()) |_| {} _ = try p.render(frame.allocator()); - const body = try panes.Terminal.screenTextAlloc(pane, gpa); + const body = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(body); try std.testing.expect(std.mem.indexOf(u8, body, "% def greet(name):\n return name") != null); } @@ -1878,7 +1878,7 @@ test "a command pane shows how its command ended, and the next command there run const pane = p.panes[dst].?; // Its first command is echoed as every later one is. { - const first = try panes.Terminal.screenTextAlloc(pane, gpa); + const first = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(first); try std.testing.expect(std.mem.startsWith(u8, first, "% make -j8")); } @@ -1909,16 +1909,16 @@ test "a command pane shows how its command ended, and the next command there run // A program that crashed out of its full screen leaves the emulator // in its modes; the next command starts clear of them. p.update(.{ .output = .{ .pane = @intCast(dst), .bytes = "\x1b[?1049h\x1b[?2004h\x1b[?1000h" } }); - try std.testing.expect(panes.Terminal.bracketedPaste(pane)); + try std.testing.expect(panes.terminal.bracketedPaste(pane)); // Done, the directory's next command runs there, below what it showed. try std.testing.expectEqual(@as(?usize, dst), exec.execute(p, 1, "make test")); - try std.testing.expect(!panes.Terminal.bracketedPaste(pane)); + try std.testing.expect(!panes.terminal.bracketedPaste(pane)); var respawned = false; while (p.nextEffect()) |effect| if (effect == .spawn and effect.spawn.pane == dst) { respawned = true; }; try std.testing.expect(respawned); - const body = try panes.Terminal.screenTextAlloc(pane, gpa); + const body = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(body); const said = std.mem.indexOf(u8, body, "compiled") orelse return error.OutputLost; const ended = std.mem.indexOf(u8, body, "exit 2") orelse return error.ExitLost; @@ -4394,7 +4394,7 @@ pub const Pardes = struct { settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, locations_config: locations.Config = .{}, locations_cache: locations.Cache = .{}, - tty_filter_palette: panes.Terminal.FilterPalette = .{}, + tty_filter_palette: panes.terminal.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, /// bodyChrome's: the theme it was worked out for, and it. @@ -4580,8 +4580,8 @@ pub const Pardes = struct { /// that still own their loop pass their own arena to `render` instead. frame_arena: std.heap.ArenaAllocator, /// the terminal motion surface, memoized against the pane it was built - /// for — see panes.Terminal.RowsCache for the lifetime rule - shell_rows: panes.Terminal.RowsCache = .{}, + /// for — see panes.terminal.RowsCache for the lifetime rule + shell_rows: panes.terminal.RowsCache = .{}, /// The message row's entry points, called from everywhere as /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. @@ -4944,7 +4944,7 @@ pub const Pardes = struct { } p.shell_rows.dropPane(pane); for (0..pane.pointer_selections.len) |slot| pane.clearPointerSelection(slot); - panes.Terminal.deinitPendingCommand(pane); + panes.terminal.deinitPendingCommand(pane); if (pane.command) |line| p.gpa.free(line); if (pane.shell) |bin| p.gpa.free(bin); if (pane.image) |*iv| { @@ -4957,7 +4957,7 @@ pub const Pardes = struct { pane.tag.deinit(p.gpa); pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); - panes.Terminal.deinitEmulator(pane, p.gpa); + panes.terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); p.gpa.destroy(pane); @@ -4986,12 +4986,12 @@ pub const Pardes = struct { pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { std.debug.assert(p.panes[id] == null); if (cwd.len > limits.host_path_cap) return error.PathTooLong; - const pane = try panes.Terminal.create(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.create(p.gpa, p.screen_w, p.screen_h); // Named by the directory it is started in from the first, so the // shell saying it is there is no rename (`new N /` then `rename`); // out of memory for it, the shell names it when it says. if (cwd.len > 0) pane.setOwnedCwd(cwd) catch {}; - panes.Terminal.armShellSpawn(pane); + panes.terminal.armShellSpawn(pane); p.installPane(id, pane); p.emitSpawn(id, pane.serial, cwd); return pane; @@ -5017,7 +5017,7 @@ pub const Pardes = struct { if (cwd.len > limits.host_path_cap) return error.PathTooLong; const owned = try p.gpa.dupe(u8, line); errdefer p.gpa.free(owned); - const pane = try panes.Terminal.create(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.create(p.gpa, p.screen_w, p.screen_h); pane.command = owned; pane.command_pty = true; pane.body.mode = .tty; @@ -5031,7 +5031,7 @@ pub const Pardes = struct { pub fn newDocPane(p: *Pardes, id: usize) !*Pane { std.debug.assert(p.panes[id] == null); - const pane = try panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); p.installPane(id, pane); return pane; } @@ -5223,7 +5223,7 @@ pub const Pardes = struct { } else |_| {} } }; - if (id < MAX_PANES) panes.Terminal.shellSpawned(p, id, prompt_marks); + if (id < MAX_PANES) panes.terminal.shellSpawned(p, id, prompt_marks); if (p.settings.shell.effective.set(executable)) p.settings.shell.pending = false; } @@ -5358,7 +5358,7 @@ pub const Pardes = struct { /// The pane a session word runs with in an empty window. pub fn standIn(p: *Pardes) ?*Pane { - if (p.stand_in == null) p.stand_in = panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h) catch null; + if (p.stand_in == null) p.stand_in = panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h) catch null; return p.stand_in; } @@ -5627,7 +5627,7 @@ pub const Pardes = struct { return; } if (!pane.isTerminal()) return; - const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch return; + const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return; defer p.gpa.free(text); p.hostWriteFile(st.pane, st.path.slice(), text); }, @@ -5839,7 +5839,7 @@ pub const Pardes = struct { const pane = p.panes[o.pane] orelse return; pane.shell_spoke = true; ctlfs.events.notePtyOutput(p, o.pane, o.bytes); - panes.Terminal.feedOutput(p, pane, o.bytes); + panes.terminal.feedOutput(p, pane, o.bytes); ctlfs.pty.noteMarks(p, o.pane, pane); exec.flushReplEnter(p, o.pane, true); }, @@ -5944,7 +5944,7 @@ pub const Pardes = struct { .normal => edit.enterInsert(p, &pane.body, .at, 1), .insert => { edit.exitInsert(p, &pane.body); - if (pane.isTerminal()) panes.Terminal.enterTty(p, id); + if (pane.isTerminal()) panes.terminal.enterTty(p, id); }, } } @@ -5960,7 +5960,7 @@ pub const Pardes = struct { if (pane.body.mode == .tty) { pane.body.mode = .normal; pane.body.normal.clear(); - } else panes.Terminal.enterTty(p, id); + } else panes.terminal.enterTty(p, id); } /// Type `keys` again (a macro, `.`): through the modal handling as @@ -6079,7 +6079,7 @@ pub const Pardes = struct { return exec.runBuiltin(p, .Last, p.active, "", null); if (key.cp == Key.escape and !key.ctrl and !key.alt and !key.shift and exec.takesCommandLine(p, p.active)) return exec.runBuiltin(p, .Last, p.active, "", null); - panes.Terminal.followOutput(pane); // typing snaps back to live output + panes.terminal.followOutput(pane); // typing snaps back to live output // Paste stays the window's, the one exception to forwarding a raw // tty's keys: Ctrl-V types the register at the program and // Ctrl-Shift-V asks the desktop for its clipboard first. Forwarded, @@ -6094,7 +6094,7 @@ pub const Pardes = struct { // Ctrl-V a black hole in every full-screen application. if (p.registers.text(p.gpa, Registers.default)) |text| return edit.typeToTty(p, p.active, pane, text); } - return panes.Terminal.forwardKey(p, p.active, key); + return panes.terminal.forwardKey(p, p.active, key); } if (p.leader_on) return p.leaderKey(key); if (p.ctrl_w_pending) { @@ -6247,7 +6247,7 @@ pub const Pardes = struct { edit.exitInsert(p, t) else edit.handleInsert(p, t, key), - .tty => panes.Terminal.forwardKey(p, p.active, key), + .tty => panes.terminal.forwardKey(p, p.active, key), } // `.`'s log: the keys of the normal command that entered insert // mode, then everything typed until it is left @@ -6738,7 +6738,7 @@ pub const Pardes = struct { errdefer p.gpa.free(path); const history = try panes.File.History.create(p.gpa); errdefer p.gpa.destroy(history); - const pane = try panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); errdefer p.gpa.destroy(pane); try p.deinitPane(p.panes[0].?); p.panes[0] = null; @@ -7086,7 +7086,7 @@ pub const Pardes = struct { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { - panes.Terminal.resizeGrid(pane, p.gpa, cols, rows); + panes.terminal.resizeGrid(pane, p.gpa, cols, rows); p.shell_rows.markStale(pane); // reflow moved every row p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); pane.fs.winsize = null; @@ -7095,12 +7095,12 @@ pub const Pardes = struct { pane.rows = rows; if (pane.file) |*file| file.syntax_dirty = true; } - panes.Terminal.releasePendingCommandIfReady(p, id, pane); + panes.terminal.releasePendingCommandIfReady(p, id, pane); // The greeting `ls` of a new terminal in a directory is typed at // its shell's FIRST prompt, or never: typed later it would land // in whatever runs then, or in the middle of a line someone - // typed (panes.Terminal.greeting). - if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (panes.Terminal.greeting(pane)) { + // typed (panes.terminal.greeting). + if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (panes.terminal.greeting(pane)) { .wait => {}, .never => pane.greet = false, .now => { @@ -7381,7 +7381,7 @@ test "argv naming nothing boots an errors pane rather than failing the launch" { } test "raw terminal cursor obeys visibility without hiding modal and tag cursors" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -7426,7 +7426,7 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" } test "raw terminal cursor follows its active row only while that row is visible" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; for ([_]bool{ false, true }) |tag_bottom| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); @@ -7445,13 +7445,13 @@ test "raw terminal cursor follows its active row only while that row is visible" try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x); try std.testing.expectEqual(body_y + 2, live.y); - panes.Terminal.scrollGrid(pane, -1); + panes.terminal.scrollGrid(pane, -1); const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, scrolled.x); try std.testing.expectEqual(live.y + 1, scrolled.y); - panes.Terminal.scrollGrid(pane, -@as(i32, pane.rows)); + panes.terminal.scrollGrid(pane, -@as(i32, pane.rows)); try std.testing.expect((try p.render(frame.allocator())).cursor == null); - panes.Terminal.followOutput(pane); + panes.terminal.followOutput(pane); const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, returned.x); try std.testing.expectEqual(live.y, returned.y); @@ -7895,31 +7895,31 @@ test "tty output follows only from the bottom" { p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - const bottom = panes.Terminal.scrollbar(sp).offset; + const bottom = panes.terminal.scrollbar(sp).offset; try std.testing.expect(bottom > 0); // Scrolled back, the reader stays put however much the shell prints. sp.scrollBy(-10); p.sync(); - const parked = panes.Terminal.scrollbar(sp).offset; + const parked = panes.terminal.scrollbar(sp).offset; try std.testing.expect(parked < bottom); for (60..70) |i| { var buf: [32]u8 = undefined; p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - try std.testing.expectEqual(parked, panes.Terminal.scrollbar(sp).offset); + try std.testing.expectEqual(parked, panes.terminal.scrollbar(sp).offset); // Typing snaps back to live output, so nobody types blind. p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); p.sync(); - try std.testing.expect(panes.Terminal.scrollbar(sp).offset > parked); + try std.testing.expect(panes.terminal.scrollbar(sp).offset > parked); // ...and from there output follows again. - const live = panes.Terminal.scrollbar(sp).offset; + const live = panes.terminal.scrollbar(sp).offset; p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = "tail\r\n" } }); p.sync(); - try std.testing.expect(panes.Terminal.scrollbar(sp).offset > live); + try std.testing.expect(panes.terminal.scrollbar(sp).offset > live); } test "Esc back into a file leaves its view where it was" { @@ -8135,7 +8135,7 @@ test "an unasked desktop paste reaches a tty pane's program, not its buffer" { _ = drainWrites(p, &buf); const pane = p.panes[0].?; - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); // No request behind it: the window manager's own paste, or SDL answering a // Ctrl-Shift-V the desktop handled. It still has to reach the shell. p.update(.{ .paste = "ls -la" }); @@ -8153,7 +8153,7 @@ test "a paste larger than the effect ring reaches the program whole and in order const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @@ -8166,7 +8166,7 @@ test "a paste larger than the effect ring reaches the program whole and in order test "a bracketed paste larger than the ring still closes its bracket" { if (platform == .web) return; - if (comptime !panes.Terminal.enabled) return; + if (comptime !panes.terminal.enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8174,10 +8174,10 @@ test "a bracketed paste larger than the ring still closes its bracket" { const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - try std.testing.expect(panes.Terminal.bracketedPaste(p.panes[0].?)); + try std.testing.expect(panes.terminal.bracketedPaste(p.panes[0].?)); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @memset(text, 'z'); @@ -8197,7 +8197,7 @@ test "pasted bytes still queued at shutdown are freed, not leaked" { const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @@ -8227,14 +8227,14 @@ test "leaving tty hides the prompt and keeps the command typed at it" { const rowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const rows = panes.Terminal.shellRows(pp, pane) catch return null; + const rows = panes.terminal.shellRows(pp, pane) catch return null; for (rows) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; } }.at; const bodyRowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const body = panes.Terminal.bodyText(pp.scratch.allocator(), pane) catch return null; + const body = panes.terminal.bodyText(pp.scratch.allocator(), pane) catch return null; var it = std.mem.splitScalar(u8, body, '\n'); while (it.next()) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; @@ -8290,7 +8290,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" p.shell_rows.stale = true; // The command shows LEFT-HUGGED, so its column 3 is the '3'... - const rows = try panes.Terminal.shellRows(p, sp); + const rows = try panes.terminal.shellRows(p, sp); var row: i32 = 0; const at = for (rows, 0..) |r, i| { if (std.mem.indexOf(u8, r, "0123456789") != null) break i; @@ -8304,7 +8304,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" sp.body.cur_col = 3; sp.body.cur_pinned = true; while (p.nextEffect()) |_| {} - panes.Terminal.enterTty(p, shell); + panes.terminal.enterTty(p, shell); // The walk is arrow keys the shell understands. Seven lefts: readline's // cursor sits past the '9' and the click was on the '3'. @@ -8347,7 +8347,7 @@ test "board heap: every inline ring the board pays for still fits its budget" { const effect_ring = 128 * @sizeOf(Effect); // ...and the undo history, the largest in `Pane` once the terminal is out: // 16 snapshots on the board against 256 on a desktop. - const undo_history = 2 * 16 * @sizeOf(panes.Terminal.Snapshot); + const undo_history = 2 * 16 * @sizeOf(panes.terminal.Snapshot); const grid = @as(usize, board_cols) * board_rows * (2 * @sizeOf(Cell) + @sizeOf(PanelCellDiff)); // Each of the three separately, so a failure names the one that grew @@ -8475,7 +8475,7 @@ test "jump history terminal rectangle follows output and clears on reflow" { try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); for (0..40) |_| p.update(.{ .output = .{ .pane = 0, .bytes = "more output\r\n" } }); try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); - panes.Terminal.resizeGrid(pane, p.gpa, pane.cols - 1, pane.rows); + panes.terminal.resizeGrid(pane, p.gpa, pane.cols - 1, pane.rows); try std.testing.expect(pane.pointerSelection(pane.sel[0]) == null); try std.testing.expectEqual(.none, pane.sel[0].state); } diff --git a/src/terminal.zig b/src/terminal.zig new file mode 100644 index 00000000..c99a92a6 --- /dev/null +++ b/src/terminal.zig @@ -0,0 +1,2670 @@ +//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay +//! typed over shell rows, and the Filter that recolours output to the theme. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const Surface = pardes.Surface; +const modal = @import("modal.zig"); +const tracy = @import("tracy.zig"); +const dump = @import("dump.zig"); +const Key = pardes.Key; +const Pane = panes.Pane; +const EditText = panes.EditText; +const File = panes.File; + +pub const enabled = pardes.terminal_panes; +const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; + +pub const history_max = if (enabled) 64 else 8; + +pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; +pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; + +/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). +pub const prompt_aid = "pardes"; + +/// ghostty's handler, plus where the shell is in its command cycle as +/// its OSC 133 marks tell it: ghostty parses D's exit status and drops +/// it, and /pane//pty/run waits on exactly that. Only marks carrying +/// pardes's own `aid` move it, so fish's native marks, a nested shell's +/// and a stray `133;D` in some file being printed all pass it by. +pub const MarkedHandler = if (enabled) struct { + inner: ghostty_vt.TerminalStream.Handler, + phase: enum { none, prompt, input, running } = .none, + /// Counts commands started (C at the input phase). + started: u32 = 0, + /// Counts prompts drawn (B), so a line the shell refused without + /// running (a fish syntax error: no C, no D, a new prompt) shows. + prompts: u32 = 0, + /// D marks outside a running command: the shell handled a line + /// without starting it (bash on a syntax error prints no C). + declined: u32 = 0, + /// The newest prompt continues an unfinished line (bash's PS2, marked + /// `k=c`): the shell still holds the start of the command. + continuation: bool = false, + /// Where the newest command's output began (its C) and ended (its + /// D) on the primary screen, pinned so scrolling keeps them. + out_start: ?*ghostty_vt.Pin = null, + out_end: ?*ghostty_vt.Pin = null, + /// The running command's output was erased under it -- a clear, ED 3, + /// a reset -- so the pins no longer span what it printed: ED 3 moves + /// a pin to the next page without flagging it `garbage` + /// (PageList.erasePage). + lost: bool = false, + + /// The newest command to end: which one, and its status if given. + finished: ?struct { seq: u32, status: ?i32 } = null, + + const Action = ghostty_vt.TerminalStream.Action; + + /// Move one of the output pins to the cursor. Only the primary screen + /// is pinned: a command's own full-screen display is not its output. + fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { + const screen = self.inner.terminal.screens.get(.primary) orelse return; + if (slot.*) |old| screen.pages.untrackPin(old); + slot.* = null; + if (!now or self.inner.terminal.screens.active_key != .primary) return; + slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; + } + + pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { + if (comptime action == .semantic_prompt) mark: { + const aid = value.readOption(.aid) orelse break :mark; + if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; + switch (value.action) { + .fresh_line_new_prompt => { + self.phase = .prompt; + self.continuation = value.readOption(.prompt_kind) == .continuation; + }, + .end_prompt_start_input => { + self.phase = .input; + self.prompts +%= 1; + }, + // bash's DEBUG trap also fires on its own PROMPT_COMMAND, + // outside the input phase; only a C that ends input counts + .end_input_start_output => if (self.phase == .input) { + self.phase = .running; + self.started +%= 1; + self.lost = false; + self.pinCursor(&self.out_start, true); + self.pinCursor(&self.out_end, false); + }, + .end_command => if (self.phase == .running) { + self.phase = .none; + self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; + self.pinCursor(&self.out_end, true); + } else { + self.declined +%= 1; + }, + else => {}, + } + } + if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .full_reset) { + if (self.phase == .running) self.lost = true; + } + self.inner.vt(action, value); + } + + pub fn deinit(self: *@This()) void { + self.inner.deinit(); + } +} else void; + +pub const Replay = struct { + bytes: [1024 * 1024]u8 = undefined, + head: usize = 0, + len: usize = 0, +}; + +pub const State = struct { + vt: VtSlot, + stream: StreamSlot, + replay: Replay, + reply: [256]u8 = undefined, + reply_len: u16 = 0, +}; + +const GColor = ghostty_vt.color; + +const FilterPaletteKey = struct { + bg: GColor.RGB, + fg: GColor.RGB, + base: [16]GColor.RGB, +}; + +pub const FilterPalette = if (enabled) LivePalette else struct {}; + +const LivePalette = struct { + key: ?FilterPaletteKey = null, + colors: GColor.Palette = GColor.default, + + fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { + const bg = asGhostRgb(theme.bg orelse theme.tag_bg); + const fg = asGhostRgb(theme.fg orelse theme.tag_fg); + var base: [16]GColor.RGB = undefined; + if (theme.palette) |palette| { + for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); + } else { + const synthesized = [16][3]u8{ + theme.bg orelse theme.tag_bg, + theme.kw, + theme.str, + theme.num, + theme.box, + theme.sel_bg, + theme.comment, + theme.fg orelse theme.tag_fg, + theme.lineno, + theme.kw, + theme.str, + theme.num, + theme.scroll_thumb, + theme.sel_fg, + theme.tag_fg, + theme.fg orelse theme.tag_fg, + }; + for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); + } + + const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; + if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; + + var seed = GColor.default; + for (base, 0..) |rgb, i| seed[i] = rgb; + self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); + self.key = key; + return &self.colors; + } +}; + +fn asGhostRgb(rgb: [3]u8) GColor.RGB { + return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; +} + +fn asPardesColor(rgb: GColor.RGB) pardes.Color { + return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; +} + +/// The owned text standing in for `rows` live terminal rows, beginning at +/// absolute surface row `row`. The emulator grid remains untouched underneath. +pub const EditBuffer = struct { + row: i32 = 0, + rows: i32 = 1, + text: []u8 = &.{}, +}; + +/// One whole-state terminal edit boundary. Null means the pane has not yet +/// materialized an edit buffer; non-null snapshots own their text. +pub const Snapshot = struct { + ovl: ?EditBuffer, + cur_row: i32, + cur_col: i32, + vsel: panes.Text.CharSel, +}; + +pub const PendingCommand = struct { + bytes: []u8 = &.{}, + wait: enum { none, spawn, input } = .none, +}; + +pub fn armShellSpawn(pane: *Pane) void { + if (comptime !enabled) return; + std.debug.assert(pane.pending_command.bytes.len == 0); + pane.pending_command.wait = .spawn; +} + +/// Remembers a line pardes types into this terminal as the command it +/// started, for Kill: it runs from the shell's next C mark to its D. +/// ponytail: of several lines queued for a shell not up yet, only the last +/// is remembered, as the first of them. +pub fn noteCommand(pane: *Pane, line: []const u8) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const word = std.mem.trim(u8, line, " \t")[0 .. std.mem.indexOfAny(u8, std.mem.trim(u8, line, " \t"), " \t") orelse std.mem.trim(u8, line, " \t").len]; + var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = state.stream.handler.started +% 1 }; + sent.len = @intCast(@min(word.len, sent.word.len)); + @memcpy(sent.word[0..sent.len], word[0..sent.len]); + pane.sent_command = sent; +} + +/// Whether the command pardes last typed here is running now. +pub fn commandRunning(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + const sent = pane.sent_command orelse return false; + const marks = &state.stream.handler; + return marks.phase == .running and marks.started == sent.seq; +} + +pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { + if (pane.pending_command.wait == .none) return false; + const old_len = pane.pending_command.bytes.len; + const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); + const bytes = if (old_len == 0) + try pane.gpa.alloc(u8, new_len) + else + try pane.gpa.realloc(pane.pending_command.bytes, new_len); + @memcpy(bytes[old_len..][0..command.len], command); + bytes[new_len - 1] = '\r'; + pane.pending_command.bytes = bytes; + pane.greet = false; + return true; +} + +pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { + const pane = p.panes[id] orelse return; + if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; + if (prompt_marks) { + pane.pending_command.wait = .input; + releasePendingCommand(p, id, pane, false); + } else { + pane.greet = false; + releasePendingCommand(p, id, pane, true); + } +} + +pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { + if (pane.pending_command.wait == .input) + releasePendingCommand(p, id, pane, promptInputReady(pane)); +} + +fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { + if (!ready) return; + const bytes = pane.pending_command.bytes; + pane.pending_command = .{}; + if (bytes.len > 0) { + p.emitWrite(id, bytes); + pane.gpa.free(bytes); + } +} + +pub fn deinitPendingCommand(pane: *Pane) void { + if (pane.pending_command.bytes.len > 0) + pane.gpa.free(pane.pending_command.bytes); + pane.pending_command = .{}; +} + +pub fn terminalIo() std.Io { + return if (comptime !pardes.hosted) + std.Io.failing + else + std.Io.Threaded.global_single_threaded.io(); +} + +/// The three numbers ghostty's scrollbar reports; all zero without an emulator. +pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; + +pub fn scrollbar(pane: *const Pane) Scrollbar { + if (comptime !enabled) return .{}; + const state = pane.terminal orelse return .{}; + const sb = state.vt.screens.active.pages.scrollbar(); + return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; +} + +/// The emulator's viewport offset, in SHELL rows: the top of what it shows. +pub fn gridOffset(pane: *const Pane) i32 { + return @intCast(scrollbar(pane).offset); +} + +/// Where the emulator itself puts the cursor, in active-area cells — the origin +/// without one, which is where an empty pane's cursor belongs anyway. +pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; + +pub fn gridCursor(pane: *const Pane) GridCursor { + if (comptime !enabled) return .{}; + const state = pane.terminal orelse return .{}; + const cur = state.vt.screens.active.cursor; + return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; +} + +pub fn visibleCursor(pane: *const Pane) ?GridCursor { + if (comptime !enabled) return null; + const state = pane.terminal orelse return null; + if (!state.vt.modes.get(.cursor_visible)) return null; + const cur = state.vt.screens.active.cursor; + const sb = scrollbar(pane); + const row = sb.total - sb.len + cur.y; + if (row < sb.offset or row - sb.offset >= sb.len) return null; + return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; +} + +/// Move the emulator's viewport by `delta` shell rows (negative scrolls back). +pub fn scrollGrid(pane: *Pane, delta: i32) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.vt.screens.active.scroll(.{ .delta_row = delta }); +} + +/// Is the viewport already showing the last row of output? +pub fn atBottom(pane: *const Pane) bool { + if (comptime !enabled) return true; + const sb = scrollbar(pane); + return sb.offset + sb.len >= sb.total; +} + +/// Snap the viewport back onto live output. +pub fn followOutput(pane: *Pane) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.vt.screens.active.scroll(.active); +} + +/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping +/// a scrollback; the next resize retries with the same numbers. +pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + if (cols != pane.cols) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; +} + +/// DECSET 2004: the program wants its pastes bracketed. +pub fn bracketedPaste(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.modes.get(.bracketed_paste); +} + +/// The program tracks the mouse itself, so a click in its body is its event. +pub fn reportsMouse(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + const m = &state.vt.modes; + return m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any); +} + +/// ...and wants them in SGR (1006) rather than the legacy X10 bytes. +pub fn mouseFormatSgr(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.modes.get(.mouse_format_sgr); +} + +/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body +/// reads and `Save` writes out. Logical lines: rows the terminal wrapped +/// are joined again (ghostty's wrap flags, as pty/run's output is), and +/// the last line ends with a newline. +pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { + if (comptime !enabled) return &.{}; + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try writeScreenText(pane, &out.writer); + return out.toOwnedSlice(); +} + +fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const screen = state.vt.screens.active; + const br = screen.pages.getBottomRight(.screen) orelse return; + var both: TeeWriter = .{ .a = w }; + try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); + if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); +} + +/// Passes bytes through, remembering how many and the last one. +const TeeWriter = struct { + a: *std.Io.Writer, + count: usize = 0, + final: u8 = 0, + writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, + + fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); + var n: usize = 0; + for (data[0 .. data.len - 1]) |bytes| { + try t.a.writeAll(bytes); + t.note(bytes); + n += bytes.len; + } + const pattern = data[data.len - 1]; + for (0..splat) |_| { + try t.a.writeAll(pattern); + t.note(pattern); + n += pattern.len; + } + return n; + } + + fn note(t: *TeeWriter, bytes: []const u8) void { + if (bytes.len == 0) return; + t.count += bytes.len; + t.final = bytes[bytes.len - 1]; + } +}; + +/// How long `screenTextAlloc` would be, counted without keeping it: the +/// length a terminal's body reads as, which its ctl line reports. +pub fn screenTextLen(pane: *Pane) usize { + if (comptime !enabled) return 0; + var buf: [256]u8 = undefined; + var counting: std.Io.Writer.Discarding = .init(&buf); + writeScreenText(pane, &counting.writer) catch return 0; + return @intCast(counting.fullCount()); +} + +/// Release the emulator's heap. The Pane allocation itself is the core's. +pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.stream.deinit(); + state.vt.deinit(gpa); + gpa.destroy(state); + pane.terminal = null; +} + +/// Allocate the live emulator half of a terminal pane. Slot ownership, serial +/// assignment, and spawn effects remain core lifecycle invariants. +pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try createDoc(gpa, cols, rows); + errdefer gpa.destroy(pane); + if (comptime !enabled) return pane; + const state = try gpa.create(State); + errdefer gpa.destroy(state); + state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ + .cols = cols, + .rows = rows, + .max_scrollback = 16 * 1024 * 1024, + }); + state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); + state.replay.head = 0; + state.replay.len = 0; + state.reply_len = 0; + state.stream.handler.inner.effects.write_pty = ptyReport; + state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; + pane.terminal = state; + pane.tty_filter = true; + return pane; +} + +pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try gpa.create(Pane); + pane.* = .{ + .gpa = gpa, + .cols = cols, + .rows = rows, + }; + return pane; +} + +/// Where a restored terminal's history ends and its new shell begins. +pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; + +/// Rebuild a dump's terminal emulator from its recorded output. `live`: a +/// shell will be spawned into it, so the history is marked off from what +/// that shell prints and the pane waits for it like any new terminal. +/// Registration and tag/cwd policy stay with the core; raw VT replay and +/// viewport restoration belong here. +pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { + const terminal = src.terminal.?; + if (comptime !enabled) { + const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); + errdefer p.gpa.destroy(pane); + if (terminal.stream.len > 0) + pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; + return pane; + } + // An older dump's raw output tail cannot come back live: cut off mid + // redraw, or written at sizes the pane no longer has, it replays as + // garbage. Its rendered text can. + const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; + const bytes = if (legacy_text) + try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") + else if (terminal.stream_b64.len > 0) + try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) + else + &.{}; + const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); + if (live) { + if (bytes.len > 0) { + ingest(pane, bytes); + ingest(pane, restored_banner); + } + followOutput(pane); + // A view left scrolled back stays on what it was showing: the + // banner's line breaks scrolled a full screen by that many more. + if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); + armShellSpawn(pane); + } else if (bytes.len > 0) { + ingest(pane, bytes); + followOutput(pane); + if (src.scroll > 0) + scrollGrid(pane, -@as(i32, @intCast(src.scroll))); + } + return pane; +} + +/// Feed the emulator and retain the bounded suffix a dump can replay. Live +/// output and restoration share this byte path, then apply different views. +fn ingest(pane: *Pane, bytes: []const u8) void { + const state = pane.terminal.?; + const replay = &state.replay; + if (bytes.len >= replay.bytes.len) { + const kept = bytes[bytes.len - replay.bytes.len ..]; + @memcpy(&replay.bytes, kept); + replay.head = 0; + replay.len = replay.bytes.len; + } else { + const overflow = bytes.len -| (replay.bytes.len - replay.len); + replay.head = (replay.head + overflow) % replay.bytes.len; + replay.len -= overflow; + const tail = (replay.head + replay.len) % replay.bytes.len; + const first = @min(bytes.len, replay.bytes.len - tail); + @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); + @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); + replay.len += bytes.len; + } + state.stream.nextSlice(bytes); +} + +/// Return the replay ring in chronological order. Wrapped records are copied +/// into `allocator`; contiguous records remain a borrowed slice of the pane. +fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { + const state = pane.terminal orelse return &.{}; + const replay = &state.replay; + if (replay.len == 0) return &.{}; + if (replay.head + replay.len <= replay.bytes.len) + return replay.bytes[replay.head..][0..replay.len]; + const out = try allocator.alloc(u8, replay.len); + const first = replay.bytes.len - replay.head; + @memcpy(out[0..first], replay.bytes[replay.head..]); + @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); + 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 and enabled, 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 "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(!mouseFormatSgr(pane)); + try std.testing.expect(!promptInputReady(pane)); + scrollGrid(pane, 100); + followOutput(pane); + resizeGrid(pane, allocator, 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.expectEqualStrings("", try replayBytes(pane, allocator)); + try std.testing.expect(!failing.has_induced_failure); +} + +test "terminal state keeps parser fragments and sends emulator replies through its owner" { + if (comptime !enabled) return error.SkipZigTest; + 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); + try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); +} + +test "replay keeps a bounded chronological suffix across large writes and wrapping" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const pane = try create(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); + ingest(pane, "hello"); + const small = try replayBytes(pane, gpa); + try std.testing.expectEqualStrings("hello", small); + try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); + + const capacity = pane.terminal.?.replay.bytes.len; + const input = try gpa.alloc(u8, capacity + 7); + defer gpa.free(input); + @memset(input, 0); + const ending = "\x1b[31mred\x1b[0m\r\n"; + @memcpy(input[input.len - ending.len ..], ending); + ingest(pane, input); + try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); + ingest(pane, "next\r\n"); + const wrapped = try replayBytes(pane, gpa); + defer gpa.free(wrapped); + try std.testing.expectEqual(capacity, wrapped.len); + try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); + try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); +} + +test "replay restores terminal cells from the retained stream" { + if (comptime !enabled) 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, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); + const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); + defer gpa.free(encoded); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = pane.cols, + .rows = pane.rows, + .terminal = .{ .stream_b64 = encoded }, + }, false); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + const before = try screenTextAlloc(pane, gpa); + defer gpa.free(before); + const after = try screenTextAlloc(restored, gpa); + defer gpa.free(after); + try std.testing.expectEqualStrings(before, after); + try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); +} + +test "a restored command pane comes back finished, its command not run again" { + if (comptime !enabled or 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 p.newCommand(cmd, "/tmp", "make test"); + feedOutput(p, p.panes[cmd].?, "ok\r\n"); + p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); + try dump.dumpState(p); + const restored = try 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 !enabled or 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"); // `Tty bash`: it comes back as bash + try dump.dumpState(p); + const restored = try 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 "an older dump comes back live from its rendered text, not its raw output tail" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + // A tail cut mid-redraw: relative moves from a cursor it never set. + const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); + defer gpa.free(tail); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = 40, + .rows = 12, + .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, + }, true); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + defer deinitPendingCommand(restored); + const text = try screenTextAlloc(restored, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); +} + +/// Record and parse one live pty read, invalidate its motion surface, and +/// follow it only when the body (possibly parked under a tag edit) is raw. +pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { + // There are no pty reads at all without an emulator to parse them into. + if (comptime !enabled) return; + if (pane.terminal == null) return; + const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or + pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or + pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; + // Sticky bottom, as every other terminal does it: output drags the + // viewport down only when the viewport was already on the last row, so + // a reader scrolled back into the scrollback stays where they scrolled. + const at_bottom = atBottom(pane); + if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); + p.shell_rows.markStale(pane); + if (pane.body.mode == .tty and at_bottom) followOutput(pane); +} + +const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; +const PositionPin = struct { + target: *i32, + row: RowPin, + overlay: ?*EditBuffer, + edit_row: ?i32 = null, +}; + +fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { + if (row < 0) return .{ .offset = row }; + const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); + var left = pages.total_rows - 1 - bounded; + var node = pages.pages.last.?; + while (left >= node.rows()) { + left -= node.rows(); + node = node.prev.?; + } + const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { + failed.* = true; + return .{}; + }; + return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; +} + +fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { + const pin = row.pin orelse return row.offset; + const alive = pages orelse return 0; + if (pin.garbage) return 0; + var after: usize = 0; + var node = alive.pages.last; + while (node) |item| : (node = item.prev) { + if (item == pin.node) + return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; + after += item.rows(); + } + return 0; +} + +fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { + var grid = target.*; + if (overlay) |edit| { + const lines: i32 = @intCast(modal.lineCount(edit.text)); + if (grid >= edit.row and grid < edit.row +| lines) + return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; + if (grid > edit.row) grid = grid -| lines +| edit.rows; + } + return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; +} + +fn pointerRowCount(pane: *const Pane) usize { + var count: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + count += rows.len; + }; + return count; +} + +fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { + const screens = &pane.terminal.?.vt.screens; + const key = screens.active_key; + const generation = screens.generation(key); + const pages = &screens.active.pages; + const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; + var groups: [history_max * 2 + 1]Group = undefined; + groups[0] = .{ + .overlay = if (pane.ovl) |*overlay| overlay else null, + .cursor = &pane.body.cur_row, + .selection = &pane.body.vsel, + }; + var ngroups: usize = 1; + for ([_][]Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { + for (history) |*snapshot| { + groups[ngroups] = .{ + .overlay = if (snapshot.ovl) |*overlay| overlay else null, + .cursor = &snapshot.cur_row, + .selection = &snapshot.vsel, + }; + ngroups += 1; + } + } + const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; + var spans: [groups.len]Span = undefined; + var nspans: usize = 0; + var positions: [groups.len * 2 + panes.Text.max_selections * 2 + 4]PositionPin = undefined; + var npositions: usize = 0; + var failed = false; + for (groups[0..ngroups]) |group| { + if (group.overlay) |overlay| { + spans[nspans] = .{ + .overlay = overlay, + .start = trackRow(pages, overlay.row, &failed), + .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), + }; + nspans += 1; + } + positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); + npositions += 1; + if (group.selection.active) { + positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); + npositions += 1; + } + } + const overlay = groups[0].overlay; + var extra: [panes.Text.max_selections * 2 + 4]*i32 = undefined; + var nextra: usize = 0; + if (pane.body.msel.active) { + extra[nextra] = &pane.body.msel.r0; + extra[nextra + 1] = &pane.body.msel.r1; + nextra += 2; + } + for (pane.body.sels[0..pane.body.nsel]) |*selection| { + extra[nextra] = &selection.row; + extra[nextra + 1] = &selection.arow; + nextra += 2; + } + if (pane.body.last_edit) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + if (pane.look_at) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + for (extra[0..nextra]) |target| { + positions[npositions] = trackPosition(pages, target, overlay, &failed); + npositions += 1; + } + const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; + defer if (pointer_positions) |pins| pane.gpa.free(pins); + if (pointer_positions) |pins| { + var index: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + for (rows) |*row| { + pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); + index += 1; + } + }; + } else failed = true; + ingest(pane, bytes); + // RIS can destroy the alternate screen and every pin it owned. + const alive = if (screens.generation(key) == generation) pages else null; + var moved = false; + var pointer_rows_lost = alive == null or pointer_positions == null; + if (pointer_positions) |pins| for (pins) |position| { + if (alive != null) if (position.row.pin) |pin| { + if (pin.garbage) pointer_rows_lost = true; + }; + }; + for (spans[0..nspans]) |span| { + const start = pinnedRow(alive, span.start); + const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); + moved = moved or start != span.overlay.row or rows != span.overlay.rows; + span.overlay.row = start; + span.overlay.rows = rows; + if (alive) |owner| { + if (span.start.pin) |pin| owner.untrackPin(pin); + if (span.end.pin) |pin| owner.untrackPin(pin); + } + } + for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { + var row = pinnedRow(alive, position.row); + if (position.overlay) |edit| { + if (position.edit_row) |relative| { + row = edit.row +| relative; + } else if (row > edit.row) { + row = if (row < edit.row +| edit.rows) + edit.row + else + row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); + } + } + moved = moved or row != position.target.*; + position.target.* = row; + if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); + }; + if (pointer_rows_lost) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. + if (failed) { + const message = "terminal edit position reset: out of memory"; + @memcpy(pane.msg[0..message.len], message); + pane.msg_len = message.len; + } +} + +test "raw terminal output needs no position tracking allocations" { + if (comptime !enabled) return error.SkipZigTest; + 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 { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active_key == .alternate; +} + +/// Whether a new terminal's greeting may be typed now: only at the shell's +/// first prompt (pardes's own marks: no command started; a prompt drawn +/// again for a resize is the same first prompt), with nothing +/// typed at it and no program on the alternate screen. Any later moment is `.never`, for good: something has run or +/// been typed first, and an `ls` then would go into it. A shell pardes +/// cannot mark has no first prompt to find, and is never greeted. +pub fn greeting(pane: *const Pane) enum { wait, now, never } { + if (comptime !enabled) return .never; + if (pane.fs.unmarked) return .never; + // Text typed into the edit buffer that stands in for the prompt row. + if (pane.ovl) |o| if (o.text.len > 0) return .never; + const state = pane.terminal orelse return .wait; + const marks = &state.stream.handler; + // (Not `declined`: bash's first prompt comes after a D of its own.) + if (marks.started > 0) return .never; + // At a prompt's input (ghostty's semantic marks, pardes's or the + // shell's own), before any command pardes's marks saw run. + if (!promptInputReady(pane)) return .wait; + return if (promptInputEmpty(pane)) .now else .never; +} + +pub fn promptInputReady(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active_key != .alternate and + state.vt.screens.active.cursor.semantic_content == .input; +} + +pub const CommandOutput = struct { + /// Owned by the caller. + text: [:0]const u8, + /// Whether `text` starts where the command did. It does not when that + /// start is not there to read: cut off by `max_rows`, scrolled out of + /// the history (ghostty moved the pin to the oldest row it kept and + /// flagged it `garbage`), erased under it (`MarkedHandler.lost`), or + /// never pinned (a C or D that came on the alternate screen). + whole: bool, +}; + +/// What the newest finished command printed: the screen text between its +/// C and D marks, read from at most `max_rows` rows above its end, so a +/// command that printed the whole history costs no more than its tail. +/// The shell exited in the middle of a command (its `exit 3`): no end mark +/// will come, so the command's output ends where the cursor is. +pub fn endOutputHere(pane: *Pane) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const marks = &state.stream.handler; + if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); +} + +pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { + // Unless there is text to read, whether the nothing it printed is the + // whole of it. + const whole = if (comptime enabled) printed: { + const state = pane.terminal orelse break :printed true; + const marks = &state.stream.handler; + const start = marks.out_start orelse break :printed false; + const end = marks.out_end orelse break :printed false; + const screen = state.vt.screens.get(.primary) orelse break :printed false; + if (end.garbage) break :printed false; + var whole = !marks.lost and !start.garbage; + // D is where the next prompt begins: the output ends a cell before. + const last = end.leftWrap(1) orelse break :printed whole; + if (start.eql(end.*) or last.before(start.*)) break :printed whole; + var from = start.*; + if (last.up(max_rows)) |floor| if (from.before(floor)) { + from = floor; + from.x = 0; + whole = false; + }; + return .{ + .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), + .whole = whole, + }; + } else true; + return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; +} + +/// At a prompt with nothing typed on its line: no input left of the +/// cursor and none under it (text typed and then Ctrl-A'd starts at the +/// cursor). Nothing further right counts: that is where fish draws a +/// right prompt, and fish suggests nothing on an empty line. +pub fn promptInputEmpty(pane: *const Pane) bool { + if (comptime !enabled) return false; + if (!promptInputReady(pane)) return false; + const cursor = &pane.terminal.?.vt.screens.active.cursor; + const row = cursor.page_pin.cells(.all); + for (row[0..@min(cursor.x + 1, row.len)]) |cell| + if (cell.semantic_content == .input and !cell.isEmpty()) return false; + return true; +} + +/// Encode one key for the program that owns a raw terminal and queue its pty +/// write, respecting the application's keyboard protocol and terminal modes. +pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { + if (comptime enabled) { + const pane = p.panes[id] orelse return; + const state = pane.terminal orelse return; + const input = ghostty_vt.input; + const function_keys = comptime keys: { + var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; + for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); + break :keys keys; + }; + const physical: input.Key = switch (key.cp) { + Key.enter => .enter, + Key.backspace => .backspace, + Key.tab => .tab, + Key.escape => .escape, + Key.up => .arrow_up, + Key.down => .arrow_down, + Key.left => .arrow_left, + Key.right => .arrow_right, + Key.home => .home, + Key.end => .end, + Key.page_up => .page_up, + Key.page_down => .page_down, + Key.delete => .delete, + Key.insert => .insert, + Key.print_screen => .print_screen, + Key.scroll_lock => .scroll_lock, + Key.pause => .pause, + Key.menu => .context_menu, + Key.f1...Key.f25 => function_keys[key.cp - Key.f1], + else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, + }; + var utf8: [4]u8 = undefined; + const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; + // A key with no text of its own types its code point only when that + // is a character: the kitty keyboard protocol numbers function and + // modifier keys in the private use area (F3 is U+E016), and a shell + // was typed those as junk. + const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) + utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] + else + ""; + var buffer: [256]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + input.encodeKey(&writer, .{ + .key = physical, + .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, + .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, + .utf8 = text, + .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, + }, options: { + var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); + // fromTerminal cannot know this one and says so, defaulting to + // "option is not alt" — right for an app that lets macOS do the + // unicode translation and hands the encoder the composed text. + // Every pardes shell resolves the modifier itself and hands the + // core the BASE key with the alt bit and no text at all (see + // PardesView.keyDown, and app.mjs doing the same with the same + // two bits), so by the time this runs alt already means alt. + // Left at the default, a macOS build drops the ESC prefix on + // the floor and forwards Alt-n to the child as a bare `n`. + opts.macos_option_as_alt = .true; + break :options opts; + }) catch return; + if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); + return; + } + var control: [1]u8 = undefined; + const bytes: ?[]const u8 = blk: { + if (key.ctrl) { + if (key.cp >= 'a' and key.cp <= 'z') { + control[0] = @intCast(key.cp - 0x60); + break :blk control[0..1]; + } + // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. + if (key.cp >= '@' and key.cp <= '_') { + control[0] = @intCast(key.cp - 0x40); + break :blk control[0..1]; + } + } + if (key.text.len > 0) break :blk key.text; + break :blk switch (key.cp) { + Key.enter => "\r", + Key.backspace => "\x7f", + Key.tab => "\t", + Key.escape => "\x1b", + Key.up => "\x1b[A", + Key.down => "\x1b[B", + Key.right => "\x1b[C", + Key.left => "\x1b[D", + Key.delete => "\x1b[3~", + else => null, + }; + }; + if (bytes) |encoded| + p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); +} + +pub fn enterTty(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; + if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { + const screen = pane.terminal.?.vt.screens.active; + const goff: i32 = @intCast(screen.pages.scrollbar().offset); + const vp_row = pane.gridRow(pane.body.cur_row) - goff; + if (vp_row < 0) break :handoff; + + var grid_col: i32 = @max(0, pane.body.cur_col); + if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { + if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { + .cut => |cols| grid_col += @intCast(cols), + .keep, .blank => {}, + }; + } + const click_pin = screen.pages.pin(.{ + .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, + }) orelse break :handoff; + const cursor_pin = screen.cursor.page_pin.*; + var prompts = cursor_pin.promptIterator(.left_up, null); + const prompt_pin = prompts.next() orelse break :handoff; + if (click_pin.before(prompt_pin)) break :handoff; + const moves = screen.promptClickMove(click_pin); + for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); + for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); + }; + + pane.body.mode = .tty; + followOutput(pane); // entering raw mode is a request for the live shell + pane.body.msel.active = false; + pane.body.vsel.active = false; + pane.body.nsel = 0; + // The raw renderer follows the live cursor. A captured mouse selection + // keeps its modal endpoint for the next return to editor mode. + pane.body.cur_pinned = selected; + pane.body.select = false; + pane.body.restore_cursor = false; + pane.body.sticky_col = -1; + pane.body.normal.clear(); +} + +// Returned slices remain valid until the next cache rebuild or reset. +pub const RowsCache = struct { + /// whose grid this describes; null = the slot is free + pane: ?*const Pane = null, + /// the rows joined by '\n' — `flatSurface` hands this back verbatim + /// instead of rebuilding the join on every keystroke + text: []const u8 = &.{}, + /// slices INTO `text`, absolute grid rows from 0 + rows: [][]const u8 = &.{}, + /// `text` is a prefix of this: blanking a prompt row shortens the join, + /// and the slack is not worth a second allocation to reclaim + text_alloc: []u8 = &.{}, + stale: bool = false, + + pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.text_alloc.len > 0) gpa.free(c.text_alloc); + if (c.rows.len > 0) gpa.free(c.rows); + c.* = .{}; + } + + /// Free a stale entry. Called at the top of `update`, and nowhere else. + pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.stale) c.reset(gpa); + } + + /// `pane`'s grid moved: the entry no longer describes it. + pub fn markStale(c: *RowsCache, pane: *const Pane) void { + if (c.pane == pane) c.stale = true; + } + + pub fn dropPane(c: *RowsCache, pane: *const Pane) void { + if (c.pane != pane) return; + c.pane = null; + c.stale = true; + } +}; + +const Rows = struct { + text_alloc: []u8, + text: []const u8, + rows: [][]const u8, +}; + +const empty_grid = [1][]const u8{""}; + +/// What LEAVING raw tty mode does to one prompt row, decided from its cells +/// alone. See config.tty_blank for why any of this happens. +const PromptCut = union(enum) { + /// show the row exactly as ghostty dumped it + keep, + /// show nothing at all + blank, + /// drop this many leading COLUMNS — the prompt — and keep the rest, which + /// is what was typed at it + cut: usize, +}; + +fn promptCut(pin: ghostty_vt.Pin) PromptCut { + if (config.tty_blank == .prompt_and_input) return .blank; + const cells = pin.cells(.all); + var cols: usize = 0; + while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; + // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or + // a repaint that has moved on. Nothing here is the prompt, so hide nothing. + if (cols == 0) return .keep; + // ...and all prompt, nothing typed yet: the row is chrome end to end. + if (cols >= cells.len) return .blank; + return .{ .cut = cols }; +} + +pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { + if (comptime !enabled) return 0; + if (row < 0) return 0; + const state = pane.terminal orelse return 0; + const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; + if (pin.rowAndCell().row.semantic_prompt == .none) return 0; + return switch (promptCut(pin)) { + .keep => 0, + .blank => raw.len, + .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), + }; +} + +fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { + const cols = switch (promptCut(pin)) { + .keep => return raw, + .blank => return "", + .cut => |n| n, + }; + const cells = pin.cells(.all); + var at: usize = 0; + var col: usize = 0; + while (col < cols and at < raw.len) { + const cell = &cells[col]; + at = @min(raw.len, at + dumpedBytes(pin, cell)); + // the tail cell of a wide glyph spells nothing of its own + col += if (cell.wide == .wide) @as(usize, 2) else 1; + } + return std.mem.trimEnd(u8, raw[at..], " \t"); +} + +fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { + switch (cell.wide) { + .spacer_head, .spacer_tail => return 0, + .narrow, .wide => {}, + } + var n: usize = switch (cell.content_tag) { + .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( + cell.codepoint(), + ) catch 1, + // A cell carrying only a colour still spells one blank in the dump. + else => 1, + }; + if (cell.content_tag == .codepoint_grapheme) { + if (pin.grapheme(cell)) |extra| for (extra) |cp| { + n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; + }; + } + return n; +} + +pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { + if (comptime !enabled) return &empty_grid; + if (pane.terminal == null) return &empty_grid; + const c = &p.shell_rows; + if (!c.stale and c.pane == pane) return c.rows; + if (c.pane != null) { + c.stale = true; + return (try buildRows(p.scratch.allocator(), p, pane)).rows; + } + const built = try buildRows(p.gpa, p, pane); + c.* = .{ + .pane = pane, + .text = built.text, + .rows = built.rows, + .text_alloc = built.text_alloc, + }; + return c.rows; +} + +/// 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 { + const rows = try shellRows(p, pane); + if (pane.ovl == null) return rows; + var last = rows.len; + if (pane.ovl) |overlay| + last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); + var count = last; + if (pane.ovl) |overlay| { + if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) + count = count - @min( + @as(usize, @intCast(overlay.rows)), + last - @as(usize, @intCast(overlay.row)), + ) + @max(1, modal.lineCount(overlay.text)); + } + const lines = try p.scratch.allocator().alloc([]const u8, count); + var n: usize = 0; + var grid_row: usize = 0; + while (grid_row < last) : (grid_row += 1) { + if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { + var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); + while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; + grid_row += @intCast(overlay.rows - 1); + continue; + }; + lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; + n += 1; + } + return lines[0..n]; +} + +/// Flatten `cursorLines` without rebuilding the common cached/no-overlay +/// case. Scratch-owned when a join is required. +pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { + const cache = &p.shell_rows; + if (!cache.stale and cache.pane == pane and + lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; + var total: usize = if (lines.len > 0) lines.len - 1 else 0; + for (lines) |line| total += line.len; + const text = try p.scratch.allocator().alloc(u8, total); + var at: usize = 0; + for (lines, 0..) |line, i| { + if (i > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..line.len], line); + at += line.len; + } + return text; +} + +/// Materialize or extend the terminal edit overlay with one exact allocation. +/// Row slices are scratch-owned/borrowed; only the joined text is installed. +pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { + const want_lo = @max(0, @min(lo, hi)); + const want_hi = @max(want_lo, @max(lo, hi)); + const fresh = pane.ovl == null; + const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; + const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); + const up = old.row - want_lo; + const down = want_hi - (old.row + lines - 1); + const extending = fresh or up > 0 or down > 0; + var row0 = old.row; + var covered = old.rows; + var text = old.text; + var owned = false; + if (extending) { + const rows = shellRows(p, pane) catch return null; + row0 = old.row - @max(0, up); + covered = old.rows + @max(0, up) + @max(0, down); + const up_len: usize = @intCast(@max(0, up)); + const down_len: usize = @intCast(@max(0, down)); + const parts = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; + for (parts[0..up_len], 0..) |*part, i| { + const src = @as(usize, @intCast(row0)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + const middle: usize = @intCast(old.row); + parts[up_len] = if (fresh) + (if (middle < rows.len) rows[middle] else "") + else + old.text; + for (parts[up_len + 1 ..], 0..) |*part, i| { + const src = @as(usize, @intCast(old.row + old.rows)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + text = std.mem.join(p.gpa, "\n", parts) catch return null; + owned = true; + } + + const row: usize = @intCast(@max(0, want_lo - row0)); + const line_len: i32 = @intCast(modal.lineSlice(text, row).len); + if (col > line_len) { + const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { + if (owned) p.gpa.free(text); + return null; + }; + @memset(spaces, ' '); + const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { + if (owned) p.gpa.free(text); + return null; + }; + if (owned) p.gpa.free(text); + text = padded; + owned = true; + } + if (owned) { + if (pane.ovl) |overlay| p.gpa.free(overlay.text); + pane.ovl = .{ .row = row0, .rows = covered, .text = text }; + } + return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; +} + +/// Consume a rewritten overlay, freeing the terminal edit text it replaces. +pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { + const overlay = if (pane.ovl) |*value| value else return pardes.edit.retireEditText(p, new); + for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + } + p.gpa.free(overlay.text); + overlay.text = new; +} + +/// The shell's screen and scrollback (the primary screen, even under a +/// full-screen program) as VT that replays to what was shown: styled +/// text, soft-wrapped lines rejoined so they reflow at another width. +fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { + const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; + var out: std.Io.Writer.Allocating = .init(arena); + try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); + return out.written(); +} + +/// Serialize terminal-only state; the core supplies shared pane metadata. +pub fn dumpPane( + pane: *Pane, + arena: std.mem.Allocator, + tag: []const u8, + body: []const u8, + scroll: usize, +) !dump.Pane { + if (!enabled or pane.terminal == null) { + const text = if (pane.ovl) |overlay| overlay.text else ""; + return .{ + .kind = .terminal, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .terminal = .{ + .cwd = try arena.dupe(u8, pane.cwdSlice()), + .shell = try arena.dupe(u8, pane.shell orelse ""), + .command = try arena.dupe(u8, pane.command orelse ""), + .status = pane.command_status, + .stream = try arena.dupe(u8, text), + .stream_b64 = &.{}, + .cursor = .{ .col = 0, .row = 0 }, + }, + }; + } + const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); + const extra = if (pane.ovl) |overlay| overlay.text.len else 0; + const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); + var len: usize = 0; + var lines = std.mem.splitAny(u8, full, "\n"); + var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); + var row: i32 = 0; + var skip: i32 = 0; + while (lines.next()) |raw| : (row += 1) { + // Hidden overlay rows still consume prompt pins to keep them aligned. + const prompt = if (pane.body.mode != .tty) prompts.next() else null; + if (skip > 0) { + skip -= 1; + continue; + } + if (row > 0) { + stream[len] = '\n'; + len += 1; + } + if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { + @memcpy(stream[len..][0..overlay.text.len], overlay.text); + len += overlay.text.len; + skip = overlay.rows - 1; + continue; + }; + const shown = if (prompt) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + @memcpy(stream[len..][0..shown.len], shown); + len += shown.len; + } + return .{ + .kind = .terminal, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .terminal = .{ + .cwd = try arena.dupe(u8, pane.cwdSlice()), + .shell = try arena.dupe(u8, pane.shell orelse ""), + .command = try arena.dupe(u8, pane.command orelse ""), + .status = pane.command_status, + .stream = stream[0..len], + .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), + .stream_is_screen = true, + .cursor = .{ + .col = pane.terminal.?.vt.screens.active.cursor.x, + .row = pane.terminal.?.vt.screens.active.cursor.y, + }, + }, + }; +} + +fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { + const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); + var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); + // split yields one more item than delimiters; the extra final slot is the + // cursor row retained below. + const n_rows = std.mem.count(u8, full, "\n") + 2; + const rows = try alloc.alloc([]const u8, n_rows); + errdefer alloc.free(rows); + // Blanking a prompt row only ever SHORTENS it and the retained cursor row + // adds one separator, so the dump's length plus one bounds the join. + const text = try alloc.alloc(u8, full.len + 1); + errdefer alloc.free(text); + var at: usize = 0; + var n: usize = 0; + var it = std.mem.splitScalar(u8, full, '\n'); + while (it.next()) |raw| { + const shown = if (pit.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + if (n > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..shown.len], shown); + rows[n] = text[at..][0..shown.len]; + at += shown.len; + n += 1; + } + text[at] = '\n'; + at += 1; + rows[n] = text[at..][0..0]; + n += 1; + std.debug.assert(n == n_rows); + return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; +} + +pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { + const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { + const state = pane.terminal orelse break :vp &.{}; + const screen = state.vt.screens.active; + var tl = screen.pages.getTopLeft(.viewport); + tl.x = 0; + const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; + var rows_out: std.Io.Writer.Allocating = .init(arena); + try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); + const raw = try rows_out.toOwnedSlice(); + var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); + const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); + var lines = std.mem.splitScalar(u8, raw, '\n'); + var n: usize = 0; + while (lines.next()) |ln| { + vp[n] = if (pane.body.mode != .tty) + if (prompts.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln + else + ln + else + ln; + n += 1; + } + std.debug.assert(n == vp.len); + break :vp vp; + }; + + const len = fillBody(null, pane, vp); + const out = try arena.alloc(u8, len); + const filled = fillBody(out, pane, vp); + std.debug.assert(filled == out.len); + return out; +} + +pub const BodyRow = union(enum) { + grid: i32, + edit: struct { line: []const u8, idx: usize }, +}; + +const BodyWalk = struct { + pane: *Pane, + goff: i32, + g: i32, + /// the buffer can start above the viewport: drop the lines scrolled past + skip: usize, + n: usize = 0, + lines: ?std.mem.SplitIterator(u8, .scalar) = null, + covered: i32 = 0, + line_idx: usize = 0, + + fn init(pane: *Pane) BodyWalk { + const off = pane.scroll(); + const goff = gridOffset(pane); + return .{ + .pane = pane, + .goff = goff, + .g = if (pane.body.mode == .tty) goff else pane.gridRow(off), + .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, + }; + } + + fn next(w: *BodyWalk) ?BodyRow { + while (w.n < w.pane.rows) { + if (w.lines) |*it| { + if (it.next()) |line| { + const idx = w.line_idx; + w.line_idx += 1; + // Lines scrolled off the top still count: the index names a + // line of the BUFFER, not of the visible body. + if (w.skip > 0) { + w.skip -= 1; + continue; + } + w.n += 1; + return .{ .edit = .{ .line = line, .idx = idx } }; + } + // The buffer stands in for `rows` shell rows however many lines + // it actually spelled, which is the whole slide. + w.g += w.covered; + w.skip = 0; + w.lines = null; + continue; + } + if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { + w.lines = std.mem.splitScalar(u8, o.text, '\n'); + w.covered = o.rows; + w.line_idx = 0; + continue; + }; + const vi = w.g - w.goff; + w.g += 1; + w.n += 1; + return .{ .grid = vi }; + } + return null; + } +}; + +/// Run the terminal body row walk. A null destination counts bytes; a slice +/// fills the exact allocation made from that count. +fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { + var walk: BodyWalk = .init(pane); + var written: usize = 0; + var first = true; + while (walk.next()) |row| { + if (!first) { + if (dst) |out| out[written] = '\n'; + written += 1; + } + first = false; + const bytes = switch (row) { + .edit => |e| e.line, + .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) + viewport[@intCast(vi)] + else + "", + }; + if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); + written += bytes.len; + } + return written; +} + +// Match surviving edit-buffer rows to their original terminal styles. +const EditAnchors = struct { + /// the buffer's own text, walked in order: a line the VIEWPORT skipped still + /// consumes the row it came from, so the lines below it stay aligned + text: []const u8 = &.{}, + at: usize = 0, + shell: []const []const u8 = &.{}, + /// the covered span, absolute grid rows, as `[first, end)` + first: usize = 0, + end: usize = 0, + lines: usize = 0, + /// the line `at` names, and the first row still unclaimed + idx: usize = 0, + cursor: usize = 0, + budget: usize = 0, + active: bool = false, + + fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { + if (o.rows <= 0 or o.row < 0) return .{}; + const first: usize = @intCast(o.row); + const screen = pane.terminal.?.vt.screens.active; + const total = screen.pages.scrollbar().total; + if (first >= total) return .{}; + const covered: usize = @intCast(o.rows); + const count = @min(covered, total - first); + const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; + const br = screen.pages.pin(.{ .screen = .{ + .x = screen.pages.cols - 1, + .y = @intCast(first + count - 1), + } }) orelse return .{}; + const arena = p.scratch.allocator(); + var output: std.Io.Writer.Allocating = .init(arena); + screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; + const shell = arena.alloc([]const u8, count) catch return .{}; + var raw = std.mem.splitScalar(u8, output.written(), '\n'); + var pins = tl.rowIterator(.right_down, br); + for (shell) |*row| { + const text = raw.next() orelse ""; + row.* = if (pins.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text + else + text; + } + const lines = std.mem.count(u8, o.text, "\n") + 1; + return .{ + .text = o.text, + .shell = shell, + .first = first, + .end = first + count, + .lines = lines, + .cursor = first, + .budget = covered + 4 * lines, + .active = true, + }; + } + + fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { + if (!a.active or idx >= a.lines) return null; + var found: ?Anchor = null; + while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); + return found; + } + + fn nextLine(a: *EditAnchors) ?[]const u8 { + if (a.at > a.text.len) return null; + const rest = a.text[a.at..]; + if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { + a.at += n + 1; + return rest[0..n]; + } + // The last line has no terminator; one past the end ends the walk. + a.at = a.text.len + 1; + return rest; + } + + /// Where this line still stands over the grid, if anywhere. + fn claim(a: *EditAnchors, line: []const u8) ?Anchor { + const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; + var k = a.cursor; + while (k < end) : (k += 1) { + if (a.budget == 0) return null; + a.budget -= 1; + if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; + a.cursor = k + 1; + return .{ .row = @intCast(k) }; + } + if (a.cursor >= a.end) return null; + const shell = a.shell[a.cursor - a.first]; + var p: usize = 0; + while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; + var s: usize = 0; + const room = @min(line.len, shell.len) - p; + while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; + if (p + s == 0) return null; + if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; + const row = a.cursor; + if (s > 0 or p >= shell.len) a.cursor += 1; + return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; + } +}; + +const Anchor = struct { + /// the row, absolute while it comes from `EditAnchors`, viewport once + /// `recolorAnsi` has subtracted the walk's offset + row: i32, + prefix: usize = std.math.maxInt(usize), + suffix: usize = 0, + /// the row's own dumped length — what the suffix is measured from on the + /// GRID side, where the edit may have changed the byte count + shell_len: usize = 0, + + fn whole(an: Anchor) bool { + return an.prefix == std.math.maxInt(usize); + } +}; + +pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { + // No emulator, no ANSI cells: the whole pass — and the 256-colour theme + // projection behind it — is compiled out. + if (comptime !enabled) return; + if (pane.terminal == null) return; + const body_y = p.bodyTop(pane, r); + var filtered_storage: FilteredColors = undefined; + const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { + const tz_filter = tracy.zone(@src(), "filterInit"); + defer tz_filter.end(); + filtered_storage = FilteredColors.init(p, pane); + break :blk &filtered_storage; + } else null; + // DECSCNM, read once: the filtered palette folds it in itself, the raw + // path needs it per cell. + const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); + const pages = &pane.terminal.?.vt.screens.active.pages; + const vp_rows: i32 = @intCast(scrollbar(pane).len); + // Which buffer lines the user has not actually changed, so a row swallowed + // by a growing buffer keeps the colour it still stands over. + var anchors: ?EditAnchors = null; + var walk: BodyWalk = .init(pane); + var lines = std.mem.splitScalar(u8, body, '\n'); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + // Before any early exit below, or the lines fall out of step with rows. + const text = lines.next() orelse ""; + const anchor: Anchor = switch (row) { + .edit => |e| blk: { + if (anchors == null) anchors = .init(p, pane, pane.ovl.?); + var an = anchors.?.shellRow(e.idx) orelse continue; + an.row -= walk.goff; + break :blk an; + }, + .grid => |v| .{ .row = v }, + }; + const vi = anchor.row; + if (vi < 0 or vi >= vp_rows) continue; + const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { + if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; + break :cut switch (promptCut(row_pin)) { + .keep => 0, + // Blanked end to end: the row shows nothing of the grid, so + // projecting the prompt's own colours onto it would be a lie. + .blank => continue, + .cut => |n| std.math.cast(u16, n) orelse continue, + }; + }; + if (cut > 0 and text.len == 0) continue; + var at: usize = 0; + var sc: u16 = 0; + var gc: u16 = cut; + var sb: usize = 0; + const mine_from = @min(anchor.prefix, text.len); + const mine_to = text.len - @min(anchor.suffix, text.len); + var crossed = false; + while (at < text.len and sc < tw) { + const stop = modal.nextGrapheme(text, at); + if (stop <= at) break; + const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; + if (at >= mine_from and at < mine_to) { + sc += span; + at = stop; + continue; + } + if (at >= mine_to and !crossed) { + crossed = true; + const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); + while (sb < upto) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + sb += dumpedBytes(row_pin, ci.cell); + gc = std.math.add(u16, gc, 1) catch break; + } + } + const want = stop - at; + // Consume every cell that contributed to this grapheme. A cluster + // ghostty split across several cells is still ONE printed glyph. + var covered: usize = 0; + var style: ?pardes.CellStyle = null; + while (covered < want) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) + style = cellStyle(p, ci, filtered, scnm); + covered += dumpedBytes(row_pin, ci.cell); + gc = std.math.add(u16, gc, 1) catch break; + // A spacer contributes no bytes; without this the loop would + // spin on a row that ends in one. + if (covered == 0 and gc >= pane.cols) break; + } + while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| { + if (t.cell.wide != .spacer_tail) break; + gc = std.math.add(u16, gc, 1) catch break; + } + if (style) |st| for (0..span) |k| { + const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = st; + }; + sb += covered; + sc += span; + at = stop; + } + var tail: ?pardes.CellStyle = null; + if (anchor.whole() or anchor.suffix > 0) { + while (sc < tw) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + gc = std.math.add(u16, gc, 1) catch break; + if (ci.cell.wide == .spacer_tail) continue; + const cell = s.at(tx + sc, body_y + vr); + sc += 1; + const style = cellStyle(p, ci, filtered, scnm); + tail = style; + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = style; + } + if (tail) |style| while (sc < tw) : (sc += 1) { + const cell = s.at(tx + sc, body_y + vr); + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = style; + }; + } + } +} + +fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { + const style = ci.style(); + var cs: pardes.CellStyle = .{ + .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), + .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), + .bold = style.flags.bold, + .dim = style.flags.faint, + .italic = style.flags.italic, + .blink = style.flags.blink, + .reverse = style.flags.inverse, + .invisible = style.flags.invisible, + .strikethrough = style.flags.strikethrough, + .ul = switch (style.flags.underline) { + .none => .off, + .single => .single, + .double => .double, + .curly => .curly, + .dotted => .dotted, + .dashed => .dashed, + }, + }; + if (filtered == null) switch (ci.cell.content_tag) { + .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), + .bg_color_rgb => { + const rgb = ci.cell.content.color_rgb; + cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; + }, + else => {}, + }; + return cs; +} + +const FilteredColors = struct { + source: GColor.Palette, + target: *const GColor.Palette, + theme_bg: GColor.RGB, + theme_fg: GColor.RGB, + dynamic_bg: ?GColor.RGB, + dynamic_fg: ?GColor.RGB, + default_bg: GColor.RGB, + /// What a foreground too near `default_bg` becomes instead. + fallback_fg: GColor.RGB, + default_bg_luminance: f64, + fg_for_palette: [256]pardes.Color = undefined, + bg_for_palette: [256]pardes.Color = undefined, + /// The two answers for a cell that names no colour of its own. + fg_default: pardes.Color = undefined, + bg_default: pardes.Color = undefined, + cache_rgb: [256]GColor.RGB = undefined, + cache_key: [256]u8 = undefined, + cache_valid: [256]bool = @splat(false), + + fn init(p: *Pardes, pane: *const Pane) FilteredColors { + var source = GColor.default; + for (&source, 0..) |*rgb, i| + rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + const theme = p.theme(); + var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); + var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); + var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); + var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); + if (pane.terminal.?.vt.modes.get(.reverse_colors)) { + std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); + std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); + } + var self: FilteredColors = .{ + .source = source, + .target = p.tty_filter_palette.get(theme), + .theme_bg = theme_bg, + .theme_fg = theme_fg, + .dynamic_bg = dynamic_bg, + .dynamic_fg = dynamic_fg, + .default_bg = theme_bg, + .fallback_fg = theme_fg, + .default_bg_luminance = luminanceOf(theme_bg), + }; + if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); + self.default_bg_luminance = luminanceOf(self.default_bg); + if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) + self.fallback_fg = self.theme_bg; + + self.fg_default = asPardesColor(self.legible( + if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, + )); + self.bg_default = asPardesColor(self.default_bg); + for (&self.source, 0..) |current, i| { + const idx: u8 = @intCast(i); + const mapped = self.paletteRgb(idx, current); + self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); + self.bg_for_palette[idx] = asPardesColor(mapped); + } + return self; + } + + fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { + return switch (style.fg_color) { + .none => self.fg_default, + .palette => |idx| self.fg_for_palette[idx], + .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ + .default = self.dynamic_fg orelse self.theme_fg, + .palette = &self.source, + .bold = null, + })))), + }; + } + + fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { + switch (cell.content_tag) { + .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], + .bg_color_rgb => {}, + else => switch (style.bg_color) { + .none => return self.bg_default, + .palette => |idx| return self.bg_for_palette[idx], + .rgb => {}, + }, + } + // Truecolour, from either the cell or its style. + return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); + } + + fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { + if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= + config.tty_filter_min_contrast) return rgb; + return self.fallback_fg; + } + + fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { + if (current.eql(GColor.default[idx])) return self.target[idx]; + return self.keyedRgb(current); + } + + fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { + return self.target[self.nearestKey(rgb)]; + } + + fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { + const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; + const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); + if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) + return self.cache_key[slot]; + + var best: u8 = 0; + var best_distance: u32 = std.math.maxInt(u32); + for (GColor.default, 0..) |candidate, i| { + const distance = colorDistance(rgb, candidate); + // Strict comparison makes duplicate-colour ties stable at the + // lowest canonical xterm key. + if (distance < best_distance) { + best_distance = distance; + best = @intCast(i); + } + } + self.cache_rgb[slot] = rgb; + self.cache_key[slot] = best; + self.cache_valid[slot] = true; + return best; + } +}; + +const channel_luminance: [256]f64 = blk: { + @setEvalBranchQuota(20000); + var table: [256]f64 = undefined; + for (&table, 0..) |*slot, c| { + const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; + slot.* = if (normalized <= 0.03928) + normalized / 12.92 + else + std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); + } + break :blk table; +}; + +fn luminanceOf(rgb: GColor.RGB) f64 { + return 0.2126 * channel_luminance[rgb.r] + + 0.7152 * channel_luminance[rgb.g] + + 0.0722 * channel_luminance[rgb.b]; +} + +/// ghostty's `RGB.contrast` with both luminances already in hand. +fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { + const lighter = @max(a_luminance, b_luminance); + const darker = @min(a_luminance, b_luminance); + return (lighter + 0.05) / (darker + 0.05); +} + +fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { + const dr = @as(i32, a.r) - @as(i32, b.r); + const dg = @as(i32, a.g) - @as(i32, b.g); + const db = @as(i32, a.b) - @as(i32, b.b); + 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)), + ); + } + } +} + +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(); + try testing.expect(pane.tty_filter); + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ + "\x1b[38;5;196mB" ++ + "\x1b[38;2;255;0;0mC" ++ + "\x1b[0;48;5;25mD" ++ + "\x1b[0;48;2;0;95;175mE" ++ + "\x1b[0;1;2;3;4;5;7;8;9mF" ++ + "\x1b[0;48;5;25m\x1b[K" ++ + "\r\n\x1b[0;38;5;2m界" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + + const raw = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); + + pane.tty_filter = true; + _ = frame.reset(.retain_capacity); + const filtered = try p.render(frame.allocator()); + var expected_cache: FilterPalette = .{}; + const expected = expected_cache.get(p.theme()); + try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); + try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); + try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); + try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); + try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); + + const attrs = filtered.at(tx + 5, body_y).style; + try testing.expect(attrs.bold); + try testing.expect(attrs.dim); + try testing.expect(attrs.italic); + try testing.expect(attrs.blink); + try testing.expect(attrs.reverse); + try testing.expect(attrs.invisible); + try testing.expect(attrs.strikethrough); + try testing.expectEqual(.single, attrs.ul); + + const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; + try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); + try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); + try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); + try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); + // A filtered terminal never delegates either colour to a backend palette, + // including cells which were empty/default before the pass. + for (0..r.w - config.GUTTER) |col| { + const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); + try testing.expect(!cell.default); + switch (cell.style.fg) { + .rgb => {}, + else => return error.FilteredForegroundWasNotRgb, + } + switch (cell.style.bg) { + .rgb => {}, + else => return error.FilteredBackgroundWasNotRgb, + } + } + + // Colors remains the global master gate. The pane remembers Filter while + // ANSI projection is dormant, and resumes it without replaying VT bytes. + p.settings.colors = false; + _ = frame.reset(.retain_capacity); + const plain = try p.render(frame.allocator()); + try testing.expect(pane.tty_filter); + try testing.expectEqual(asPardesColor(asGhostRgb(p.theme().fg.?)), plain.at(tx, body_y).style.fg); + p.settings.colors = true; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); + const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; + try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); + pane.tty_filter = false; + pane.tty_filter = true; + try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); + _ = frame.reset(.retain_capacity); + const osc_palette = try p.render(frame.allocator()); + try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); + + // Dynamic default foreground/background colours key every default cell, + // including the otherwise blank end of the row. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ + "\x1b]11;#5f5f5f\x1b\\" } }); + const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; + const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; + try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); + try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); + _ = frame.reset(.retain_capacity); + const dynamic = try p.render(frame.allocator()); + const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), blank.fg); + try testing.expectEqual(asPardesColor(expected[59]), blank.bg); + + const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; + try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); + try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); + const reversed_explicit = reversed.at(tx, body_y).style; + try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); + try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); + try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); + _ = frame.reset(.retain_capacity); + const unreversed = try p.render(frame.allocator()); + const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); + try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); + + // The cache is keyed by values, not a theme name. Replacing a custom + // theme in place immediately recolours already-rendered indexed cells. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); + var custom = p.theme().*; + custom.name = try p.gpa.dupe(u8, "same-name"); + custom.palette = null; + custom.kw = .{ 1, 2, 3 }; + p.custom_theme = custom; + _ = frame.reset(.retain_capacity); + const custom_first = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); + if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; + _ = frame.reset(.retain_capacity); + const custom_second = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); +} + +test "terminal Filter keeps extended keys dark-to-light on a light theme" { + const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); + defer p.deinit(); + try std.testing.expectEqualStrings("acme", p.theme().name); + var cache: FilterPalette = .{}; + const palette = cache.get(p.theme()); + try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); + try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); +} + +test "terminal Filter preserves exact palette-null light theme default roles" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + var light = p.theme().*; + light.name = try p.gpa.dupe(u8, "filter-light-defaults"); + light.bg = .{ 0xf8, 0xf8, 0xf8 }; + light.fg = .{ 0x38, 0x38, 0x38 }; + light.palette = null; + p.custom_theme = light; + + const pane = p.panes[0].?; + try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); + try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); + pane.tty_filter = true; + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + const ordinary = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); +} + +test "terminal Filter maps the default roles before it maps anything else" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + // Native dark/light palettes plus legacy helix/dark/acme, including + // the null-page fallback that only the legacy dark theme exercises. + for (0..9) |t| { + p.settings.theme = @intCast(t); + const stage_one = FilteredColors.init(p, pane); + // `dark` declares no background of its own, which is exactly why the + // resolver reads the tag colours as the fallback rather than `.?`. + const theme = p.theme(); + try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); + try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); + // With no OSC 11 in play the mapped page IS that anchor, and the + // fallback is the other one: a background never contrasts with itself. + try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); + try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); + } + + p.settings.theme = 0; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); + var moved = FilteredColors.init(p, pane); + try testing.expect(!moved.default_bg.eql(moved.theme_bg)); + try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); +} + +test "terminal Filter refuses a foreground that would collapse onto the page" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ + "\x1b[0;30mB" ++ + "\x1b[0;31mR" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + + for (0..9) |t| { + p.settings.theme = @intCast(t); + var fc = FilteredColors.init(p, pane); + const page = asPardesColor(fc.default_bg); + const rescued = asPardesColor(fc.fallback_fg); + _ = frame.reset(.retain_capacity); + const g = try p.render(frame.allocator()); + + // The colour each of the three would have been given with no floor. + const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); + const raw_black = fc.paletteRgb(0, GColor.default[0]); + const raw_red = fc.paletteRgb(1, GColor.default[1]); + + for ([_]struct { at: u16, raw: GColor.RGB }{ + .{ .at = 0, .raw = raw_white }, + .{ .at = 1, .raw = raw_black }, + .{ .at = 2, .raw = raw_red }, + }) |case| { + const cell = g.at(tx + case.at, body_y).style; + try testing.expectEqual(page, cell.bg); + if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { + // Refused: the projection's answer is not painted, the anchor is. + try testing.expectEqual(rescued, cell.fg); + try testing.expect(!std.meta.eql(cell.fg, cell.bg)); + } else { + // Cleared the floor, so stage two leaves it exactly alone. + try testing.expectEqual(asPardesColor(case.raw), cell.fg); + } + // Either way a filtered cell delegates neither colour to a backend. + switch (cell.fg) { + .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= + config.tty_filter_min_contrast), + else => return error.FilteredForegroundWasNotRgb, + } + } + + // At least one of the three has to have been a real collapse, or this + // theme proved nothing: white on the light theme, black on the dark. + try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or + raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); + // A saturated red is never the page on any curated theme. + try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); + } +} + +test "terminal Filter holds every projected foreground off the page" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + + for (0..9) |t| { + p.settings.theme = @intCast(t); + var fc = FilteredColors.init(p, pane); + var refused: usize = 0; + for (fc.target, 0..) |projected, key| { + const ink = fc.legible(projected); + try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); + if (!ink.eql(projected)) { + refused += 1; + try testing.expect(ink.eql(fc.fallback_fg)); + // Only ever refused for being too near the page. + try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); + } + // The key a background asks for is handed back untouched, including + // the one whose value is the page itself. + try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); + } + // Every curated theme owns at least one collapsing key — that is why + // the floor exists — and the floor must not be flattening the palette. + try testing.expect(refused > 0); + try testing.expect(refused < fc.target.len / 8); + } +} + +test "tty ansi colors follow the prompt hug into normal mode" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; + const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; + + // tty mode projects the emulator's ansi colours cell for cell. + pane.body.mode = .tty; + p.shell_rows.stale = true; + const tty = try p.render(frame.allocator()); + try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); + try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); + + pane.body.mode = .normal; + p.shell_rows.stale = true; + _ = frame.reset(.retain_capacity); + const norm = try p.render(frame.allocator()); + try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); + try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); + try testing.expectEqual(red, norm.at(tx, body_y).style.fg); + try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); +} + +test "a prompt row hidden end to end paints nothing at all" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tag_expanded = false; // a 12x8 screen: the body, not the tag + p.sync(); + pane.tty_filter = false; + pane.body.mode = .normal; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + p.shell_rows.stale = true; + const s = try p.render(frame.allocator()); + + try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); + 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 }; +} + +pub 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. + if (comptime !enabled) return; + 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); +} + +pub fn undo(p: *Pardes, pane: *Pane) void { + const back_to = pane.body.step(p.gpa, pane.ovl, true) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = back_to.ovl; + pane.ensureCursorVisible(); +} + +pub fn redo(p: *Pardes, pane: *Pane) void { + const forward_to = pane.body.step(p.gpa, pane.ovl, false) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = forward_to.ovl; + pane.ensureCursorVisible(); +} + +pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { + const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); + const room = state.reply.len - state.reply_len; + const n = @min(room, data.len); + @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); + state.reply_len += @intCast(n); +} + +const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( + @FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"), +).optional.child).pointer.child).@"fn".return_type.?; +pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs { + return .{}; +} diff --git a/src/tty/tty.zig b/src/tty/tty.zig index f5ae078a..3902271c 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1915,7 +1915,7 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { shell.gens[0] = 2; _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.panes.Terminal.screenTextAlloc(core.panes[0].?, gpa); + const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); diff --git a/test/mode.zig b/test/mode.zig index cba93c30..767cda93 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -26,7 +26,7 @@ fn customTag(pane: *pardes.Pane, text: []const u8) !void { } test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100 }); defer p.deinit(); p.presentation.enabled = false; diff --git a/test/panes.zig b/test/panes.zig index 3b2bea0a..f7ca9fc5 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -864,7 +864,7 @@ const TtySelectionTests = struct { } test "tty selection yields to a new modal cursor selection" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); p.presentation.enabled = false; @@ -889,7 +889,7 @@ const TtySelectionTests = struct { } test "tty selection preserves its exact stream through yank clipboard and mode changes" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |prompt| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -949,7 +949,7 @@ const TtySelectionTests = struct { } test "tty selection pastes across panes once with existing bracket and mouse protocols" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |bracketed| { for ([_]bool{ false, true }) |reports_mouse| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 24 }); @@ -1028,14 +1028,14 @@ const TtySelectionTests = struct { // than the text goes and reads the desktop clipboard on its own account, // and a coding agent reading it is looking for an image, not for words. test "raw tty paste chords type at the program instead of reaching it as keys" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |bracketed| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); const pane = p.panes[0].?; try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); if (bracketed) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - try std.testing.expectEqual(bracketed, panes.Terminal.bracketedPaste(pane)); + try std.testing.expectEqual(bracketed, panes.terminal.bracketedPaste(pane)); p.registers.put(p.gpa, '"', "one\ntwo", 0, 1, true); // what a `y` anywhere left behind var buf: [256]u8 = undefined; _ = childInput(p, &buf); @@ -1833,7 +1833,7 @@ test "terminal overlay recoloring never materializes unrelated history" { _ = try p.render(frame.allocator()); try testing.expect(p.shell_rows.pane == null); - pane.ovl.?.row = panes.Terminal.gridOffset(pane); + pane.ovl.?.row = panes.terminal.gridOffset(pane); p.gpa.free(pane.ovl.?.text); pane.ovl.?.text = try p.gpa.dupe(u8, "caf\xc3\xa9 \xe7\x95\x8c"); _ = frame.reset(.retain_capacity); @@ -1847,7 +1847,7 @@ test "terminal overlay recoloring never materializes unrelated history" { } test "terminal output keeps following new rows after scrollback eviction" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1863,9 +1863,9 @@ test "terminal output keeps following new rows after scrollback eviction" { for (0..3) |phase| { if (phase > 0) { pane.body.mode = .normal; - panes.Terminal.scrollGrid(pane, -30); + panes.terminal.scrollGrid(pane, -30); try std.testing.expect(pages.scrollbar().offset < pages.scrollbar().total - pane.rows); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); } for (phase * 20_000..(phase + 1) * 20_000) |n| { var buf: [64]u8 = undefined; @@ -1878,7 +1878,7 @@ test "terminal output keeps following new rows after scrollback eviction" { try std.testing.expect(pages.page_size <= pages.maxSize()); const sb = pages.scrollbar(); try std.testing.expectEqual(sb.total - pane.rows, sb.offset); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); var last_buf: [16]u8 = undefined; const last = try std.fmt.bufPrint(&last_buf, "row-{d:0>5}", .{(phase + 1) * 20_000 - 1}); @@ -1908,7 +1908,7 @@ test "terminal output keeps following new rows after scrollback eviction" { } test "terminal edit stays on its surviving row when old scrollback is evicted" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1946,7 +1946,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { } } try std.testing.expect(removed > 0 and removed < original_row); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); const row = original_row - @as(i32, @intCast(removed)); try std.testing.expectEqualStrings(last, modal.lineSlice(full, @intCast(row))); @@ -1956,7 +1956,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { } test "terminal edits and undo survive partial history clearing and whole-screen loss" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const Action = enum { clear_history, partial_clear_history, reset_primary, reset_alternate, evict_all, hidden_undo }; for (std.enums.values(Action)) |action| { @@ -1978,7 +1978,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen pane.body.cur_col = 4; pane.body.cur_pinned = true; pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); const overlay = pane.ovl.?; pane.body.ed_redo[0] = .{ .ovl = .{ .row = overlay.row, .rows = overlay.rows, .text = try gpa.dupe(u8, overlay.text) }, @@ -1990,7 +1990,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen if (action == .hidden_undo) { gpa.free(pane.ovl.?.text); pane.ovl = null; - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); } const bytes = switch (action) { .clear_history, .partial_clear_history => "\x1b[3J", @@ -2006,20 +2006,20 @@ test "terminal edits and undo survive partial history clearing and whole-screen try std.testing.expectEqual(expected + 1, pane.body.cur_row); try std.testing.expectEqual(expected, pane.body.vsel.row); } - for ([_]panes.Terminal.Snapshot{ pane.body.ed_undo[0], pane.body.ed_redo[0] }) |snapshot| { + for ([_]panes.terminal.Snapshot{ pane.body.ed_undo[0], pane.body.ed_redo[0] }) |snapshot| { try std.testing.expectEqual(expected, snapshot.ovl.?.row); try std.testing.expectEqual(expected + 1, snapshot.cur_row); try std.testing.expectEqualStrings("edit one\nedit two", snapshot.ovl.?.text); } try std.testing.expectEqual(@as(usize, 2), pane.terminal.?.vt.screens.active.pages.countTrackedPins()); - panes.Terminal.undo(p, pane); + panes.terminal.undo(p, pane); try std.testing.expectEqualStrings("edit one\nedit two", pane.ovl.?.text); try std.testing.expectEqual(expected, pane.ovl.?.row); } } test "terminal lower scroll regions do not move edits above them" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -2030,23 +2030,23 @@ test "terminal lower scroll regions do not move edits above them" { pane.ovl = .{ .row = 1, .rows = 1, .text = try gpa.dupe(u8, "unsent") }; pane.body.cur_row = 1; pane.body.cur_pinned = true; - panes.Terminal.pushUndo(p, pane); - const total = panes.Terminal.scrollbar(pane).total; + panes.terminal.pushUndo(p, pane); + const total = panes.terminal.scrollbar(pane).total; var setup: [64]u8 = undefined; const bytes = try std.fmt.bufPrint(&setup, "\x1b[4;{d}r\x1b[{d};1H", .{ pane.rows, pane.rows }); p.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); p.update(.{ .output = .{ .pane = 0, .bytes = "tail\r\n" ** 50 } }); - try std.testing.expectEqual(total, panes.Terminal.scrollbar(pane).total); + try std.testing.expectEqual(total, panes.terminal.scrollbar(pane).total); try std.testing.expectEqual(@as(i32, 1), pane.ovl.?.row); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 1), pane.body.ed_undo[0].ovl.?.row); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); try std.testing.expect(std.mem.startsWith(u8, full, "top\nsecond\nthird\n")); } test "terminal eviction and lower-region scrolling in one read preserve a surviving edit" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -2071,7 +2071,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv pane.ovl = .{ .row = old_row, .rows = 1, .text = try gpa.dupe(u8, "kept edit") }; pane.body.cur_row = old_row; pane.body.cur_pinned = true; - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); const old_total = pages.total_rows; var buf: [128]u8 = undefined; const bytes = try std.fmt.bufPrint(&buf, "new\r\n\x1b[4;{d}r\x1b[{d};1Hregion\r\n", .{ pane.rows, pane.rows }); @@ -3342,11 +3342,11 @@ const TerminalTests = struct { // Tests asserting raw ANSI indices explicitly select helix, whose palette // is inherited. Native-palette coverage lives in the overlay/eviction and // trailing-blank tests and checks their concrete RGB values instead. - const gridOffset = panes.Terminal.gridOffset; - const scrollGrid = panes.Terminal.scrollGrid; - const promptInputReady = panes.Terminal.promptInputReady; - const forwardKey = panes.Terminal.forwardKey; - const enterTty = panes.Terminal.enterTty; + const gridOffset = panes.terminal.gridOffset; + const scrollGrid = panes.terminal.scrollGrid; + const promptInputReady = panes.terminal.promptInputReady; + const forwardKey = panes.terminal.forwardKey; + const enterTty = panes.terminal.enterTty; // Align normal-mode glyphs with the VT grid and compare their styles. fn modeStyleDiffs(p: *Pardes, pane: *Pane, gpa: std.mem.Allocator, note: []const u8) !usize { @@ -4798,7 +4798,7 @@ test "Zig keywords keep every rendered byte colored across line-number widths" { } test "terminal overlays preserve trailing blank styles without coloring inserted rows" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index 56a5da91..567a8b02 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2022,"med_us":2284,"p90_us":2363,"max_us":2431},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":90,"max_us":94},{"op":"key-down","fixture":"medium","min_us":79,"med_us":82,"p90_us":87,"max_us":97},{"op":"key-right","fixture":"medium","min_us":82,"med_us":83,"p90_us":91,"max_us":95},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":86},{"op":"wheel","fixture":"medium","min_us":79,"med_us":82,"p90_us":85,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1190,"med_us":1621,"p90_us":1843,"max_us":2008},{"op":"body-2m","fixture":"medium","min_us":9178,"med_us":16872,"p90_us":20886,"max_us":22596}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2022,"med_us":2284,"p90_us":2363,"max_us":2431},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":90,"max_us":94},{"op":"key-down","fixture":"medium","min_us":79,"med_us":82,"p90_us":87,"max_us":97},{"op":"key-right","fixture":"medium","min_us":82,"med_us":83,"p90_us":91,"max_us":95},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":86},{"op":"wheel","fixture":"medium","min_us":79,"med_us":82,"p90_us":85,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1190,"med_us":1621,"p90_us":1843,"max_us":2008},{"op":"body-2m","fixture":"medium","min_us":9178,"med_us":16872,"p90_us":20886,"max_us":22596}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index 9c4b5ebe..8ba0cdec 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1902,"med_us":2386,"p90_us":2484,"max_us":2686},{"op":"render","fixture":"medium","min_us":83,"med_us":87,"p90_us":93,"max_us":118},{"op":"key-down","fixture":"medium","min_us":88,"med_us":94,"p90_us":100,"max_us":156},{"op":"key-right","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":92},{"op":"page-down","fixture":"medium","min_us":78,"med_us":84,"p90_us":89,"max_us":101},{"op":"wheel","fixture":"medium","min_us":77,"med_us":84,"p90_us":89,"max_us":132},{"op":"edit-char","fixture":"medium","min_us":1177,"med_us":1519,"p90_us":1721,"max_us":1909},{"op":"body-2m","fixture":"medium","min_us":8533,"med_us":15772,"p90_us":21361,"max_us":23276}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1902,"med_us":2386,"p90_us":2484,"max_us":2686},{"op":"render","fixture":"medium","min_us":83,"med_us":87,"p90_us":93,"max_us":118},{"op":"key-down","fixture":"medium","min_us":88,"med_us":94,"p90_us":100,"max_us":156},{"op":"key-right","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":92},{"op":"page-down","fixture":"medium","min_us":78,"med_us":84,"p90_us":89,"max_us":101},{"op":"wheel","fixture":"medium","min_us":77,"med_us":84,"p90_us":89,"max_us":132},{"op":"edit-char","fixture":"medium","min_us":1177,"med_us":1519,"p90_us":1721,"max_us":1909},{"op":"body-2m","fixture":"medium","min_us":8533,"med_us":15772,"p90_us":21361,"max_us":23276}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index 984d480a..ab5ed3b6 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2061,"med_us":2326,"p90_us":2462,"max_us":2503},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":86,"max_us":98},{"op":"key-down","fixture":"medium","min_us":78,"med_us":83,"p90_us":91,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":86,"max_us":90},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":90},{"op":"wheel","fixture":"medium","min_us":75,"med_us":82,"p90_us":87,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":1277,"med_us":1713,"p90_us":1948,"max_us":2063},{"op":"body-2m","fixture":"medium","min_us":9261,"med_us":17043,"p90_us":23512,"max_us":23722}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2061,"med_us":2326,"p90_us":2462,"max_us":2503},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":86,"max_us":98},{"op":"key-down","fixture":"medium","min_us":78,"med_us":83,"p90_us":91,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":86,"max_us":90},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":90},{"op":"wheel","fixture":"medium","min_us":75,"med_us":82,"p90_us":87,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":1277,"med_us":1713,"p90_us":1948,"max_us":2063},{"op":"body-2m","fixture":"medium","min_us":9261,"med_us":17043,"p90_us":23512,"max_us":23722}]} diff --git a/test/perf.zig b/test/perf.zig index 38c640b4..fca4a3b0 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -275,12 +275,12 @@ fn measureCreation(io: std.Io, reps: usize, json: bool) !void { const allocator = counter.allocator(); const begin = nowNs(); const pane = if (terminal) - try pardes.panes.Terminal.create(allocator, screen_cols, screen_rows) + try pardes.panes.terminal.create(allocator, screen_cols, screen_rows) else - try pardes.panes.Terminal.createDoc(allocator, screen_cols, screen_rows); + try pardes.panes.terminal.createDoc(allocator, screen_cols, screen_rows); const constructed = nowNs(); const retained = counter.live; - pardes.panes.Terminal.deinitEmulator(pane, allocator); + pardes.panes.terminal.deinitEmulator(pane, allocator); allocator.destroy(pane); const destroyed = nowNs(); if (counter.live != 0) return error.LeakedPaneMemory; @@ -707,7 +707,7 @@ fn checkTerminalTail(core: *pardes.Pardes, surface: *pardes.Surface, batch: usiz const pane = core.panes[0] orelse return error.MissingTerminal; const rect = core.rects[0]; const x = rect.x + pardes.config.GUTTER; - const y = (if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H) + pardes.panes.Terminal.gridCursor(pane).y; + const y = (if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H) + pardes.panes.terminal.gridCursor(pane).y; var expected_buffer: [32]u8 = undefined; const expected = try std.fmt.bufPrint(&expected_buffer, "TURN {d:0>10} READY", .{batch}); for (expected, 0..) |byte, col| { @@ -773,7 +773,7 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he pane.body.cur_row = first + 1; pane.body.cur_col = 1; pane.body.vsel = .{ .active = true, .row = first, .col = 0 }; - pardes.panes.Terminal.pushUndo(core, pane); + pardes.panes.terminal.pushUndo(core, pane); core.gpa.free(pane.ovl.?.text); pane.ovl = null; if (pane.body.ed_undo_len != index + 1) return error.TerminalUndoSnapshotFailed; @@ -782,7 +782,7 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |snapshot| if (snapshot.ovl) |overlay| core.gpa.free(overlay.text); pane.body.ed_undo_len = 0; } - pardes.panes.Terminal.enterTty(core, 0); + pardes.panes.terminal.enterTty(core, 0); pump(core); const tracked_before = pages.countTrackedPins(); const start = try pages.trackPin(pages.pin(.{ .screen = .{ .y = @intCast(first) } }).?); @@ -895,7 +895,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void } const stream_wall_ns = nowNs() - stream_begin; const live_after_output = counter.live; - const first_row = @as(i32, @intCast(state.vt.screens.active.pages.scrollbar().offset)) + @as(i32, pardes.panes.Terminal.gridCursor(pane).y); + const first_row = @as(i32, @intCast(state.vt.screens.active.pages.scrollbar().offset)) + @as(i32, pardes.panes.terminal.gridCursor(pane).y); _ = arena.reset(.retain_capacity); const modal_begin = nowNs(); core.update(.{ .key = .{ .cp = core.opts.tty_toggle, .ctrl = true } }); @@ -943,7 +943,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void const begin = nowNs(); core.update(.{ .output = .{ .pane = 0, .bytes = update } }); pump(core); - const cursor_row = pardes.panes.Terminal.gridOffset(pane) + @as(i32, pardes.panes.Terminal.gridCursor(pane).y); + const cursor_row = pardes.panes.terminal.gridOffset(pane) + @as(i32, pardes.panes.terminal.gridCursor(pane).y); pane.ovl.?.row = if (phase == 0) 0 else cursor_row - 1; pane.body.cur_row = pane.ovl.?.row; pane.body.cur_col = 0; -- cgit v1.3 From d4960472375ea68f709c56a677d8a37571419ff7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 22:27:38 -0300 Subject: Config opens the startup file, DumpConfig the settings report, and the workspace tag reads Dump Themes Config Debug Exit Config (SPC f c) opens init, found as the settings report finds it (opts.startup_config_path: $XDG_CONFIG_HOME/pardes/init or ~/.config/pardes/init, and the macOS and Windows paths config.md gives). A pane that already holds it is gone to instead; a file on disk is looked at; with none, an empty pane is named for it, and Save makes its directory and any above it first (File.make_dirs, fs.makeDirs) before writing. Without a configuration directory it says so and opens nothing. The report Config used to open, the startup path and every live setting, is DumpConfig, in a +DumpConfig pane. No alias keeps the old meaning. The workspace tag's default words put Themes where NextColor was, NextColor staying a builtin, and Config beside it. A tag the user edited is kept as it was: a dump stores only an edited one (topbar_custom), and a restore puts back only that. theme.snap types NextColor onto the workspace tag to click it, and tagnav's walk back to Dump takes five long-word steps. The rest of the re-recorded goldens differ in the workspace words and their widths only. Co-Authored-By: Claude Opus 5.5 --- docs/config.md | 11 ++-- docs/macos.md | 4 +- docs/tags.md | 4 +- docs/themes.md | 2 +- docs/ui-review.md | 2 +- src/CHANGELOG.md | 10 +++ src/File.zig | 4 ++ src/Messages.zig | 2 +- src/Output.zig | 2 +- src/builtins.zig | 32 +++++++++- src/config.zig | 11 ++-- src/crash.zig | 2 +- src/fs.zig | 19 ++++++ src/ninep/ctl.zig | 6 +- src/pardes.zig | 10 +-- src/tutor.txt | 4 +- test/appearance_gallery.py | 4 +- test/font_size.py | 4 +- test/output.zig | 98 +++++++++++++++++++++++++++--- test/snapshots/argv.golden | 8 +-- test/snapshots/badutf.golden | 2 +- test/snapshots/boot.golden | 2 +- test/snapshots/builtins.golden | 2 +- test/snapshots/chordcut.golden | 2 +- test/snapshots/cmdexit.golden | 2 +- test/snapshots/cmdword.golden | 2 +- test/snapshots/colgrip.golden | 2 +- test/snapshots/collapse.golden | 6 +- test/snapshots/cornerdrag-left.golden | 2 +- test/snapshots/cornerdrag.golden | 2 +- test/snapshots/cursorline.golden | 2 +- test/snapshots/delask.golden | 2 +- test/snapshots/doccol.golden | 2 +- test/snapshots/dump.golden | 2 +- test/snapshots/edit.golden | 2 +- test/snapshots/emptycol.golden | 2 +- test/snapshots/exec-bigdrag.golden | 2 +- test/snapshots/exec.golden | 2 +- test/snapshots/fileedit.golden | 2 +- test/snapshots/filewatch.golden | 2 +- test/snapshots/find.golden | 2 +- test/snapshots/fsearch.golden | 2 +- test/snapshots/ghostty-mid.golden | 2 +- test/snapshots/grep.golden | 2 +- test/snapshots/headersweep-restored.golden | 4 +- test/snapshots/headersweep.golden | 6 +- test/snapshots/hscroll.golden | 2 +- test/snapshots/images.golden | 4 +- test/snapshots/jumps.golden | 2 +- test/snapshots/layout-close.golden | 2 +- test/snapshots/layout-open.golden | 2 +- test/snapshots/leader.golden | 2 +- test/snapshots/load.golden | 2 +- test/snapshots/logquiet.golden | 2 +- test/snapshots/look-center.golden | 2 +- test/snapshots/look-dir.golden | 2 +- test/snapshots/look-file-1col.golden | 2 +- test/snapshots/look-file.golden | 2 +- test/snapshots/lookloaded.golden | 2 +- test/snapshots/lookpanes.golden | 2 +- test/snapshots/lookrange.golden | 2 +- test/snapshots/lsp-client-edit.golden | 2 +- test/snapshots/lsp-client.golden | 2 +- test/snapshots/lsp-rename.golden | 2 +- test/snapshots/lsp.golden | 2 +- test/snapshots/lspcomplete.golden | 8 +-- test/snapshots/lspcompletemoved.golden | 2 +- test/snapshots/lspdebug.golden | 2 +- test/snapshots/lsprelpath.golden | 4 +- test/snapshots/markup.golden | 4 +- test/snapshots/mini.golden | 12 ++-- test/snapshots/modal.golden | 2 +- test/snapshots/msg.golden | 4 +- test/snapshots/multicursor.golden | 2 +- test/snapshots/nested.golden | 6 +- test/snapshots/ninep.golden | 12 ++-- test/snapshots/pipe.golden | 2 +- test/snapshots/psearch.golden | 2 +- test/snapshots/reflow.golden | 2 +- test/snapshots/respawn.golden | 2 +- test/snapshots/restore.golden | 2 +- test/snapshots/rsearch.golden | 2 +- test/snapshots/savepane.golden | 2 +- test/snapshots/scroll.golden | 2 +- test/snapshots/scrolloff.golden | 2 +- test/snapshots/selarg.golden | 2 +- test/snapshots/selregex.golden | 2 +- test/snapshots/shellset.golden | 2 +- test/snapshots/shrinktag.golden | 2 +- test/snapshots/splitparent.golden | 6 +- test/snapshots/stepgrain.golden | 2 +- test/snapshots/syntax.golden | 2 +- test/snapshots/tag.golden | 2 +- test/snapshots/tagalign.golden | 10 +-- test/snapshots/tagalign2col.golden | 2 +- test/snapshots/tagbottom.golden | 2 +- test/snapshots/tagbottomimage.golden | 2 +- test/snapshots/tagbottomshort.golden | 12 ++-- test/snapshots/tagcmd.golden | 2 +- test/snapshots/tagnav.golden | 8 +-- test/snapshots/tagnav.snap | 4 +- test/snapshots/tagpath.golden | 2 +- test/snapshots/theme.golden | 40 ++++++------ test/snapshots/theme.snap | 8 +++ test/snapshots/themesel.golden | 2 +- test/snapshots/tinywin.golden | 6 +- test/snapshots/topbarexec.golden | 2 +- test/snapshots/tty.golden | 2 +- test/snapshots/ttyclick.golden | 2 +- test/snapshots/ttyedit.golden | 2 +- test/snapshots/ttyfollow.golden | 2 +- test/snapshots/ttyhelp.golden | 2 +- test/snapshots/ttylook.golden | 2 +- test/snapshots/ttyonly.golden | 2 +- test/snapshots/ttypaste.golden | 2 +- test/snapshots/ttyprompt.golden | 2 +- test/snapshots/ttytaken.golden | 2 +- test/snapshots/tutor.golden | 2 +- test/snapshots/wheeldrift.golden | 2 +- test/snapshots/winch.golden | 4 +- test/snapshots/windownav.golden | 2 +- test/snapshots/windowops.golden | 4 +- test/snapshots/wrap.golden | 2 +- test/snapshots/yankpaste.golden | 2 +- test/window_opacity.py | 12 ++-- 125 files changed, 371 insertions(+), 218 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/config.md b/docs/config.md index f25c8746..bc4acf12 100644 --- a/docs/config.md +++ b/docs/config.md @@ -31,10 +31,13 @@ not stop later ones. Text that is no builtin is not run as a shell command (`Exec ...` still is). Key bindings are compile-time choices in `src/config.zig`; `init` does not remap them. -`Config` (`SPC f c`) opens a `+Config` pane with the startup path (a right -click opens it) and every live setting; a setting the frontend cannot show -reads `unsupported`. The root `ctl` file reads the settings back in the -words a write takes ([fs.md](fs.md#the-root-ctl)). +`Config` (`SPC f c`) opens `init` itself in a pane, or goes to its pane when +it is open. With no file there yet, the pane is named for it, empty, and +Save writes it, making its directory first. `DumpConfig` opens a +`+DumpConfig` pane with the startup path (a right click opens it) and every +live setting; a setting the frontend cannot show reads `unsupported`. The +root `ctl` file reads the settings back in the words a write takes +([fs.md](fs.md#the-root-ctl)). ## Settings diff --git a/docs/macos.md b/docs/macos.md index 8bb81be6..5512edbd 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -525,7 +525,7 @@ what is on screen. Cmd+=, Cmd- and Cmd+0 change the point size, rebuild `Metrics`, and report the new cell through the same resize path a window drag uses. They also observe the -effective face/point tuple through `pardes_font_observe`, so the single `Config` +effective face/point tuple through `pardes_font_observe`, so the single `DumpConfig` report follows a host-owned zoom without resolving a pending face request. The initial system face is observed the same way. Cmd+= rather than Cmd++ because AppKit matches the character and `=` is what is under the finger. @@ -759,7 +759,7 @@ separation is currently macOS-specific; other hosts keep the opaque raster path. `WindowBlur <0..100>` controls the strength of that native backdrop independently of `WindowOpacity`. It is a macOS-only builtin, also accepted in the startup -config and reported by `Config`. It defaults to 0 (off); 100 shows the full +config and reported by `DumpConfig`. It defaults to 0 (off); 100 shows the full AppKit material and intermediate values blend the material with the unblurred backdrop using the effect view's alpha. An opaque themed background hides the effect; lowering `WindowOpacity` makes the remembered strength visible again. diff --git a/docs/tags.md b/docs/tags.md index 8fe63804..93c8a6fa 100644 --- a/docs/tags.md +++ b/docs/tags.md @@ -11,8 +11,8 @@ pane's directory. Over 9P the tags are `/tag`, `/col//tag` and ## Default words -- Workspace: `Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor - Debug Exit`. +- Workspace: `Newcol Joincol Find Grep Help Changelog Tutor Dump Themes + Config Debug Exit`. - Column: `New Tty Find Grep Joincol Delcol`. - File pane: `Save Tty Collapse Del`; a source file with a grammar adds `TreeContext`, a result list `LocationsConfig`. PDF: `manual.pdf [1/12] diff --git a/docs/themes.md b/docs/themes.md index d163b243..c7204173 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -174,7 +174,7 @@ colors switch directly so syntax and ANSI content stay coherent. `FocusTint` toggles the focused pane's tag tint, which is on by default. `SyntaxBold` toggles bold syntax keywords, which are off by default. Both commands take no argument, work in GUI and TTY, and report their states in -`Config`. Use them in the startup configuration to reverse the defaults. +`DumpConfig`. Use them in the startup configuration to reverse the defaults. The original required roles remain unchanged: nullable `bg` and `fg`, `sel_bg`, `sel_fg`, `tag_bg`, `tag_fg`, `box`, `box_dim`, `kw`, `str`, `num`, diff --git a/docs/ui-review.md b/docs/ui-review.md index decf042d..6702ce31 100644 --- a/docs/ui-review.md +++ b/docs/ui-review.md @@ -206,7 +206,7 @@ pass does not change that environment code or skip the affected tests. The appearance checks cover native palette contrast, old ThemeFile documents, wrapped search matches, selection precedence, immediate body colors during theme fades, light-theme carets and both quiet and bold syntax preferences. -The 9P walkthrough also verifies `FocusTint` and `SyntaxBold` through `Config`. +The 9P walkthrough also verifies `FocusTint` and `SyntaxBold` through `DumpConfig`. All 97 terminal snapshot scripts passed without retries after reviewing and refreshing 32 appearance goldens. Of those, 27 preserve identical visible text, diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 50149551..ca37856e 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +- `Config` (`SPC f c`) opens the startup file, `init`, in a pane, or goes + to its pane when it is open. With no file yet, it opens an empty pane of + that name, and Save writes it, making the directory first. The settings + report `Config` used to open is `DumpConfig`, in a `+DumpConfig` pane. +- The workspace tag reads `… Dump Themes Config Debug Exit`: `Themes` in + place of `NextColor`, which stays a builtin, and `Config` beside it. A + workspace tag you edited, and one a dump kept, stays as it is. + ## 0.0.5 - Over a slow link the terminal build keeps at most one frame in flight: it diff --git a/src/File.zig b/src/File.zig index 8babb27d..e8a9e2f8 100644 --- a/src/File.zig +++ b/src/File.zig @@ -58,6 +58,10 @@ pub const State = struct { /// as an undo to the save point is in acme. saved_hash: ?u64 = null, watch_after_save: bool = false, + /// Save makes the file's directory, and any above it, first: `Config`'s + /// pane for an init file that is not there yet, whose directory may not + /// be either. + make_dirs: bool = false, /// The file changed on disk under unsaved edits, which were kept (see /// `changed`): its hash, so the same change is said once, until a Save /// or get settles it. A Save warns once before overwriting it, as acme's diff --git a/src/Messages.zig b/src/Messages.zig index 7dcb22ed..d1478ac7 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -782,7 +782,7 @@ test "a message falls in, lingers past the input that dismisses it, and dissolve try std.testing.expect(p.executeBuiltinLine(p.active, "MessageDissolve 0")); try std.testing.expectEqual(@as(u16, 3), messageFrames(p.settings.message_fall_ms)); try std.testing.expectEqual(@as(u16, 1), messageFrames(p.settings.message_dissolve_ms)); - // The Config report reads back as configuration. + // The DumpConfig report reads back as configuration. try std.testing.expect(p.executeBuiltinLine(p.active, "MessageAnimation")); try std.testing.expect(!p.settings.message_animation); try std.testing.expect(p.executeBuiltinLine(p.active, "Msg plain")); diff --git a/src/Output.zig b/src/Output.zig index fb8fe7a3..69e9644c 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -835,7 +835,7 @@ pub fn openConfig(p: *Pardes, id: usize) !void { .state = &p.settings, }); const content = try out.toOwnedSlice(); - return openRead(p, id, .{ .cmd = .Config }, "", content); + return openRead(p, id, .{ .cmd = .DumpConfig }, "", content); } /// The message-row log, oldest first — the lines that were said in passing and diff --git a/src/builtins.zig b/src/builtins.zig index c549b17f..c40b2e00 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1283,10 +1283,38 @@ pub const Help = struct { } }; -/// Open the settings in effect, each a word to click. +/// Open the startup file, `init`, in a pane: its pane when it is open, else +/// the file, else a pane of that name for Save to make it and its directory. pub const Config = struct { pub const scope: Scope = .session; - pub const output: OutputTraits = .{ .name = config.config_buffer }; + pub fn run(c: Ctx) void { + const path = c.p.opts.startup_config_path orelse + return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory"); + var real_buf: [4096]u8 = undefined; + const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; + for (c.p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null) continue; + if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue; + return look.focusPaneLine(c.p, id, .{}, .keep); + } + if (real != null) return look.lookAt(c.p, c.id, path); + // Not there yet: a pane named for it, which Save makes. + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Config", error.NoPaneSlots); + c.p.newScratchFor(c.id, .scratch); + const pane = c.p.panes[free] orelse return; + @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, "Config", err); + pane.file.?.make_dirs = true; + c.p.active = free; + } +}; + +/// Open the settings in effect, each a word to click, and the startup +/// file's path. +pub const DumpConfig = struct { + pub const scope: Scope = .session; + pub const output: OutputTraits = .{ .name = config.dump_config_buffer }; pub fn run(c: Ctx) void { panes.Output.openConfig(c.p, c.id) catch |err| c.p.reportError(c.id, "config", err); } diff --git a/src/config.zig b/src/config.zig index ea7a877a..bb033823 100644 --- a/src/config.zig +++ b/src/config.zig @@ -68,6 +68,7 @@ pub const leader_path = paths: { .Recent = "fr", .Grep = "fg", .Config = "fc", + .DumpConfig = null, .LocationsConfig = null, .Tutor = "ht", .Changelog = "hc", @@ -266,7 +267,7 @@ pub const child_term = "xterm-256color"; pub const child_colorterm = "truecolor"; pub const child_term_program = "pardes"; -pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit"; +pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit"; pub const pane_builtins_str = "Tty Collapse Del"; pub const pdf_pane_builtins_str = "Tty PdfSections PdfTint Collapse Del"; @@ -452,7 +453,7 @@ pub const pipe_marker = " |"; pub const search_buffer = "+Search"; pub const help_buffer = "+Help"; -pub const config_buffer = "+Config"; +pub const dump_config_buffer = "+DumpConfig"; pub const effect_code_buffer = "+EffectCode"; pub const jumps_buffer = "+Jumps"; pub const recent_buffer = "+Recent"; @@ -968,7 +969,7 @@ pub const Runtime = struct { } }; - // The builtin registry and Config report share this command table. + // The builtin registry and DumpConfig report share this command table. pub const settings = [_]Setting{ .{ .word = "Colors", .action = .{ .toggle = .colors }, .doc = "Syntax colours in text panes, on or off." }, .{ .word = "Wrap", .action = .{ .toggle = .wrap }, .doc = "Long lines wrap onto the next row, on or off." }, @@ -1292,7 +1293,7 @@ pub const Runtime = struct { /// Each line reads as the command that would set it: the word, then the /// value you would type after it. No colons, no units — `WindowOpacity 70` - /// is both what Config prints and what you write back. + /// is both what DumpConfig prints and what you write back. pub fn writeReport(out: *std.Io.Writer, context: ReportContext) !void { const state = context.state; var wrote_transition = false; @@ -1653,7 +1654,7 @@ pub const Runtime = struct { try std.testing.expect(FontSpec.parse(bad) == null); } - test "Config report observes every simple setting and all live context" { + test "DumpConfig report observes every simple setting and all live context" { var state: Runtime = .{}; // Every setting, every context line: the report outgrows 4K. var storage: [8192]u8 = undefined; diff --git a/src/crash.zig b/src/crash.zig index 10d38591..99822aad 100644 --- a/src/crash.zig +++ b/src/crash.zig @@ -23,7 +23,7 @@ const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("pardes.zig"); -/// Beside `init`, so `Config` opens the directory that holds both. +/// The crash log's name, beside `init` in the configuration directory. pub const name = "crashes"; /// The config directory `config.User.load` resolved, COPIED rather than diff --git a/src/fs.zig b/src/fs.zig index fc3eb98f..1d0bbc22 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -637,6 +637,25 @@ test "a path with a part over 255 bytes is NameTooLong, never a panic" { try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); } +/// 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; + var z: [4096:0]u8 = undefined; + if (dir.len == 0 or dir.len >= z.len) return; + @memcpy(z[0..dir.len], dir); + z[dir.len] = 0; + pardes.turn.yield(); + defer pardes.turn.back(); + for (z[1..dir.len], 1..) |c, i| if (c == '/') { + z[i] = 0; + _ = libc.mkdir(z[0..i :0], 0o755); + z[i] = '/'; + }; + _ = libc.mkdir(z[0..dir.len :0], 0o755); +} + 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..]; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 060e0d6c..5ed03c58 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -485,7 +485,7 @@ const e_prompt = "control message needs its argument"; /// Every setting, one a line, in the words a write of it takes, so that the /// file read back is the configuration, as webfs's ctl reads (webfs(4)). /// What is not a setting -- platform, themes, where the config came from -- -/// is /status's or the Config window's. +/// is /status's or the DumpConfig window's. fn writeSettings(p: *Pardes, w: *std.Io.Writer) !void { try writeSettingsOf(p, &p.settings, w); try w.writeAll("LocationsConfig "); @@ -523,7 +523,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) inline else => |field| try w.print("{s} {s}\n", .{ word, @tagName(@field(s, @tagName(field))) }), }, .message_ms => |which| try w.print("{s} {d}\n", .{ word, @field(s, "message_" ++ @tagName(which) ++ "_ms") }), - // The directory in effect, as Config reports it; bare only when + // The directory in effect, as DumpConfig reports it; bare only when // there is none (no home to put the default in). .dump_dir => { var buf: [900]u8 = undefined; @@ -1165,7 +1165,7 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi try testing.expectEqual(@as(u64, settings.len), call(p, .{ .tag = 1, .op = .getattr, .node = root_ctl }).reply.attr.size); try testing.expect(std.mem.indexOf(u8, settings, "Verbose on\n") != null); try testing.expect(std.mem.indexOf(u8, settings, "LocationsConfig ") != null); - // Settings only: nothing /status or the Config window says. + // Settings only: nothing /status or the DumpConfig window says. try testing.expect(std.mem.indexOf(u8, settings, "Platform") == null); try testing.expect(std.mem.indexOf(u8, settings, "requested") == null); diff --git a/src/pardes.zig b/src/pardes.zig index 18794975..e3db97d9 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1329,7 +1329,7 @@ test "acme placement: New and 9P's new take the bottom half of the last pane" { try std.testing.expect(p.rects[made].y > was.y + BOX_H); } -test "Placement pardes brings back the old rules, and says so in Config" { +test "Placement pardes brings back the old rules, and says so in DumpConfig" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); try std.testing.expect(p.executeBuiltinLine(p.active, "Placement pardes")); @@ -3493,7 +3493,7 @@ test "s in a header selects in the header's own text" { var ranges: [Text.max_selections]modal.Selection = undefined; const text = try edit.flatSurface(p, &p.global_tag); const got = p.global_tag.ranges(text, 0, &ranges); - try std.testing.expectEqual(@as(usize, 3), got.n); // Newcol, Joincol, NextColor + try std.testing.expectEqual(@as(usize, 2), got.n); // Newcol, Joincol try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); } @@ -5261,7 +5261,7 @@ pub const Pardes = struct { } /// Resolve the request already handed to the GUI host. Requested and - /// effective tuples deliberately remain separate so Config can show both. + /// effective tuples deliberately remain separate so DumpConfig can show both. pub fn acknowledgeFont( p: *Pardes, effective_name: []const u8, @@ -5596,6 +5596,8 @@ pub const Pardes = struct { const was = f.saved_revision; const failures = p.fs.failures; f.saved_revision = f.revision; + if (f.make_dirs) if (filesystem.localPath(f.path)) |local| + filesystem.makeDirs(std.fs.path.dirname(local) orelse "/"); p.hostWriteFile(sf.pane, f.path, f.content); const saved_pane = p.panes[sf.pane] orelse return; if (saved_pane.serial != serial) return; @@ -6721,7 +6723,7 @@ pub const Pardes = struct { } /// A native post pass proved unavailable: the chain is emptied, which - /// Config then reports. + /// DumpConfig then reports. pub fn disableSceneEffects(p: *Pardes) void { p.settings.post.clear(); } diff --git a/src/tutor.txt b/src/tutor.txt index c59deeae..f8aa7aef 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -65,8 +65,8 @@ Every pane has Collapse: hide its body, then execute again to expand it. The top bar is: - Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor - Debug Exit + Newcol Joincol Find Grep Help Changelog Tutor Dump Themes + Config Debug Exit Reach it from the keyboard with `k` off the topmost tagline; `j` comes back down. diff --git a/test/appearance_gallery.py b/test/appearance_gallery.py index 46b17dd9..c321c7c0 100644 --- a/test/appearance_gallery.py +++ b/test/appearance_gallery.py @@ -91,8 +91,8 @@ def run(args): def config_report(): before = set(panes(client)) - command(client, right, 'Config') - pane = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'Config output missing') + command(client, right, 'DumpConfig') + pane = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'DumpConfig output missing') text = client.read(f'/pane/{pane}/body').decode() client.write(f'/pane/{pane}/exec', b'Del\n') return text diff --git a/test/font_size.py b/test/font_size.py index b7104099..ef685a9e 100644 --- a/test/font_size.py +++ b/test/font_size.py @@ -25,10 +25,10 @@ def run(args): control = new_pane(client, b'') def report(size): - execute(client, control, 'Config') + execute(client, control, 'DumpConfig') def ready(): for serial, tag in panes(client).items(): - if '/+Config ' in tag: + if '/+DumpConfig ' in tag: body = client.read(f'/pane/{serial}/body').decode() if f'Font effective size {size:.2f} pixels' in body: return body diff --git a/test/output.zig b/test/output.zig index 1b1b80c9..da17eccc 100644 --- a/test/output.zig +++ b/test/output.zig @@ -89,7 +89,7 @@ fn resultId(p: *Pardes) !usize { } test "output callers opt into location highlighting instead of matching prose colons" { - for ([_]panes.Output.Origin{ .{ .cmd = .LocationsConfig }, .{ .cmd = .Config }, .{ .query = .hover } }) |origin| { + for ([_]panes.Output.Origin{ .{ .cmd = .LocationsConfig }, .{ .cmd = .DumpConfig }, .{ .query = .hover } }) |origin| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 30 }); defer p.deinit(); p.locations_config.layout = .@"inline"; @@ -533,12 +533,12 @@ test "Mini failures leave its existing snapshot and focus unchanged" { try std.testing.expectEqual(next, p.freeSlot()); } -test "Config prints the startup path and refreshes its one output" { +test "DumpConfig prints the startup path and refreshes its one output" { const path = "/home/pardes-test/.config/pardes/init"; const p = try Pardes.init(std.testing.allocator, .{ .startup_config_path = path }); defer p.deinit(); - try std.testing.expect(p.executeBuiltinLine(0, "Config")); + try std.testing.expect(p.executeBuiltinLine(0, "DumpConfig")); const opened = p.active; const out = p.panes[opened].?.file.?; for ([_][]const u8{ @@ -549,28 +549,106 @@ test "Config prints the startup path and refreshes its one output" { }) |line| try std.testing.expect(std.mem.indexOf(u8, out.content, line) != null); var default_line: [256]u8 = undefined; try std.testing.expect(std.mem.indexOf(u8, out.content, try std.fmt.bufPrint(&default_line, "Shell requested (new panes) {s} (default)\n", .{config.defaultShell()})) != null); - try std.testing.expectEqualStrings(config.config_buffer, std.fs.path.basename(out.path)); - try std.testing.expectEqual(panes.Output.Origin{ .cmd = .Config }, out.output.?.from); + try std.testing.expectEqualStrings(config.dump_config_buffer, std.fs.path.basename(out.path)); + try std.testing.expectEqual(panes.Output.Origin{ .cmd = .DumpConfig }, out.output.?.from); - try std.testing.expect(p.executeBuiltinLine(0, "Config")); + try std.testing.expect(p.executeBuiltinLine(0, "DumpConfig")); try std.testing.expectEqual(opened, p.active); var buffers: usize = 0; for (p.panes) |slot| { const f = (slot orelse continue).file orelse continue; const origin = (f.output orelse continue).from; - buffers += @intFromBool(std.meta.eql(origin, panes.Output.Origin{ .cmd = .Config })); + buffers += @intFromBool(std.meta.eql(origin, panes.Output.Origin{ .cmd = .DumpConfig })); } try std.testing.expectEqual(@as(usize, 1), buffers); } -test "Config reports the absence of a per-user config path" { +test "DumpConfig reports the absence of a per-user config path" { const p = try Pardes.init(std.testing.allocator, .{}); defer p.deinit(); - try std.testing.expect(p.executeBuiltinLine(0, "Config")); + try std.testing.expect(p.executeBuiltinLine(0, "DumpConfig")); const report = p.panes[p.active].?.file.?.content; try std.testing.expect(std.mem.indexOf(u8, report, "no per-user config path") != null); } +/// The file Config names, in a fresh temporary directory: `pardes/init` +/// under it, written with `content` unless that is null. +fn configFixture(tmp: *std.testing.TmpDir, content: ?[]const u8, buf: *[4096]u8) ![]const u8 { + if (content) |text| { + try tmp.dir.createDirPath(std.testing.io, "pardes"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes/init", .data = text }); + } + const len = try tmp.dir.realPath(std.testing.io, buf); + return std.fmt.bufPrint(buf[len..], "{s}/pardes/init", .{buf[0..len]}) catch unreachable; +} + +test "Config opens the startup file, and a second Config goes back to its pane" { + if (comptime !pardes.hosted) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const path = try configFixture(&tmp, "Theme orchard\n", &buf); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .startup_config_path = path }); + defer p.deinit(); + const first = p.active; + + try std.testing.expect(p.executeBuiltinLine(first, "Config")); + const opened = p.active; + try std.testing.expect(opened != first); + const f = p.panes[opened].?.file.?; + try std.testing.expectEqualStrings(path, f.path); + try std.testing.expectEqualStrings("Theme orchard\n", f.content); + try std.testing.expect(f.output == null); + + p.active = first; + try std.testing.expect(p.executeBuiltinLine(first, "Config")); + try std.testing.expectEqual(opened, p.active); + var named: usize = 0; + for (p.panes) |slot| if (slot) |pane| if (pane.file) |file| { + named += @intFromBool(std.mem.eql(u8, file.path, path)); + }; + try std.testing.expectEqual(@as(usize, 1), named); +} + +test "Config with no startup file opens a pane of its name, and Save makes its directory" { + if (comptime !pardes.hosted) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const path = try configFixture(&tmp, null, &buf); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .startup_config_path = path }); + defer p.deinit(); + const first = p.active; + + try std.testing.expect(p.executeBuiltinLine(first, "Config")); + const opened = p.active; + try std.testing.expect(opened != first); + const f = p.panes[opened].?.file.?; + try std.testing.expectEqualStrings(path, f.path); + try std.testing.expectEqualStrings("", f.content); + try std.testing.expect(f.output == null); + + // Again: the same pane, not a second one. + p.active = first; + try std.testing.expect(p.executeBuiltinLine(first, "Config")); + try std.testing.expectEqual(opened, p.active); + + try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(std.testing.io, "pardes", .{})); + // Save's effect, as a host performs it. + try std.testing.expect(p.executeBuiltinLine(opened, "Save")); + p.perform(.{ .save_file = .{ .pane = @intCast(opened) } }); + const made = try tmp.dir.statFile(std.testing.io, "pardes", .{}); + try std.testing.expectEqual(std.Io.File.Kind.directory, made.kind); +} + +test "Config without a configuration directory says so and opens nothing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const before = p.freeSlot(); + try std.testing.expect(p.executeBuiltinLine(p.active, "Config")); + try std.testing.expectEqual(before, p.freeSlot()); +} + test "EffectCode lists readable virtual sources used by this backend" { if (comptime !builtins.EffectCode.enabled) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); @@ -651,7 +729,7 @@ test "every enabled setting builtin mutates the State Config reports" { } } - try std.testing.expect(p.executeBuiltinLine(p.active, "Config")); + try std.testing.expect(p.executeBuiltinLine(p.active, "DumpConfig")); const report = p.panes[p.active].?.file.?.content; for ([_][]const u8{ "Colors off\n", diff --git a/test/snapshots/argv.golden b/test/snapshots/argv.golden index e4d41d6c..65b0ac71 100644 --- a/test/snapshots/argv.golden +++ b/test/snapshots/argv.golden @@ -1,5 +1,5 @@ == snap noargs grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/argv/cwd Tty+bash Save Mode Filter Collapse Del | $ echo ARGV''TTY @@ -23,7 +23,7 @@ | /tmp/pardes-snap/argv/cwd/+New Save Tty Collapse Del | 1 == snap filearg grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del | 3 line 3 @@ -34,7 +34,7 @@ | 8 line 8 | 9 == snap filearg-n3 grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del | 1 line 1 @@ -47,7 +47,7 @@ | 8 line 8 | 9 == snap dirarg grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/argv/cwd/sub Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/badutf.golden b/test/snapshots/badutf.golden index d013a610..14aa71dc 100644 --- a/test/snapshots/badutf.golden +++ b/test/snapshots/badutf.golden @@ -1,5 +1,5 @@ == snap badbytes grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/badutf/cwd/bad.txt Save Tty Collapse Del | 1 hello �� world diff --git a/test/snapshots/boot.golden b/test/snapshots/boot.golden index 3aedceff..ac674ed2 100644 --- a/test/snapshots/boot.golden +++ b/test/snapshots/boot.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/boot/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/builtins.golden b/test/snapshots/builtins.golden index f40d563e..6b79d47f 100644 --- a/test/snapshots/builtins.golden +++ b/test/snapshots/builtins.golden @@ -1,5 +1,5 @@ == snap boot grid=120x67 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/builtins/cwd/notes.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/snapshots/chordcut.golden b/test/snapshots/chordcut.golden index f0443a01..817c534c 100644 --- a/test/snapshots/chordcut.golden +++ b/test/snapshots/chordcut.golden @@ -1,5 +1,5 @@ == snap opened grid=120x31 cursor=7,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C | ollapse Del ollapse Del diff --git a/test/snapshots/cmdexit.golden b/test/snapshots/cmdexit.golden index c5c314b9..7d950a43 100644 --- a/test/snapshots/cmdexit.golden +++ b/test/snapshots/cmdexit.golden @@ -1,5 +1,5 @@ == snap opened grid=120x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cmdexit/cwd/cmds.txt Save Tty Collapse Del | 1 sleep 30 & echo BG''STARTED diff --git a/test/snapshots/cmdword.golden b/test/snapshots/cmdword.golden index 748bf06b..af2fbcb8 100644 --- a/test/snapshots/cmdword.golden +++ b/test/snapshots/cmdword.golden @@ -1,5 +1,5 @@ == snap opened grid=120x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cmdword/cwd/cmds.txt Save Tty Collapse Del | 1 @`echo ZZ''E` @`echo ZZ''L` Look p.txt @`Look .` diff --git a/test/snapshots/colgrip.golden b/test/snapshots/colgrip.golden index 1491a1f3..26a0b1c0 100644 --- a/test/snapshots/colgrip.golden +++ b/test/snapshots/colgrip.golden @@ -26,7 +26,7 @@ == style held grid=100x24 |1: 0-1 d,#887455, 2-2 d,#1d2824, 3-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#f4c086, 52-52 #b2c3b8,#314738, 53-99 #becfc4,#314738, == snap resize-drag grid=100x24 cursor=54,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/colgrip/cwd/w.txt S╎ve Tty Col /tmp/pardes-snap/colgrip/cwd Tty+bash Save Mode | lapse Del ╎ Filter Collapse Del diff --git a/test/snapshots/collapse.golden b/test/snapshots/collapse.golden index 23dfa8f3..57aafc8f 100644 --- a/test/snapshots/collapse.golden +++ b/test/snapshots/collapse.golden @@ -1,5 +1,5 @@ == snap before grid=160x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del | 1 KEEP-FIRST @@ -10,8 +10,8 @@ |4: |5: == 9p middle-collapsed-cursor grid=160x25 cursor=none -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-159 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-159 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-159 d,#314738,,tagline |2: /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del diff --git a/test/snapshots/cornerdrag-left.golden b/test/snapshots/cornerdrag-left.golden index 22bdd5b7..a5f36319 100644 --- a/test/snapshots/cornerdrag-left.golden +++ b/test/snapshots/cornerdrag-left.golden @@ -1,5 +1,5 @@ == snap right-split grid=100x31 cursor=54,11 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S | ave Mode Filter Collapse Del ave Mode Filter Collapse Del diff --git a/test/snapshots/cornerdrag.golden b/test/snapshots/cornerdrag.golden index 30c1830a..8dd21eff 100644 --- a/test/snapshots/cornerdrag.golden +++ b/test/snapshots/cornerdrag.golden @@ -1,5 +1,5 @@ == snap hover-corner grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save ╎ /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save M | ode Filter Collapse Del ╎ ode Filter Collapse Del diff --git a/test/snapshots/cursorline.golden b/test/snapshots/cursorline.golden index 85c23f7f..6b99a30a 100644 --- a/test/snapshots/cursorline.golden +++ b/test/snapshots/cursorline.golden @@ -1,5 +1,5 @@ == snap top grid=150x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/delask.golden b/test/snapshots/delask.golden index ed5dd66a..d1487a36 100644 --- a/test/snapshots/delask.golden +++ b/test/snapshots/delask.golden @@ -1,5 +1,5 @@ == snap three grid=100x36 cursor=18,20 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/delask/cwd/top.txt Save Tty Collapse Del | 1 top-marker diff --git a/test/snapshots/doccol.golden b/test/snapshots/doccol.golden index db2b0074..21424456 100644 --- a/test/snapshots/doccol.golden +++ b/test/snapshots/doccol.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/doccol/cwd/a.txt Save Tty Coll /tmp/pardes-snap/doccol/cwd Tty+bash Save Mode | apse Del Filter Collapse Del diff --git a/test/snapshots/dump.golden b/test/snapshots/dump.golden index 9220c450..b9608741 100644 --- a/test/snapshots/dump.golden +++ b/test/snapshots/dump.golden @@ -4,7 +4,7 @@ .version = 1, .screen = .{ .cols = 100, .rows = 31 }, .active = 0, - .topbar = "Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit", + .topbar = "Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit", .topbar_custom = null, .theme = "orchard", .locations_config = .{ diff --git a/test/snapshots/edit.golden b/test/snapshots/edit.golden index f03f7e24..aa39ed9c 100644 --- a/test/snapshots/edit.golden +++ b/test/snapshots/edit.golden @@ -1,5 +1,5 @@ == snap inserted grid=100x31 cursor=16,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fi /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fi | lter Collapse Del lter Collapse Del diff --git a/test/snapshots/emptycol.golden b/test/snapshots/emptycol.golden index 1e3f916d..9bac8492 100644 --- a/test/snapshots/emptycol.golden +++ b/test/snapshots/emptycol.golden @@ -1,5 +1,5 @@ == snap newcol grid=100x24 cursor=53,1 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/emptycol/cwd/notes.txt Save Tt | y Collapse Del diff --git a/test/snapshots/exec-bigdrag.golden b/test/snapshots/exec-bigdrag.golden index c74fd8f9..a2ac6610 100644 --- a/test/snapshots/exec-bigdrag.golden +++ b/test/snapshots/exec-bigdrag.golden @@ -1,5 +1,5 @@ == snap alive grid=200x61 cursor=119,38 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del | ls 2 diff --git a/test/snapshots/exec.golden b/test/snapshots/exec.golden index 216327b3..a9f8716e 100644 --- a/test/snapshots/exec.golden +++ b/test/snapshots/exec.golden @@ -1,5 +1,5 @@ == snap exec grid=140x31 cursor=16,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del | ls Exec ls diff --git a/test/snapshots/fileedit.golden b/test/snapshots/fileedit.golden index 4c651d3c..5ba6e18a 100644 --- a/test/snapshots/fileedit.golden +++ b/test/snapshots/fileedit.golden @@ -1,5 +1,5 @@ == snap edited grid=150x31 cursor=17,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/filewatch.golden b/test/snapshots/filewatch.golden index 589cfc3a..36f51582 100644 --- a/test/snapshots/filewatch.golden +++ b/test/snapshots/filewatch.golden @@ -1,5 +1,5 @@ == snap edited grid=210x31 cursor=15,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/filewatch/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index 61716d87..c9c6b755 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -1,5 +1,5 @@ == snap group grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del | 1 Find SPC f diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index d459f8c7..7ba94492 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -1,5 +1,5 @@ == snap opened grid=180x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/ghostty-mid.golden b/test/snapshots/ghostty-mid.golden index ab117f8a..4bd8bf1f 100644 --- a/test/snapshots/ghostty-mid.golden +++ b/test/snapshots/ghostty-mid.golden @@ -1,5 +1,5 @@ == snap ghostty-mid grid=100x31 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del diff --git a/test/snapshots/grep.golden b/test/snapshots/grep.golden index 65b2fd5b..687d7099 100644 --- a/test/snapshots/grep.golden +++ b/test/snapshots/grep.golden @@ -1,5 +1,5 @@ == snap opened grid=180x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/headersweep-restored.golden b/test/snapshots/headersweep-restored.golden index 765f221f..38b505e7 100644 --- a/test/snapshots/headersweep-restored.golden +++ b/test/snapshots/headersweep-restored.golden @@ -21,7 +21,7 @@ |19: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |20: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, == snap col-swept grid=120x21 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit Restore /tmp/pardes-snap/headersweep-restored/du +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap/headersweep-restore | New Tty Find Grep Joincol Delcol echo RE''STORED-COL New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save M /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save M | ode Filter Collapse Del ode Filter Collapse Del @@ -44,6 +44,6 @@ |7: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, == snap ws-swept grid=120x21 cursor=4,11 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit Restore /tmp/pardes-snap/headersweep-restored ec +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap/headersweep-rest ec |9: echo RE''STORED-WS |10: RESTORED-WS diff --git a/test/snapshots/headersweep.golden b/test/snapshots/headersweep.golden index 92d23a1b..38004c08 100644 --- a/test/snapshots/headersweep.golden +++ b/test/snapshots/headersweep.golden @@ -21,7 +21,7 @@ |19: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |20: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, == snap col-swept grid=120x21 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol echo SW''EPT-COL New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filte /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filte | r Collapse Del r Collapse Del @@ -38,11 +38,11 @@ | ls | hay.txt == snap ws-swept grid=120x21 cursor=4,10 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit echo SW''EPT-WS +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit echo SW''EPT-WS |8: echo SW''EPT-WS |9: SWEPT-WS == snap ws-looked grid=120x21 cursor=7,19 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit echo SW''EPT-WS xxhay.txtxx +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit echo SW''EPT-WS xxhay.txtxx |17: /tmp/pardes-snap/headersweep/cwd/hay.txt Save Tty Collaps |18: e Del |19: 1 ZQNEEDLE diff --git a/test/snapshots/hscroll.golden b/test/snapshots/hscroll.golden index ddd7bab7..e73bf4c3 100644 --- a/test/snapshots/hscroll.golden +++ b/test/snapshots/hscroll.golden @@ -1,5 +1,5 @@ == snap opened grid=90x31 cursor=7,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/hscroll/cwd Tty+bash Save /tmp/pardes-snap/hscroll/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del diff --git a/test/snapshots/images.golden b/test/snapshots/images.golden index 940e293e..e888460d 100644 --- a/test/snapshots/images.golden +++ b/test/snapshots/images.golden @@ -1,5 +1,5 @@ == snap img-open grid=150x31 cursor=11,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del | ls ls @@ -75,7 +75,7 @@ |15: │█🬝▄ |16: 🬝🬹 == snap tag-edit grid=400x31 cursor=87,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/jumps.golden b/test/snapshots/jumps.golden index 65435443..27884f6a 100644 --- a/test/snapshots/jumps.golden +++ b/test/snapshots/jumps.golden @@ -1,5 +1,5 @@ == snap start grid=150x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/jumps/cwd/big.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/snapshots/layout-close.golden b/test/snapshots/layout-close.golden index d708d764..95806a16 100644 --- a/test/snapshots/layout-close.golden +++ b/test/snapshots/layout-close.golden @@ -1,5 +1,5 @@ == snap built grid=140x41 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/layout-close/cwd Tty+bash Save Mode Filter Collaps /tmp/pardes-snap/layout-close/cwd Tty+bash Save Mode Filter Collaps | e Del e Del diff --git a/test/snapshots/layout-open.golden b/test/snapshots/layout-open.golden index 91d41790..a3d9dfdd 100644 --- a/test/snapshots/layout-open.golden +++ b/test/snapshots/layout-open.golden @@ -1,5 +1,5 @@ == snap before grid=100x31 cursor=2,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/layout-open/cwd Tty+bash Save /tmp/pardes-snap/layout-open/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del diff --git a/test/snapshots/leader.golden b/test/snapshots/leader.golden index 6c154c6c..52528cde 100644 --- a/test/snapshots/leader.golden +++ b/test/snapshots/leader.golden @@ -1,5 +1,5 @@ == snap spc grid=100x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/leader/cwd/cmds.txt Save Tty Collapse Del | 1 Help SPC diff --git a/test/snapshots/load.golden b/test/snapshots/load.golden index d18fd235..38a6d59b 100644 --- a/test/snapshots/load.golden +++ b/test/snapshots/load.golden @@ -1,5 +1,5 @@ == snap loaded grid=100x31 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/load/cwd Tty+bash Save Mode Fi /tmp/pardes-snap/load/cwd Tty+bash Save Mode Fi | lter Collapse Del lter Collapse Del diff --git a/test/snapshots/logquiet.golden b/test/snapshots/logquiet.golden index 366fc0f7..45b643db 100644 --- a/test/snapshots/logquiet.golden +++ b/test/snapshots/logquiet.golden @@ -1,5 +1,5 @@ == snap quiet grid=100x31 cursor=62,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/logquiet/cwd Tty+bash Save Mode Filter Collapse Del | $ ls diff --git a/test/snapshots/look-center.golden b/test/snapshots/look-center.golden index e5db101e..c861bb8f 100644 --- a/test/snapshots/look-center.golden +++ b/test/snapshots/look-center.golden @@ -1,5 +1,5 @@ == snap center-open grid=150x31 cursor=15,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/look-dir.golden b/test/snapshots/look-dir.golden index 7f20fdc6..29e67d5f 100644 --- a/test/snapshots/look-dir.golden +++ b/test/snapshots/look-dir.golden @@ -1,5 +1,5 @@ == snap dir-open grid=100x31 cursor=4,11 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mod /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mod | e Filter Collapse Del e Filter Collapse Del diff --git a/test/snapshots/look-file-1col.golden b/test/snapshots/look-file-1col.golden index 45f9f20f..81ba4ded 100644 --- a/test/snapshots/look-file-1col.golden +++ b/test/snapshots/look-file-1col.golden @@ -1,5 +1,5 @@ == snap file-open-1col grid=100x31 cursor=14,19 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/look-file-1col/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/look-file.golden b/test/snapshots/look-file.golden index 695fd2c1..4d4bbdfe 100644 --- a/test/snapshots/look-file.golden +++ b/test/snapshots/look-file.golden @@ -1,5 +1,5 @@ == snap file-open grid=150x31 cursor=14,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/lookloaded.golden b/test/snapshots/lookloaded.golden index 70b42102..a968a6dc 100644 --- a/test/snapshots/lookloaded.golden +++ b/test/snapshots/lookloaded.golden @@ -1,5 +1,5 @@ == snap file-open grid=100x31 cursor=14,13 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lookloaded/cwd Tty+bash Save M /tmp/pardes-snap/lookloaded/cwd Tty+bash Save M | ode Filter Collapse Del ode Filter Collapse Del diff --git a/test/snapshots/lookpanes.golden b/test/snapshots/lookpanes.golden index 98dfd8b9..e0f55f5f 100644 --- a/test/snapshots/lookpanes.golden +++ b/test/snapshots/lookpanes.golden @@ -1,5 +1,5 @@ == snap shells grid=130x51 cursor=122,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lookpanes/cwd/beta/bmark.txt Save Tty Collaps /tmp/pardes-snap/lookpanes/cwd Tty+bash Save Mode Filter Colla | e Del pse Del diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index 25306ce1..f57ee457 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -1,5 +1,5 @@ == snap opened grid=150x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lookrange/cwd/look.txt Save Tty Collapse Del | 1 r.txt:3-5 diff --git a/test/snapshots/lsp-client-edit.golden b/test/snapshots/lsp-client-edit.golden index 29ec05af..c36d15be 100644 --- a/test/snapshots/lsp-client-edit.golden +++ b/test/snapshots/lsp-client-edit.golden @@ -1,5 +1,5 @@ == snap formatted grid=100x25 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext | 1 // formatted by mock formatted 1 range(s) diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index 17eb0d40..23d86e11 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -1,5 +1,5 @@ == snap gd-jumped grid=100x25 cursor=16,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse Del TreeContext | 1 mod lib; --:--:-- lsp rust-analyzer: ready diff --git a/test/snapshots/lsp-rename.golden b/test/snapshots/lsp-rename.golden index 03fb2311..ba19d8f0 100644 --- a/test/snapshots/lsp-rename.golden +++ b/test/snapshots/lsp-rename.golden @@ -1,5 +1,5 @@ == snap renamed grid=110x25 cursor=17,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); renamed 2 range(s) diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index be0090fb..153ae5cc 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -1,5 +1,5 @@ == snap opened grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden index 0b29034f..29a81f93 100644 --- a/test/snapshots/lspcomplete.golden +++ b/test/snapshots/lspcomplete.golden @@ -1,5 +1,5 @@ == snap opened grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { @@ -31,13 +31,13 @@ == snap step grid=120x41 cursor=19,4 |2: * /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext == snap txtindent grid=120x41 cursor=15,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcomplete/cwd/notes.txt Save Tty Collapse Del | 1 abc. def ghi | 2 == snap nosemi grid=100x19 cursor=29,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { @@ -53,7 +53,7 @@ | 2 c.zig:3:5-12 cinnabar cinnabar, | 3 == snap nobrace grid=100x19 cursor=16,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { diff --git a/test/snapshots/lspcompletemoved.golden b/test/snapshots/lspcompletemoved.golden index a033ed56..e759cbd8 100644 --- a/test/snapshots/lspcompletemoved.golden +++ b/test/snapshots/lspcompletemoved.golden @@ -1,5 +1,5 @@ == snap typedthrough grid=120x21 cursor=16,14 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { diff --git a/test/snapshots/lspdebug.golden b/test/snapshots/lspdebug.golden index cf2eb097..650b41b2 100644 --- a/test/snapshots/lspdebug.golden +++ b/test/snapshots/lspdebug.golden @@ -1,5 +1,5 @@ == snap opened grid=120x45 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index 201f6dd4..904e076a 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,5 +1,5 @@ == snap absrow grid=100x35 cursor=16,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext | 1 const shade = @import("../shade.zig"); @@ -58,7 +58,7 @@ |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, == snap subrow grid=100x35 cursor=16,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext | 1 const tint = @import("inner/tint.zig"); diff --git a/test/snapshots/markup.golden b/test/snapshots/markup.golden index 8c712a58..6991cdf6 100644 --- a/test/snapshots/markup.golden +++ b/test/snapshots/markup.golden @@ -1,5 +1,5 @@ == snap typst grid=92x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/markup/cwd/paper.typ Save Tty Collapse Del TreeContext | 1 = Typst heading @@ -38,7 +38,7 @@ |23: 0-0 d,#608269, 1-91 d,#0d1410, |24: 0-0 d,#608269, 1-91 d,#0d1410, == snap markdown grid=92x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/markup/cwd/notes.md Save Tty Collapse Del TreeContext | 1 # Markdown heading with *italic* diff --git a/test/snapshots/mini.golden b/test/snapshots/mini.golden index cc8dd612..8d0205f7 100644 --- a/test/snapshots/mini.golden +++ b/test/snapshots/mini.golden @@ -1,5 +1,5 @@ == snap opened grid=90x23 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del | 1 @`Mini demo.zig` Mini @@ -34,8 +34,8 @@ |21: 0-0 d,#608269, 1-89 d,#0d1410, |22: 0-0 d,#608269, 1-89 d,#0d1410, == 9p opened grid=90x23 cursor=7,6,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-89 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-89 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-89 d,#314738,,tagline |2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del @@ -105,7 +105,7 @@ |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-8 #b9f480,#0d1410, 9-11 #c9a7ed,#0d1410, 12-89 #b9f480,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-19 #f8c082,#0d1410, 20-89 #e5eee5,#0d1410, == snap resized grid=105x27 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del | 1 @`Mini demo.zig` @@ -117,8 +117,8 @@ | 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ | 4 == 9p resized grid=105x27 cursor=7,7,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-104 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-104 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-104 d,#314738,,tagline |2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del diff --git a/test/snapshots/modal.golden b/test/snapshots/modal.golden index 4ade84f2..6dc6376d 100644 --- a/test/snapshots/modal.golden +++ b/test/snapshots/modal.golden @@ -1,5 +1,5 @@ == snap top grid=100x31 cursor=2,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/modal/cwd Tty+bash Save Mode F /tmp/pardes-snap/modal/cwd Tty+bash Save Mode F | ilter Collapse Del ilter Collapse Del diff --git a/test/snapshots/msg.golden b/test/snapshots/msg.golden index ff7b39a0..caa234d3 100644 --- a/test/snapshots/msg.golden +++ b/test/snapshots/msg.golden @@ -1,5 +1,5 @@ == snap opened grid=70x15 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exi +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del | 1 line 1 @@ -12,7 +12,7 @@ == snap saved grid=70x15 cursor=7,3 |3: 1 line 1 --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt == snap repainted grid=70x17 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exi +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del | 1 line 1 --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt diff --git a/test/snapshots/multicursor.golden b/test/snapshots/multicursor.golden index c3d5dbe2..0b3bbcb2 100644 --- a/test/snapshots/multicursor.golden +++ b/test/snapshots/multicursor.golden @@ -1,5 +1,5 @@ == snap three-cursors grid=150x31 cursor=7,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/nested.golden b/test/snapshots/nested.golden index 9758c491..07d6148d 100644 --- a/test/snapshots/nested.golden +++ b/test/snapshots/nested.golden @@ -1,5 +1,5 @@ == snap file-arg grid=100x31 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nested.txt @@ -23,7 +23,7 @@ | /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del | 1 == snap no-arg grid=100x31 cursor=4,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) @@ -47,7 +47,7 @@ | /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del | 1 == snap dir-arg grid=100x31 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nestdir diff --git a/test/snapshots/ninep.golden b/test/snapshots/ninep.golden index f3733ab4..c6b5f0af 100644 --- a/test/snapshots/ninep.golden +++ b/test/snapshots/ninep.golden @@ -1,5 +1,5 @@ == snap opened grid=90x15 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext | 1 const greeting = "café λ 界 é"; @@ -26,8 +26,8 @@ |13: 0-0 d,#608269, 1-89 d,#0d1410, |14: 0-0 d,#608269, 1-89 d,#0d1410, == 9p opened grid=90x15 cursor=7,3,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-89 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-89 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-89 d,#314738,,tagline |2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext @@ -148,8 +148,8 @@ |18: 0-0 d,#608269, 1-104 d,#0d1410, |19: 0-0 d,#608269, 1-104 d,#0d1410, == 9p resized grid=105x20 cursor=7,4,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-104 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-104 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-104 d,#314738,,tagline |2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext @@ -191,7 +191,7 @@ |19: @19: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body == snap resized grid=105x20 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext | 1 // café λ 界 Colors diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index b7a8da86..2fd54c27 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -1,5 +1,5 @@ == snap prompt grid=180x13 cursor=179,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del | 1 alpha beta |tr a-z A-Z diff --git a/test/snapshots/psearch.golden b/test/snapshots/psearch.golden index 544086c5..e830a206 100644 --- a/test/snapshots/psearch.golden +++ b/test/snapshots/psearch.golden @@ -1,5 +1,5 @@ == snap output grid=140x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/psearch/cwd Tty+bash Save Mode Filter Collapse Del | printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' diff --git a/test/snapshots/reflow.golden b/test/snapshots/reflow.golden index afd4b93f..17c42d0d 100644 --- a/test/snapshots/reflow.golden +++ b/test/snapshots/reflow.golden @@ -1,5 +1,5 @@ == snap widened grid=200x25 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/reflow/cwd Tty+bash Save Mode Filter Collapse Del | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy diff --git a/test/snapshots/respawn.golden b/test/snapshots/respawn.golden index d6d21a81..1e6425d2 100644 --- a/test/snapshots/respawn.golden +++ b/test/snapshots/respawn.golden @@ -1,5 +1,5 @@ == snap respawn grid=140x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/restore.golden b/test/snapshots/restore.golden index af2b82c1..0bb53676 100644 --- a/test/snapshots/restore.golden +++ b/test/snapshots/restore.golden @@ -1,5 +1,5 @@ == snap dumped grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit Restore /tmp/pardes-snap/res +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/restore/cwd Tty+bash Save Mode Filter Collapse Del | $ ls Dump diff --git a/test/snapshots/rsearch.golden b/test/snapshots/rsearch.golden index 89c4f7bd..eb98853a 100644 --- a/test/snapshots/rsearch.golden +++ b/test/snapshots/rsearch.golden @@ -1,5 +1,5 @@ == snap opened grid=210x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/rsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/savepane.golden b/test/snapshots/savepane.golden index 8660a437..bea7146b 100644 --- a/test/snapshots/savepane.golden +++ b/test/snapshots/savepane.golden @@ -1,5 +1,5 @@ == snap scratch grid=100x31 cursor=20,18 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/savepane/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/scroll.golden b/test/snapshots/scroll.golden index 9250590a..44b6b264 100644 --- a/test/snapshots/scroll.golden +++ b/test/snapshots/scroll.golden @@ -1,5 +1,5 @@ == snap bottom grid=100x31 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode | Filter Collapse Del Filter Collapse Del diff --git a/test/snapshots/scrolloff.golden b/test/snapshots/scrolloff.golden index 17ca7e7b..299df49d 100644 --- a/test/snapshots/scrolloff.golden +++ b/test/snapshots/scrolloff.golden @@ -1,5 +1,5 @@ == snap top grid=210x16 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/scrolloff/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/selarg.golden b/test/snapshots/selarg.golden index f41c355b..741864ef 100644 --- a/test/snapshots/selarg.golden +++ b/test/snapshots/selarg.golden @@ -1,5 +1,5 @@ == snap kept grid=100x31 cursor=6,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode | Filter Collapse Del Filter Collapse Del diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index c99d48e1..e3f3b2d7 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -1,5 +1,5 @@ == snap prompt-armed grid=160x25 cursor=159,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext | 1 const one = 1; Select / diff --git a/test/snapshots/shellset.golden b/test/snapshots/shellset.golden index 0d13f017..9d566be7 100644 --- a/test/snapshots/shellset.golden +++ b/test/snapshots/shellset.golden @@ -1,5 +1,5 @@ == snap boot grid=90x21 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/shellset/cwd/cmd.txt Save Tty Collapse Del | 1 Shell zznosuchshell diff --git a/test/snapshots/shrinktag.golden b/test/snapshots/shrinktag.golden index 9aa29e11..d73c0072 100644 --- a/test/snapshots/shrinktag.golden +++ b/test/snapshots/shrinktag.golden @@ -1,5 +1,5 @@ == snap before grid=100x31 cursor=2,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo | de Filter Collapse Del de Filter Collapse Del diff --git a/test/snapshots/splitparent.golden b/test/snapshots/splitparent.golden index e626cea7..f83bbb66 100644 --- a/test/snapshots/splitparent.golden +++ b/test/snapshots/splitparent.golden @@ -1,5 +1,5 @@ == snap shrunk grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del @@ -13,14 +13,14 @@ |11: Mode Filter Collapse Del |12: ls == snap tallest grid=100x6 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save | /tmp/pardes-snap/splitparent/cwd Tty+bash Save Mode Filter Collapse Del | /tmp/pardes-snap/splitparent/cwd Tty+bash Save ls | e in that column: each keeps its tag and 2 rows == snap regrown grid=100x31 cursor=4,13 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index bdd506e9..7c445492 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -1,5 +1,5 @@ == snap results grid=150x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/stepgrain/cwd/a.txt Save Tty Collapse Del | 1 hello ZQMARK one diff --git a/test/snapshots/syntax.golden b/test/snapshots/syntax.golden index 096dab27..2f7a6b74 100644 --- a/test/snapshots/syntax.golden +++ b/test/snapshots/syntax.golden @@ -1,5 +1,5 @@ == snap zig-open grid=150x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/tag.golden b/test/snapshots/tag.golden index 0f9af5dc..0d20859a 100644 --- a/test/snapshots/tag.golden +++ b/test/snapshots/tag.golden @@ -1,5 +1,5 @@ == snap tag-focus grid=150x31 cursor=36,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/tagalign.golden b/test/snapshots/tagalign.golden index 8a522ced..a557ff95 100644 --- a/test/snapshots/tagalign.golden +++ b/test/snapshots/tagalign.golden @@ -1,5 +1,5 @@ == snap aligned grid=100x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha @@ -9,7 +9,7 @@ | ls | deep == snap fits grid=87x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Co | llapse Del @@ -19,7 +19,7 @@ | ls | deep == snap overby1 grid=86x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty C | ollapse Del @@ -29,7 +29,7 @@ | ls | deep == snap clicked grid=100x31 cursor=11,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha @@ -39,7 +39,7 @@ | ls | deep == snap revealed grid=70x31 cursor=30,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exi +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/documen | t.txt Save Tty Collapse Del diff --git a/test/snapshots/tagalign2col.golden b/test/snapshots/tagalign2col.golden index a35edccb..129141b6 100644 --- a/test/snapshots/tagalign2col.golden +++ b/test/snapshots/tagalign2col.golden @@ -1,5 +1,5 @@ == snap onecol grid=160x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Collapse De /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filter Collapse Del | l ls Left diff --git a/test/snapshots/tagbottom.golden b/test/snapshots/tagbottom.golden index d5f1f720..8469c741 100644 --- a/test/snapshots/tagbottom.golden +++ b/test/snapshots/tagbottom.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del | 1 aaa diff --git a/test/snapshots/tagbottomimage.golden b/test/snapshots/tagbottomimage.golden index 89e96f6b..2bf9231e 100644 --- a/test/snapshots/tagbottomimage.golden +++ b/test/snapshots/tagbottomimage.golden @@ -1,5 +1,5 @@ == snap img-top grid=150x31 cursor=11,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagbottomimage/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/tagbottomshort.golden b/test/snapshots/tagbottomshort.golden index 3fd3b180..efa8b3f1 100644 --- a/test/snapshots/tagbottomshort.golden +++ b/test/snapshots/tagbottomshort.golden @@ -1,5 +1,5 @@ == snap roomy grid=80x11 cursor=79,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one /ZZ | 2 two @@ -11,21 +11,21 @@ | | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap two-body grid=80x5 cursor=79,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one /ZZ | 2 two | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap one-body grid=80x4 cursor=79,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one /ZZ | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap tag-only grid=80x2 cursor=79,1 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap regrown grid=80x11 cursor=79,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one /ZZ | 2 two @@ -37,7 +37,7 @@ | | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap leader-one-body grid=80x4 cursor=7,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one SPC | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del diff --git a/test/snapshots/tagcmd.golden b/test/snapshots/tagcmd.golden index 8f1dc8d2..2c1ca73f 100644 --- a/test/snapshots/tagcmd.golden +++ b/test/snapshots/tagcmd.golden @@ -1,5 +1,5 @@ == snap edited grid=100x31 cursor=13,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/tagcmd/cwd/c.txt Save Tty Collapse Del | 1 ZZEDITline 1 diff --git a/test/snapshots/tagnav.golden b/test/snapshots/tagnav.golden index e06c578e..a86854a9 100644 --- a/test/snapshots/tagnav.golden +++ b/test/snapshots/tagnav.golden @@ -1,5 +1,5 @@ == snap start grid=100x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll /tmp/pardes-snap/tagnav/cwd Tty+bash Save Mode | apse Del Filter Collapse Del @@ -34,13 +34,13 @@ |4: 1 alpha ls == snap workspace-tag grid=100x31 cursor=0,0 |4: 1 alpha Up ls -== snap topbar-dollar grid=100x31 cursor=70,0 +== snap topbar-dollar grid=100x31 cursor=74,0 |4: 1 alpha ls == snap topbar-dump-word grid=100x31 cursor=46,0 == snap topbar-exec grid=100x31 cursor=7,4 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit Restore /tmp/pardes-snap/tag +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap |4: 1 alpha Dump ls -== snap topbar-restore-word grid=100x31 cursor=72,0 +== snap topbar-restore-word grid=100x31 cursor=76,0 |4: 1 alpha ls == snap topbar-restored grid=100x31 cursor=7,4 |4: 1 alpha $ ls diff --git a/test/snapshots/tagnav.snap b/test/snapshots/tagnav.snap index f145480e..2f5906bb 100644 --- a/test/snapshots/tagnav.snap +++ b/test/snapshots/tagnav.snap @@ -93,7 +93,7 @@ snap column-word key c-w k stable 400 5000 snap workspace-tag -# `$` is the last cell; four long-word steps back land on `Dump`, and the +# `$` is the last cell; five long-word steps back land on `Dump`, and the # execute key runs it and gives the keyboard back to the body FIRST -- `Exit` # lives up here too, so a builtin that frees the session must never return # into a focused header. Dump grows a `Restore ` word, which is also the @@ -101,7 +101,7 @@ snap workspace-tag key g l stable 400 5000 snap topbar-dollar -key B B B B +key B B B B B stable 400 5000 snap topbar-dump-word key tab diff --git a/test/snapshots/tagpath.golden b/test/snapshots/tagpath.golden index 6f082c7a..1216bdeb 100644 --- a/test/snapshots/tagpath.golden +++ b/test/snapshots/tagpath.golden @@ -1,5 +1,5 @@ == snap start grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagpath/cwd/c.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/snapshots/theme.golden b/test/snapshots/theme.golden index 443d639c..351f8905 100644 --- a/test/snapshots/theme.golden +++ b/test/snapshots/theme.golden @@ -1,5 +1,5 @@ -== snap orchard grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +== snap orchard grid=100x31 cursor=85,0 +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit NextColor | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/theme/cwd Tty+bash Save Mode F /tmp/pardes-snap/theme/cwd Tty+bash Save Mode F | ilter Collapse Del ilter Collapse Del @@ -55,7 +55,7 @@ == snap dusk grid=100x31 cursor=4,6 |4: ls NextColor ls == style dusk grid=100x31 -|0: 0-50 #c6b6c5,#2c2630, 51-59 #fff0eb,#654053, 60-60 #fff0eb,#2c2630, 61-99 #c6b6c5,#2c2630, +|0: 0-75 #c6b6c5,#2c2630, 76-84 #fff0eb,#654053, 85-99 #fff0eb,#2c2630, |1: 0-1 d,#757a5f, 2-2 d,#533d4d, 3-49 #d2c2d1,#533d4d, 50-51 #d2c2d1,#757a5f, 52-52 #d2c2d1,#2c2630, 53-99 #c6b6c5,#2c2630, |2: 0-1 d,#edb092, 2-2 d,#533d4d, 3-29 #d2c2d1,#533d4d, 30-38 #a1d5c4,#533d4d, 39-49 #d2c2d1,#533d4d, 50-51 #d2c2d1,#745469, 52-52 #d2c2d1,#2c2630, 53-79 #c6b6c5,#2c2630, 80-88 #96c9b8,#2c2630, 89-99 #c6b6c5,#2c2630, |3: 0-2 d,#533d4d, 3-49 #d2c2d1,#533d4d, 50-52 #d2c2d1,#2c2630, 53-99 #c6b6c5,#2c2630, @@ -88,7 +88,7 @@ |30: 0-0 d,#8e667c, 1-49 d,#39323b, 50-50 d,#8e667c, 51-99 d,#39323b, == snap ink grid=100x31 cursor=4,6 == style ink grid=100x31 -|0: 0-50 #d5e4f1,#15212c, 51-59 #ffffff,#1b547c, 60-60 #ffffff,#15212c, 61-99 #d5e4f1,#15212c, +|0: 0-75 #d5e4f1,#15212c, 76-84 #ffffff,#1b547c, 85-99 #ffffff,#15212c, |1: 0-1 d,#8f7d5b, 2-2 d,#2b4051, 3-49 #e1eef9,#2b4051, 50-51 #e1eef9,#8f7d5b, 52-52 #e1eef9,#15212c, 53-99 #d5e4f1,#15212c, |2: 0-1 d,#86d8ff, 2-2 d,#2b4051, 3-29 #e1eef9,#2b4051, 30-38 #ffeab8,#2b4051, 39-49 #e1eef9,#2b4051, 50-51 #e1eef9,#5f7990, 52-52 #e1eef9,#15212c, 53-79 #d5e4f1,#15212c, 80-88 #f5e0ac,#15212c, 89-99 #d5e4f1,#15212c, |3: 0-2 d,#2b4051, 3-49 #e1eef9,#2b4051, 50-52 #e1eef9,#15212c, 53-99 #d5e4f1,#15212c, @@ -121,7 +121,7 @@ |30: 0-0 d,#86a8c2, 1-49 d,#000000, 50-50 d,#86a8c2, 51-99 d,#000000, == snap paper grid=100x31 cursor=4,6 == style paper grid=100x31 -|0: 0-50 #52625a,#e8eae3, 51-59 #203e31,#c5e2d0, 60-60 #203e31,#e8eae3, 61-99 #52625a,#e8eae3, +|0: 0-75 #52625a,#e8eae3, 76-84 #203e31,#c5e2d0, 85-99 #203e31,#e8eae3, |1: 0-1 d,#bda27e, 2-2 d,#bdd8ca, 3-49 #4a5a52,#bdd8ca, 50-51 #4a5a52,#bda27e, 52-52 #4a5a52,#e8eae3, 53-99 #52625a,#e8eae3, |2: 0-1 d,#367157, 2-2 d,#bdd8ca, 3-29 #4a5a52,#bdd8ca, 30-38 #69447a,#bdd8ca, 39-49 #4a5a52,#bdd8ca, 50-51 #4a5a52,#8fa594, 52-52 #4a5a52,#e8eae3, 53-79 #52625a,#e8eae3, 80-88 #724c83,#e8eae3, 89-99 #52625a,#e8eae3, |3: 0-2 d,#bdd8ca, 3-49 #4a5a52,#bdd8ca, 50-52 #4a5a52,#e8eae3, 53-99 #52625a,#e8eae3, @@ -154,7 +154,7 @@ |30: 0-0 d,#869d8a, 1-49 d,#f5f3ed, 50-50 d,#869d8a, 51-99 d,#f5f3ed, == snap daybreak grid=100x31 cursor=4,6 == style daybreak grid=100x31 -|0: 0-50 #29465e,#edf2f7, 51-59 #10364f,#b9dffb, 60-60 #10364f,#edf2f7, 61-99 #29465e,#edf2f7, +|0: 0-75 #29465e,#edf2f7, 76-84 #10364f,#b9dffb, 85-99 #10364f,#edf2f7, |1: 0-1 d,#b79a7a, 2-2 d,#c7dcec, 3-49 #213e56,#c7dcec, 50-51 #213e56,#b79a7a, 52-52 #213e56,#edf2f7, 53-99 #29465e,#edf2f7, |2: 0-1 d,#006198, 2-2 d,#c7dcec, 3-29 #213e56,#c7dcec, 30-38 #52255f,#c7dcec, 39-49 #213e56,#c7dcec, 50-51 #213e56,#7b9eb7, 52-52 #213e56,#edf2f7, 53-79 #29465e,#edf2f7, 80-88 #5a2d67,#edf2f7, 89-99 #29465e,#edf2f7, |3: 0-2 d,#c7dcec, 3-49 #213e56,#c7dcec, 50-52 #213e56,#edf2f7, 53-99 #29465e,#edf2f7, @@ -187,7 +187,7 @@ |30: 0-0 d,#6685a0, 1-49 d,#ffffff, 50-50 d,#6685a0, 51-99 d,#ffffff, == snap atelier grid=100x31 cursor=4,6 == style atelier grid=100x31 -|0: 0-50 #3d6055,#e4f0ed, 51-59 #35492d,#edf2a5, 60-60 #35492d,#e4f0ed, 61-99 #3d6055,#e4f0ed, +|0: 0-75 #3d6055,#e4f0ed, 76-84 #35492d,#edf2a5, 85-99 #35492d,#e4f0ed, |1: 0-1 d,#bca481, 2-2 d,#bfdcce, 3-49 #35584d,#bfdcce, 50-51 #35584d,#bca481, 52-52 #35584d,#e4f0ed, 53-99 #3d6055,#e4f0ed, |2: 0-1 d,#36826b, 2-2 d,#bfdcce, 3-29 #35584d,#bfdcce, 30-38 #653f6b,#bfdcce, 39-49 #35584d,#bfdcce, 50-51 #35584d,#95baa2, 52-52 #35584d,#e4f0ed, 53-79 #3d6055,#e4f0ed, 80-88 #6e4774,#e4f0ed, 89-99 #3d6055,#e4f0ed, |3: 0-2 d,#bfdcce, 3-49 #35584d,#bfdcce, 50-52 #35584d,#e4f0ed, 53-99 #3d6055,#e4f0ed, @@ -225,7 +225,7 @@ == snap forge grid=100x31 cursor=4,6 |4: ls NextColor ls == style forge grid=100x31 -|0: 0-50 #c5c9d2,#22252b, 51-59 #e2eef4,#1c5172, 60-60 #e2eef4,#22252b, 61-99 #c5c9d2,#22252b, +|0: 0-75 #c5c9d2,#22252b, 76-84 #e2eef4,#1c5172, 85-99 #e2eef4,#22252b, |1: 0-1 d,#6a7b67, 2-2 d,#374253, 3-49 #d1d5de,#374253, 50-51 #d1d5de,#6a7b67, 52-52 #d1d5de,#22252b, 53-99 #c5c9d2,#22252b, |2: 0-1 d,#9cc3f7, 2-2 d,#374253, 3-29 #d1d5de,#374253, 30-38 #f8cba7,#374253, 39-49 #d1d5de,#374253, 50-51 #d1d5de,#55647b, 52-52 #d1d5de,#22252b, 53-79 #c5c9d2,#22252b, 80-88 #ecbf9b,#22252b, 89-99 #c5c9d2,#22252b, |3: 0-2 d,#374253, 3-49 #d1d5de,#374253, 50-52 #d1d5de,#22252b, 53-99 #c5c9d2,#22252b, @@ -258,7 +258,7 @@ |30: 0-0 d,#708095, 1-49 d,#0c0c0e, 50-50 d,#708095, 51-99 d,#0c0c0e, == snap lagoon grid=100x31 cursor=4,6 == style lagoon grid=100x31 -|0: 0-50 #bbd7cb,#29443f, 51-59 #e6f2f3,#325f6c, 60-60 #e6f2f3,#29443f, 61-99 #bbd7cb,#29443f, +|0: 0-75 #bbd7cb,#29443f, 76-84 #e6f2f3,#325f6c, 85-99 #e6f2f3,#29443f, |1: 0-1 d,#9a7662, 2-2 d,#3a6154, 3-49 #c7e3d7,#3a6154, 50-51 #c7e3d7,#9a7662, 52-52 #c7e3d7,#29443f, 53-99 #bbd7cb,#29443f, |2: 0-1 d,#81cfb7, 2-2 d,#3a6154, 3-29 #c7e3d7,#3a6154, 30-38 #f0cef8,#3a6154, 39-49 #c7e3d7,#3a6154, 50-51 #c7e3d7,#548372, 52-52 #c7e3d7,#29443f, 53-79 #bbd7cb,#29443f, 80-88 #e4c2ec,#29443f, 89-99 #bbd7cb,#29443f, |3: 0-2 d,#3a6154, 3-49 #c7e3d7,#3a6154, 50-52 #c7e3d7,#29443f, 53-99 #bbd7cb,#29443f, @@ -291,7 +291,7 @@ |30: 0-0 d,#6e9b8b, 1-49 d,#34464c, 50-50 d,#6e9b8b, 51-99 d,#34464c, == snap solarium grid=100x31 cursor=4,6 == style solarium grid=100x31 -|0: 0-50 #c7d4bd,#123f43, 51-59 #eee8d5,#1f5c64, 60-60 #eee8d5,#123f43, 61-99 #c7d4bd,#123f43, +|0: 0-75 #c7d4bd,#123f43, 76-84 #eee8d5,#1f5c64, 85-99 #eee8d5,#123f43, |1: 0-1 d,#347a9a, 2-2 d,#2f5c5c, 3-49 #d3e0c9,#2f5c5c, 50-51 #d3e0c9,#347a9a, 52-52 #d3e0c9,#123f43, 53-99 #c7d4bd,#123f43, |2: 0-1 d,#e1c266, 2-2 d,#2f5c5c, 3-29 #d3e0c9,#2f5c5c, 30-38 #f5cdec,#2f5c5c, 39-49 #d3e0c9,#2f5c5c, 50-51 #d3e0c9,#467f76, 52-52 #d3e0c9,#123f43, 53-79 #c7d4bd,#123f43, 80-88 #e9c1e0,#123f43, 89-99 #c7d4bd,#123f43, |3: 0-2 d,#2f5c5c, 3-49 #d3e0c9,#2f5c5c, 50-52 #d3e0c9,#123f43, 53-99 #c7d4bd,#123f43, @@ -324,7 +324,7 @@ |30: 0-0 d,#65978c, 1-49 d,#173e45, 50-50 d,#65978c, 51-99 d,#173e45, == snap spectrum grid=100x31 cursor=4,6 == style spectrum grid=100x31 -|0: 0-50 #ddd8bb,#3b3830, 51-59 #fcfcfa,#513f60, 60-60 #fcfcfa,#3b3830, 61-99 #ddd8bb,#3b3830, +|0: 0-75 #ddd8bb,#3b3830, 76-84 #fcfcfa,#513f60, 85-99 #fcfcfa,#3b3830, |1: 0-1 d,#706596, 2-2 d,#5a523a, 3-49 #e9e4c7,#5a523a, 50-51 #e9e4c7,#706596, 52-52 #e9e4c7,#3b3830, 53-99 #ddd8bb,#3b3830, |2: 0-1 d,#ffd866, 2-2 d,#5a523a, 3-29 #e9e4c7,#5a523a, 30-38 #d7e3ff,#5a523a, 39-49 #e9e4c7,#5a523a, 50-51 #e9e4c7,#92844f, 52-52 #e9e4c7,#3b3830, 53-79 #ddd8bb,#3b3830, 80-88 #c5d7ff,#3b3830, 89-99 #ddd8bb,#3b3830, |3: 0-2 d,#5a523a, 3-49 #e9e4c7,#5a523a, 50-52 #e9e4c7,#3b3830, 53-99 #ddd8bb,#3b3830, @@ -357,7 +357,7 @@ |30: 0-0 d,#948d6f, 1-49 d,#100e11, 50-50 d,#948d6f, 51-99 d,#100e11, == snap harvest grid=100x31 cursor=4,6 == style harvest grid=100x31 -|0: 0-50 #d5d8b8,#343b2e, 51-59 #f3f2cc,#4f5834, 60-60 #f3f2cc,#343b2e, 61-99 #d5d8b8,#343b2e, +|0: 0-75 #d5d8b8,#343b2e, 76-84 #f3f2cc,#4f5834, 85-99 #f3f2cc,#343b2e, |1: 0-1 d,#9b583f, 2-2 d,#4a583e, 3-49 #e1e4c4,#4a583e, 50-51 #e1e4c4,#9b583f, 52-52 #e1e4c4,#343b2e, 53-99 #d5d8b8,#343b2e, |2: 0-1 d,#d8bd83, 2-2 d,#4a583e, 3-29 #e1e4c4,#4a583e, 30-38 #c5e7f7,#4a583e, 39-49 #e1e4c4,#4a583e, 50-51 #e1e4c4,#7b7e4e, 52-52 #e1e4c4,#343b2e, 53-79 #d5d8b8,#343b2e, 80-88 #badbeb,#343b2e, 89-99 #d5d8b8,#343b2e, |3: 0-2 d,#4a583e, 3-49 #e1e4c4,#4a583e, 50-52 #e1e4c4,#343b2e, 53-99 #d5d8b8,#343b2e, @@ -390,7 +390,7 @@ |30: 0-0 d,#888e5e, 1-49 d,#100e0b, 50-50 d,#888e5e, 51-99 d,#100e0b, == snap clay grid=100x31 cursor=4,6 == style clay grid=100x31 -|0: 0-50 #d7d6b6,#343f36, 51-59 #fbf1c7,#505c38, 60-60 #fbf1c7,#343f36, 61-99 #d7d6b6,#343f36, +|0: 0-75 #d7d6b6,#343f36, 76-84 #fbf1c7,#505c38, 85-99 #fbf1c7,#343f36, |1: 0-1 d,#875e65, 2-2 d,#4d5c48, 3-49 #e3e2c2,#4d5c48, 50-51 #e3e2c2,#875e65, 52-52 #e3e2c2,#343f36, 53-99 #d7d6b6,#343f36, |2: 0-1 d,#8ac874, 2-2 d,#4d5c48, 3-29 #e3e2c2,#4d5c48, 30-38 #b5ecec,#4d5c48, 39-49 #e3e2c2,#4d5c48, 50-51 #e3e2c2,#687c4d, 52-52 #e3e2c2,#343f36, 53-79 #d7d6b6,#343f36, 80-88 #aae0e0,#343f36, 89-99 #d7d6b6,#343f36, |3: 0-2 d,#4d5c48, 3-49 #e3e2c2,#4d5c48, 50-52 #e3e2c2,#343f36, 53-99 #d7d6b6,#343f36, @@ -423,7 +423,7 @@ |30: 0-0 d,#8c9467, 1-49 d,#10100e, 50-50 d,#8c9467, 51-99 d,#10100e, == snap forge-black grid=100x31 cursor=4,6 == style forge-black grid=100x31 -|0: 0-50 #c5c9d2,#22252b, 51-59 #e2eef4,#1c5172, 60-60 #e2eef4,#22252b, 61-99 #c5c9d2,#22252b, +|0: 0-75 #c5c9d2,#22252b, 76-84 #e2eef4,#1c5172, 85-99 #e2eef4,#22252b, |1: 0-1 d,#6a7b67, 2-2 d,#374253, 3-49 #d1d5de,#374253, 50-51 #d1d5de,#6a7b67, 52-52 #d1d5de,#22252b, 53-99 #c5c9d2,#22252b, |2: 0-1 d,#9cc3f7, 2-2 d,#374253, 3-29 #d1d5de,#374253, 30-38 #f8cba7,#374253, 39-49 #d1d5de,#374253, 50-51 #d1d5de,#55647b, 52-52 #d1d5de,#22252b, 53-79 #c5c9d2,#22252b, 80-88 #ecbf9b,#22252b, 89-99 #c5c9d2,#22252b, |3: 0-2 d,#374253, 3-49 #d1d5de,#374253, 50-52 #d1d5de,#22252b, 53-99 #c5c9d2,#22252b, @@ -456,7 +456,7 @@ |30: 0-0 d,#708095, 1-49 d,#000000, 50-50 d,#708095, 51-99 d,#000000, == snap forge-soft grid=100x31 cursor=4,6 == style forge-soft grid=100x31 -|0: 0-50 #c5c9d2,#2a2d34, 51-59 #e2eef4,#1c5172, 60-60 #e2eef4,#2a2d34, 61-99 #c5c9d2,#2a2d34, +|0: 0-75 #c5c9d2,#2a2d34, 76-84 #e2eef4,#1c5172, 85-99 #e2eef4,#2a2d34, |1: 0-1 d,#6d7f6c, 2-2 d,#404a58, 3-49 #d1d5de,#404a58, 50-51 #d1d5de,#6d7f6c, 52-52 #d1d5de,#2a2d34, 53-99 #c5c9d2,#2a2d34, |2: 0-1 d,#9cc3f7, 2-2 d,#404a58, 3-29 #d1d5de,#404a58, 30-38 #f8cba7,#404a58, 39-49 #d1d5de,#404a58, 50-51 #d1d5de,#55647b, 52-52 #d1d5de,#2a2d34, 53-79 #c5c9d2,#2a2d34, 80-88 #ecbf9b,#2a2d34, 89-99 #c5c9d2,#2a2d34, |3: 0-2 d,#404a58, 3-49 #d1d5de,#404a58, 50-52 #d1d5de,#2a2d34, 53-99 #c5c9d2,#2a2d34, @@ -489,7 +489,7 @@ |30: 0-0 d,#708095, 1-49 d,#35383e, 50-50 d,#708095, 51-99 d,#35383e, == snap orchard-black grid=100x31 cursor=4,6 == style orchard-black grid=100x31 -|0: 0-50 #b2c3b8,#1d2824, 51-59 #f5f7ee,#3c614a, 60-60 #f5f7ee,#1d2824, 61-99 #b2c3b8,#1d2824, +|0: 0-75 #b2c3b8,#1d2824, 76-84 #f5f7ee,#3c614a, 85-99 #f5f7ee,#1d2824, |1: 0-1 d,#887455, 2-2 d,#314738, 3-49 #becfc4,#314738, 50-51 #becfc4,#887455, 52-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, |2: 0-1 d,#add38a, 2-2 d,#314738, 3-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-49 #becfc4,#314738, 50-51 #becfc4,#496656, 52-52 #becfc4,#1d2824, 53-79 #b2c3b8,#1d2824, 80-88 #d3b0d9,#1d2824, 89-99 #b2c3b8,#1d2824, |3: 0-2 d,#314738, 3-49 #becfc4,#314738, 50-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, @@ -522,7 +522,7 @@ |30: 0-0 d,#608269, 1-49 d,#000000, 50-50 d,#608269, 51-99 d,#000000, == snap acme grid=100x31 cursor=4,6 == style acme grid=100x31 -|0: 0-50 #000000,#eaffff, 51-59 #000000,#9eeeee, 60-99 #000000,#eaffff, +|0: 0-75 #000000,#eaffff, 76-84 #000000,#9eeeee, 85-99 #000000,#eaffff, |1: 0-1 d,#8888cc, 2-2 d,#eaffff, 3-49 #000000,#eaffff, 50-51 #000000,#8888cc, 52-99 #000000,#eaffff, |2: 0-1 d,#8888cc, 2-2 d,#eaffff, 3-29 #000000,#eaffff, 30-38 #000099,#eaffff, 39-49 #000000,#eaffff, 50-51 #000000,#b9c3e5, 52-79 #000000,#eaffff, 80-88 #000099,#eaffff, 89-99 #000000,#eaffff, |3: 0-2 d,#eaffff, 3-99 #000000,#eaffff, @@ -555,7 +555,7 @@ |30: 0-99 d,#ffffea, == snap lapis grid=100x31 cursor=4,6 == style lapis grid=100x31 -|0: 0-50 #9aa6d9,#0f1a4a, 51-59 #0f1a4a,#e8c46a, 60-60 #0f1a4a,#0f1a4a, 61-99 #9aa6d9,#0f1a4a, +|0: 0-75 #9aa6d9,#0f1a4a, 76-84 #0f1a4a,#e8c46a, 85-99 #0f1a4a,#0f1a4a, |1: 0-1 d,#8a3a3a, 2-2 d,#25397d, 3-49 #eee6d2,#25397d, 50-51 #eee6d2,#8a3a3a, 52-52 #eee6d2,#0f1a4a, 53-99 #9aa6d9,#0f1a4a, |2: 0-1 d,#e8c46a, 2-2 d,#25397d, 3-29 #eee6d2,#25397d, 30-38 #f2d280,#25397d, 39-49 #eee6d2,#25397d, 50-51 #eee6d2,#6a78b1, 52-52 #eee6d2,#0f1a4a, 53-79 #9aa6d9,#0f1a4a, 80-88 #e8c46a,#0f1a4a, 89-99 #9aa6d9,#0f1a4a, |3: 0-2 d,#25397d, 3-49 #eee6d2,#25397d, 50-52 #eee6d2,#0f1a4a, 53-99 #9aa6d9,#0f1a4a, @@ -588,7 +588,7 @@ |30: 0-0 d,#e8c46a, 1-49 d,#0a1030, 50-50 d,#e8c46a, 51-99 d,#0a1030, == snap dark-plus grid=100x31 cursor=4,6 == style dark-plus grid=100x31 -|0: 0-50 #a7a7a7,#3c3c3c, 51-59 #d4d4d4,#264f78, 60-60 #d4d4d4,#3c3c3c, 61-99 #a7a7a7,#3c3c3c, +|0: 0-75 #a7a7a7,#3c3c3c, 76-84 #d4d4d4,#264f78, 85-99 #d4d4d4,#3c3c3c, |1: 0-1 d,#458276, 2-2 d,#1e1e1e, 3-49 #ffffff,#1e1e1e, 50-51 #ffffff,#458276, 52-52 #ffffff,#3c3c3c, 53-99 #a7a7a7,#3c3c3c, |2: 0-1 d,#007fd4, 2-2 d,#1e1e1e, 3-29 #ffffff,#1e1e1e, 30-38 #cbe5fc,#1e1e1e, 39-49 #ffffff,#1e1e1e, 50-51 #ffffff,#1c608e, 52-52 #ffffff,#3c3c3c, 53-79 #a7a7a7,#3c3c3c, 80-88 #68aee9,#3c3c3c, 89-99 #a7a7a7,#3c3c3c, |3: 0-2 d,#1e1e1e, 3-49 #ffffff,#1e1e1e, 50-52 #ffffff,#3c3c3c, 53-99 #a7a7a7,#3c3c3c, @@ -621,7 +621,7 @@ |30: 0-0 d,#424242, 1-49 d,#1e1e1e, 50-50 d,#424242, 51-99 d,#1e1e1e, == snap solarized-dark grid=100x31 cursor=4,6 == style solarized-dark grid=100x31 -|0: 0-50 #01090b,#657b83, 51-59 #002b36,#586e75, 60-60 #002b36,#657b83, 61-99 #01090b,#657b83, +|0: 0-75 #01090b,#657b83, 76-84 #002b36,#586e75, 85-99 #002b36,#657b83, |1: 0-1 d,#758a41, 2-2 d,#93a1a1, 3-49 #073642,#93a1a1, 50-51 #073642,#758a41, 52-52 #073642,#657b83, 53-99 #01090b,#657b83, |2: 0-1 d,#2483c5, 2-2 d,#93a1a1, 3-29 #073642,#93a1a1, 30-38 #2d3502,#93a1a1, 39-49 #073642,#93a1a1, 50-51 #073642,#185986, 52-52 #073642,#657b83, 53-79 #01090b,#657b83, 80-88 #121600,#657b83, 89-99 #01090b,#657b83, |3: 0-2 d,#93a1a1, 3-49 #073642,#93a1a1, 50-52 #073642,#657b83, 53-99 #01090b,#657b83, diff --git a/test/snapshots/theme.snap b/test/snapshots/theme.snap index b770d7f3..4cb360d3 100644 --- a/test/snapshots/theme.snap +++ b/test/snapshots/theme.snap @@ -5,6 +5,14 @@ file t.txt x start 31 100 -n 3 wait 8000 t.txt stable 700 20000 +# NextColor is no default word of the workspace tag: typed onto its end +press left 99 1 +release left 99 1 +key space +text NextColor +key esc +settle 100 +stable 700 10000 snap orchard snapstyle orchard press middle @NextColor 1 diff --git a/test/snapshots/themesel.golden b/test/snapshots/themesel.golden index d9c4f4ba..a82d88f5 100644 --- a/test/snapshots/themesel.golden +++ b/test/snapshots/themesel.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/themesel/cwd/t.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/snapshots/tinywin.golden b/test/snapshots/tinywin.golden index c847a2f1..f4d20a9a 100644 --- a/test/snapshots/tinywin.golden +++ b/test/snapshots/tinywin.golden @@ -1,5 +1,5 @@ == snap stacked grid=100x31 cursor=14,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Collapse Del | $ :^[n^[n^[n @@ -23,12 +23,12 @@ | /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del | 1 == snap shrunk grid=60x4 cursor=59,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Co | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Co | /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del == snap columns grid=100x31 cursor=23,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Collapse Del | $ :^[n^[n^[n cn cn cn diff --git a/test/snapshots/topbarexec.golden b/test/snapshots/topbarexec.golden index 500f9f2a..3ede27e8 100644 --- a/test/snapshots/topbarexec.golden +++ b/test/snapshots/topbarexec.golden @@ -1,5 +1,5 @@ == snap selected grid=90x21 cursor=14,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/topbarexec/cwd Tty+bash S /tmp/pardes-snap/topbarexec/cwd Tty+bash S | ave Mode Filter Collapse Del ave Mode Filter Collapse Del diff --git a/test/snapshots/tty.golden b/test/snapshots/tty.golden index b876ace6..981a5c7f 100644 --- a/test/snapshots/tty.golden +++ b/test/snapshots/tty.golden @@ -1,5 +1,5 @@ == snap tty-on grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/tty/cwd Tty+bash Save Mode Fil /tmp/pardes-snap/tty/cwd Tty+bash Save Mode Fil | ter Collapse Del ter Collapse Del diff --git a/test/snapshots/ttyclick.golden b/test/snapshots/ttyclick.golden index a69d951f..5076e882 100644 --- a/test/snapshots/ttyclick.golden +++ b/test/snapshots/ttyclick.golden @@ -1,5 +1,5 @@ == snap tty-bodyclick grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/ttyclick/cwd Tty+bash Save Mod /tmp/pardes-snap/ttyclick/cwd Tty+bash Save Mod | e Filter Collapse Del e Filter Collapse Del diff --git a/test/snapshots/ttyedit.golden b/test/snapshots/ttyedit.golden index 4411962e..ab1b1b5b 100644 --- a/test/snapshots/ttyedit.golden +++ b/test/snapshots/ttyedit.golden @@ -1,5 +1,5 @@ == snap before grid=100x31 cursor=7,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttyedit/cwd Tty+bash Save Mode /tmp/pardes-snap/ttyedit/cwd Tty+bash Save Mode | Filter Collapse Del Filter Collapse Del diff --git a/test/snapshots/ttyfollow.golden b/test/snapshots/ttyfollow.golden index 1527ce86..3fb41e89 100644 --- a/test/snapshots/ttyfollow.golden +++ b/test/snapshots/ttyfollow.golden @@ -1,5 +1,5 @@ == snap held-pre grid=100x31 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttyfollow/cwd Tty+bash Save Mo /tmp/pardes-snap/ttyfollow/cwd Tty+bash Save Mo | de Filter Collapse Del de Filter Collapse Del diff --git a/test/snapshots/ttyhelp.golden b/test/snapshots/ttyhelp.golden index c252ff28..7d21bc00 100644 --- a/test/snapshots/ttyhelp.golden +++ b/test/snapshots/ttyhelp.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=4,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/ttyhelp/cwd Tty+bash Save Mode Filter Collapse Del | $ diff --git a/test/snapshots/ttylook.golden b/test/snapshots/ttylook.golden index a8ed1b95..b839a174 100644 --- a/test/snapshots/ttylook.golden +++ b/test/snapshots/ttylook.golden @@ -1,5 +1,5 @@ == snap tok1 grid=120x31 cursor=2,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttylook/cwd Tty+bash Save Mode Filter Co /tmp/pardes-snap/ttylook/cwd Tty+bash Save Mode Filter Co | llapse Del llapse Del diff --git a/test/snapshots/ttyonly.golden b/test/snapshots/ttyonly.golden index 24f54b29..208aa485 100644 --- a/test/snapshots/ttyonly.golden +++ b/test/snapshots/ttyonly.golden @@ -1,5 +1,5 @@ == snap ttyonly grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/ttyonly/cwd Tty+bash Save Mode Filter Collapse Del | $ echo TTY''ONLY diff --git a/test/snapshots/ttypaste.golden b/test/snapshots/ttypaste.golden index 40e0ae4c..ec98834e 100644 --- a/test/snapshots/ttypaste.golden +++ b/test/snapshots/ttypaste.golden @@ -1,5 +1,5 @@ == snap bracketed-paste-reached-the-shell grid=100x31 cursor=18,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/ttypaste/cwd Tty+bash Save Mod /tmp/pardes-snap/ttypaste/cwd Tty+bash Save Mod | e Filter Collapse Del e Filter Collapse Del diff --git a/test/snapshots/ttyprompt.golden b/test/snapshots/ttyprompt.golden index 0033c78f..eb99f417 100644 --- a/test/snapshots/ttyprompt.golden +++ b/test/snapshots/ttyprompt.golden @@ -1,5 +1,5 @@ == snap greeted grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttyprompt/cwd Tty+bash Save Mo /tmp/pardes-snap/ttyprompt/cwd Tty+bash Save Mo | de Filter Collapse Del de Filter Collapse Del diff --git a/test/snapshots/ttytaken.golden b/test/snapshots/ttytaken.golden index d0f2eee9..73a75088 100644 --- a/test/snapshots/ttytaken.golden +++ b/test/snapshots/ttytaken.golden @@ -1,5 +1,5 @@ == snap opened grid=210x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttytaken/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/tutor.golden b/test/snapshots/tutor.golden index 9793ca34..1be72b87 100644 --- a/test/snapshots/tutor.golden +++ b/test/snapshots/tutor.golden @@ -1,5 +1,5 @@ == snap tutor grid=150x31 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tutor/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/tutor/cwd Tty+bash Save Mode Filter Collapse Del | ls Tutor ls diff --git a/test/snapshots/wheeldrift.golden b/test/snapshots/wheeldrift.golden index 256c2999..b5c4d231 100644 --- a/test/snapshots/wheeldrift.golden +++ b/test/snapshots/wheeldrift.golden @@ -1,5 +1,5 @@ == snap home grid=70x17 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exi +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/wheeldrift/cwd/drift.txt Save Tty Collapse Del | 1 line 1_0123456789_abcdefghij_ZEND Wrap diff --git a/test/snapshots/winch.golden b/test/snapshots/winch.golden index a1e8afc4..c6972f79 100644 --- a/test/snapshots/winch.golden +++ b/test/snapshots/winch.golden @@ -1,5 +1,5 @@ == snap storm grid=100x31 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/winch/cwd Tty+bash Save Mode F /tmp/pardes-snap/winch/cwd Tty+bash Save Mode F | ilter Collapse Del ilter Collapse Del @@ -20,7 +20,7 @@ | ilter Collapse Del | ls == snap resized grid=106x35 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/winch/cwd Tty+bash Save Mode Filt /tmp/pardes-snap/winch/cwd Tty+bash Save Mode Filt | er Collapse Del er Collapse Del diff --git a/test/snapshots/windownav.golden b/test/snapshots/windownav.golden index 13fc7ae7..91e80e6d 100644 --- a/test/snapshots/windownav.golden +++ b/test/snapshots/windownav.golden @@ -1,5 +1,5 @@ == snap start grid=100x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/windownav/cwd/w.txt Save Tty C /tmp/pardes-snap/windownav/cwd Tty+bash Save Mo | ollapse Del de Filter Collapse Del diff --git a/test/snapshots/windowops.golden b/test/snapshots/windowops.golden index d729f179..6a48785e 100644 --- a/test/snapshots/windowops.golden +++ b/test/snapshots/windowops.golden @@ -1,5 +1,5 @@ == snap hover-v grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/windowops/cwd Tty+bash Save M╎ /tmp/pardes-snap/windowops/cwd Tty+bash Save Mo | de Filter Collapse Del ╎ de Filter Collapse Del @@ -153,7 +153,7 @@ |10: ╰────────────────────────────────────╯ |20: ls == style debug-on grid=100x31 -|0: 0-60 #b2c3b8,#1d2824, 61-65 #f5f7ee,#3c614a, 66-66 #f5f7ee,#1d2824, 67-99 #b2c3b8,#1d2824, +|0: 0-64 #b2c3b8,#1d2824, 65-69 #f5f7ee,#3c614a, 70-70 #f5f7ee,#1d2824, 71-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-2 d,#1d2824, 3-39 #b2c3b8,#1d2824, 40-41 #b2c3b8,#887455, 42-42 #b2c3b8,#314738, 43-61 #becfc4,#314738, 62-99 d,d, |2: 0-1 d,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-39 #d3b0d9,#1d2824, 40-41 #d3b0d9,#add38a, 42-42 #d3b0d9,#314738, 43-61 #becfc4,#314738, 62-62 d,d, 63-79 #b2c3b8,d, 80-98 #b2c3b8,#152019, 99-99 d,d, |3: 0-2 d,#1d2824, 3-5 #d3b0d9,#1d2824, 6-39 #b2c3b8,#1d2824, 40-42 #b2c3b8,#314738, 43-61 #becfc4,#314738, 62-62 d,d, 63-76 #b2c3b8,d, 77-98 #b2c3b8,#152019, 99-99 d,d, diff --git a/test/snapshots/wrap.golden b/test/snapshots/wrap.golden index cc834fc5..b620b2a9 100644 --- a/test/snapshots/wrap.golden +++ b/test/snapshots/wrap.golden @@ -35,7 +35,7 @@ |10: 3 third line |11: 4 == snap on-wide grid=128x15 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/wrap/cwd/long.txt Save Tty Collapse Del | 1 0---------1---------2---------3---------4---------5---------6---------7---------8---------9---------A---------B---------↩ diff --git a/test/snapshots/yankpaste.golden b/test/snapshots/yankpaste.golden index 22cc787f..e81587f8 100644 --- a/test/snapshots/yankpaste.golden +++ b/test/snapshots/yankpaste.golden @@ -1,5 +1,5 @@ == snap linewise-below grid=100x31 cursor=13,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/yankpaste/cwd/f.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/window_opacity.py b/test/window_opacity.py index a576b1bd..0253e15c 100644 --- a/test/window_opacity.py +++ b/test/window_opacity.py @@ -66,15 +66,15 @@ def run(args): help_text = output('Help') require('WindowOpacity' in help_text and 'FgOpacity' not in help_text, 'help did not replace FgOpacity with WindowOpacity') - settings = output('Config') + settings = output('DumpConfig') require('WindowOpacity: 100%\n' in settings and 'FgOpacity' not in settings, - 'initial Config opacity not applied: ' + settings) + 'initial DumpConfig opacity not applied: ' + settings) require('Wayland opacity: background-only transparent surface' in log.read_text(errors='replace'), 'background-only surface path not selected') report['renderer_path'] = 'background-only transparent surface' def wait_applied(percent): - require(wait_for(lambda: f'WindowOpacity: {percent}%\n' in output('Config')), + require(wait_for(lambda: f'WindowOpacity: {percent}%\n' in output('DumpConfig')), 'opacity did not apply: ' + str(percent)) geometry = None @@ -138,10 +138,10 @@ def run(args): wait_applied(70) require(samples() == baseline, 'opacity altered editor or terminal core RGB/text') capture(70) - settings = output('Config') + settings = output('DumpConfig') require('WindowOpacity: 70%\n' in settings, '70% opacity not applied: ' + settings) command(client, source, 'WindowOpacity 101') - require('WindowOpacity: 70%\n' in output('Config'), 'invalid opacity changed state') + require('WindowOpacity: 70%\n' in output('DumpConfig'), 'invalid opacity changed state') command(client, source, 'WindowOpacity 0') wait_applied(0) require(samples() == baseline, 'zero opacity altered editor or terminal core RGB/text') @@ -207,7 +207,7 @@ def run(args): log.read_text(errors='replace')) require(all(int(value) == 0xffffffff for value in multipliers), 'whole-window alpha modifier would fade foreground text') - require('WindowOpacity: 100%\n' in output('Config'), '100% opacity not restored') + require('WindowOpacity: 100%\n' in output('DumpConfig'), '100% opacity not restored') require(source_path.read_bytes() == original == client.read(f'/pane/{source}/body'), 'source contents changed') client.write(f'/pane/{terminal}/pty/data', b'exit\r') -- cgit v1.3 From a96c7e873d26686f0e49cf2882c1336046396d37 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 10:58:24 -0300 Subject: Pane, column and workspace tags take one set of write checks, and a refused `>` write leaves the tag as it was A column's or the workspace's tag took any length, so a write past 4096 bytes went in and a later Dump failed on it (bad dump tag), and a truncating open wiped any tag before the write after it could be refused. The column and workspace tags now refuse what a pane tag refuses: the 4096-byte limit (ENOSPC, tag: no space: over 4096 bytes) as well as the control characters they already did. A truncation of any of the three is held until the write after it is known to fit, and done with it; a refused write drops it; a close or read with no write after it does it then (so `: > tag` still clears). A test runs a truncating write too long, a control character and a bare truncation at each kind, and Dumps after. docs/fs.md says so. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 5 +++- src/fs.zig | 3 +++ src/ninep/cols.zig | 60 ++++++++++++++++++++++++++++++++++++++++++++- src/ninep/pane.zig | 72 +++++++++++++++++++++++++++++++++++++----------------- src/ninep/tree.zig | 1 + 5 files changed, 117 insertions(+), 24 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index 06fa1406..b30ae3ef 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -320,7 +320,10 @@ blank matters; `echo` would start a second line). A pane tag may hold several lines; a column or workspace tag is one, a newline written into it becoming a space. Control characters other than tab, DEL, C1 controls and non-UTF-8 bytes are refused (`invalid tag text`). The editable text is at -most 4096 bytes (`tag: no space: over 4096 bytes`, ENOSPC). A clear is an ordinary edit +most 4096 bytes (`tag: no space: over 4096 bytes`, ENOSPC). All three kinds +take the same checks, whole or not at all, and a `>` whose write is refused +changes nothing: its truncation is done with the write that fits, or at the +close (or a read) when none came. A clear is an ordinary edit and `u` in the tag undoes it. [tags.md](tags.md) covers tags on screen. ## Panes diff --git a/src/fs.zig b/src/fs.zig index 1d0bbc22..e66a6a49 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1335,6 +1335,9 @@ pub const Namespace = struct { /// 0 the workspace's, a column's its index + 1; and whether the newline /// that ended its last write is held back. header_rewrite: ?u32 = null, + /// A column's or the workspace's tag truncated, not yet done (as a + /// pane tag's `tag_trunc_pending`): its key, the workspace's 0. + header_trunc_pending: ?u32 = null, /// A look or exec a 9P write made found every pane slot taken; the /// write fails with what was said, kept at the head of `ename`. no_pane_slot: bool = false, diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index cc583c93..c049e0f3 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -7,6 +7,7 @@ const std = @import("std"); const pardes = @import("../pardes.zig"); const Pardes = pardes.Pardes; const tree = @import("tree.zig"); +const limits = @import("../memory.zig").limits; const tagline = pardes.tagline; const layout = pardes.layout; const Text = pardes.panes.Text; @@ -65,6 +66,7 @@ pub fn headerText(p: *Pardes, serial: ?u32) ?[]const u8 { } pub fn read(p: *Pardes, req: Req, serial: ?u32) Reply { + applyTruncation(p, serial); const text = headerText(p, serial) orelse return Reply.fail(req.tag, E.NOENT); const out = p.fs.stage(p.gpa); out.appendSlice(p.gpa, text) catch return Reply.fail(req.tag, E.NOMEM); @@ -78,7 +80,19 @@ pub fn read(p: *Pardes, req: Req, serial: ?u32) Reply { pub fn write(p: *Pardes, req: Req, serial: ?u32) Reply { const t = (header(p, serial) orelse return Reply.fail(req.tag, E.NOENT)).text; if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - if (pardes.ctlfs.pane.tagFault(req.data)) |why| return tree.failText(req.tag, E.INVAL, why); + const pending = p.fs.header_trunc_pending == rewriteKey(serial); + // The same checks as a pane tag's, whole or not at all; a refused + // write drops the truncation it would have come with. + if (pardes.ctlfs.pane.tagFault(req.data)) |why| { + if (pending) p.fs.header_trunc_pending = null; + return tree.failText(req.tag, E.INVAL, why); + } + const had = if (pending) 0 else headerText(p, serial).?.len; + if (req.data.len > limits.max_tag_tail -| had) { + if (pending) p.fs.header_trunc_pending = null; + return tree.failText(req.tag, E.NOSPC, pardes.ctlfs.pane.e_tag_over); + } + applyTruncation(p, serial); const was = headerText(p, serial).?; var data = req.data; const rewriting = p.fs.header_rewrite == rewriteKey(serial); @@ -99,6 +113,20 @@ pub fn write(p: *Pardes, req: Req, serial: ?u32) Reply { /// Truncating clears it, as a pane tag's `cleartag`: its default words go /// too, and `u` in it brings them back. pub fn truncate(p: *Pardes, serial: ?u32) tree.Status { + if (header(p, serial) == null) return .err; + // Done with the write after it, which may yet be refused. + p.fs.header_trunc_pending = rewriteKey(serial); + return .ok; +} + +/// A pending truncation of this header, done. +pub fn applyTruncation(p: *Pardes, serial: ?u32) void { + if (p.fs.header_trunc_pending != rewriteKey(serial)) return; + p.fs.header_trunc_pending = null; + _ = clear(p, serial); +} + +fn clear(p: *Pardes, serial: ?u32) tree.Status { const t = (header(p, serial) orelse return .err).text; const empty = p.gpa.alloc(u8, 0) catch return .err; t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null); @@ -118,6 +146,7 @@ fn rewriteKey(serial: ?u32) u32 { } pub fn released(p: *Pardes, serial: ?u32) void { + applyTruncation(p, serial); if (p.fs.header_rewrite != rewriteKey(serial)) return; p.fs.header_rewrite = null; p.fs.header_held = false; @@ -356,6 +385,35 @@ test "a focus write makes its pane's column the active one: layout says so and p } } +test "a refused write after a truncation leaves every kind of tag as it was, and Dump still works" { + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = th.serialOf(p); + const col = layout.columnSerial(p, 0); + const big = "w" ** (limits.max_tag_tail + 1); + // Each tag: a truncating open, then a write too long: nothing changes. + for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @intFromEnum(tree.TopFile.tag) }) |node| { + _ = th.wr(p, node, " Mine"); + const before = try testing.allocator.dupe(u8, th.rd(p, node, 0, 1 << 16).bytes); + defer testing.allocator.free(before); + _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = node, .truncate = true }); + const h = th.call(p, .{ .tag = 2, .op = .open, .node = node, .omode = 1 }).reply.handle; + const r = th.call(p, .{ .tag = 3, .op = .write, .node = node, .handle = h, .data = big }); + try testing.expectEqual(E.NOSPC, r.errno()); + try testing.expectEqualStrings("tag: no space: over 4096 bytes", r.reply.ename); + _ = th.call(p, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true }); + try testing.expectEqualStrings(before, th.rd(p, node, 0, 1 << 16).bytes); + // A control character is refused the same way on every kind. + try testing.expectEqual(E.INVAL, th.wr(p, node, "a\x01b").errno()); + // A truncation with no write after it clears at the close. + _ = th.call(p, .{ .tag = 5, .op = .setattr, .node = node, .truncate = true }); + const e = th.call(p, .{ .tag = 6, .op = .open, .node = node, .omode = 1 }).reply.handle; + _ = th.call(p, .{ .tag = 7, .op = .release, .node = node, .handle = e, .opened = true }); + try testing.expect(std.mem.indexOf(u8, th.rd(p, node, 0, 1 << 16).bytes, "Mine") == null); + } + try pardes.dump.dumpState(p); +} + test "a column's ctl and exec act on it as its tag would, and rmdir closes it only empty" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index af8bb52c..eb317655 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -77,6 +77,10 @@ pub const State = struct { /// whole of it is dropped and draws no empty row. tag_rewrite: bool = false, tag_held_newline: bool = false, + /// A truncation of `tag` not yet done: the write after it does it, once + /// the write is known to fit, so a refused `>` leaves the tag as it was; + /// a read or a close with no write does it then. + tag_trunc_pending: bool = false, /// The pty's size as pty/ctl's winsize last set it, until the pane's own /// grid resizes and gives the pty its size again. winsize: ?[2]u16 = null, @@ -396,6 +400,7 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply }, .body => readBody(p, req, id, pane), .tag => tag: { + applyTagTruncation(p, pane); const out = p.fs.stage(p.gpa); out.appendSlice(p.gpa, tagOf(p, pane)) catch {}; break :tag tree.stagedReply(p, req); @@ -516,7 +521,7 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply return switch (file) { .name => writeName(p, req, id, pane), .body => writeBody(p, req, id, pane), - .tag => writeTag(req, pane), + .tag => writeTag(p, req, pane), .ctl => ctl.writePane(p, req, pane), .addr, .dot, .limit => writeRange(req, pane, file), .data, .xdata => writeData(p, req, pane), @@ -630,16 +635,28 @@ pub fn tagFault(data: []const u8) ?[]const u8 { return null; } -fn writeTag(req: Req, pane: *Pane) Reply { +/// A tag write's limit, the same for a pane's, a column's and the +/// workspace's: whole or not at all. +pub const e_tag_over = std.fmt.comptimePrint("tag: no space: over {d} bytes", .{limits.max_tag_tail}); + +fn writeTag(p: *Pardes, req: Req, pane: *Pane) Reply { if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - if (tagFault(req.data)) |why| return tree.failText(req.tag, E.INVAL, why); + const pf = &pane.fs; + // A refused write after a truncation changes nothing: the truncation + // it would have come with is dropped too. + if (tagFault(req.data)) |why| { + pf.tag_trunc_pending = false; + return tree.failText(req.tag, E.INVAL, why); + } // The tag's own text grows by what is written, newlines and all: a tag // is a text like any other (acme's tag file appends the same way). - const pf = &pane.fs; - const had = tagline.curTail(pane).len; - const room = limits.max_tag_tail -| had -| @intFromBool(pf.tag_held_newline); - // Whole or not at all: a write that would pass the limit changes nothing. - if (req.data.len > room) return tree.failText(req.tag, E.NOSPC, std.fmt.comptimePrint("tag: no space: over {d} bytes", .{limits.max_tag_tail})); + const had = if (pf.tag_trunc_pending) 0 else tagline.curTail(pane).len; + const room = limits.max_tag_tail -| had -| @intFromBool(pf.tag_held_newline and !pf.tag_trunc_pending); + if (req.data.len > room) { + pf.tag_trunc_pending = false; + return tree.failText(req.tag, E.NOSPC, e_tag_over); + } + applyTagTruncation(p, pane); const take = wholeUtf8(req.data); // A truncating write drops ONE trailing newline, its whole text's: a // newline held from a write before goes in once more text follows it. @@ -656,6 +673,26 @@ fn writeTag(req: Req, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } +/// A pending truncation of the tag, done: its text cleared as `cleartag` +/// clears it, the prefix left. +pub fn applyTagTruncation(p: *Pardes, pane: *Pane) void { + const pf = &pane.fs; + if (!pf.tag_trunc_pending) return; + pf.tag_trunc_pending = false; + const empty = p.gpa.alloc(u8, 0) catch return; + // An edit like a keyboard one: `u` in the tag brings it back. + pane.tag.remember(p.gpa, if (pane.tag.own) |own| .{ .text = own } else null); + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = empty; + // what is left is the prefix; the cursor goes after it + pane.tag.cur_row = 0; + pane.tag.cur_col = if (tagline.pathPrefix(p.scratch.allocator(), pane)) |prefix| @intCast(prefix.len) else |_| 0; + pane.tag.vsel.active = false; + pane.tag.nsel = 0; + pf.tag_rewrite = true; + pf.tag_held_newline = false; +} + /// A write only text takes, to a pane with none: said, as every EINVAL is. pub const e_no_text = "invalid write: this pane has no text (a terminal, an image or a PDF)"; @@ -923,20 +960,8 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { setDot(pane, .{ .q0 = shiftOne(before.q0, q0, q1 - q0, 0), .q1 = shiftOne(before.q1, q0, q1 - q0, 0) }); pf.addr = .{ .q0 = q0, .q1 = q0 }; }, - .tag => { - const empty = p.gpa.alloc(u8, 0) catch return .err; - // An edit like a keyboard one: `u` in the tag brings it back. - pane.tag.remember(p.gpa, if (pane.tag.own) |own| .{ .text = own } else null); - if (pane.tag.own) |own| p.gpa.free(own); - pane.tag.own = empty; - // what is left is the prefix; the cursor goes after it - pane.tag.cur_row = 0; - pane.tag.cur_col = if (tagline.pathPrefix(p.scratch.allocator(), pane)) |prefix| @intCast(prefix.len) else |_| 0; - pane.tag.vsel.active = false; - pane.tag.nsel = 0; - pf.tag_rewrite = true; - pf.tag_held_newline = false; - }, + // Done with the write after it, which may yet be refused. + .tag => pf.tag_trunc_pending = true, // A shell's `>` truncates before it writes: the address written // is evaluated from where the last one left off, as with `>>`. // `0` (or `,`) is how to start over. See State.addr. @@ -1397,12 +1422,15 @@ test "truncating the tag clears its editable tail" { try testing.expect(tagline.curTail(pane).len > 0); const cleared = call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true }); try testing.expectEqual(Status.ok, cleared.reply.status); + // Done at the first read or write after it (or the close). + _ = rd(p, tag, 0, 4096); try testing.expectEqualStrings("", pane.tag.own.?); try testing.expect(std.mem.indexOf(u8, rd(p, tag, 0, 4096).bytes, " Mine") == null); // The tag keeps its undo: undoing in it brings back what was cleared. pardes.edit.doUndo(p, &pane.tag); try testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Mine")); _ = call(p, .{ .tag = 2, .op = .setattr, .node = tag, .truncate = true }); + _ = rd(p, tag, 0, 4096); try testing.expectEqualStrings("", pane.tag.own.?); // Written back without a leading space, the text still stands apart diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 5f3ffc9c..d39854e1 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -935,6 +935,7 @@ fn releaseHandle(p: *Pardes, req: Req) void { // A truncating write to `tag` is over when its open goes (pane.zig // writeTag): a newline it held back is dropped. if (t == .pane and t.pane.file == .tag) if (p.paneBySerial(t.pane.serial)) |id| { + pane.applyTagTruncation(p, p.panes[id].?); p.panes[id].?.fs.tag_rewrite = false; p.panes[id].?.fs.tag_held_newline = false; }; -- cgit v1.3 From 5e8d2b7ac7d7880ac36ec45484b2711669ac7ae1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 11:30:18 -0300 Subject: A failure naming a long path keeps its reason, and name refuses a component over 255 bytes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Save of a 3000-byte path failed with the record "err 2 ctl: Save…", which lost the reason. The first cause was reportError, which formatted into 256 bytes, so the operation's path filled the buffer before the reason was written. The second was the waiting write's late failure, which took the first 256 bytes of the message row, never its end. Now reportError has room for the longest path. reportFailure also keeps the words fitted as an err is (fitErr: the path gives up its middle, the reason stays), and the late failure of a Save, a Dump, a shell or a ThemeFile takes those words. fs.md already said a name holds up to 255 bytes a component, but a longer one was taken and only failed later at Save. Now it is refused when written. Co-Authored-By: Claude Opus 5.5 --- src/Messages.zig | 10 +++++++++- src/fs.zig | 6 ++++++ src/ninep/pane.zig | 23 +++++++++++++++++++++++ src/pardes.zig | 22 ++++++++-------------- 4 files changed, 46 insertions(+), 15 deletions(-) (limited to 'src/fs.zig') diff --git a/src/Messages.zig b/src/Messages.zig index d1478ac7..3eeb8c92 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -463,7 +463,10 @@ pub fn dialReason(err: anyerror) ?[]const u8 { } pub fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) void { - var buf: [256]u8 = undefined; + // Room for an operation naming the longest path and the reason after + // it: a shorter one cut the reason off (`Save /long…`), and the reason + // is what a failure is for. Where it must be shorter, the path gives. + var buf: [@max(256, limits.host_path_cap + 128)]u8 = undefined; var w = std.Io.Writer.fixed(&buf); w.print("{s}: ", .{operation}) catch {}; // A peer out of reach says so, not the error's name (`dial`). @@ -503,6 +506,11 @@ pub fn clip(text: []const u8, max: usize) []const u8 { /// reportError with the words already chosen. pub fn reportFailure(p: *Pardes, id: usize, text: []const u8) void { p.fs.failures +%= 1; + var fitted: @TypeOf(p.fs.said) = undefined; + const said = pardes.ctlfs.fitErr(text, &fitted); + @memcpy(p.fs.said[0..said.len], said); + p.fs.said_len = @intCast(said.len); + p.fs.said_at = p.fs.failures; // A builtin a ctl write runs: its first error is also the write's, its // path shortened in the middle if it must be, never its reason. const failing_write = p.fs.no_prompt or p.fs.capturing or p.fs.write_waits; diff --git a/src/fs.zig b/src/fs.zig index e66a6a49..30ad9c43 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1343,6 +1343,12 @@ pub const Namespace = struct { no_pane_slot: bool = false, no_pane_slot_len: u16 = 0, header_held: bool = false, + /// The newest failure said (reportFailure), fitted as an err is: its + /// path cut in the middle, never its reason, which the message row's + /// first 256 bytes lose. `said_at` is the `failures` count it was. + said: [256]u8 = undefined, + said_len: u16 = 0, + said_at: u32 = 0, late_failure: [256]u8 = undefined, late_failure_len: u16 = 0, /// A 9P write asked a language server something: the answer count it diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 30530c3b..de7f7cd4 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -845,6 +845,9 @@ fn nameFault(name: []const u8) ?[]const u8 { } if (name[0] == ' ') return e_name_char ++ ": a blank at its start"; if (name[name.len - 1] == ' ') return e_name_char ++ ": a blank at its end"; + // No file system takes a longer one (NAME_MAX): a Save would only fail. + var parts = std.mem.splitScalar(u8, name, '/'); + while (parts.next()) |part| if (part.len > 255) return "invalid file name: a component over 255 bytes"; return null; } @@ -1364,6 +1367,26 @@ test "a write of two lines to name is refused EINVAL, on a held open or not" { try testing.expectEqualStrings("/tmp/pardes-a", nameOf(p, p.panes[p.paneBySerial(serial).?].?)); } +test "a name with a component over 255 bytes is refused, and a long path's failed Save keeps its reason" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const refused = wr(p, Node.of(serial, .name), "/tmp/" ++ "c" ** 256 ++ "/f.txt\n"); + try testing.expectEqual(E.INVAL, refused.errno()); + try testing.expectEqualStrings("invalid file name: a component over 255 bytes", refused.reply.ename); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/" ++ "c" ** 255 ++ "\n").reply.status); + // A Save of a 3000-byte path the host refuses: the waiting write's + // reason is at the end, the path giving up its middle. + const long = "/nonexistent-pardes-root/" ++ ("d" ** 200 ++ "/") ** 15 ++ "f.txt"; + const id = p.paneBySerial(serial).?; + try nameBuffer(p, id, long, false); + p.fs.late_failure_len = 0; + p.saveFailed(@intCast(id), long, error.AccessDenied); + const late = p.fs.late_failure[0..p.fs.late_failure_len]; + try testing.expect(std.mem.startsWith(u8, late, "Save /nonexistent-pardes-root/")); + try testing.expect(std.mem.endsWith(u8, late, "/f.txt: no such directory")); +} + test "a name cut across writes is one name, applied once at its newline or its close" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/pardes.zig b/src/pardes.zig index ef713e0c..7fddf19f 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5341,10 +5341,7 @@ pub const Pardes = struct { } // A 9P write that asked for the shell (pty/ctl's exec), waiting on // it, fails with what was said, as a failed Save's does. - const said = pane.msg[0..pane.msg_len]; - const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len); - @memcpy(p.fs.late_failure[0..kept.len], kept); - p.fs.late_failure_len = @intCast(kept.len); + p.noteLateFailure(id); } pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { @@ -5362,10 +5359,7 @@ pub const Pardes = struct { p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: no such directory", .{path}) catch "Save: no such directory") else p.reportError(id, std.fmt.bufPrint(&what, "Save {s}", .{path}) catch "Save", err); - const said = if (p.panes[id]) |pane| pane.msg[0..pane.msg_len] else "Save failed"; - const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len); - @memcpy(p.fs.late_failure[0..kept.len], kept); - p.fs.late_failure_len = @intCast(kept.len); + p.noteLateFailure(id); } /// A Dump the host could not write: said on the message row and in the @@ -5388,10 +5382,7 @@ pub const Pardes = struct { } else p.reportError(p.active, operation, err); // In the words the message row has, so the write's err is the one // record of it (its msg goes: 9p_io, dropMessage). - const said = if (p.panes[p.active]) |pane| pane.msg[0..pane.msg_len] else "Dump failed"; - const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len); - @memcpy(p.fs.late_failure[0..kept.len], kept); - p.fs.late_failure_len = @intCast(kept.len); + p.noteLateFailure(p.active); } /// The path a watch is about: a real file's, or a PDF's. @@ -6460,8 +6451,11 @@ pub const Pardes = struct { /// What was said of a failure just now on pane `id` is also the waiting /// 9P write's (9p_io, `fs.late_failure`). pub fn noteLateFailure(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const said = pane.msg[0..pane.msg_len]; + // Said by reportFailure just now: its words fitted whole, the + // reason kept; else what the message row has. + const said = if (p.fs.said_at == p.fs.failures and p.fs.said_len > 0) + p.fs.said[0..p.fs.said_len] + else if (p.panes[id]) |pane| pane.msg[0..pane.msg_len] else return; const kept = @import("Messages.zig").clip(said, p.fs.late_failure.len); @memcpy(p.fs.late_failure[0..kept.len], kept); p.fs.late_failure_len = @intCast(kept.len); -- cgit v1.3 From 12c257e624d3f1f80ca3df041b54026ff772d638 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 14:53:46 -0300 Subject: A path typed with a leading ~ is the home directory, at every entry point that takes one, through one helper Only DumpDir (dump.zig) and ShaderBuild expanded `~/`, each its own way. So a look at `~/notes.txt`, `name ~/x`, `Save ~/x`, ThemeFile, Restore and a quoted `pardes '~/x'` all took `~` as a directory of that name under the pane's. There is now one rule, filesystem.expandHome. A leading `~`, alone or before `/` or `:`, is $HOME, else the passwd entry's home; `~user` is that user's (getpwnam). As in a shell, it applies even beside a file named `~`, and `./~` names that file. Every entry point runs its typed path through it: - look, B3 and 9P, before any parsing, so `~/x:12`, `~/x:12:3` and `~/x:/re/` all work; - name, and a tag's rename; - Save ; - ThemeFile, DumpDir, Restore and ShaderBuild's shader files; - the forwarding launch. Recent rows are not shown with `~` and need nothing. How names are shown is unchanged. Tests: expandHome's cases, and HOME unset (passwd), with HOME passed in rather than set, since setenv moves the environ a spawned child reads. fs.py covers Save into missing directories under `~`, `name ~/x`, a look at `~/x:3`, and a forwarded `pardes '~/x'`. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 6 +++++- src/ShaderBuild.zig | 8 +++----- src/builtins.zig | 3 ++- src/dump.zig | 7 ++----- src/exec.zig | 3 ++- src/fs.zig | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++- src/look.zig | 5 ++++- src/main.zig | 7 +++++-- src/ninep/pane.zig | 3 ++- src/tagline.zig | 3 ++- test/fs.py | 22 +++++++++++++++++++++ 11 files changed, 105 insertions(+), 19 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index b37511dd..146ff17b 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -199,7 +199,11 @@ A line written to `look` is a right click on it: selects line 12, newline included; `file:12:5` puts the caret at line 12, byte column 5; `file:` takes any address (below), **evaluated from the file's dot**: `file:/re/` finds the next match after the selection, - `file:0/re/` the first. `:addr` addresses the pane itself. + `file:0/re/` the first. `:addr` addresses the pane itself. A leading `~` + is the home directory ($HOME, else the passwd entry's; `~user` that + user's) here and wherever a path is typed (`name`, `Save`, `ThemeFile`, + `DumpDir`, `Restore`, `pardes '~/x'`), even beside a file named `~`: write + `./~` for that. - `@p:` addresses a pane by serial, a terminal's logical lines too. - a directory types `ls` into a terminal idle there, else opens one there. diff --git a/src/ShaderBuild.zig b/src/ShaderBuild.zig index c2610fd7..b50999a5 100644 --- a/src/ShaderBuild.zig +++ b/src/ShaderBuild.zig @@ -236,11 +236,9 @@ fn collect(b: *Build, gpa: std.mem.Allocator, core: *pardes.Pardes, job: *Job) v } } -/// `~/` is the home directory. -fn expand(buf: []u8, path: []const u8) []const u8 { - if (!std.mem.startsWith(u8, path, "~/")) return path; - const home = libc.getenv("HOME") orelse return path; - return std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.span(home), path[2..] }) catch path; +/// `~` is the home directory (the one rule, filesystem.expandHome). +fn expand(buf: *[4096]u8, path: []const u8) []const u8 { + return pardes.filesystem.expandHome(path, buf); } /// The compile thread: each file behind the prefix, through glslc with the diff --git a/src/builtins.zig b/src/builtins.zig index ba67766d..6aabba8d 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -818,7 +818,8 @@ pub const ThemeFile = struct { pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime !enabled) unreachable; - const arg = std.mem.trim(u8, c.arg orelse return, " \t\r\n"); + var home_buf: [4096]u8 = undefined; + const arg = pardes.filesystem.expandHome(std.mem.trim(u8, c.arg orelse return, " \t\r\n"), &home_buf); // Said with why, not "invalid theme path". if (!std.mem.endsWith(u8, arg, ".zon")) { var said: [320]u8 = undefined; diff --git a/src/dump.zig b/src/dump.zig index 1cc115be..8e767240 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -100,13 +100,10 @@ fn hostEnv(name: [*:0]const u8) ?[*:0]u8 { /// setting when set (a leading `~/` is the home directory), else the default. pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { if (dir_setting.len == 0) return defaultDirectory(buf); - var joined: [2048]u8 = undefined; + var joined: [4096]u8 = undefined; // `~/x`, else a relative one from the directory pardes started in: the // same place however it was written, and shown so. - const raw = if (std.mem.startsWith(u8, dir_setting, "~/")) (if (hostEnv("HOME")) |h| - std.fmt.bufPrint(&joined, "{s}/{s}", .{ std.mem.span(h), dir_setting[2..] }) catch return null - else - dir_setting) else dir_setting; + const raw = pardes.filesystem.expandHome(dir_setting, &joined); var fba_buf: [4096]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&fba_buf); var cwd_buf: [1024]u8 = undefined; diff --git a/src/exec.zig b/src/exec.zig index 7d682d74..d114dbf8 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -295,9 +295,10 @@ pub fn saveTo(p: *Pardes, id: usize, path: []const u8) void { if (path.len == 0 or path[path.len - 1] == '/' or std.mem.indexOfScalar(u8, path, '\n') != null) return p.reportError(id, "save", error.NoFilename); + var home_buf: [4096]u8 = undefined; const full = std.fs.path.resolvePosix( p.scratch.allocator(), - &.{ Pardes.paneDir(pane), path }, + &.{ Pardes.paneDir(pane), @import("fs.zig").expandHome(path, &home_buf) }, ) catch return; if (!std.fs.path.isAbsolute(full)) return p.reportError(id, "save", error.NoDirectory); if (full.len > Pardes.SavePath.cap) return p.reportError(id, "save", error.PathTooLong); diff --git a/src/fs.zig b/src/fs.zig index 30ad9c43..7695d497 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -732,6 +732,59 @@ pub fn dotRelative(word: []const u8) bool { /// 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 (comptime !pardes.hosted) return path; + 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; @@ -1171,7 +1224,9 @@ pub fn readFile(gpa: std.mem.Allocator, path: []const u8) ![]u8 { /// Restore first tries a relative argument under the default dump directory, /// then preserves the ordinary file lookup. Absolute paths remain verbatim. -pub fn readRestore(gpa: std.mem.Allocator, path: []const u8, dir_setting: []const u8) ![]u8 { +pub fn readRestore(gpa: std.mem.Allocator, typed: []const u8, dir_setting: []const u8) ![]u8 { + var home_buf: [4096]u8 = undefined; + const path = expandHome(typed, &home_buf); var dir_buf: [4096]u8 = undefined; const dir = @import("dump.zig").directory(&dir_buf, dir_setting); return readRestoreIn(gpa, path, dir); diff --git a/src/look.zig b/src/look.zig index de51804d..357a9c63 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1499,8 +1499,11 @@ fn isRecentList(pane: *const Pane) bool { return std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Recent }) or std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Jumplist }); } -pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { +pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const pane = p.panes[id] orelse return; + // `~/x`, `~/x:12`, `~/x:/re/`: home, before anything reads the text. + var home_buf: [4096]u8 = undefined; + const operand = filesystem.expandHome(std.mem.trim(u8, operand_raw, " \t\r\n"), &home_buf); // A +Recent row is a remembered place: reopened and clamped to the file // as it is now, never a miss for a line the file no longer has. if (isRecentList(pane)) { diff --git a/src/main.zig b/src/main.zig index 576efc8e..dfeed52d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -407,7 +407,7 @@ fn nativeMain(init: std.process.Init) !void { // itself, which is what a right click in that pane would have been. var look_buf: [64]u8 = undefined; const look = try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); - const word = positional orelse { + const typed_word = positional orelse { var tag_buf: [64]u8 = undefined; const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch |err| Refuse.with(init.io, tag, err); @@ -415,7 +415,10 @@ fn nativeMain(init: std.process.Init) !void { try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); std.process.exit(1); }; - if (std.mem.indexOfAny(u8, word, "\r\n") != null) Refuse.with(init.io, "a file name", error.NotOneLine); + if (std.mem.indexOfAny(u8, typed_word, "\r\n") != null) Refuse.with(init.io, "a file name", error.NotOneLine); + // `pardes '~/x'`, quoted so the shell left it: home, as a look's. + var home_buf: [4096]u8 = undefined; + const word = pardes.filesystem.expandHome(typed_word, &home_buf); const target = @import("look.zig").parsePathLine(word); var realbuf: [4096]u8 = undefined; var newbuf: [4096]u8 = undefined; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index dc8b4b10..7526075b 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -860,7 +860,8 @@ fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { "rename not allowed: a terminal is named by its shell's directory; cd there, or Tty in another" else "rename not allowed: an image or PDF is named by the file it shows"); - const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ pardes.Pardes.paneDir(pane), name }) catch + var home_buf: [4096]u8 = undefined; + const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ pardes.Pardes.paneDir(pane), fs.expandHome(name, &home_buf) }) catch return Reply.fail(req.tag, E.NOMEM); if (!std.fs.path.isAbsolute(full) or full.len >= 4096) return tree.failText(req.tag, E.INVAL, "invalid file name: longer than a path may be"); nameBuffer(p, id, full, false) catch |err| return Reply.fail(req.tag, switch (err) { diff --git a/src/tagline.zig b/src/tagline.zig index 1923871a..dc7d10d4 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -344,7 +344,8 @@ pub fn commitTagName(p: *Pardes, pane: *Pane) bool { p.reportError(id, "name", error.InvalidName); return false; }; - const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(pane), name }) catch |err| { + var home_buf: [4096]u8 = undefined; + const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(pane), pardes.filesystem.expandHome(name, &home_buf) }) catch |err| { p.reportError(id, "name", err); return false; }; diff --git a/test/fs.py b/test/fs.py index b02b9e45..55ec3257 100644 --- a/test/fs.py +++ b/test/fs.py @@ -383,6 +383,19 @@ def discovery(binary, embedded=False): client.remove(f'/pane/{scratch}') # A Save makes the directories its file goes in, whatever names # it: the pane's own name or Save's path. + # `~` is home (this session's HOME, the test's root) wherever a + # path is typed: Save, name, a look, with an address or not. + tilde = new_pane(client, b'one\ntwo\nthree\n') + client.write(f'/pane/{tilde}/ctl', b'Save ~/tilde-made/sub/x.txt\n') + assert (root / 'tilde-made/sub/x.txt').read_bytes() == b'one\ntwo\nthree\n' + client.write(f'/pane/{tilde}/name', b'~/tilde-named.txt\n') + assert client.read(f'/pane/{tilde}/name') == f'{root}/tilde-named.txt\n'.encode() + client.remove(f'/pane/{tilde}') + client.write('/look', b'~/tilde-made/sub/x.txt:3\n') + looked = [row for row in client.read('/index').decode().splitlines() if row.split()[3] == f'{root}/tilde-made/sub/x.txt'] + assert len(looked) == 1, client.read('/index') + assert client.read(f'/pane/{looked[0].split()[0]}/addr').startswith(b'8 '), client.read(f'/pane/{looked[0].split()[0]}/addr') + client.remove(f'/pane/{looked[0].split()[0]}') made_dirs = new_pane(client, b'deep\n') client.write(f'/pane/{made_dirs}/ctl', f'Save {root}/save-made/a/b/x.txt\n'.encode()) assert (root / 'save-made/a/b/x.txt').read_bytes() == b'deep\n' @@ -1333,6 +1346,15 @@ def test(binary, quic=False): execute(client, named, 'Save') client.remove(f'/pane/{named}') assert deep.read_bytes() == b'deep\n' + # `pardes '~/x'`, quoted so the shell left the `~`: home all the + # same: the launching shell's HOME. + before = serials() + quoted = subprocess.run([binary, '~/fwd-tilde.txt'], cwd=root, env=dict(env, HOME=str(root)), + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=10) + assert quoted.returncode == 0, quoted.stderr + assert f'{root}/fwd-tilde.txt'.encode() in client.read('/index'), client.read('/index') + for serial in serials() - before: + client.remove(f'/pane/{serial}') # A name the session refuses: its reason and exit 1, as B's, # never a nested editor, and no pane left for it. before = serials() -- cgit v1.3 From d1955996ce192df9e2dc4e150f204d6af53179e3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 17:17:29 -0300 Subject: A Restore logs and names the whole path of the dump it reads, not the name as typed `Restore x.dump.zon` read the DumpDir's x.dump.zon but logged `restore x.dump.zon`, and `~/d.zon` logged the tilde. A follower could not tell which file was restored. The builtin now resolves the name once (fs.restorePath: `~` expanded, a relative name the DumpDir's when one is there, else the current directory's) and hands that path to the host, which reads it and logs `restore `. Its messages name it too. Co-Authored-By: Claude Opus 5.5 --- src/builtins.zig | 6 +++++- src/fs.zig | 22 ++++++++++++++++++++++ src/ninep/ctl.zig | 16 ++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) (limited to 'src/fs.zig') diff --git a/src/builtins.zig b/src/builtins.zig index 6aabba8d..6688d05f 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -666,7 +666,11 @@ pub const Restore = struct { pub const scope: Scope = .session; pub const takes_arg = true; pub fn run(c: Ctx) void { - const path = c.arg orelse (c.p.last_dump orelse return c.p.reportFailure(c.id, "Restore: no dump yet; name one")); + const typed = c.arg orelse (c.p.last_dump orelse return c.p.reportFailure(c.id, "Restore: no dump yet; name one")); + // The file it reads, whole (`~`, the DumpDir, the directory it runs + // in): what the log's `restore` record and every message name. + var full_buf: [4096]u8 = undefined; + const path = if (comptime pardes.hosted) @import("fs.zig").restorePath(typed, c.p.settings.dump_dir.get(), &full_buf) else typed; if (path.len > c.p.restore_buf.len) return c.p.reportFailure(c.id, "Restore: that name is too long"); // A dump that cannot be read is said now, and fails a ctl write: the // host reads it only after this step, where nobody hears. First, diff --git a/src/fs.zig b/src/fs.zig index 7695d497..bc35e1cb 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1232,6 +1232,28 @@ pub fn readRestore(gpa: std.mem.Allocator, typed: []const u8, dir_setting: []con return readRestoreIn(gpa, path, dir); } +/// The file a Restore of `typed` reads, whole: `~` expanded, a relative name +/// the DumpDir's when one is there, else the current directory's. What the +/// log and the message say, not the name as typed. `typed` itself (home +/// expanded) when nothing resolves: the read then says why. +pub fn restorePath(typed: []const u8, dir_setting: []const u8, out: *[4096]u8) []const u8 { + var home_buf: [4096]u8 = undefined; + const path = expandHome(typed, &home_buf); + if (!std.fs.path.isAbsolute(path)) { + var dir_buf: [4096]u8 = undefined; + if (@import("dump.zig").directory(&dir_buf, dir_setting)) |base| { + var buf: [4096]u8 = undefined; + if (std.fmt.bufPrint(&buf, "{s}/{s}", .{ base, path })) |candidate| { + if (resolveOs(candidate, out)) |r| if (!r.dir) return r.path; + } else |_| {} + } + } + if (resolveOs(path, out)) |r| return r.path; + const n = @min(path.len, out.len); + @memcpy(out[0..n], path[0..n]); + return out[0..n]; +} + fn readRestoreIn(gpa: std.mem.Allocator, path: []const u8, dir: ?[]const u8) ![]u8 { if (!std.fs.path.isAbsolute(path)) { if (dir) |base| { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index aebd07e2..fdc83da8 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2589,6 +2589,22 @@ test "a focus moved over 9P tells the programs that asked for focus reports, as try testing.expectEqualStrings("\x1b[O\x1b[I", moved.pty_buf[0..moved.pty_len]); } +test "a Restore of a name in the DumpDir asks for, and logs, the whole path it reads" { + if (comptime !pardes.hosted) return error.SkipZigTest; + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + try pardes.dump.dumpState(p); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "x.dump.zon", .data = p.dump_out.? }); + var buf: [4096]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + try testing.expect(p.settings.dump_dir.set(dir)); + try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "Restore x.dump.zon\n").reply.status); + var want: [4200]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x.dump.zon", .{dir}), p.restore_req.?); +} + test "a line starting with # runs as nothing at an exec or a ctl, silently" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); -- cgit v1.3 From f8710ab27b54bf0241ad2ed629ccc98aaa619709 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 21:40:57 -0300 Subject: Edit's w and the other left-out sam commands fail EIO in words, never EOPNOTSUPP, and /os refuses a rename or a chmod as not permitted, EACCES "w is not supported in pardes" read through a mount as EOPNOTSUPP, as if the file system lacked an operation, and a chmod under /os was answered "invalid truncate", EINVAL. An Edit command pardes leaves out now says so in words 9ns reads as EIO, and a rename or mode change of an /os file is "permission denied", EACCES. fs.md's Failure section and /os entry say both. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 8 +++++--- src/fs.zig | 29 +++++++++++++++++++++++++++++ src/ninep/ctl.zig | 1 + src/sam_edit.zig | 6 +++--- 4 files changed, 38 insertions(+), 6 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/fs.md b/docs/fs.md index c01587a1..15f490ec 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -139,8 +139,9 @@ never a C library string. Through 9ns the kernel sees an errno 9ns reads from those words (cloud9 `9ns/src/nine.zig`, `enameToErrno`): `control message`, `invalid` or `bad ` is EINVAL (malformed input); `no such`, `not found` ENOENT; `in use` EBUSY; `no space` ENOSPC; `denied` EACCES; anything -else, such as `no match for regexp`, `address out of range` or `Modified`, -EIO. The `err` record has the words; a shell sees +else, such as `no match for regexp`, `address out of range`, `Modified` or +an `Edit` command pardes leaves out (`w`, `e`, `r`, `|`: `w is a sam command +pardes's Edit leaves out`), EIO; no refusal reads as EOPNOTSUPP. The `err` record has the words; a shell sees only the errno, most often `Invalid argument` or `Input/output error`. Not failures: a look that finds nothing (it answers nothing and logs one @@ -708,7 +709,8 @@ become spaces. one at its last (a PDF's is its page); a look at a row reopens it there. - `/status`: `pid`, `version`, `panes`. - `/os/`: existing regular files take read, write and truncation to zero; - create, remove, rename and metadata changes are refused; ownership is + create, remove, rename and mode changes are refused as not permitted + (`permission denied`, EACCES through a mount); ownership is synthetic. Linux v9fs's truncation `mtime` hint is accepted and dropped. - `/src/` (and `/shaders` on GUI builds) with `-Dembed-sources=true`; `EffectCode ` lists an effect's files under `/virtual`. diff --git a/src/fs.zig b/src/fs.zig index bc35e1cb..d13e36bd 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -213,6 +213,11 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; }, .read, .write, .setattr => { + // A rename or a mode change (`mv`, `chmod`) is refused as not + // permitted, EACCES through a mount: /os reads and writes the + // files it shows and changes nothing about them. + if (req.op == .setattr and (req.set.name or req.set.mode)) + return tree.failText(req.tag, E.PERM, "permission denied: /os renames nothing and changes no mode"); if (stat.kind != .file) return Reply.fail(req.tag, E.PERM); var z: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return Reply.fail(req.tag, E.NOENT); @@ -255,6 +260,30 @@ 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" { + if (comptime !pardes.hosted) return error.SkipZigTest; + 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 = .{}; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 5a199f55..6e09084b 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1854,6 +1854,7 @@ test "an error's words give the errno a mount reads: EINVAL for what is malforme .{ .text = addressing.e_order, .malformed = false }, .{ .text = addressing.e_slow, .malformed = false }, .{ .text = "/tmp/x.txt: Modified (Exit again to discard)", .malformed = false }, + .{ .text = "Edit: w is a sam command pardes's Edit leaves out (it has no file or shell commands)", .malformed = false }, }) |c| { const says_einval = for (einval) |w| { if (std.ascii.findIgnoreCase(c.text, w) != null) break true; diff --git a/src/sam_edit.zig b/src/sam_edit.zig index 94cf6fe0..9b055ef9 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -242,7 +242,7 @@ const Parser = struct { } }, '\'' => return fail(ps.why, "can't handle '", .{}), - '"' => return fail(ps.why, "file addresses are not supported", .{}), + '"' => return fail(ps.why, "a file address is no address pardes's Edit takes", .{}), else => break, } } @@ -410,7 +410,7 @@ const Parser = struct { if (nest == 0) return fail(ps.why, "right brace with no left brace", .{}); return null; }, - 'b', 'B', 'D', 'e', 'r', 'w', 'f', 'X', 'Y', '<', '|', '>' => return fail(ps.why, "{c} is not supported in pardes", .{c}), + 'b', 'B', 'D', 'e', 'r', 'w', 'f', 'X', 'Y', '<', '|', '>' => return fail(ps.why, "{c} is a sam command pardes's Edit leaves out (it has no file or shell commands)", .{c}), else => return fail(ps.why, "unknown command {c}", .{c}), } return cmd; @@ -768,7 +768,7 @@ test "an Edit that fails halfway changes nothing, and says why in acme's words" .{ "}", "right brace with no left brace" }, .{ ",x/foo/{", "unmatched `{'" }, .{ ",x/foo/{\nd", "unmatched `{'" }, - .{ "w /tmp/x", "w is not supported in pardes" }, + .{ "w /tmp/x", "w is a sam command pardes's Edit leaves out (it has no file or shell commands)" }, .{ ",s/(a)/\\1/", "no \\1: mvzr keeps no submatches" }, .{ "1 m 1,2", "move overlaps itself" }, .{ ",x/(^|\\n)foo/d", "bad regular expression: in a pattern with \\n, ^ can only come first and $ only just before a \\n" }, -- cgit v1.3 From 4f65855f372186406f4e48708ec3d5eb9aceb6d3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 22:51:17 -0300 Subject: log stats 0, and pardes re-pins cloud9 whose 9ns opens such a file direct and nonseekable: fs.md's follow recipe with cat works through a mount The log stated the length an open would freeze, a length a mount's kernel could take as its end, and a splicing cat read it from the kernel's offset. log now stats 0, as the other streams and generated views do, and the re-pinned cloud9's 9ns opens any file stating 0 FOPEN_DIRECT_IO | FOPEN_NONSEEKABLE. A look at such a file (the mounted index) reads a regular file that will not seek as a stream rather than refusing it as a pipe. selfmount runs the recipe, exec 3<>log; echo follow >&3; cat <&3, through the mount and hears a record made after it started. Co-Authored-By: Claude Opus 5.5 --- build.zig.zon | 4 ++-- src/fs.zig | 8 +++++++- src/ninep/events.zig | 12 ------------ src/ninep/tree.zig | 12 +++++++++++- test/selfmount.py | 10 ++++++++++ 5 files changed, 30 insertions(+), 16 deletions(-) (limited to 'src/fs.zig') diff --git a/build.zig.zon b/build.zig.zon index 4df012bc..106ef085 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,8 +9,8 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#705be665742fa0332585a4321640b5e2245610cb", - .hash = "cloud9-0.1.0-yt86qt8NHgDuS2WNp0TgW03h-eVIgWmkznn0t0nMQKbr", + .url = "git+https://git.sr.ht/~gbrls/cloud9#a03d1649108510cda5951e918e561d7cae43d6b0", + .hash = "cloud9-0.1.0-yt86qiISHgBgvO5D4UOz0pZnWrLmL337v38Z8ROAeLG0", }, // Pinned to the exact libvaxis commit ghostty is built against, so it // is compatible with ghostty's uucode configuration (the one we share diff --git a/src/fs.zig b/src/fs.zig index d13e36bd..91edd429 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1360,7 +1360,13 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { defer _ = libc.close(fd); const end = libc.lseek(fd, 0, libc.SEEK.END); - if (end < 0 and libc.errno(end) == .SPIPE) return error.NotAFile; + // Not seekable: a pipe or a FIFO is no file; a regular file that is a + // stream (a 9ns mount's log or screen, opened nonseekable) is read to + // its end, as one with no length is. + if (end < 0 and libc.errno(end) == .SPIPE) { + const facts = ninep_io.statNoFollow(path_z) orelse return error.NotAFile; + if (facts.mode & 0o170000 != 0o100000) return error.NotAFile; + } const size: usize = if (end < 0) 0 else @intCast(end); if (end >= 0 and libc.lseek(fd, 0, libc.SEEK.SET) < 0) return error.ReadFailed; if (size == 0) { diff --git a/src/ninep/events.zig b/src/ninep/events.zig index bacf3ad6..9752e287 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -494,18 +494,6 @@ pub fn writeLog(p: *Pardes, req: Req) Reply { return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } -/// The length a stat reports: the text an open would freeze now. -pub fn logLen(q: *const Queue) u64 { - var n: u64 = 0; - var at = q.head; - while (at + 4 <= q.buf.items.len) { - const len = std.mem.readInt(u32, q.buf.items[at..][0..4], .little); - n += len; - at += 4 + len; - } - return n; -} - // ---- per-pane event records ---- pub const max_record_text = 256; diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index be03e8f0..8c536c51 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -646,7 +646,9 @@ fn topSize(p: *Pardes, f: TopFile) u64 { .README => fs.help.len, .status => ctl.statusLen(p), .look, .exec, .tagexec => ctl.resultsLen(p), - .log => events.logLen(&p.fs.log), + // A stream: a length would read as its end to a kernel that caches + // one (a 9ns mount's splice), and a follower's reads go past it. + .log => 0, .ctl => ctl.rootLen(p), .commands => ctl.commandsLen(), .focus => focus: { @@ -1335,6 +1337,14 @@ test "filesystem inspection preserves pending and displayed Look hover" { try testing.expect(!p.raw_hover_intent); } +test "log stats 0 however much it holds, a stream as acme's generated files are" { + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + _ = th.wr(p, Node.of(th.serialOf(p), .exec), "Msg a record for the log\n"); + try testing.expect(th.logHas(p, "a record for the log")); + try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.log) }).reply.attr.size); +} + test "filesystem pane creation and truncation cancel Look hover" { const requests = [_]Req{ // Opening `new` is what makes a pane now; walking to it makes none, diff --git a/test/selfmount.py b/test/selfmount.py index 86c32fa8..dd59083c 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -176,6 +176,16 @@ def run(binary): held = run(f"for i in $(seq 40); do cat {mount}/pane/{first}/event > /dev/null & done; " f"sleep 1; timeout 10 cat {mount}/layout > /dev/null; st=$?; kill $(jobs -p); exit $st\n".encode()) check(held == '0', f'cat layout answers beside 40 held event reads ({held!r})') + # fs.md's follow recipe, as written, with plain cat, its output + # a pipe (where coreutils cat splices): it hears a record made + # after it started. + recipe = Path(f'/tmp/{name}.follow') + ran = run(f"exec 3<>{mount}/log; echo follow >&3; " + f"(sleep 1; echo 'Msg recipe-heard' > {mount}/exec) & " + f"timeout 5 cat <&3 | cat > {recipe}; exit 0\n".encode()) + followed = recipe.read_text() if recipe.exists() else '' + recipe.unlink(missing_ok=True) + check(ran == '0' and 'recipe-heard' in followed, f'the log follow recipe with cat hears a new record ({followed[-120:]!r})') client.write('/exec', b'Msg still here\n') text = ''.join(cell[0] for cell in client.screen()['cells']) check('still here' in text, 'the editor answers after all of that') -- cgit v1.3 From 422ad65025edd994b04728632fc96de4ebda07f7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 03:04:35 -0300 Subject: A log follower hears every record queued before a Restore: the read it holds takes all that fit, before the hangup cuts it A follower reads one record per read, and a Restore hangs every client up, so records queued just before it -- the ones a script most wants, what led up to the Restore -- were lost: the read after the first was cut. Before the cut, each held read of /log is answered with every whole record queued that fits it. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 27 +++++++++++++++++++++++++++ src/fs.zig | 3 +++ src/ninep/events.zig | 13 ++++++++++++- 3 files changed, 42 insertions(+), 1 deletion(-) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index d80d7b30..b11a4997 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -566,6 +566,12 @@ pub const Listener = struct { /// answer nothing, their connections being hung up. The connections pay their releases on their own tasks, so /// the editor rests while they do. pub fn reset(l: *Listener, replacement: *pardes.Pardes) void { + // A follower of the log hears every record queued before the cut, in + // the answer to the read it holds; the read after it is cut. + l.core.fs.hanging_up = true; + l.core.fs.news = true; + answerHeld(l); + l.core.fs.hanging_up = false; for (0..quic_slots) |i| l.drop(@intCast(i)); if (comptime quic_enabled) while (l.tick().pending) {}; l.core = replacement; @@ -1831,6 +1837,27 @@ test "a held read is answered when the log has news, and a flushed one spends no s.drop(1); s.drop(2); try heldNow.count(p, 0); + + // 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); } extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; diff --git a/src/fs.zig b/src/fs.zig index 91edd429..965eb47c 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1506,6 +1506,9 @@ pub const Namespace = struct { /// Something a held read may be waiting on changed since they were last /// answered: a record queued, a run answered, a pane gone. news: bool = false, + /// A Restore is about to hang every client up: a follower's held read + /// of /log takes every queued record that fits, not one (events.readLog). + hanging_up: bool = false, /// The editor-wide event ring: panes made, renamed, saved and closed, and /// what the editor said. Recorded whether or not anyone reads /log. log: tree.events.Queue = .{ .cap = limits.log_bytes }, diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 8fae6eab..d60c07ad 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -492,7 +492,18 @@ pub fn readLog(p: *Pardes, req: Req) Reply { slot.next += 1; slot.part = 0; } - return .{ .tag = req.tag, .payload = .{ .staged = @intCast(n) } }; + // This is the last read a Restore lets through: it takes every + // whole record that fits, or they were lost with the hangup. + if (p.fs.hanging_up and slot.part == 0) { + at += 4 + len; + while (at + 4 <= q.buf.items.len) : (slot.next += 1) { + const more = std.mem.readInt(u32, q.buf.items[at..][0..4], .little); + if (out.items.len + more > req.size) break; + out.appendSlice(p.gpa, q.buf.items[at + 4 ..][0..more]) catch break; + at += 4 + more; + } + } + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; } at += 4 + len; } -- cgit v1.3 From 250db41743f77ce3d8421f729bdea0065aa6bc79 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 05:01:31 -0300 Subject: A name under a directory that may not be searched or written is refused, permission denied, and a Save there says so, not no such directory `pardes noperm/a/b/c` and `pardes /proc/1/root/x` took the missing directory for one Save would make, opened a pane and exited 0; its Save then said "no such directory". fs.deniedAbove finds the nearest directory there and asks whether it may be searched and written: forwarding refuses such a name, exit 1, "permission denied", and a failed Save says "permission denied", which the writer's 9P error carries as EPERM (9ns: EACCES). Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 2 +- src/fs.zig | 20 ++++++++++++++++++++ src/main.zig | 8 ++++++-- src/ninep/ctl.zig | 9 +++++++++ src/ninep/pane.zig | 6 ++++-- src/pardes.zig | 6 +++++- test/fs.py | 11 +++++++++++ 7 files changed, 56 insertions(+), 6 deletions(-) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 9fc19df9..ea3f799c 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -328,7 +328,7 @@ pub const Listener = struct { // builtin's failure saying so is (ctl.failureErrno). const errno = if (std.mem.indexOf(u8, late, "no such") != null or std.mem.indexOf(u8, late, "not found") != null) pardes.ctlfs.E.NOENT - else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else pardes.ctlfs.E.IO; + else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else if (std.mem.indexOf(u8, late, "permission denied") != null) pardes.ctlfs.E.PERM else pardes.ctlfs.E.IO; const failed = pardes.ctlfs.failText(req.tag, errno, late); // Its err record says it (the path in it), the one record: it // was said with no msg while this waited (fs.write_waits). diff --git a/src/fs.zig b/src/fs.zig index 965eb47c..e5980fe9 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -685,6 +685,26 @@ pub fn makeDirs(dir: []const u8) void { _ = libc.mkdir(z[0..dir.len :0], 0o755); } +/// 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.fs.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" { + 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..]; diff --git a/src/main.zig b/src/main.zig index a7d354b5..86558bae 100644 --- a/src/main.zig +++ b/src/main.zig @@ -256,7 +256,7 @@ fn forwardWords(err: anyerror, buf: []u8) []const u8 { error.NotOneLine => "a file name is one line, and this one holds a newline", error.NotAFileName => "names a directory, not a file", error.NoWorkingDirectory => "this shell's working directory is gone", - error.DirectoryNotWritable => "its directory may not be read or written, so it could never be saved", + error.DirectoryNotWritable => "permission denied: its directory may not be read or written, so it could never be saved", error.NotAPaneAddress => "not a pane address: @p and a pane's number", error.NoSuchPane => "this session has no such pane", else => if (pardes.Messages.dialReason(err)) |why| why else words: { @@ -653,7 +653,11 @@ fn nativeMain(init: std.process.Init) !void { var cwd_buf: [4096]u8 = undefined; if (std.c.getcwd(&cwd_buf, cwd_buf.len) == null) Refuse.with(init.io, word, error.NoWorkingDirectory); const cwd = std.mem.sliceTo(&cwd_buf, 0); - break :named std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); + const absolute = std.fs.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); + // Missing because one above may not be searched or written: + // its Save could never make it, so refused now. + if (pardes.filesystem.deniedAbove(std.fs.path.dirname(absolute) orelse "/")) Refuse.with(init.io, word, error.DirectoryNotWritable); + break :named absolute; }; // A directory that is there but may not be read or written: a // pane for the name could only fail at its Save, so refused now. diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index c88eb328..d6d7a6ee 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4056,3 +4056,12 @@ test "a command pane an exec open was answered is leased to it while it stays op try testing.expectEqual(Status.ok, wr(p, exec, "echo c\n").reply.status); try testing.expectEqual(a_pane, p.paneBySerial(p.fs.results[0]).?); } + +test "a Save whose directory is missing because one above refuses says permission denied, not no such directory" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + p.saveFailed(0, "/proc/1/root/x/f.txt", error.FileNotFound); + try testing.expect(th.logHas(p, "Save /proc/1/root/x/f.txt: permission denied")); + p.saveFailed(0, "/tmp/pardes-surely-missing-dir/f.txt", error.FileNotFound); + try testing.expect(th.logHas(p, "no such directory")); +} diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index b9fa2857..3963c605 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1535,13 +1535,15 @@ test "a name with a component over 255 bytes is refused, and a long path's faile try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/" ++ "c" ** 255 ++ "\n").reply.status); // A Save of a 3000-byte path the host refuses: the waiting write's // reason is at the end, the path giving up its middle. - const long = "/nonexistent-pardes-root/" ++ ("d" ** 200 ++ "/") ** 15 ++ "f.txt"; + // (Under /tmp: under / a user's Save is refused permission, not + // missing.) + const long = "/tmp/nonexistent-pardes-root/" ++ ("d" ** 200 ++ "/") ** 15 ++ "f.txt"; const id = p.paneBySerial(serial).?; try nameBuffer(p, id, long, false); p.fs.late_failure_len = 0; p.saveFailed(@intCast(id), long, error.AccessDenied); const late = p.fs.late_failure[0..p.fs.late_failure_len]; - try testing.expect(std.mem.startsWith(u8, late, "Save /nonexistent-pardes-root/")); + try testing.expect(std.mem.startsWith(u8, late, "Save /tmp/nonexistent-pardes-root/")); try testing.expect(std.mem.endsWith(u8, late, "/f.txt: no such directory")); } diff --git a/src/pardes.zig b/src/pardes.zig index 945fcafa..f5001797 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5541,7 +5541,11 @@ pub const Pardes = struct { const parent = std.fs.path.dirname(path) orelse "/"; const no_dir = err == error.FileNotFound or err == error.NotDir or (if (comptime hosted) (if (filesystem.localPath(parent)) |local| !exec.isDirectory(local) else false) else false); - if (no_dir) + // Not there because one above refuses: that is the reason, EACCES. + const denied = no_dir and (if (comptime hosted) (if (filesystem.localPath(parent)) |local| filesystem.deniedAbove(local) else false) else false); + if (denied) + p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: permission denied", .{path}) catch "Save: permission denied") + else if (no_dir) p.reportFailure(id, std.fmt.bufPrint(&what, "Save {s}: no such directory", .{path}) catch "Save: no such directory") else p.reportError(id, std.fmt.bufPrint(&what, "Save {s}", .{path}) catch "Save", err); diff --git a/test/fs.py b/test/fs.py index 6c6bcbef..2ccd0690 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1405,6 +1405,17 @@ def test(binary, quic=False): dashed, = serials() - before assert client.read(f'/pane/{dashed}/name').rstrip(b'\n') == str(dash).encode() client.remove(f'/pane/{dashed}') + # A name under a directory that may not be searched is refused, + # permission denied, exit 1, no pane: its Save could never be. + (root / 'noperm').mkdir() + (root / 'noperm').chmod(0) + before = serials() + try: + denied = subprocess.run([binary, 'noperm/a/b/c'], cwd=root, env=env, capture_output=True, timeout=10) + finally: + (root / 'noperm').chmod(0o755) + assert denied.returncode == 1 and b'permission denied' in denied.stderr, denied + assert serials() == before # --wait waits on the pane its look answered, on the look's own # open: a name /index shows escaped (a backslash is `\\` there) # is still the pane waited on, not one already gone. -- cgit v1.3 From df10c37122cc3e6565d13aeefb9466dc6c0dc780 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 06:17:47 -0300 Subject: Grep and Find pass over a directory they may not open and keep every other hit, saying in one line how many they skipped One `chmod 000` directory anywhere under a pane made every Grep say `pattern not found` and every Find `access denied`: the walk's `try w.enter`/`try w.next` ended it at the first refusal. Each is now counted and passed over, and the +Search ends `N directories skipped: permission denied` under the hits. Co-Authored-By: Claude Opus 5.5 --- src/fs.zig | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++------- src/look.zig | 12 ++++++++++-- 2 files changed, 60 insertions(+), 9 deletions(-) (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index e5980fe9..0c04e873 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1079,7 +1079,10 @@ const find_skip = [_][]const u8{ ".venv", "__pycache__", ".zig-cache", "zig-out", }; -pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u8) !usize { +/// A directory the walk may not open or read is passed over and counted in +/// `skipped`, its siblings' hits kept: one locked directory is not every +/// search's failure. +pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u8, skipped: *usize) !usize { var hits: [find_max_hits][]const u8 = undefined; var hits_len: usize = 0; if (platform_has_fs) { @@ -1093,14 +1096,19 @@ pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u var steps: usize = 0; walk: while (steps < find_max_steps and hits_len < hits.len) { steps += 1; // an unreadable dir burns a step too, so it cannot spin - const e = (try w.next(io)) orelse break; + const e = (w.next(io) catch { + skipped.* += 1; + continue; + }) orelse break; if (std.ascii.indexOfIgnoreCase(e.basename, pat) != null) { hits[hits_len] = try arena.dupe(u8, e.path); hits_len += 1; } if (e.kind != .directory or e.depth() >= find_max_depth) continue; for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - try w.enter(io, e); + w.enter(io, e) catch { + skipped.* += 1; + }; } } else { for (sources) |s| { @@ -1152,7 +1160,7 @@ fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budg return result; } -pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, base: []const u8, pat: []const u8, out: []u8) !usize { +pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, base: []const u8, pat: []const u8, out: []u8, skipped: *usize) !usize { var hits: usize = 0; var written: usize = 0; if (!platform_has_fs) { @@ -1180,11 +1188,16 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b var steps: usize = 0; walk: while (steps < find_max_steps and files_len < files.len) { steps += 1; - const e = (try w.next(io)) orelse break; + const e = (w.next(io) catch { + skipped.* += 1; + continue; + }) orelse break; if (e.kind == .directory) { if (e.depth() >= find_max_depth) continue; for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - try w.enter(io, e); + w.enter(io, e) catch { + skipped.* += 1; + }; continue; } if (e.kind != .file) continue; @@ -1253,13 +1266,43 @@ test "grep skips a file it cannot read instead of abandoning the search" { defer arena.deinit(); const out = try gpa.alloc(u8, 64 * 1024); defer gpa.free(out); - const n = try grep(arena.allocator(), gpa, dir, dir, "needle", out); + var skipped: usize = 0; + const n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, &skipped); _ = libc.chmod(locked, 0o644); // so `tmp.cleanup` can remove it try std.testing.expect(std.mem.indexOf(u8, out[0..n], "b-open.txt") != null); try std.testing.expect(std.mem.indexOf(u8, out[0..n], "a-locked.txt") == null); } +test "a directory the walk may not open is skipped and counted: Grep and Find keep every other hit" { + if (!platform_has_fs) return; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + try tmp.dir.createDirPath(std.testing.io, "locked"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "locked/needle-in.txt", .data = "needle\n" }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "needle-out.txt", .data = "needle\n" }); + var locked_buf: [std.fs.max_path_bytes]u8 = undefined; + const locked = try std.fmt.bufPrintSentinel(&locked_buf, "{s}/locked", .{dir}, 0); + if (libc.chmod(locked, 0) != 0) return; + defer _ = libc.chmod(locked, 0o755); // so `tmp.cleanup` can remove it + if (isDir(locked)) return error.SkipZigTest; // root reads it anyway + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const out = try gpa.alloc(u8, 64 * 1024); + defer gpa.free(out); + var skipped: usize = 0; + var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, &skipped); + try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt:1:") != null); + try std.testing.expectEqual(@as(usize, 1), skipped); + skipped = 0; + n = try find(arena.allocator(), dir, "needle", out, &skipped); + try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt") != null); + try std.testing.expectEqual(@as(usize, 1), skipped); +} + fn isDir(path: [*:0]const u8) bool { const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true }); if (fd < 0) return false; diff --git a/src/look.zig b/src/look.zig index f208c1fb..21148b37 100644 --- a/src/look.zig +++ b/src/look.zig @@ -593,6 +593,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start var out_len: usize = 0; var nrows: usize = 0; var anchor: ?usize = null; + var skipped: usize = 0; if (kind == .grep) { var roots: [MAX_PANES][]const u8 = undefined; var nroots: usize = 0; @@ -625,13 +626,13 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start // not made yet, a peer's) has nothing to grep: passed over, not the // search's failure. for (roots[0..nroots]) |r| - out_len += filesystem.grep(arena, p.gpa, r, dir, pat, out[out_len..]) catch |err| switch (err) { + out_len += filesystem.grep(arena, p.gpa, r, dir, pat, out[out_len..], &skipped) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.AccessDenied => continue, else => return err, }; nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (kind == .find) { - out_len = try filesystem.find(arena, dir, pat, out); + out_len = try filesystem.find(arena, dir, pat, out, &skipped); nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (pane.hasPdf()) { if (comptime pdf_enabled) { @@ -672,6 +673,13 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start nrows += 1; } } + // What the walk could not open is said in one line under the hits, so + // a locked directory reads as passed over, not as nothing there. + if (skipped > 0) { + const note = std.fmt.bufPrint(out[out_len..], "{d} director{s} skipped: permission denied\n", .{ skipped, if (skipped == 1) "y" else "ies" }) catch ""; + out_len += note.len; + nrows += @intFromBool(note.len > 0); + } // A Find or Grep that finds nothing empties its directory's +Search, if // there is one, rather than leave the last search's rows looking like // this one's. -- cgit v1.3 From fb330ce04c4eec4de317637d26310b74e2ee5923 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 06:22:44 -0300 Subject: A Rename that previews other files answers its preview pane to the 9P write that asked it, and says on the message row that it previewed and applied nothing A multi-file Rename filled a +Search preview but the waiting exec write answered the pane it was asked from, and nothing was said. lspResponse now notes the pane it filled (fs.lsp_result); the write that waited for the answer reads that pane back, as a look or an exec answers the pane it went to, and the message row says `Rename: N edit(s) across files, previewed, not applied`. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 13 +++++++++++++ src/fs.zig | 3 +++ src/ninep/ctl.zig | 12 ++++++++++++ src/pardes.zig | 9 +++++++++ 4 files changed, 37 insertions(+) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index ea3f799c..a4340ddf 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -317,7 +317,20 @@ pub const Listener = struct { if (core.effects_len != 0) pardes.turn.awaitSettled(epoch); if (core.fs.lsp_answer_at) |n| { core.fs.lsp_answer_at = null; + core.fs.lsp_result = null; pardes.turn.awaitLsp(n); + // The answer filled a pane (a Rename's preview): that is what + // this write's open reads back, as look and exec answer. + if (l.core == core) if (core.fs.lsp_result) |serial| { + core.fs.lsp_result = null; + core.fs.results[0] = serial; + core.fs.results_len = 1; + if (pardes.ctlfs.openOf(core, req)) |o| { + o.results.list[0] = serial; + o.results.len = 1; + o.results.read = 0; + } + }; } core.fs.write_waits = false; // ponytail: one slot, so a failure of another client's effects that diff --git a/src/fs.zig b/src/fs.zig index 0c04e873..7d6b0d71 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1529,6 +1529,9 @@ pub const Namespace = struct { /// A 9P write asked a language server something: the answer count it /// waits to change (`turn.lsp_answers`), so its failure is the write's. lsp_answer_at: ?u64 = null, + /// The pane a language answer filled (a Rename's preview): what the + /// waiting 9P write answers once it is in (9p_io). + lsp_result: ?u32 = null, /// The most a Twrite of the request being served can carry (msize less /// its header), 0 when unknown: a write shorter than it is the whole of /// what its client wrote, one that fills it may be cut and go on. diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index b17f150a..f0dab28d 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4105,3 +4105,15 @@ test "Tty+bash on a pane ctl is Tty with its argument, as exec and the tag take try testing.expectEqual(Status.ok, r.reply.status); try testing.expect(r.spawned); } + +test "a Rename that reaches other files previews them, says so, and is the pane a waiting write answers" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const id = p.active; + p.fs.lsp_result = null; + p.lspRequest(id, .rename, "sum"); + p.lspResponse(p.lsp_wait.?.id, "lib.rs:2:8 sum\nmain.rs:4:13-15 sum\n"); + const preview = p.panes[p.panes[id].?.search_pane.?].?; + try testing.expectEqual(preview.serial, p.fs.lsp_result.?); + try testing.expect(th.logHas(p, "Rename: 2 edit(s) across files, previewed, not applied")); +} diff --git a/src/pardes.zig b/src/pardes.zig index f5001797..ca0980f4 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -6764,6 +6764,15 @@ pub const Pardes = struct { p.reportError(w.pane, "language response", err); return; }; + // What a 9P write that asked it answers: the pane the rows are in + // (a multi-file Rename's preview), not the pane it was asked from. + if (pane.search_pane) |rid| if (p.panes[rid]) |rp| { + p.fs.lsp_result = rp.serial; + }; + if (w.kind == .rename) { + var said_buf: [96]u8 = undefined; + p.setMessage(w.pane, std.fmt.bufPrint(&said_buf, "Rename: {d} edit(s) across files, previewed, not applied", .{nrows}) catch "Rename: previewed"); + } if (panes.Output.traits(from).jumps) { const result = p.panes[pane.search_pane orelse return] orelse return; const file = pane.file orelse return; -- cgit v1.3 From a274bd2c706fdfd3effa0ad88c5b4083c0dc0f33 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 08:15:56 -0300 Subject: Grep and Find say when a cap hid what they might have found: `cut at 512 hits`, `N files read only in part (first 256 KiB)`, `walk cut at N entries`; one that finds nothing leaves the +Search as it was Grep reads 256 KiB of a file and stops at 512 hits, and its walk at 20000 files or 100000 entries; Find stops at 512 names. A cap hit was silent, so a match past one read as `pattern not found`. The walk now notes each cap it hit (fs.WalkNotes) and the +Search says it in a line under the hits, as it says directories skipped; a search that found nothing but hit a cap opens the +Search with those lines, not a miss. A Find or Grep that finds nothing and passed nothing over leaves the directory's +Search with the last search's rows, its failure saying so, where it used to empty it. Co-Authored-By: Claude Opus 5.5 --- src/fs.zig | 118 ++++++++++++++++++++++++++++++++++++++++++++++-------- src/look.zig | 28 ++++++------- src/ninep/ctl.zig | 5 ++- 3 files changed, 118 insertions(+), 33 deletions(-) (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index 7d6b0d71..9eb3fd0f 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1070,6 +1070,43 @@ pub const platform_has_fs = !pardes.isolated and switch (pardes.platform) { }; const find_max_hits = 512; + +/// What a Find or Grep walk passed over, said under its hits: directories +/// it might not open, files read only in part, and caps it stopped at. +pub const WalkNotes = struct { + skipped: usize = 0, + /// Files longer than grep_max_bytes, searched in their first part only. + partial: usize = 0, + hits_cut: bool = false, + /// The cap on entries walked it stopped at, 0 if none. + walk_cut: usize = 0, + + pub const max_hits = find_max_hits; + pub const max_file_bytes = grep_max_bytes; + pub const max_files = grep_max_files; + pub const max_depth = find_max_depth; + + /// The lines that say it, each ending in a newline, into `out`. + pub fn write(n: WalkNotes, out: []u8) usize { + var w = std.Io.Writer.fixed(out); + if (n.hits_cut) w.print("cut at {d} hits\n", .{max_hits}) catch {}; + if (n.partial > 0) w.print("{d} file{s} read only in part (first {d} KiB)\n", .{ n.partial, if (n.partial == 1) "" else "s", max_file_bytes / 1024 }) catch {}; + if (n.walk_cut > 0) w.print("walk cut at {d} entries\n", .{n.walk_cut}) catch {}; + if (n.skipped > 0) w.print("{d} director{s} skipped: permission denied\n", .{ n.skipped, if (n.skipped == 1) "y" else "ies" }) catch {}; + return w.buffered().len; + } + + /// Whether `line` is one of those, not a hit. + pub fn isNote(line: []const u8) bool { + if (std.mem.startsWith(u8, line, "cut at ") or std.mem.startsWith(u8, line, "walk cut at ")) return true; + const digits = for (line, 0..) |c, i| { + if (!std.ascii.isDigit(c)) break i; + } else line.len; + if (digits == 0) return false; + const rest = line[digits..]; + return std.mem.startsWith(u8, rest, " director") or std.mem.startsWith(u8, rest, " file"); + } +}; const find_max_depth = 16; const find_max_steps = 100_000; pub const search_max_output_bytes = pardes.MAX_PANES * find_max_hits * (4096 + 320); @@ -1080,9 +1117,9 @@ const find_skip = [_][]const u8{ }; /// A directory the walk may not open or read is passed over and counted in -/// `skipped`, its siblings' hits kept: one locked directory is not every -/// search's failure. -pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u8, skipped: *usize) !usize { +/// `notes.skipped`, its siblings' hits kept: one locked directory is not +/// every search's failure. A cap the walk hit is noted too. +pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u8, notes: *WalkNotes) !usize { var hits: [find_max_hits][]const u8 = undefined; var hits_len: usize = 0; if (platform_has_fs) { @@ -1097,7 +1134,7 @@ pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u walk: while (steps < find_max_steps and hits_len < hits.len) { steps += 1; // an unreadable dir burns a step too, so it cannot spin const e = (w.next(io) catch { - skipped.* += 1; + notes.skipped += 1; continue; }) orelse break; if (std.ascii.indexOfIgnoreCase(e.basename, pat) != null) { @@ -1107,9 +1144,11 @@ pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u if (e.kind != .directory or e.depth() >= find_max_depth) continue; for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; w.enter(io, e) catch { - skipped.* += 1; + notes.skipped += 1; }; } + if (hits_len >= hits.len) notes.hits_cut = true; + if (steps >= find_max_steps) notes.walk_cut = find_max_steps; } else { for (sources) |s| { if (hits_len >= hits.len) break; @@ -1160,7 +1199,7 @@ fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budg return result; } -pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, base: []const u8, pat: []const u8, out: []u8, skipped: *usize) !usize { +pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, base: []const u8, pat: []const u8, out: []u8, notes: *WalkNotes) !usize { var hits: usize = 0; var written: usize = 0; if (!platform_has_fs) { @@ -1189,14 +1228,14 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b walk: while (steps < find_max_steps and files_len < files.len) { steps += 1; const e = (w.next(io) catch { - skipped.* += 1; + notes.skipped += 1; continue; }) orelse break; if (e.kind == .directory) { if (e.depth() >= find_max_depth) continue; for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; w.enter(io, e) catch { - skipped.* += 1; + notes.skipped += 1; }; continue; } @@ -1204,6 +1243,7 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b files[files_len] = try std.fmt.allocPrint(arena, "{s}/{s}", .{ root_path, e.path }); files_len += 1; } + if (files_len >= files.len) notes.walk_cut = grep_max_files else if (steps >= find_max_steps) notes.walk_cut = find_max_steps; } std.mem.sort([]const u8, files[0..files_len], {}, struct { fn lt(_: void, a: []const u8, b: []const u8) bool { @@ -1213,7 +1253,10 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b const buf = try gpa.alloc(u8, grep_max_bytes); defer gpa.free(buf); for (files[0..files_len]) |path| { - if (hits >= find_max_hits or written == out.len) break; + if (hits >= find_max_hits or written == out.len) { + notes.hits_cut = true; + break; + } var pathbuf: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{path}, 0) catch return error.PathTooLong; const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NONBLOCK = true }); @@ -1230,14 +1273,19 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b if (n == 0) break; len += @intCast(n); } + // Read to its cap with more behind it: searched in part, and said. + var more: [1]u8 = undefined; + const longer = readable and len == buf.len and libc.read(fd, &more, 1) > 0; _ = libc.close(fd); if (!readable) continue; const text = buf[0..len]; if (std.mem.indexOfScalar(u8, text[0..@min(len, 1024)], 0) != null) continue; + if (longer) notes.partial += 1; const shown = lsp.rel(home, path); const result = grepText(shown, text, pat, out[written..], find_max_hits - hits); hits += result.hits; written += result.bytes; + if (hits >= find_max_hits) notes.hits_cut = true; } return written; } @@ -1266,8 +1314,8 @@ test "grep skips a file it cannot read instead of abandoning the search" { defer arena.deinit(); const out = try gpa.alloc(u8, 64 * 1024); defer gpa.free(out); - var skipped: usize = 0; - const n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, &skipped); + var notes: WalkNotes = .{}; + const n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); _ = libc.chmod(locked, 0o644); // so `tmp.cleanup` can remove it try std.testing.expect(std.mem.indexOf(u8, out[0..n], "b-open.txt") != null); @@ -1293,14 +1341,50 @@ test "a directory the walk may not open is skipped and counted: Grep and Find ke defer arena.deinit(); const out = try gpa.alloc(u8, 64 * 1024); defer gpa.free(out); - var skipped: usize = 0; - var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, &skipped); + var notes: WalkNotes = .{}; + var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt:1:") != null); - try std.testing.expectEqual(@as(usize, 1), skipped); - skipped = 0; - n = try find(arena.allocator(), dir, "needle", out, &skipped); + try std.testing.expectEqual(@as(usize, 1), notes.skipped); + notes = .{}; + n = try find(arena.allocator(), dir, "needle", out, ¬es); try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt") != null); - try std.testing.expectEqual(@as(usize, 1), skipped); + try std.testing.expectEqual(@as(usize, 1), notes.skipped); +} + +test "Grep says when a cap hid what it might have found: a file read in part, the hits cut" { + if (!platform_has_fs) return; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + // The match past the first 256 KiB of a long file. + const long = try gpa.alloc(u8, grep_max_bytes + 64); + defer gpa.free(long); + @memset(long, 'x'); + for (0..long.len / 64) |i| long[i * 64] = '\n'; + @memcpy(long[long.len - 8 ..][0..7], "needle\n"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "long.txt", .data = long }); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const out = try gpa.alloc(u8, 256 * 1024); + defer gpa.free(out); + var notes: WalkNotes = .{}; + var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); + try std.testing.expectEqual(@as(usize, 0), n); + try std.testing.expectEqual(@as(usize, 1), notes.partial); + // More hits than the cap. + var many: std.ArrayList(u8) = .empty; + defer many.deinit(gpa); + for (0..find_max_hits + 10) |_| try many.appendSlice(gpa, "needle\n"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "many.txt", .data = many.items }); + notes = .{}; + n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); + try std.testing.expect(notes.hits_cut); + var said: [256]u8 = undefined; + const lines = said[0..notes.write(&said)]; + try std.testing.expectEqualStrings("cut at 512 hits\n1 file read only in part (first 256 KiB)\n", lines); + try std.testing.expect(WalkNotes.isNote("cut at 512 hits") and WalkNotes.isNote("2 directories skipped: permission denied") and !WalkNotes.isNote("src/2 directories.txt")); } fn isDir(path: [*:0]const u8) bool { diff --git a/src/look.zig b/src/look.zig index c77119c5..11c77760 100644 --- a/src/look.zig +++ b/src/look.zig @@ -593,7 +593,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start var out_len: usize = 0; var nrows: usize = 0; var anchor: ?usize = null; - var skipped: usize = 0; + var notes: filesystem.WalkNotes = .{}; if (kind == .grep) { var roots: [MAX_PANES][]const u8 = undefined; var nroots: usize = 0; @@ -626,13 +626,13 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start // not made yet, a peer's) has nothing to grep: passed over, not the // search's failure. for (roots[0..nroots]) |r| - out_len += filesystem.grep(arena, p.gpa, r, dir, pat, out[out_len..], &skipped) catch |err| switch (err) { + out_len += filesystem.grep(arena, p.gpa, r, dir, pat, out[out_len..], ¬es) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.AccessDenied => continue, else => return err, }; nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (kind == .find) { - out_len = try filesystem.find(arena, dir, pat, out, &skipped); + out_len = try filesystem.find(arena, dir, pat, out, ¬es); nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (pane.hasPdf()) { if (comptime pdf_enabled) { @@ -673,17 +673,17 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start nrows += 1; } } - // What the walk could not open is said in one line under the hits, so - // a locked directory reads as passed over, not as nothing there. - if (skipped > 0) { - const note = std.fmt.bufPrint(out[out_len..], "{d} director{s} skipped: permission denied\n", .{ skipped, if (skipped == 1) "y" else "ies" }) catch ""; - out_len += note.len; - nrows += @intFromBool(note.len > 0); - } - // A Find or Grep that finds nothing empties its directory's +Search, if - // there is one, rather than leave the last search's rows looking like - // this one's. - if (!open_empty and nrows == 0 and (kind == .text or !panes.Output.hasFileSearch(p, dir))) return 0; + // What the walk passed over -- a directory it might not open, a file + // read in part, a cap it stopped at -- is said in lines under the hits, + // so a search that found nothing where it did not look says so, never + // just "not found". + const noted = notes.write(out[out_len..]); + out_len += noted; + nrows += std.mem.count(u8, out[out_len - noted .. out_len], "\n"); + // A Find or Grep that finds nothing leaves its directory's +Search as + // it was: the failure says why, and the last search's rows are still + // that search's (its tag names it). + if (!open_empty and nrows == 0) return 0; const content = try p.gpa.dupe(u8, out[0..out_len]); // the buffer records WHICH search filled it, pattern and all: Find and // Grep are builtins (words you can execute), the bare `/` is a key diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index c564da6e..d4f36bea 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2563,8 +2563,9 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir var after: usize = 0; for (p.panes) |slot| after += @intFromBool(slot != null); try testing.expectEqual(count, after); - // The +Search the miss would have filled is emptied, not left stale. - try testing.expectEqualStrings("", found.file.?.content); + // The +Search a miss would have filled keeps the last search's rows: + // the miss is said, and its tag names what they are of. + try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") != null); } test "Unmount of a name not mounted says no such mount, which a mount reads as ENOENT" { -- cgit v1.3 From edad6d960dc0fc1165cbb3b801e0538045b2247f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 10:09:54 -0300 Subject: A +Pager keeps its program's colours: the session parses what /pager is written after its directory with ghostty-vt, SGR becomes spans drawn over the plain text, every other escape is dropped, and PagerColor off pages it plain --- src/9p_io.zig | 28 ++- src/File.zig | 40 ++++- src/config.zig | 8 +- src/fs.zig | 7 + src/main.zig | 129 +++----------- src/ninep/ctl.zig | 103 +++++++++-- src/ninep/tree.zig | 58 +++++- src/pager.zig | 373 +++++++++++++++++++++++++++++++++++++++ src/pardes.zig | 12 +- test/fs.py | 20 +++ test/selfmount.py | 14 ++ test/snapshots/pagercolor.golden | 120 +++++++++++++ test/snapshots/pagercolor.snap | 24 +++ 13 files changed, 806 insertions(+), 130 deletions(-) create mode 100644 src/pager.zig create mode 100644 test/snapshots/pagercolor.golden create mode 100644 test/snapshots/pagercolor.snap (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 9a38b438..57df0c5f 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -266,6 +266,7 @@ pub const Listener = struct { const restores = pardes.turn.restores; // Asked first: a release that runs a held line has none after. const changes = pardes.ctlfs.changesPane(core, req); + const fills = pardes.ctlfs.holdsPage(core, req); const reply = core.serveFs(req); if (req.op == .release and quiet) l.collectOs(); // A read with nothing yet stays parked in the engine, and the core @@ -299,6 +300,13 @@ pub const Listener = struct { // file written. A change carries no payload, so the reply is still // whole after the wait. l.kick(); + // A read that put a /pager open's text in (ctl.fillPager), or a + // close that handed it to the editor's step, waits on nothing the + // editor performs: its answer goes now, while the turn still keeps + // a read's payload whole. Waiting would hang a close through a + // mount: 9ns answers nothing else on it while a clunk is out, and + // the editor's step may be out opening a file through that mount. + if (fills) return conn.reply(&reply, core.fsPayload(reply)); // A refusal answers at once: its text may be in the core's one // buffer for it, which a request run while this one waited would // write over. @@ -2341,10 +2349,12 @@ pub const Client = struct { gpa.destroy(s); } - /// Writes `request` 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`. - pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8) ![]u8 { + /// 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); @@ -2356,7 +2366,15 @@ pub const Client = struct { defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); - _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = request } }, &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) { diff --git a/src/File.zig b/src/File.zig index 4fac0073..b3c28290 100644 --- a/src/File.zig +++ b/src/File.zig @@ -75,6 +75,11 @@ pub const State = struct { /// A +Pager pane (`pardes -`) whose text is a diff (`git diff`, `show`, /// `log -p`): drawn and looked at as a diff (Pane.colorAlgo). pager_diff: bool = false, + /// A +Pager's colours, as its program printed them (pager.zig): drawn + /// over its text by recolorSyntax, never read over 9P. ponytail: any + /// edit drops them (setContentSpan); shifting them through the splice, + /// as pane.zig's shiftOne moves dot, would keep them. + pager_spans: []pardes.pager.Span = &.{}, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -982,6 +987,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.mini) |*mini| mini.deinit(p.gpa); if (file.line_starts.len > 0) p.gpa.free(file.line_starts); if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); + p.gpa.free(file.pager_spans); locations.freeRows(p.gpa, file.location_rows); if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); if (file.node_tree) |tree| syntax.freeTree(tree); @@ -1010,6 +1016,8 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span: ?Span) void { locations.freeRows(p.gpa, f.location_rows); f.location_rows = &.{}; + p.gpa.free(f.pager_spans); + f.pager_spans = &.{}; for (p.panes) |slot| if (slot) |pane| { if (pane.file) |*file| if (file == f) { for (0..pane.sel.len) |button| { @@ -1483,7 +1491,8 @@ fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { const highlights = if (f.mini) |mini| mini.colors else f.highlights; const highlight_start = if (f.mini != null) 0 else f.highlight_start; - if (highlights.len == 0 and f.output == null) return; + const spans = f.pager_spans; + if (highlights.len == 0 and f.output == null and spans.len == 0) return; const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); @@ -1526,6 +1535,14 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. else null else null; if (tint) |t| if (prefix_width < tw) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, t.bg); + // A +Pager's own colours (pager.zig) on every row but one the diff + // look tints: an added or removed line is drawn as pardes draws a + // diff, and git's red and green on it would only fight the tint. + var span_at = if (tint != null) spans.len else std.sort.partitionPoint(pardes.pager.Span, spans, base + hs, struct { + fn before(at: usize, span: pardes.pager.Span) bool { + return span.end <= at; + } + }.before); var c: usize = 0; var screen_c: usize = 0; while (hs + c < limit and prefix_width + screen_c < tw) { @@ -1562,6 +1579,27 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (style.bg != .default) cell.style.bg = style.bg; } } + while (span_at < spans.len and spans[span_at].end <= idx) span_at += 1; + if (span_at < spans.len and spans[span_at].start <= idx) { + const st = spans[span_at].style; + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); + if (cell.default) continue; + // A palette colour through the theme's sixteen, as a + // terminal pane's cell; truecolor as it is. + if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + cell.style.bold = cell.style.bold or st.bold; + cell.style.dim = st.dim; + cell.style.italic = st.italic; + cell.style.blink = st.blink; + cell.style.reverse = st.reverse; + cell.style.invisible = st.invisible; + cell.style.strikethrough = st.strikethrough; + if (st.ul != .off) cell.style.ul = st.ul; + } + } screen_c += cells; c = grapheme_end - hs; } diff --git a/src/config.zig b/src/config.zig index 7559d481..86baa9fe 100644 --- a/src/config.zig +++ b/src/config.zig @@ -82,6 +82,7 @@ pub const leader_path = paths: { .BootShell = null, .LookWord = null, .Pager = null, + .PagerColor = null, .TermImages = null, .Debug = "td", .Msg = null, @@ -762,6 +763,9 @@ pub const Runtime = struct { /// PAGER and GIT_PAGER set to `pardes -`, a +Pager pane, where the /// user's environment set neither; `off`, the environment as it is. pager: Pager = .pardes, + /// A +Pager keeps its program's colours (SGR, as spans over the text, + /// pager.zig), or is plain; for the next text paged. + pager_color: bool = true, /// How a new terminal pane draws the kitty graphics its program sends /// (yazi's previews): `real`, as pixels where the shell can, or /// `petscii`, as glyph art. The Petscii builtin flips one pane. @@ -939,7 +943,7 @@ pub const Runtime = struct { /// The message timings a setting word sets, each in milliseconds. pub const MessageTime = enum { linger, fall, dissolve }; - pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, syntax_bold, verbose, message_animation, ligatures, cursor_blink, selection_glow, hover_glow, occlusion, parallax, jump_trail, chip_shadow, thumb_flash }; + pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, syntax_bold, pager_color, verbose, message_animation, ligatures, cursor_blink, selection_glow, hover_glow, occlusion, parallax, jump_trail, chip_shadow, thumb_flash }; /// A bundled post pass, a Shadertoy file in shaders/post/: the CRT, and /// G4's bloom, vignette and grain (docs/effects.md). pub const Scene = enum { crt, bloom, vignette, grain }; @@ -1040,6 +1044,7 @@ pub const Runtime = struct { .{ .word = "BootShell", .action = .{ .choice = .boot_shell }, .doc = "A document dropped where a lone untouched shell stands: keep the shell, or replace it." }, .{ .word = "LookWord", .action = .{ .choice = .look_word }, .doc = "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search." }, .{ .word = "Pager", .action = .{ .choice = .pager }, .doc = "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it." }, + .{ .word = "PagerColor", .action = .{ .toggle = .pager_color }, .doc = "A +Pager keeps its program's colours, on or off; for the next text paged." }, .{ .word = "TermImages", .action = .{ .choice = .term_images }, .doc = "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art." }, }; @@ -1748,6 +1753,7 @@ pub const Runtime = struct { .debug => "Debug on\n", .focus_tint => "FocusTint off\n", .syntax_bold => "SyntaxBold on\n", + .pager_color => "PagerColor off\n", .verbose => "Verbose off\n", .message_animation => "MessageAnimation off\n", .ligatures => "Ligatures off\n", diff --git a/src/fs.zig b/src/fs.zig index 9eb3fd0f..4a243b10 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1631,6 +1631,11 @@ pub const Namespace = struct { /// append to `body`, an insert at `data`'s address), held and put in /// as one edit when anything else comes (ninep/pane.zig flushBatch): a /// 10 MB write in 8 KB pieces is one copy and one undo step, not 1280. + /// The text of /pager opens closed before a read put it in, each with + /// its +Pager's serial, for the editor's step to put in (ctl.fillPager): + /// a close through a mount may not wait for the editor to be quiet, + /// as 9ns answers nothing else on that mount while a clunk is out. + pages: std.ArrayList(struct { serial: u32, bytes: std.ArrayList(u8) }) = .empty, batch: struct { serial: u32 = 0, node: u64 = 0, @@ -1678,6 +1683,8 @@ pub const Namespace = struct { for (st.os_paths.items) |entry| gpa.free(entry.path); st.os_paths.deinit(gpa); for (&st.opens) |*o| o.deinit(gpa); + for (st.pages.items) |*page| page.bytes.deinit(gpa); + st.pages.deinit(gpa); st.log.deinit(gpa); st.out.deinit(gpa); } diff --git a/src/main.zig b/src/main.zig index e998accc..6d895307 100644 --- a/src/main.zig +++ b/src/main.zig @@ -50,9 +50,10 @@ const help_text = \\ \\With no arguments the shell pane starts in tty mode. A FILE argument \\(optionally file:LINE) opens it alone, filling the window; a DIRECTORY - \\argument becomes the cwd shells spawn in. `-` reads stdin, its terminal - \\escapes stripped, into a +Pager pane: inside a pardes pane the outer - \\session's, returning at once (a terminal's PAGER), else a new editor's. + \\argument becomes the cwd shells spawn in. `-` reads stdin into a +Pager + \\pane, its colours kept (PagerColor) and every other escape dropped: + \\inside a pardes pane the outer session's, returning at once (a + \\terminal's PAGER), else a new editor's. \\ \\Options: \\ --tty start as one shell pane already in tty mode @@ -100,11 +101,12 @@ const help_text = \\ ; -/// `pardes -` inside a session: `text` into the directory's one +Pager -/// (/pager, refilled when it is there), written into its -/// body through one open, as one undo step, and left clean. A text -/// the session would not take is never lost: it goes to stderr, with why, -/// and the exit is 1. +/// `pardes -` inside a session: `text`, stdin as it came, escapes and all, +/// into the directory's one +Pager (/pager, refilled when it is there): +/// written after the directory on that one open, the session parses it +/// (pager.zig) and puts it in as one undo step, left clean. A text the +/// session would not take is never lost: it goes to stderr, a terminal, +/// with why, and the exit is 1. fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void { const Fail = struct { fn with(o: std.Io, t: []const u8, what: []const u8, err: anyerror) noreturn { @@ -128,22 +130,16 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const } else !pardes.filesystem.deniedAbove(cwd); var line_buf: [4200]u8 = undefined; const dir_line = std.fmt.bufPrint(&line_buf, "{s}\n", .{if (plain) cwd else ""}) catch "\n"; - // Its serial read back on the open that asked: another client's exec - // meanwhile can never send this text into that client's pane. - const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line) catch |err| Fail.with(io, text, "no +Pager pane", err); - const serial = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); - // The whole text through one open of the body (truncated once, then - // written at rising offsets): one undo step, and every byte of it. - var body_buf: [64]u8 = undefined; - const body = std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{serial}) catch unreachable; - ninep_io.Client.write(gpa, dial, body, text) catch |err| Fail.with(io, text, "the +Pager pane would not take it", err); - var ctl_buf: [64]u8 = undefined; - ninep_io.Client.write(gpa, dial, std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable, "clean\n") catch {}; + // Its serial read back on the open that asked, once the text is in: + // another client's exec meanwhile can never send it into that + // client's pane. + const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line, text) catch |err| Fail.with(io, text, "no +Pager pane", err); + _ = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); } -/// Stdin to its end, its terminal escapes stripped (a pager's input is -/// coloured for a terminal; a text pane shows text), at most a file's -/// limit, a longer one cut there and said so at its end. +/// Stdin to its end, as it came (its escapes are the session's to parse, +/// pager.zig), at most a file's limit, a longer one cut there and said so +/// at its end. fn readStdinText(gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; var raw: std.ArrayList(u8) = .empty; @@ -164,90 +160,13 @@ fn readStdinText(gpa: std.mem.Allocator) ![]u8 { } try raw.appendSlice(gpa, chunk[0..got]); } - var text = try stripEscapes(gpa, raw.items); if (cut) { - const said = "\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; - text = try std.mem.concat(gpa, u8, &.{ text, said }); - } - return text; -} - -/// `bytes` without terminal escapes: CSI (`ESC [` ... a final byte, SGR -/// colour among them), OSC (`ESC ]` ... BEL or `ESC \`), any other -/// two-byte `ESC x`, and a man page's overstrike (`x BS x`, `_ BS x`). -pub fn stripEscapes(gpa: std.mem.Allocator, bytes: []const u8) ![]u8 { - var out = try std.ArrayList(u8).initCapacity(gpa, bytes.len); - var i: usize = 0; - while (i < bytes.len) { - const c = bytes[i]; - if (c == 0x1b and i + 1 < bytes.len) { - const kind = bytes[i + 1]; - i += 2; - if (kind == '[') { - while (i < bytes.len and !(bytes[i] >= 0x40 and bytes[i] <= 0x7e)) i += 1; - i += 1; - } else if (std.mem.indexOfScalar(u8, "()*+", kind) != null) { - i += 1; // a charset's name after it - } else if (kind == ']') { - while (i < bytes.len) : (i += 1) { - if (bytes[i] == 0x07) { - i += 1; - break; - } - if (bytes[i] == 0x1b and i + 1 < bytes.len and bytes[i + 1] == '\\') { - i += 2; - break; - } - } - } - continue; - } - // Overstrike: the byte before a backspace is struck over. - if (c == 0x08) { - if (out.items.len > 0) _ = out.pop(); - i += 1; - continue; - } - // A carriage return: CRLF is a newline; alone, the line starts - // over, as on a terminal, so a progress line keeps its last state. - if (c == '\r') { - if (i + 1 < bytes.len and bytes[i + 1] == '\n') { - i += 1; - continue; - } - const line_start = if (std.mem.lastIndexOfScalar(u8, out.items, '\n')) |nl| nl + 1 else 0; - out.shrinkRetainingCapacity(line_start); - i += 1; - continue; - } - // Bytes a terminal acts on and never shows: NUL, BEL, SO, SI. - if (c == 0 or c == 0x07 or c == 0x0e or c == 0x0f) { - i += 1; - continue; - } - out.appendAssumeCapacity(c); - i += 1; - } - return out.toOwnedSlice(gpa); -} - -test "stripEscapes takes out colour, other escapes and overstrike, and keeps the text" { - const gpa = std.testing.allocator; - const cases = [_][2][]const u8{ - .{ "\x1b[33mcommit abc\x1b[m\n", "commit abc\n" }, - .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, - .{ "N\x08NA\x08AM\x08ME\x08E _\x08u", "NAME u" }, - .{ "plain\ttext\n", "plain\ttext\n" }, - .{ "\x1b(Bdone", "done" }, - .{ "a\r\nb\r\n", "a\nb\n" }, - .{ "10%\r50%\r100%\ndone\n", "100%\ndone\n" }, - .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, - }; - for (cases) |c| { - const got = try stripEscapes(gpa, c[0]); - defer gpa.free(got); - try std.testing.expectEqualStrings(c[1], got); + // CAN ends an escape the cut left half sent, and SGR 0 its colour, + // so the note is never swallowed or tinted. + const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + try raw.appendSlice(gpa, said); } + return raw.toOwnedSlice(gpa); } /// A forwarding failure in words, never an error's name: the ones this @@ -693,7 +612,7 @@ fn nativeMain(init: std.process.Init) !void { const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err); // The pane it went to, read on the open that asked (another // client's look meanwhile is not this one's): what --wait waits on. - const went = ninep_io.Client.ask(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); + const went = ninep_io.Client.ask(arena, parent.dial, look, command, "") catch |err| Refuse.with(init.io, word, err); var rows = std.mem.tokenizeAny(u8, went, " \n"); if (rows.next()) |row| made_serial = std.fmt.parseInt(u32, row, 10) catch null; } else { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index cd8bc6c9..d4751191 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -650,7 +650,8 @@ pub fn readRoot(p: *Pardes, req: Req) Reply { /// /pager, `pardes -`'s: the directory written (empty, or not absolute: the /// session's) gets its one +Pager, made or emptied; the serial is what a -/// read of this same open answers, never another client's. +/// read of this same open answers, never another client's. What the open +/// writes after that line is the text, held by tree.zig for `fillPager`. pub fn writePager(p: *Pardes, req: Req) Reply { // A refused write leaves its open no answer, not the last one's. p.fs.results_len = 0; @@ -690,6 +691,35 @@ pub fn writePager(p: *Pardes, req: Req) Reply { return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } +/// The text a /pager open wrote after its directory (`held`), a program's +/// output for a terminal, put in the +Pager `serial` as `pardes -` once +/// wrote it to the body: through ghostty-vt (pager.zig), its colours kept +/// as the pane's spans unless PagerColor is off, one undo step, and left +/// clean. Reads of the pane are its plain text. The held bytes go either way. +pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfMemory}!void { + if (held.items.len == 0) return; + defer held.clearAndFree(p.gpa); + const id = p.paneBySerial(serial) orelse return; + const pane = p.panes[id].?; + const f = if (pane.file) |*file| file else return; + const page = try pardes.pager.parse(p.gpa, held.items, p.settings.pager_color); + held.clearAndFree(p.gpa); + if (page.text.len == 0 and f.content.len == 0) return page.deinit(p.gpa); + if (!pane.fs.nomark) panes.File.pushUndo(p, pane); + panes.File.setContent(p, f, page.text); + f.pager_spans = page.spans; + f.saved_revision = f.revision; +} + +/// The editor's step: the text of /pager opens closed unread goes in. +pub fn fillClosedPagers(p: *Pardes) void { + for (p.fs.pages.items) |*page| { + fillPager(p, page.serial, &page.bytes) catch {}; + page.bytes.deinit(p.gpa); + } + p.fs.pages.clearRetainingCapacity(); +} + /// One session builtin a line, at whichever pane has the keyboard as each /// runs, as the root's look and exec click there; all are checked first. pub fn writeRoot(p: *Pardes, req: Req) Reply { @@ -4088,21 +4118,26 @@ test "pager answers its +Pager on the open that asked, whatever another client e // `pardes -` once read, and wrote its text into. try testing.expect(!std.mem.eql(u8, want, rd(p, exec, 0, 64).bytes)); try testing.expectEqualStrings(want, call(p, .{ .tag = 5, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); - // Refused, the same open answers nothing, not its last answer. - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .write, .node = pager, .handle = asked, .data = "relative\n" }).errno()); - try testing.expectEqualStrings("", call(p, .{ .tag = 7, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + _ = call(p, .{ .tag = 6, .op = .release, .node = pager, .handle = asked, .opened = true }); + // Refused, an open answers nothing, not the session's last answer. + const refused = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 2 }).reply.handle; + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = refused, .data = "relative\n" }).errno()); + try testing.expectEqualStrings("", call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = refused, .size = 64 }).bytes); + _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = refused, .opened = true }); // Resolved: `/tmp/../tmp/.` is /tmp's +Pager, the one made above. - const again = call(p, .{ .tag = 8, .op = .open, .node = pager, .omode = 2 }).reply.handle; - try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = again, .data = "/tmp/../tmp/.\n" }).reply.status); - try testing.expectEqualStrings(want, call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = again, .size = 64 }).bytes); - _ = call(p, .{ .tag = 9, .op = .release, .node = pager, .handle = again }); + const resolved = call(p, .{ .tag = 11, .op = .open, .node = pager, .omode = 2 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 12, .op = .write, .node = pager, .handle = resolved, .data = "/tmp/../tmp/.\n" }).reply.status); + try testing.expectEqualStrings(want, call(p, .{ .tag = 13, .op = .read, .node = pager, .handle = resolved, .size = 64 }).bytes); + _ = call(p, .{ .tag = 14, .op = .release, .node = pager, .handle = resolved, .opened = true }); // One that may not be written is refused, permission denied. try testing.expectEqual(E.PERM, wr(p, pager, "/proc/1\n").errno()); // One directory a write, absolute, and there. try testing.expectEqual(E.INVAL, wr(p, pager, "/a\n/b\n").errno()); - // A second line on an open that asked already, as a mount sends two. + // One directory an open: one refused is not followed by another, as a + // mount sends two lines in two writes. (After one taken, what follows + // is the paged text: the test below.) const twice = call(p, .{ .tag = 20, .op = .open, .node = pager, .omode = 2 }).reply.handle; - try testing.expectEqual(Status.ok, call(p, .{ .tag = 21, .op = .write, .node = pager, .handle = twice, .data = "/tmp\n" }).reply.status); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 21, .op = .write, .node = pager, .handle = twice, .data = "relative\n" }).errno()); try testing.expectEqual(E.INVAL, call(p, .{ .tag = 22, .op = .write, .node = pager, .handle = twice, .data = "/tmp\n" }).errno()); _ = call(p, .{ .tag = 23, .op = .release, .node = pager, .handle = twice }); const relative = wr(p, pager, "relative\n"); @@ -4112,6 +4147,54 @@ test "pager answers its +Pager on the open that asked, whatever another client e try testing.expectEqual(E.NOTDIR, wr(p, pager, "/etc/passwd\n").errno()); } +test "what a /pager open writes after its directory is the text: plain in the body, its colours the pane's, clean, in by the read" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const pager = @intFromEnum(tree.TopFile.pager); + const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; + // The directory and the text's start in one write, escapes and all, a + // second line no directory; the rest in writes after it. + try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = pager, .handle = asked, .data = "/tmp\n\x1b[31mred\x1b[m /a\n" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = pager, .handle = asked, .data = "\x1b]0;title\x07N\x08Next\r\n" }).reply.status); + const id = for (p.panes, 0..) |slot, i| { + const pn = slot orelse continue; + if (pn.file) |f| if (std.mem.eql(u8, f.path, "/tmp/+Pager")) break i; + } else return error.NoPager; + const pn = p.panes[id].?; + try testing.expectEqualStrings("", pn.file.?.content); + // The read that answers the pane finds the text in. + var line: [16]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{pn.serial}), call(p, .{ .tag = 4, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + _ = call(p, .{ .tag = 5, .op = .release, .node = pager, .handle = asked, .opened = true }); + const f = &pn.file.?; + try testing.expectEqualStrings("red /a\nNext\n", f.content); + try testing.expectEqualStrings("red /a\nNext\n", rd(p, Node.of(pn.serial, .body), 0, 64).bytes); + try testing.expectEqual(f.revision, f.saved_revision); + try testing.expectEqual(@as(usize, 2), f.pager_spans.len); + try testing.expectEqualStrings("red", f.content[f.pager_spans[0].start..f.pager_spans[0].end]); + try testing.expectEqual(pardes.Color{ .index = 1 }, f.pager_spans[0].style.fg); + try testing.expect(f.pager_spans[1].style.bold); + // One undo step back to the empty pane. + try testing.expect(f.history.undo_len > 0); + try testing.expectEqualStrings("", f.history.undo[f.history.undo_len - 1].content); + // An edit drops the colours (pager.zig's ponytail). + try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = Node.of(pn.serial, .body), .data = "more\n" }).reply.status); + try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + + // PagerColor off, and an open closed with no read: the same text, plain, + // in at the editor's next step (a close through a mount never waits). + p.settings.pager_color = false; + const shut = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 1 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = shut, .data = "/tmp\n" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 9, .op = .write, .node = pager, .handle = shut, .data = "\x1b[1;32mgreen\x1b[m\n" }).reply.status); + _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = shut, .opened = true }); + try testing.expectEqualStrings("", f.content); + fillClosedPagers(p); + try testing.expectEqualStrings("green\n", f.content); + try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + try testing.expectEqual(f.revision, f.saved_revision); +} + test "a command pane an exec open was answered is leased to it while it stays open: another client's command gets a pane of its own" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 40543ecf..5499a337 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -89,6 +89,7 @@ pub fn needsQuiet(p: *Pardes, req: Req) bool { return switch (req.op) { .write, .setattr => true, .release => req.remove or holdsLines(p, req), + .read => holdsPage(p, req), else => false, }; } @@ -99,8 +100,9 @@ pub fn changesPane(p: *Pardes, req: Req) bool { return switch (req.op) { .write, .setattr => true, .open => req.node == @intFromEnum(TopFile.new), - .release => req.remove or holdsLines(p, req), - .lookup, .getattr, .read, .readdir => false, + .release => req.remove or holdsLines(p, req) or holdsPage(p, req), + .read => holdsPage(p, req), + .lookup, .getattr, .readdir => false, }; } @@ -138,6 +140,10 @@ pub const Open = struct { /// `/listeners`, a ctl opened to read) frozen at the open, as /// `/screen` is: reads in several chunks never splice two moments. frozen: []const u8, + /// A /pager open past its directory line: the +Pager's serial, the + /// text after that line held in `pending` until its read puts it + /// in (ctl.fillPager), or its close hands it to the editor's step. + pager: u32, } = .{ .snapshot = null }, /// What a write to a file of command lines left unfinished: a last line /// with no newline yet, or an Edit block still open. A write through a @@ -194,7 +200,7 @@ pub const Open = struct { gpa.free(run.line); }, .frozen => |bytes| gpa.free(bytes), - .event, .pty_data, .ctl, .lines, .writes => {}, + .event, .pty_data, .ctl, .lines, .writes, .pager => {}, } o.pending.deinit(gpa); if (o.replay) |r| gpa.free(r.bytes); @@ -899,7 +905,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { pn.fs.event_reader = pn.fs.event_reader or reader; }, .pty_data => pane_of.?.fs.pty_reader = true, - .run, .ctl, .lines, .writes => {}, + .run, .ctl, .lines, .writes, .pager => {}, } return .{ .tag = req.tag, .handle = @intCast(i + 1) }; } @@ -961,6 +967,12 @@ fn releaseHandle(p: *Pardes, req: Req) void { if (t == .col and t.col.file == .tag) cols.released(p, t.col.serial); if (t == .top and t.top == .tag) cols.released(p, null); const o = openOf(p, req) orelse return; + // A /pager open's text, not read for, goes in at the editor's next + // step (ctl.fillClosedPagers): this close need not wait for quiet. + if (o.what == .pager and o.pending.items.len > 0) { + p.fs.pages.append(p.gpa, .{ .serial = o.what.pager, .bytes = o.pending }) catch o.pending.deinit(p.gpa); + o.pending = .empty; + } // The last line an open wrote with no newline after it runs now. if (o.pending.items.len > 0) { const rest = p.scratch.allocator().dupe(u8, o.pending.items) catch ""; @@ -990,7 +1002,7 @@ fn releaseHandle(p: *Pardes, req: Req) void { .ctl => if (pn.fs.lock == req.handle) { pn.fs.lock = null; }, - .snapshot, .log, .lines, .writes, .frozen => {}, + .snapshot, .log, .lines, .writes, .frozen, .pager => {}, }; o.deinit(p.gpa); } @@ -1014,6 +1026,8 @@ fn setattr(p: *Pardes, req: Req, target: Target) Reply { } fn read(p: *Pardes, req: Req, target: Target) Reply { + // A /pager open's text goes in before its read answers the pane. + if (openOf(p, req)) |o| if (o.what == .pager) ctl.fillPager(p, o.what.pager, &o.pending) catch return Reply.fail(req.tag, E.NOMEM); // A listing reads what it was at the open. if (openOf(p, req)) |o| if (o.what == .frozen) { const bytes = o.what.frozen; @@ -1158,7 +1172,7 @@ fn linesOpen(target: Target, req: Req) bool { /// A release that will run a line its open held back. fn holdsLines(p: *Pardes, req: Req) bool { const o = openOf(p, req) orelse return false; - return o.pending.items.len > 0; + return o.pending.items.len > 0 and o.what != .pager; } /// A line held back longer than this is refused rather than kept growing. @@ -1173,7 +1187,39 @@ fn ctlFile(target: Target) bool { }; } +/// /pager on an open: its first line names the directory and runs as any +/// line does; what follows it, in that write and the open's later ones, is +/// a program's output, escapes and all, held whole and never run as lines. fn write(p: *Pardes, req: Req, target: Target) Reply { + const o = (if (target == .top and target.top == .pager) openOf(p, req) else null) orelse return writeLines(p, req, target); + if (o.what == .pager) { + if (o.pending.items.len + req.data.len > pager_cap) return failText(req.tag, E.NOSPC, "pager: no space: the text is over a file's limit"); + o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + } + const nl = std.mem.indexOfScalar(u8, req.data, '\n') orelse return writeLines(p, req, target); + var head = req; + head.data = req.data[0 .. nl + 1]; + const reply = writeLines(p, head, target); + if (reply.status != .ok or o.results.len == 0) return reply; + o.what = .{ .pager = o.results.list[0] }; + o.pending.clearRetainingCapacity(); + o.pending.appendSlice(p.gpa, req.data[nl + 1 ..]) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +/// The most a /pager open holds: a file's limit, and `pardes -`'s note +/// that its stdin was cut there. +const pager_cap = @import("../memory.zig").limits.max_file_bytes + 4096; + +/// A /pager open holding text: its read puts it in (ctl.fillPager), its +/// close hands it to the editor's step. +pub fn holdsPage(p: *Pardes, req: Req) bool { + const o = openOf(p, req) orelse return false; + return o.what == .pager and o.pending.items.len > 0; +} + +fn writeLines(p: *Pardes, req: Req, target: Target) Reply { // A command line holds no control character but a tab: the whole write // is refused at once, not held to fail unseen at the close. if (resultsFile(target) or ctlFile(target)) for (req.data) |c| if ((c < ' ' and c != '\t' and c != '\n' and c != '\r') or c == 0x7f) return failText(req.tag, E.INVAL, ctl.e_control); diff --git a/src/pager.zig b/src/pager.zig new file mode 100644 index 00000000..30418623 --- /dev/null +++ b/src/pager.zig @@ -0,0 +1,373 @@ +//! A program's output, paged into a +Pager (`pardes -`): the text it +//! prints, and its SGR colours as spans over that text. ghostty-vt, which +//! terminal panes already drive, parses every escape; this keeps what is +//! printed and how SGR styles it, and drops every other control (cursor +//! motion, OSC titles and hyperlinks, modes). The spans are display state +//! of the pane only: no 9P file reads them (File.recolorSyntax draws them). +const std = @import("std"); +const pardes = @import("pardes.zig"); +const CellStyle = @import("surface.zig").CellStyle; +const ghostty_vt = if (pardes.terminal_panes) @import("ghostty-vt") else struct {}; + +/// Bytes `start..end` of the text, drawn in `style`. A palette colour stays +/// `.index`, resolved through the theme as it is drawn (terminal.palColor), +/// and `.default` is the pane's own. +pub const Span = struct { start: u32, end: u32, style: CellStyle }; + +/// ponytail: past this many spans the rest of a page is plain, rather than +/// ~100 MB of spans for a 256 MiB coloured log; a packed style if it matters. +pub const max_spans = 4 << 20; + +pub const Page = struct { + text: []u8, + spans: []Span, + + pub fn deinit(page: Page, gpa: std.mem.Allocator) void { + gpa.free(page.text); + gpa.free(page.spans); + } +}; + +/// `raw`, a program's output for a terminal, as text and, `colour` on +/// (PagerColor), its spans. Both are `gpa`'s. +pub fn parse(gpa: std.mem.Allocator, raw: []const u8, colour: bool) !Page { + // ponytail: no ghostty-vt on esp32p4 (no terminal panes, no PAGER): + // the text is taken as sent. + if (comptime !pardes.terminal_panes) return .{ .text = try gpa.dupe(u8, raw), .spans = &.{} }; + var h: Handler = .{ .gpa = gpa, .colour = colour }; + errdefer h.text.deinit(gpa); + errdefer h.spans.deinit(gpa); + try h.text.ensureTotalCapacity(gpa, raw.len); + var stream: ghostty_vt.Stream(*Handler) = .init(&h); + defer stream.deinit(); + stream.nextSlice(raw); + if (h.failed) return error.OutOfMemory; + const text = try h.text.toOwnedSlice(gpa); + errdefer gpa.free(text); + return .{ .text = text, .spans = try h.spans.toOwnedSlice(gpa) }; +} + +const Handler = struct { + gpa: std.mem.Allocator, + colour: bool, + text: std.ArrayList(u8) = .empty, + spans: std.ArrayList(Span) = .empty, + /// What SGR has set so far. + style: CellStyle = .{}, + /// Where the line being printed starts, and its last character. + line_start: usize = 0, + last: usize = 0, + /// A carriage return not yet followed by a newline: the line starts + /// over at the next print, as on a terminal, so a progress line keeps + /// its last state. + cr: bool = false, + /// A backspace: the next print strikes over the character before it. + bs: bool = false, + failed: bool = false, + + const Action = ghostty_vt.StreamAction; + + pub fn vt(h: *Handler, comptime action: Action.Tag, value: Action.Value(action)) void { + switch (action) { + .print => h.print(value.cp), + .print_slice => h.printRun(value.cps), + // CSI b repeats the last character, as a terminal draws it; + // a terminal stops at its edge, and this at a line's worth. + .print_repeat => if (h.text.items.len > h.last) { + const cp = std.unicode.utf8Decode(h.text.items[h.last..]) catch return; + for (0..@min(value, 1024)) |_| h.print(cp); + }, + .set_attribute => if (h.colour) h.attribute(value), + .linefeed => { + h.append("\n"); + h.line_start = h.text.items.len; + h.last = h.line_start; + h.cr = false; + h.bs = false; + }, + .carriage_return => h.cr = true, + .backspace => h.bs = h.text.items.len > h.line_start, + .horizontal_tab => for (0..@min(value, 64)) |_| h.print('\t'), + else => {}, + } + } + + pub fn deinit(_: *Handler) void {} + + // ponytail: bytes that are not UTF-8 reach here as U+FFFD (ghostty's + // decoder replaces them, as a terminal shows them); a raw-byte pass + // through the stream if a +Pager must keep them. + fn print(h: *Handler, cp: u21) void { + // A control a terminal acts on and never draws: ghostty's fast path + // hands those past 0x0f (CAN, DEL, the C1 set) on as printed text. + // A tab is HT's, printed here. + if ((cp < 0x20 and cp != '\t') or (cp >= 0x7f and cp < 0xa0)) return; + if (h.cr) { + h.text.shrinkRetainingCapacity(h.line_start); + h.cut(h.line_start); + h.last = h.line_start; + h.cr = false; + h.bs = false; + } + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(cp, &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; + if (h.bs) { + // A man page's overstrike: a character struck over itself is + // bold, one struck with `_` (either way round) is underlined; + // any other is replaced, as on a terminal. + h.bs = false; + const prev = h.text.items[h.last..]; + var struck = h.style; + if (std.mem.eql(u8, prev, buf[0..n])) { + struck.bold = true; + } else if (std.mem.eql(u8, prev, "_")) { + h.text.shrinkRetainingCapacity(h.last); + h.append(buf[0..n]); + struck.ul = .single; + } else if (cp == '_') { + struck.ul = .single; + } else { + h.text.shrinkRetainingCapacity(h.last); + h.cut(h.last); + h.last = h.text.items.len; + h.append(buf[0..n]); + h.span(h.last, h.style); + return; + } + h.cut(h.last); + h.span(h.last, struck); + return; + } + h.last = h.text.items.len; + h.append(buf[0..n]); + h.span(h.last, h.style); + } + + /// A run of printed characters (most of a page): the first as `print` + /// takes it, a pending return or backspace and all, the rest straight + /// on, as one span. A 256 MiB page goes through here. + fn printRun(h: *Handler, cps: []const u32) void { + if (cps.len == 0) return; + h.print(@intCast(cps[0])); + const rest = cps[1..]; + if (rest.len == 0) return; + var need: usize = 0; + for (rest) |cp| need += if (cp < 0x80) 1 else std.unicode.utf8CodepointSequenceLength(@intCast(cp)) catch 3; + h.text.ensureUnusedCapacity(h.gpa, need) catch { + h.failed = true; + return; + }; + const from = h.text.items.len; + for (rest) |cp| { + if (cp < 0x20 or (cp >= 0x7f and cp < 0xa0)) continue; + h.last = h.text.items.len; + if (cp < 0x80) { + h.text.appendAssumeCapacity(@intCast(cp)); + continue; + } + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(@intCast(cp), &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; + h.text.appendSliceAssumeCapacity(buf[0..n]); + } + h.span(from, h.style); + } + + fn append(h: *Handler, bytes: []const u8) void { + h.text.appendSlice(h.gpa, bytes) catch { + h.failed = true; + }; + } + + /// `from` to the text's end drawn in `style`: the span before it goes + /// on when it ends there in the same style. + fn span(h: *Handler, from: usize, style: CellStyle) void { + if (!h.colour or std.meta.eql(style, CellStyle{})) return; + const end: u32 = @intCast(h.text.items.len); + if (h.spans.items.len > 0) { + const tail = &h.spans.items[h.spans.items.len - 1]; + if (tail.end == from and std.meta.eql(tail.style, style)) { + tail.end = end; + return; + } + } + if (h.spans.items.len >= max_spans) return; + h.spans.append(h.gpa, .{ .start = @intCast(from), .end = end, .style = style }) catch { + h.failed = true; + }; + } + + /// No span reaches past `at` any more: the text there is gone. + fn cut(h: *Handler, at: usize) void { + while (h.spans.items.len > 0) { + const tail = &h.spans.items[h.spans.items.len - 1]; + if (tail.end <= at) return; + if (tail.start < at) { + tail.end = @intCast(at); + return; + } + _ = h.spans.pop(); + } + } + + fn attribute(h: *Handler, attr: ghostty_vt.Attribute) void { + const s = &h.style; + switch (attr) { + .unset => s.* = .{}, + .bold => s.bold = true, + // SGR 22 ends faint as well as bold. + .reset_bold => { + s.bold = false; + s.dim = false; + }, + .faint => s.dim = true, + .italic => s.italic = true, + .reset_italic => s.italic = false, + .underline => |u| s.ul = switch (u) { + .none => .off, + .single => .single, + .double => .double, + .curly => .curly, + .dotted => .dotted, + .dashed => .dashed, + }, + .blink => s.blink = true, + .reset_blink => s.blink = false, + .inverse => s.reverse = true, + .reset_inverse => s.reverse = false, + .invisible => s.invisible = true, + .reset_invisible => s.invisible = false, + .strikethrough => s.strikethrough = true, + .reset_strikethrough => s.strikethrough = false, + .direct_color_fg => |c| s.fg = .{ .rgb = .{ c.r, c.g, c.b } }, + .direct_color_bg => |c| s.bg = .{ .rgb = .{ c.r, c.g, c.b } }, + .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @intFromEnum(name) }, + .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @intFromEnum(name) }, + .@"256_fg" => |i| s.fg = .{ .index = i }, + .@"256_bg" => |i| s.bg = .{ .index = i }, + .reset_fg => s.fg = .default, + .reset_bg => s.bg = .default, + // A cell has no overline and no underline colour to take. + .overline, .reset_overline, .underline_color, .@"256_underline_color", .reset_underline_color, .unknown => {}, + } + } +}; + +// ---- tests ---- + +const testing = std.testing; + +/// The text `raw` pages to, and its spans as `text[start..end]=style` lines. +fn expectPage(raw: []const u8, text: []const u8, spans: []const struct { []const u8, CellStyle }) !void { + if (comptime !pardes.terminal_panes) return error.SkipZigTest; + const page = try parse(testing.allocator, raw, true); + defer page.deinit(testing.allocator); + try testing.expectEqualStrings(text, page.text); + for (spans, 0..) |want, i| { + if (i >= page.spans.len) { + std.debug.print("missing span {d}: \"{s}\"\n", .{ i, want[0] }); + return error.TestExpectedEqual; + } + const got = page.spans[i]; + try testing.expectEqualStrings(want[0], page.text[got.start..got.end]); + try testing.expectEqualDeep(want[1], got.style); + } + try testing.expectEqual(spans.len, page.spans.len); +} + +test "git log --color: the commit line yellow, the rest plain" { + try expectPage( + "\x1b[33mcommit 0123abc\x1b[m\x1b[33m (\x1b[m\x1b[1;36mHEAD -> \x1b[m\x1b[1;32mmain\x1b[m\x1b[33m)\x1b[m\nAuthor: a \n\n subject\n", + "commit 0123abc (HEAD -> main)\nAuthor: a \n\n subject\n", + &.{ + .{ "commit 0123abc (", .{ .fg = .{ .index = 3 } } }, + .{ "HEAD -> ", .{ .fg = .{ .index = 6 }, .bold = true } }, + .{ "main", .{ .fg = .{ .index = 2 }, .bold = true } }, + .{ ")", .{ .fg = .{ .index = 3 } } }, + }, + ); +} + +test "ls --color=always: 01;34 directories and 01;32 executables, reset by 0 and none" { + try expectPage( + "\x1b[0m\x1b[01;34mdir\x1b[0m\n\x1b[01;32mrun.sh\x1b[0m\nplain.txt\n", + "dir\nrun.sh\nplain.txt\n", + &.{ + .{ "dir", .{ .fg = .{ .index = 4 }, .bold = true } }, + .{ "run.sh", .{ .fg = .{ .index = 2 }, .bold = true } }, + }, + ); +} + +test "grep --color=always: the match, the file name and the separator, and EL dropped" { + try expectPage( + "\x1b[35m\x1b[Ka.txt\x1b[m\x1b[K\x1b[36m\x1b[K:\x1b[m\x1b[Kone \x1b[01;31m\x1b[Kfoo\x1b[m\x1b[K two\n", + "a.txt:one foo two\n", + &.{ + .{ "a.txt", .{ .fg = .{ .index = 5 } } }, + .{ ":", .{ .fg = .{ .index = 6 } } }, + .{ "foo", .{ .fg = .{ .index = 1 }, .bold = true } }, + }, + ); +} + +test "a man page's overstrike: bold and underline, and a stray backspace" { + try expectPage( + "N\x08NA\x08AM\x08ME\x08E _\x08u_\x08s x\x08_ a\x08b\x08\n", + "NAME us x b\n", + &.{ + .{ "NAME", .{ .bold = true } }, + .{ "us", .{ .ul = .single } }, + .{ "x", .{ .ul = .single } }, + }, + ); +} + +test "truecolor, 256 colours, background, italic, faint, inverse and curly underline" { + try expectPage( + "\x1b[38;2;255;128;0mo\x1b[48;5;236mb\x1b[0;3;2mi\x1b[7mr\x1b[0;4:3mc\x1b[m.\n", + "obirc.\n", + &.{ + .{ "o", .{ .fg = .{ .rgb = .{ 255, 128, 0 } } } }, + .{ "b", .{ .fg = .{ .rgb = .{ 255, 128, 0 } }, .bg = .{ .index = 236 } } }, + .{ "i", .{ .italic = true, .dim = true } }, + .{ "r", .{ .italic = true, .dim = true, .reverse = true } }, + .{ "c", .{ .ul = .curly } }, + }, + ); +} + +test "every other escape is dropped, and a stray or broken one loses no text after it" { + const cases = [_][2][]const u8{ + .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, + .{ "\x1b]0;title\x07\x1b[2J\x1b[H\x1b[?1049hdone\n", "done\n" }, + .{ "\x1b(Bdone", "done" }, + .{ "plain\ttext\n", "plain\ttext\n" }, + .{ "a\r\nb\r\n", "a\nb\n" }, + .{ "10%\r50%\r\x1b[K100%\ndone\n", "100%\ndone\n" }, + .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, + // Controls ghostty's fast path prints: CAN, FS, DEL and a C1. + .{ "x\x18y\x1cz\x7f!\u{85}?\n", "xyz!?\n" }, + // A broken CSI: its parameter bytes are eaten up to a final byte, as + // a terminal eats them; CAN abandons one, and the text goes on. + .{ "a\x1b[31;\x18b\x1b[m\n", "ab\n" }, + // An unknown SGR changes nothing; an ESC at the very end is dropped. + .{ "\x1b[99mz\x1b", "z" }, + }; + for (cases) |c| try expectPage(c[0], c[1], &.{}); +} + +test "bytes that are not UTF-8 page as U+FFFD, the text around them kept" { + try expectPage("caf\xe9 \xff\xfe ok\n", "caf\u{fffd} \u{fffd}\u{fffd} ok\n", &.{}); +} + +test "PagerColor off: the same text, no spans, overstrike included" { + if (comptime !pardes.terminal_panes) return error.SkipZigTest; + const page = try parse(testing.allocator, "\x1b[31mred\x1b[m N\x08N\n", false); + defer page.deinit(testing.allocator); + try testing.expectEqualStrings("red N\n", page.text); + try testing.expectEqual(@as(usize, 0), page.spans.len); +} + +test "a carriage return's rewrite takes the spans of what it rewrote with it" { + try expectPage("\x1b[31m10%\r\x1b[32m100%\x1b[m\n", "100%\n", &.{.{ "100%", .{ .fg = .{ .index = 2 } } }}); +} diff --git a/src/pardes.zig b/src/pardes.zig index c6850451..5d9f8606 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const ctlfs = @import("ninep/tree.zig"); pub const syntax = @import("syntax.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const pager = @import("pager.zig"); const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); @@ -496,6 +497,7 @@ test { _ = @import("recent.zig"); _ = @import("Presentation.zig"); _ = @import("animation.zig"); + _ = @import("pager.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4221,7 +4223,8 @@ pub const Options = struct { file: ?[]const u8 = null, file_line: usize = 0, missing: ?struct { word: []const u8, dir: []const u8 } = null, - /// `pardes -`: stdin, its escapes stripped, for a +Pager pane at boot. + /// `pardes -`: stdin as it came, for a +Pager pane at boot (pager.zig + /// parses it). stdin_text: ?[]const u8 = null, tty_toggle: u21 = config.tty_toggle_default, /// load a dump of another instance instead of spawning shells (acme -l) @@ -4638,7 +4641,9 @@ pub const Pardes = struct { p.oneColumn(); }, .stdin => { - const content = try gpa.dupe(u8, opts.stdin_text.?); + const page = try pager.parse(gpa, opts.stdin_text.?, p.settings.pager_color); + errdefer gpa.free(page.spans); + const content = page.text; errdefer gpa.free(content); const dir = p.sessionDir(); const shown = try panes.Output.open(p, 0, dir, .{ .cmd = .New }, "", content); @@ -4647,6 +4652,7 @@ pub const Pardes = struct { gpa.free(shown.file.?.path); shown.file.?.path = named; shown.file.?.pager_diff = panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]); + shown.file.?.pager_spans = page.spans; p.oneColumn(); }, .embedded => { @@ -5748,6 +5754,8 @@ pub const Pardes = struct { if (v.now) |clock| p.advance(clock(h.ctx)); // What a 9P open wrote in a row goes in once the writes pause. ctlfs.pane.flushPausedBatch(p); + // ...and what a /pager open was written before its close. + ctlfs.ctl.fillClosedPagers(p); while (p.nextQueued()) |ev| p.update(ev); while (p.nextEffect()) |e| p.perform(e); turn.settle(); diff --git a/test/fs.py b/test/fs.py index 8eed2e29..33abb835 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1529,6 +1529,26 @@ def test(binary, quic=False): log_now = client.read('/log').decode() assert f'\nnew {made_now} {root}/+Pager\n' in '\n' + log_now, log_now[-400:] assert f'\nrename {made_now} ' not in '\n' + log_now + # Its colours are the pane's, drawn and never read: the body is + # the plain text, and the screen shows `red` in the theme's red + # and `rgb` in the colour given, the rest in the pane's ink. + fed = subprocess.run([binary, '-'], cwd=root, env=env, + input=b'\x1b]0;title\x07\x1b[31mred\x1b[m \x1b[38;2;1;2;3mrgb\x1b[m plain\n', + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert fed.returncode == 0, fed.stderr + assert client.read(f'/pane/{made_now}/body') == b'red rgb plain\n' + screen = client.screen() + for row in range(screen['rows']): + cells = screen['cells'][row * screen['cols']:(row + 1) * screen['cols']] + text = ''.join(cell[0] for cell in cells) + at = text.find('red rgb plain') + if at >= 0: + break + else: + raise AssertionError(('the paged text is not on the screen', screen)) + ink = [screen['styles'][cells[at + i][1]]['fg'] for i in (0, 4, 8)] + assert ink[1] == {'rgb': [1, 2, 3]}, ink + assert ink[0] != ink[2] and ink[0] != ink[1], ink # The directory's one +Pager: the next paged text refills it. fed = subprocess.run([binary, '-'], cwd=root, env=env, input=b'again\r\nprogress 10%\rprogress 100%\n', stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) diff --git a/test/selfmount.py b/test/selfmount.py index ddfb77dc..57dfffa8 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -182,6 +182,20 @@ def run(binary): log = client.read('/log').decode() check(log.count('over 1 MiB') == 1 and 'unknown control message' not in log and 'after-long' in log, 'a 1.1 MiB line is refused once, its tail never a line, the next line runs') + # `pardes -` by hand through the mount: the directory, then a + # program's output, escapes and all, on one open of /pager; the + # +Pager reads back the plain text. + got = run(f"{{ pwd; printf '\\033[31mred\\033[m\\n'; }} > {mount}/pager\n".encode()) + rows = [row.rsplit(maxsplit=1)[0].split(maxsplit=3) for row in client.read('/index').decode().splitlines()] + paged = [row[0] for row in rows if len(row) == 4 and row[3].endswith('/+Pager')] + check(got == '0' and len(paged) == 1, f'a +Pager made through the mount ({got!r}, {paged!r})') + if paged: + # The text goes in at the open's close, and a mount's close + # (FUSE's release) comes after close(2) has returned. + deadline = time.monotonic() + 5 + while (said := client.read(f'/pane/{paged[0]}/body')) != b'red\n' and time.monotonic() < deadline: + time.sleep(.05) + check(said == b'red\n', f'its body is the plain text ({said!r})') # Forty event reads held through the mount, a follower each, and # the mount still answers the rest: 9ns keeps workers past what # the editor holds (128), so `cat layout` is not queued behind diff --git a/test/snapshots/pagercolor.golden b/test/snapshots/pagercolor.golden new file mode 100644 index 00000000..811d3d96 --- /dev/null +++ b/test/snapshots/pagercolor.golden @@ -0,0 +1,120 @@ +== snap pager grid=100x50 cursor=4,5 +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/pagercolor/cwd Tty+bash Save Mode Filter Collapse Del +| $ printf '\033]0;title\007\033[31mred\033[m \033[1;32mbold green\033[m \033[38;2;200;100;0mrgb\033 +| [m \033[4mul\033[m N\bNA\bAM\bME\bE _\bu_\bs plain\n' | $(readlink /proc/$PPID/exe) - +| $ +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| /tmp/pardes-snap/pagercolor/cwd/+New Save Tty Collapse Del +| 1 +| +| +| +| +| +| +| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Collapse Del +| 1 red bold green rgb ul NAME us plain +| 2 +== style pager-colours grid=100x50 +|0: 0-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, +|2: 0-1 #000000,#add38a, 2-2 #000000,#314738, 3-34 #becfc4,#314738, 35-43 #dfbce5,#314738, 44-99 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|6: 0-0 d,#608269, 1-99 d,#0d1410, +|7: 0-0 d,#608269, 1-99 d,#0d1410, +|8: 0-0 d,#608269, 1-99 d,#0d1410, +|9: 0-0 d,#608269, 1-99 d,#0d1410, +|10: 0-0 d,#608269, 1-99 d,#0d1410, +|11: 0-0 d,#608269, 1-99 d,#0d1410, +|12: 0-0 d,#608269, 1-99 d,#0d1410, +|13: 0-0 d,#608269, 1-99 d,#0d1410, +|14: 0-0 d,#608269, 1-99 d,#0d1410, +|15: 0-0 d,#608269, 1-99 d,#0d1410, +|16: 0-0 d,#608269, 1-99 d,#0d1410, +|17: 0-0 d,#608269, 1-99 d,#0d1410, +|18: 0-0 d,#608269, 1-99 d,#0d1410, +|19: 0-0 d,#608269, 1-99 d,#0d1410, +|20: 0-0 d,#608269, 1-99 d,#0d1410, +|21: 0-0 d,#608269, 1-99 d,#0d1410, +|22: 0-0 d,#608269, 1-99 d,#0d1410, +|23: 0-0 d,#608269, 1-99 d,#0d1410, +|24: 0-0 d,#608269, 1-99 d,#0d1410, +|25: 0-0 d,#608269, 1-99 d,#0d1410, +|26: 0-0 d,#608269, 1-99 d,#0d1410, +|27: 0-0 d,#608269, 1-99 d,#0d1410, +|28: 0-0 d,#608269, 1-99 d,#0d1410, +|29: 0-0 d,#608269, 1-99 d,#0d1410, +|30: 0-0 d,#608269, 1-99 d,#0d1410, +|31: 0-0 d,#608269, 1-99 d,#0d1410, +|32: 0-0 d,#608269, 1-99 d,#0d1410, +|33: 0-0 d,#608269, 1-99 d,#0d1410, +|34: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-39 #d3b0d9,#1d2824, 40-99 #b2c3b8,#1d2824, +|35: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|36: 0-0 d,#608269, 1-99 d,#0d1410, +|37: 0-0 d,#608269, 1-99 d,#0d1410, +|38: 0-0 d,#608269, 1-99 d,#0d1410, +|39: 0-0 d,#608269, 1-99 d,#0d1410, +|40: 0-0 d,#608269, 1-99 d,#0d1410, +|41: 0-0 d,#608269, 1-99 d,#0d1410, +|42: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, +|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f1a39b,#0d1410, 11-20 #b6ce94,#0d1410,b 21-21 #b6ce94,#0d1410, 22-25 #c86400,#0d1410, 26-27 #e5eee5,#0d1410,u 28-28 #e5eee5,#0d1410, 29-32 #e5eee5,#0d1410,b 33-33 #e5eee5,#0d1410, 34-35 #e5eee5,#0d1410,u 36-99 #e5eee5,#0d1410, +|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|45: 0-0 d,#608269, 1-99 d,#0d1410, +|46: 0-0 d,#608269, 1-99 d,#0d1410, +|47: 0-0 d,#608269, 1-99 d,#0d1410, +|48: 0-0 d,#608269, 1-99 d,#0d1410, +|49: 0-0 d,#608269, 1-99 d,#0d1410, +== snap pager-diff grid=100x50 cursor=4,8 +|5: $ printf '\033[33mcommit 0123\033[33mabc\033[m\n\033[1mdiff --git a/x b/x\033[m\n\033[1m--- a/x\03 +|6: 3[m\n\033[1m+++ b/x\033[m\n\033[36m@@ -1 +1 @@\033[m\n\033[31m-old\033[m\n\033[32m+new\033[m\n' | +|7: $(readlink /proc/$PPID/exe) - +|8: $ +|43: 1 commit 0123abc +|44: 2 diff --git a/x b/x +|45: 3 --- a/x +|46: 4 +++ b/x +|47: 5 @@ -1 +1 @@ +|48: 6 -old +|49: 7 +new +== style pager-diff-colours grid=100x50 +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e9c680,#0d1410, +|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-24 #b9f480,#0d1410,b 25-99 #b9f480,#0d1410, +|45: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, +|46: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, +|47: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b6c59e,#0d1410, +|48: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #f1a39b,#302b25,b 8-99 #f8c082,#302b25, +|49: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-99 #b8d88a,#263025, diff --git a/test/snapshots/pagercolor.snap b/test/snapshots/pagercolor.snap new file mode 100644 index 00000000..650792b3 --- /dev/null +++ b/test/snapshots/pagercolor.snap @@ -0,0 +1,24 @@ +# `pardes -` keeps a program's colours (PagerColor, on by default): its SGR +# becomes the +Pager's own colours over the plain text (red through the +# theme's palette, truecolor as given, bold and underline, a man page's +# overstrike), and every other escape (the OSC title) is dropped. The +# needles waited for are split by escapes in the typed line, so only the +# paged text holds them. +start 50 100 +wait 8000 $ +stable 700 20000 +text printf '\033]0;title\007\033[31mred\033[m \033[1;32mbold green\033[m \033[38;2;200;100;0mrgb\033[m \033[4mul\033[m N\bNA\bAM\bME\bE _\bu_\bs plain\n' | $(readlink /proc/$PPID/exe) - +key enter +wait 20000 red bold green +stable 700 20000 +snap pager +snapstyle pager-colours +# A coloured diff: the rows pardes tints as added or removed are drawn as +# its own diff, and git's colours stay on the rest (the bold header, the +# cyan hunk line, the yellow commit line). +text printf '\033[33mcommit 0123\033[33mabc\033[m\n\033[1mdiff --git a/x b/x\033[m\n\033[1m--- a/x\033[m\n\033[1m+++ b/x\033[m\n\033[36m@@ -1 +1 @@\033[m\n\033[31m-old\033[m\n\033[32m+new\033[m\n' | $(readlink /proc/$PPID/exe) - +key enter +wait 20000 0123abc +stable 700 20000 +snap pager-diff +snapstyle pager-diff-colours -- cgit v1.3 From c5e5db988e59689b44feb42c59090c07687bcd42 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 10:45:57 -0300 Subject: `> exec` through a mount no longer hangs the editor, and a close holding a last line is answered at once: the line runs at the editor's next step A shell's truncating open of exec (or look, ctl, log, pager) sends a setattr that changes nothing; it waited for the editor to be quiet, and through a 9ns mount that quiet could never come: 9ns answers nothing else on the mount while the setattr is out, and the editor's step may be out reading a pane's file through it. This was the "truncating open of exec hangs, only in selfmount" mystery. Only a truncate of a pane's file or a tag waits now. A close holding a last line with no newline hands it to the editor's step (tree.runClosedLines, beside fillClosedPagers), as a /pager close does, and is answered at once; a refusal is the log's err. Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 5 ++-- src/fs.zig | 7 +++++ src/ninep/pane.zig | 1 + src/ninep/tree.zig | 76 +++++++++++++++++++++++++++++++++++++++++++++++------- src/pardes.zig | 2 ++ test/selfmount.py | 14 ++++++++-- 6 files changed, 92 insertions(+), 13 deletions(-) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 57df0c5f..cb345b00 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -266,7 +266,7 @@ pub const Listener = struct { const restores = pardes.turn.restores; // Asked first: a release that runs a held line has none after. const changes = pardes.ctlfs.changesPane(core, req); - const fills = pardes.ctlfs.holdsPage(core, req); + const fills = pardes.ctlfs.handsOff(core, req); const reply = core.serveFs(req); if (req.op == .release and quiet) l.collectOs(); // A read with nothing yet stays parked in the engine, and the core @@ -301,7 +301,8 @@ pub const Listener = struct { // whole after the wait. l.kick(); // A read that put a /pager open's text in (ctl.fillPager), or a - // close that handed it to the editor's step, waits on nothing the + // close that handed its text or last line to the editor's step + // (ctl.fillClosedPagers, tree.runClosedLines), waits on nothing the // editor performs: its answer goes now, while the turn still keeps // a read's payload whole. Waiting would hang a close through a // mount: 9ns answers nothing else on it while a clunk is out, and diff --git a/src/fs.zig b/src/fs.zig index 4a243b10..7a56d387 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1636,6 +1636,11 @@ pub const Namespace = struct { /// a close through a mount may not wait for the editor to be quiet, /// as 9ns answers nothing else on that mount while a clunk is out. pages: std.ArrayList(struct { serial: u32, bytes: std.ArrayList(u8) }) = .empty, + /// The last line each closed open wrote with no newline after it, with + /// the node it was written to, for the editor's step to run + /// (tree.runClosedLines): a close is answered at once, for the same + /// reason as `pages`. + closed_lines: std.ArrayList(struct { node: u64, bytes: std.ArrayList(u8) }) = .empty, batch: struct { serial: u32 = 0, node: u64 = 0, @@ -1685,6 +1690,8 @@ pub const Namespace = struct { for (&st.opens) |*o| o.deinit(gpa); for (st.pages.items) |*page| page.bytes.deinit(gpa); st.pages.deinit(gpa); + for (st.closed_lines.items) |*line| line.bytes.deinit(gpa); + st.closed_lines.deinit(gpa); st.log.deinit(gpa); st.out.deinit(gpa); } diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index e2ec31d1..c496571f 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1571,6 +1571,7 @@ test "a name cut across writes is one name, applied once at its newline or its c _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h3, .data = "/tmp/pardes-closed.txt" }); try testing.expectEqualStrings("/tmp/pardes-name.txt", nameOf(p, p.panes[p.paneBySerial(serial).?].?)); _ = call(p, .{ .tag = 3, .op = .release, .node = node, .handle = h3, .opened = true }); + tree.runClosedLines(p); try testing.expectEqualStrings("/tmp/pardes-closed.txt", nameOf(p, p.panes[p.paneBySerial(serial).?].?)); } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 5499a337..b0ffdd68 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -87,18 +87,34 @@ pub const features: cloud9.fs.Features = .{ .remove = true, .create = true }; /// so what parks here is never the syscall's own request. pub fn needsQuiet(p: *Pardes, req: Req) bool { return switch (req.op) { - .write, .setattr => true, - .release => req.remove or holdsLines(p, req), + .write => true, + .setattr => truncates(req), + .release => req.remove, .read => holdsPage(p, req), else => false, }; } +/// A setattr that changes something: a truncate of a pane's file or a +/// tag. `> exec` (a shell's truncating open) changes nothing, so it waits +/// on nothing: through a mount it hung, as 9ns answers nothing else on the +/// mount while it is out, and the editor's step may be out reading a pane's +/// file through that mount, the quiet it waited for never coming. +fn truncates(req: Req) bool { + if (!req.truncate) return false; + return switch (Node.target(req.node) orelse return false) { + .pane => true, + .col => |c| c.file == .tag, + .top => |f| f == .tag, + }; +} + /// `needsQuiet`, plus the open that makes a pane: what costs a frame and a /// wake of the editor. pub fn changesPane(p: *Pardes, req: Req) bool { return switch (req.op) { - .write, .setattr => true, + .write => true, + .setattr => truncates(req), .open => req.node == @intFromEnum(TopFile.new), .release => req.remove or holdsLines(p, req) or holdsPage(p, req), .read => holdsPage(p, req), @@ -973,13 +989,11 @@ fn releaseHandle(p: *Pardes, req: Req) void { p.fs.pages.append(p.gpa, .{ .serial = o.what.pager, .bytes = o.pending }) catch o.pending.deinit(p.gpa); o.pending = .empty; } - // The last line an open wrote with no newline after it runs now. + // The last line an open wrote with no newline after it runs at the + // editor's next step (runClosedLines), as a /pager open's text does. if (o.pending.items.len > 0) { - const rest = p.scratch.allocator().dupe(u8, o.pending.items) catch ""; - o.pending.clearRetainingCapacity(); - const w: Req = .{ .tag = req.tag, .op = .write, .node = req.node, .handle = req.handle, .data = rest }; - const reply = writeNow(p, w, t); - if (reply.status == .err) events.noteError(p, w, reply); + p.fs.closed_lines.append(p.gpa, .{ .node = req.node, .bytes = o.pending }) catch o.pending.deinit(p.gpa); + o.pending = .empty; } const of: ?*Pane = if (t == .pane) (if (p.paneBySerial(t.pane.serial)) |id| p.panes[id] else null) else null; if (of) |pn| switch (o.what) { @@ -1169,6 +1183,25 @@ fn linesOpen(target: Target, req: Req) bool { return req.omode & 3 != 0 or resultsFile(target); } +/// The editor's step: the last lines of closed opens run, each as a write +/// of its own; a refusal is the log's err, as no open is left to answer. +pub fn runClosedLines(p: *Pardes) void { + for (p.fs.closed_lines.items) |*line| { + defer line.bytes.deinit(p.gpa); + const t = Node.target(line.node) orelse continue; + const w: Req = .{ .tag = 0, .op = .write, .node = line.node, .data = line.bytes.items }; + const reply = writeNow(p, w, t); + if (reply.status == .err) events.noteError(p, w, reply); + } + p.fs.closed_lines.clearRetainingCapacity(); +} + +/// A close that hands its open's held text, a last line or a /pager's +/// page, to the editor's step: answered at once, never waiting on it. +pub fn handsOff(p: *Pardes, req: Req) bool { + return (req.op == .release and holdsLines(p, req)) or holdsPage(p, req); +} + /// A release that will run a line its open held back. fn holdsLines(p: *Pardes, req: Req) bool { const o = openOf(p, req) orelse return false; @@ -1806,6 +1839,24 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e try testing.expect(std.mem.indexOf(u8, made.reply.ename, said) != null); } +test "nothing a mount's close or a no-op truncate sends waits on the editor: a held line runs at its next step" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const exec = @intFromEnum(TopFile.exec); + // `> exec` truncates nothing; `> body` does. + try testing.expect(!needsQuiet(p, .{ .tag = 1, .op = .setattr, .node = exec, .truncate = true })); + try testing.expect(!changesPane(p, .{ .tag = 1, .op = .setattr, .node = exec, .truncate = true })); + try testing.expect(needsQuiet(p, .{ .tag = 1, .op = .setattr, .node = Node.of(serialOf(p), .body), .truncate = true })); + const h = call(p, .{ .tag = 2, .op = .open, .node = exec, .omode = 1 }).reply.handle; + _ = call(p, .{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "Msg at-step" }); + const close: Req = .{ .tag = 4, .op = .release, .node = exec, .handle = h, .opened = true }; + try testing.expect(!needsQuiet(p, close) and handsOff(p, close)); + _ = call(p, close); + try testing.expect(!th.logHas(p, " at-step\n")); + runClosedLines(p); + try testing.expect(th.logHas(p, " at-step\n")); +} + test "a command line cut across writes runs once whole, and the last runs at release; an Edit block waits for its end" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); @@ -1821,6 +1872,7 @@ test "a command line cut across writes runs once whole, and the last runs at rel try testing.expect(th.logHas(p, " hello\n") and th.logHas(p, " world\n")); try testing.expect(!th.logHas(p, " he\n") and !th.logHas(p, " tail\n")); _ = call(p, .{ .tag = 3, .op = .release, .node = exec, .handle = h, .opened = true }); + runClosedLines(p); try testing.expect(th.logHas(p, " tail\n")); // An Edit block's text lines come in later writes on the same open. const serial = serialOf(p); @@ -1829,6 +1881,7 @@ test "a command line cut across writes runs once whole, and the last runs at rel for ([_][]const u8{ "Edit ,a\n", "one\ntw", "o\n", ".\n" }) |piece| try testing.expectEqual(Status.ok, call(p, .{ .tag = 5, .op = .write, .node = ctl_node, .handle = c, .data = piece }).reply.status); _ = call(p, .{ .tag = 6, .op = .release, .node = ctl_node, .handle = c, .opened = true }); + runClosedLines(p); try testing.expectEqualStrings("x\none\ntwo\n", p.panes[0].?.file.?.content); } @@ -1878,6 +1931,7 @@ test "a write with no newline waits for its newline or the close, whatever its s try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = ctl_node, .handle = c, .data = "bogus" }).reply.status); try testing.expect(!th.logHas(p, "bogus")); _ = call(p, .{ .tag = 7, .op = .release, .node = ctl_node, .handle = c, .opened = true }); + runClosedLines(p); try testing.expect(th.logHas(p, "unknown control message \"bogus\"")); // A name: a NUL fails its write, not the close after it. const name = Node.of(serial, .name); @@ -1886,6 +1940,7 @@ test "a write with no newline waits for its newline or the close, whatever its s try testing.expectEqual(Status.err, bad.reply.status); try testing.expect(std.mem.indexOf(u8, bad.reply.ename, "a NUL") != null); try testing.expectEqual(Status.ok, call(p, .{ .tag = 12, .op = .release, .node = name, .handle = n, .opened = true }).reply.status); + runClosedLines(p); } test "look and exec read back what their own open's write touched; a fresh open reads the session's last" { @@ -1973,6 +2028,7 @@ test "an Edit block still open when its open closes fails there with an err and const c = call(p, .{ .tag = 1, .op = .open, .node = ctl_node, .omode = 1 }).reply.handle; _ = call(p, .{ .tag = 2, .op = .write, .node = ctl_node, .handle = c, .data = "Edit ,x/b/{\ni/[/\n" }); _ = call(p, .{ .tag = 3, .op = .release, .node = ctl_node, .handle = c, .opened = true }); + runClosedLines(p); try testing.expect(th.logHas(p, "unmatched")); try testing.expectEqualStrings("abc\n", p.panes[0].?.file.?.content); } @@ -1984,6 +2040,7 @@ test "an a, c or i text still open when its open closes fails there too and chan const c = call(p, .{ .tag = 1, .op = .open, .node = ctl_node, .omode = 1 }).reply.handle; _ = call(p, .{ .tag = 2, .op = .write, .node = ctl_node, .handle = c, .data = "Edit $a\nhalf of a block\n" }); _ = call(p, .{ .tag = 3, .op = .release, .node = ctl_node, .handle = c, .opened = true }); + runClosedLines(p); try testing.expect(th.logHas(p, "not ended by a . line")); try testing.expectEqualStrings("abc\n", p.panes[0].?.file.?.content); } @@ -1995,6 +2052,7 @@ test "an a, c or i text cut short through exec is an err in the log, not a msg" const c = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 1 }).reply.handle; _ = call(p, .{ .tag = 2, .op = .write, .node = exec, .handle = c, .data = "Edit $a\nhalf\n" }); _ = call(p, .{ .tag = 3, .op = .release, .node = exec, .handle = c, .opened = true }); + runClosedLines(p); var want: [64]u8 = undefined; try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "err {d} exec: Edit: a, c or i text not ended", .{serialOf(p)}))); try testing.expect(!th.logHas(p, "msg 1 Edit: a, c or i")); diff --git a/src/pardes.zig b/src/pardes.zig index 5d9f8606..612a09aa 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5756,6 +5756,8 @@ pub const Pardes = struct { ctlfs.pane.flushPausedBatch(p); // ...and what a /pager open was written before its close. ctlfs.ctl.fillClosedPagers(p); + // ...and the last line of an open closed with no newline after it. + ctlfs.runClosedLines(p); while (p.nextQueued()) |ev| p.update(ev); while (p.nextEffect()) |e| p.perform(e); turn.settle(); diff --git a/test/selfmount.py b/test/selfmount.py index 57dfffa8..8d78487d 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -196,6 +196,18 @@ def run(binary): while (said := client.read(f'/pane/{paged[0]}/body')) != b'red\n' and time.monotonic() < deadline: time.sleep(.05) check(said == b'red\n', f'its body is the plain text ({said!r})') + # `>`'s truncate of exec changes nothing and waits on nothing, + # and a last line with no newline runs once its open closes, at + # the editor's next step, the close answered at once. Either + # waiting on the editor hung: 9ns answers nothing else on the + # mount while a setattr or a clunk is out, and the step may be + # out reading a pane's file through it (the mounted index above). + got = run(f"for i in $(seq 40); do printf 'Msg held-%d' $i > {mount}/exec || exit 9; done\n".encode()) + deadline = time.monotonic() + 5 + while 'held-40\n' not in (log := client.read('/log').decode()) and time.monotonic() < deadline: + time.sleep(.05) + check(got == '0' and all(f' held-{i}\n' in log for i in range(1, 41)), + f'40 closes holding a last line each through the mount, all answered, every line run ({got!r})') # Forty event reads held through the mount, a follower each, and # the mount still answers the rest: 9ns keeps workers past what # the editor holds (128), so `cat layout` is not queued behind @@ -225,8 +237,6 @@ def run(binary): f'a bash read loop on event reads a whole record ({got_line!r})') # Past the session's 64 open records (write opens of exec take # them too) an open is refused EMFILE, "Too many open files". - # (>> here: a truncating open of exec through the mount can - # hang, reported, not yet understood.) many = Path(f'/tmp/{name}.many') ran = run((f"timeout 10 bash -c 'for i in $(seq 80); do exec {{fd}}>>{mount}/exec || exit 9; done' 2> {many}; " f"st=$?; echo rc=$st >> {many}; exit $st\n").encode()) -- cgit v1.3 From 805b9f188768fee523d462411d846912e0877ff3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 17:43:39 -0300 Subject: Edit runs acme's file and shell commands: < | > through the session's Shell off the loop (one undo step, a failure changes nothing, its stderr in +Errors, a 9P write answered when done), X and Y over the open text panes, b B D e r f w and the "file" address; checked against sam -d, and the reference's Edit section and Coming from acme row say so Co-Authored-By: Claude Opus 5.5 --- docs/typ/builtins-gui.json | 2 +- docs/typ/builtins-tty.json | 2 +- docs/typ/reference.typ | 43 ++- src/9p_io.zig | 7 + src/Pipe.zig | 63 ++-- src/builtins.zig | 35 +-- src/edit_cmd.zig | 487 +++++++++++++++++++++++++++++++ src/fs.zig | 3 + src/ninep/ctl.zig | 7 + src/pardes.zig | 50 +++- src/sam_edit.zig | 705 ++++++++++++++++++++++++++++++++++++++------- src/selection_pipe.zig | 90 +++++- test/fs.py | 59 ++++ 13 files changed, 1377 insertions(+), 176 deletions(-) create mode 100644 src/edit_cmd.zig (limited to 'src/fs.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 95eeaa07..b42f9c72 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -32,7 +32,7 @@ {"name": "DumpConfig", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the settings in effect, each a word to click, and the startup file's path."}, {"name": "DumpDir", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The directory Dump writes to and a relative Restore reads from; bare, the default."}, {"name": "DumpThemes", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the bundled themes into the config directory's themes, to edit."}, - {"name": "Edit", "leader": null, "also": [], "arg": true, "scope": "both", "setting": false, "choices": null, "doc": "acme's Edit: sam's command language over the pane's body, from a tag, a pane ctl or exec."}, + {"name": "Edit", "leader": null, "also": [], "arg": true, "scope": "both", "setting": false, "choices": null, "doc": "acme's Edit: sam's command language over the open text panes, from a tag, a pane ctl or exec, starting in the pane's body."}, {"name": "EffectCode", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Open the source of a panel transition or post shader, by name."}, {"name": "Exec", "leader": null, "also": ["tab", "middle-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Execute its argument as a middle click on it would, a builtin or a shell command."}, {"name": "Exit", "leader": "SPC q", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 887393ac..53bcf033 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -29,7 +29,7 @@ {"name": "DumpConfig", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the settings in effect, each a word to click, and the startup file's path."}, {"name": "DumpDir", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The directory Dump writes to and a relative Restore reads from; bare, the default."}, {"name": "DumpThemes", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the bundled themes into the config directory's themes, to edit."}, - {"name": "Edit", "leader": null, "also": [], "arg": true, "scope": "both", "setting": false, "choices": null, "doc": "acme's Edit: sam's command language over the pane's body, from a tag, a pane ctl or exec."}, + {"name": "Edit", "leader": null, "also": [], "arg": true, "scope": "both", "setting": false, "choices": null, "doc": "acme's Edit: sam's command language over the open text panes, from a tag, a pane ctl or exec, starting in the pane's body."}, {"name": "EffectCode", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Open the source of a panel transition or post shader, by name."}, {"name": "Exec", "leader": null, "also": ["tab", "middle-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Execute its argument as a middle click on it would, a builtin or a shell command."}, {"name": "Exit", "leader": "SPC q", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it."}, diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 5bcd8f6f..321860d6 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -98,8 +98,8 @@ own), never a C library string; a bad setting value is quoted, the value itself (`bad value in control message; takes on, off "maybe"`); a ctl refusal quotes the offending word alone (`wrong #args in control message "Newcol"`). Through 9ns the kernel sees an errno 9ns reads from those words (cloud9's `fs.enameErrno`): the first of these that the -words hold, case aside, wins, and anything else is EIO (`Modified`, an -#word("Edit") command pardes leaves out): +words hold, case aside, wins, and anything else is EIO (`Modified`, a +sam command pardes's #word("Edit") leaves out, `B #word("Edit") `` on a pane's #file("ctl") or #file("exec") (or the -root's, at the pane with the keyboard) runs acme's #word("Edit") on the body: addresses as -above, commands `x y g v c a i d s p = m t u` and `{ }`. All changes are -one undo step, applied only if every command succeeds; a failure changes -nothing and fails the write with acme's words (`Edit: no substitution`). -An `x` that finds nothing succeeds silently. `p` and `=` print to the -directory's `+Errors`. Not there: `b B D e r w f X Y`, `< | >`, -`\1`-`\9`. In `s`, `&` is the match (`\&` a literal); in `c`, `a`, `i` it -is a literal. `y` yields the stretch before the first match too. Braces -take a command a line, so a block goes on one open, in one write or +root's, at the pane with the keyboard) runs acme's #word("Edit") over the open text +panes, from that pane's body. Addresses are as above, and `"re"` is the one +open file whose line matches. Commands: + +- `x y g v c a i d s p = m t u` and `{ }`. +- `X`/`Y` run a command in each open file whose line (` +. /path`, `'` when + edited) matches, or does not: `X/'/w` writes every edited file. +- `b` makes a file current, `B` opens files, `D` closes panes (an edited one + on the second asking, as #word("Del")). +- `e` reads a file over the whole text and names the pane after it, `r` + over dot. `w` writes all of it, or the address, to its file or a name; + all of it to its own name leaves it clean. `f` names the pane and prints + its line. +- `cmd` sends dot to it and prints what it writes. + +Each command runs in its file's directory through #word("Shell"), off the +loop, so the editor goes on; the write that ran the Edit is answered when +they are done, and a line after it in the same write is refused. A command +that fails (an exit status, 10 seconds, 1 MiB of output) fails the Edit, its +stderr in `+Errors`. Each file's changes are one undo step, applied only if +every command succeeds; a failure changes nothing and fails the write with +acme's words (`Edit: no substitution`), as does a file edited while the +commands ran. An `x` that finds nothing succeeds silently. `p`, `=` and `>` +print to the directory's `+Errors`. Not there: `B /\\n}\\n' > $p/ctl") @@ -1040,7 +1059,7 @@ with Client(sys.argv[1]) as c: # a socket path, or (ip, port) [`Snarf`, `Cut`, `Paste`], [refused: the chords, #key("y"), #key("p")], [`Font`, `Send`, `ID`], [#word("Font"); #word("Repl") and #word("Exec"); `$winid`], [acme's other builtins], [refused: `Sort`, `Local`, `Abort` (plan9port's debugging word)], - [Edit], [no `< | >`, `X`, `Y`, `b B D e r w f`, no `\1`-`\9`; an alternation takes the first branch that matches, not the longest (#doc("fs", section: "edit"))], + [Edit], [every acme command but `B ` command changes nothing, where acme puts in what it wrote (#doc("fs", section: "edit"))], [`win`], [#word("Tty") is a VT terminal pane; #file("pty/run") runs a line at its prompt and answers `exit N` and the output; with #word("Repl") bound, #word("Exec") on a source pane types the text into it], [a directory window], [as acme's: a text pane named `dir/` (#file("index") kind `text`, #file("ctl") isdir 1), its entries in columns sorted bytewise, dotfiles shown, a directory's marked `/`; blanks pad the columns where acme's tabs do; a #word("Look") at an entry is from that directory, `Get` or a look at it again reads it again, and an edit is kept until then rather than lost to a resize; never dirty, #word("Save") refuses it; #word("DirLook") `terminal` types `ls` into a terminal there instead], [the plumber], [none: #word("Look") on an `http://` or `https://` URL runs `xdg-open` (`open` on macOS); files, addresses and directories follow built-in rules], diff --git a/src/9p_io.zig b/src/9p_io.zig index 68f6f6b7..671a1852 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -268,6 +268,9 @@ pub const Listener = struct { const changes = pardes.ctlfs.changesPane(core, req); const fills = pardes.ctlfs.handsOff(core, req); const reply = core.serveFs(req); + // Taken now: a request served while this one waits starts afresh. + const edit_at = core.fs.edit_answer_at; + core.fs.edit_answer_at = null; if (req.op == .release and quiet) l.collectOs(); // A close's held last line runs now when no step is out, so its err // is logged before the close is answered, as before; with a step @@ -346,6 +349,10 @@ pub const Listener = struct { } }; } + // An Edit whose `<`, `|` or `>` commands run off the loop: the write + // is answered once they have and the Edit is applied, or failed + // (late_failure), as `echo Edit , | sort > ctl` must return sorted. + if (edit_at) |n| if (l.core == core) pardes.turn.awaitEdit(n); core.fs.write_waits = false; // ponytail: one slot, so a failure of another client's effects that // settle in the same wait is told to this write too. diff --git a/src/Pipe.zig b/src/Pipe.zig index 48e98b7b..6981c023 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -8,6 +8,7 @@ const panes = @import("panes.zig"); const config = @import("config.zig"); const selection_pipe = @import("selection_pipe.zig"); const edit = @import("edit.zig"); +const edit_cmd = @import("edit_cmd.zig"); const Pane = panes.Pane; const Text = panes.Text; const Key = pardes.Key; @@ -18,6 +19,21 @@ const Pipe = @This(); seq: u32 = 0, /// The request in flight, and what it needs to apply its answer. wait: ?PendingPipe = null, +/// An Edit waiting on its `<`, `|` and `>` commands, which share the ids. +edit_run: ?*edit_cmd.Pending = null, +/// What an Edit's `w` took, for the `edit_write` effect to write. +writes: std.ArrayList(edit_cmd.Write) = .empty, + +pub fn deinit(pipe: *Pipe, gpa: std.mem.Allocator) void { + if (pipe.wait) |*wait| wait.deinit(gpa); + if (pipe.edit_run) |pending| { + pending.deinit(gpa); + // A 9P write waiting on it is answered (the core is going). + pardes.turn.editAnswered(); + } + for (pipe.writes.items) |*w| w.deinit(gpa); + pipe.writes.deinit(gpa); +} fn nextPipeEffect(p: *Pardes) ?u32 { while (p.nextEffect()) |effect| switch (effect) { @@ -164,6 +180,7 @@ pub fn pipeRequest(pipe: *const Pipe, id: u32) ?selection_pipe.Request { if (pipe.wait) |*wait| { if (wait.id == id) return wait.request(); } + if (pipe.edit_run) |pending| if (pending.id == id) return pending.request; return null; } @@ -172,26 +189,9 @@ fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?selection_pipe.Fai defer out.deinit(); const w = &out.writer; w.print("| {s}\n\n", .{wait.command}) catch return; - if (failure) |fail| { - if (wait.inputs.len > 1) - w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch return; - switch (fail.kind) { - .exit => w.print("exit status {d}\n", .{fail.code}) catch return, - .signal => w.writeAll("killed by a signal\n") catch return, - .timeout => w.print( - "still running after {d} seconds, and stopped\n", - .{selection_pipe.command_timeout_seconds}, - ) catch return, - .too_large => w.writeAll("produced more output than a filter may return\n") catch return, - .spawn => w.writeAll("could not be started\n") catch return, - .io => w.writeAll("could not be read\n") catch return, - } - if (fail.stderr.len > 0) w.print("\n{s}", .{fail.stderr}) catch return; - } else { - // No diagnosis at all: nobody ran it. The detached daemon, the - // browser and the board all leave `pipe` null on purpose. - w.writeAll("this session cannot run filters\n") catch return; - } + if (wait.inputs.len > 1) if (failure) |fail| + w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch return; + writeFailure(w, failure) catch return; const content = out.toOwnedSlice() catch return; const was = p.active; panes.Output.openErrors(p, wait.pane, content) catch |err| { @@ -203,6 +203,28 @@ fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?selection_pipe.Fai if (p.panes[was] != null) p.active = was; } +/// How a filter failed, a line, and the command's stderr after it: what +/// +Errors says of a `|` and of an Edit's `< | >`. +pub fn writeFailure(w: *std.Io.Writer, failure: ?selection_pipe.Failure) !void { + const fail = failure orelse { + // No diagnosis at all: nobody ran it. The detached daemon, the + // browser and the board all leave `pipe` null on purpose. + return w.writeAll("this session cannot run filters\n"); + }; + switch (fail.kind) { + .exit => try w.print("exit status {d}\n", .{fail.code}), + .signal => try w.writeAll("killed by a signal\n"), + .timeout => try w.print( + "still running after {d} seconds, and stopped\n", + .{selection_pipe.command_timeout_seconds}, + ), + .too_large => try w.writeAll("produced more output than a filter may return\n"), + .spawn => try w.writeAll("could not be started\n"), + .io => try w.writeAll("could not be read\n"), + } + if (fail.stderr.len > 0) try w.print("\n{s}", .{fail.stderr}); +} + fn pipeCut(wait: *const PendingPipe, content: []const u8, i: usize) ?struct { lo: usize, hi: usize } { const range = wait.ranges[i]; const lo = @min(range.anchor, range.head); @@ -240,6 +262,7 @@ pub fn pipeResponse( outputs: []const []const u8, failure: ?selection_pipe.Failure, ) void { + if (p.pipe.edit_run) |pending| if (pending.id == id) return edit_cmd.finish(p, success, outputs, failure); // A SUPERSEDED OR UNKNOWN id is the one silence worth keeping: it is // the answer to a question nobody is still asking. if (p.pipe.wait == null or p.pipe.wait.?.id != id) return; diff --git a/src/builtins.zig b/src/builtins.zig index da87ba37..ed6ac467 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -555,9 +555,9 @@ fn warnModified(c: Ctx, asking: Pane.Discarding) bool { /// Which panes a refusal asks about: every one (Exit, Restore), one (Del), /// or a column's (Delcol). -const Asked = union(enum) { all, pane: usize, column: usize }; +pub const Asked = union(enum) { all, pane: usize, column: usize }; -fn warnModifiedIn(c: Ctx, asking: Pane.Discarding, which: Asked) bool { +pub fn warnModifiedIn(c: Ctx, asking: Pane.Discarding, which: Asked) bool { // Every pane asked about is an `unsaved ` record, as // acme's rowclean names them all (wind.c:511); the refusal a write // gets names the one, or counts them, never a list cut short. @@ -1330,36 +1330,15 @@ pub const Togglettymode = struct { }; /// acme's Edit (exec.c `edit`, edit.c): sam's command language over the -/// pane's body, from a tag, a pane ctl or exec. One undo step; a failure -/// changes nothing and says why. src/sam_edit.zig has what is left out. +/// open text panes, from a tag, a pane ctl or exec, starting in the pane's +/// body. One undo step in each file it changes; a failure changes nothing +/// and says why. src/edit_cmd.zig runs it; src/sam_edit.zig has what is +/// left out. pub const Edit = struct { pub const takes_arg = true; pub const requires_arg = true; pub fn run(c: Ctx) void { - const sam = @import("sam_edit.zig"); - const ninep_pane = @import("ninep/pane.zig"); - const f = ninep_pane.fileOf(c.pane) orelse return c.p.reportFailure(c.id, "Edit: only a text pane is edited"); - const arena = c.p.scratch.allocator(); - var why: sam.Why = .{}; - var said: [260]u8 = undefined; - const res = sam.run(arena, f.content, ninep_pane.dotOf(c.pane), f.path, c.arg orelse "", &why) catch |err| switch (err) { - error.Edit => return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Edit: {s}", .{why.text()}) catch "Edit: failed"), - error.OutOfMemory => return c.p.reportError(c.id, "Edit", err), - }; - if (res.undo != 0) { - for (0..@abs(res.undo)) |_| if (res.undo > 0) panes.File.undo(c.p, c.pane) else panes.File.redo(c.p, c.pane); - return; - } - if (res.ops.len > 0) { - const new = sam.apply(c.p.gpa, f.content, res.ops) catch |err| return c.p.reportError(c.id, "Edit", err); - // `s/a/a/` changes nothing: no undo step, no new revision. - if (std.mem.eql(u8, new, f.content)) c.p.gpa.free(new) else { - panes.File.pushUndo(c.p, c.pane); - panes.File.setContent(c.p, f, new); - } - } - ninep_pane.setDot(c.pane, sam.moveDot(res.dot, res.ops)); - if (res.printed.len > 0) _ = ninep_pane.appendErrors(c.p, c.id, res.printed); + @import("edit_cmd.zig").run(c.p, c.id, c.arg orelse ""); } }; diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig new file mode 100644 index 00000000..7f5c6279 --- /dev/null +++ b/src/edit_cmd.zig @@ -0,0 +1,487 @@ +//! acme's Edit in the editor (exec.c `edit`, edit.c editcmd): the panes an +//! Edit sees and what it does to them. src/sam_edit.zig runs the commands +//! over the open text panes; here they are handed over, and what came of +//! them applied: each file's changes as one undo step, the dots, `w`'s +//! writes, the names `e` and `f` gave, `D`'s closes, and what was printed, +//! to +Errors. +//! +//! An Edit with `<`, `|` or `>` runs their commands off the loop, as the +//! `|` key's filter does (selection_pipe.zig, Pipe.zig): the commands go out +//! as one pipe request, each in its file's directory through the session's +//! Shell, and the Edit is applied when they have all answered -- or not at +//! all, when one fails or a file it changes was edited meanwhile. One Edit +//! waits at a time; a 9P write that ran it is answered when it is done +//! (9p_io, `fs.edit_answer_at`). +const std = @import("std"); +const pardes = @import("pardes.zig"); +const sam = @import("sam_edit.zig"); +const panes = @import("panes.zig"); +const layout = @import("layout.zig"); +const look = @import("look.zig"); +const builtins = @import("builtins.zig"); +const filesystem = @import("fs.zig"); +const selection_pipe = @import("selection_pipe.zig"); +const Pipe = @import("Pipe.zig"); +const ninep_pane = @import("ninep/pane.zig"); +const Pardes = pardes.Pardes; + +/// An Edit whose commands are running: what it came to, and the request +/// for them, all in `arena`. +pub const Pending = struct { + id: u32 = 0, + arena: std.heap.ArenaAllocator, + /// The pane the Edit ran from, which hears how it went. + origin: usize, + origin_serial: u32, + res: sam.Result = undefined, + /// Each file's pane serial and text revision when the Edit read it. + serials: []u32 = &.{}, + revisions: []u32 = &.{}, + request: selection_pipe.Request = undefined, + + pub fn deinit(pd: *Pending, gpa: std.mem.Allocator) void { + pd.arena.deinit(); + gpa.destroy(pd); + } +}; + +/// What `w` took, written by the `edit_write` effect (pardes.zig perform). +pub const Write = struct { + pane: u8, + serial: u32, + path: []u8, + bytes: []u8, + /// The pane comes clean if its text is still this revision. + clean: ?u32 = null, + /// A scratch written whole is that file from then on (exec.saveTo). + promote: bool = false, + + pub fn deinit(w: *Write, gpa: std.mem.Allocator) void { + gpa.free(w.path); + gpa.free(w.bytes); + } +}; + +/// `B`, `e` and `r` through the editor. +const World = struct { + p: *Pardes, + from: usize, + + fn open(ctx: *anyopaque, path: []const u8, why: *sam.Why) ?sam.File { + const w: *World = @ptrCast(@alignCast(ctx)); + const p = w.p; + if (comptime pardes.hosted) if (filesystem.localPath(path)) |local| if (@import("exec.zig").isDirectory(local)) + return said(sam.File, why, "B: {s} is a directory", .{path}); + // A look opens it, or finds it open, where a look would; the + // keyboard stays where the Edit ran. + const was = p.active; + look.lookAt(p, w.from, path); + if (p.panes[was] != null) p.active = was; + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const f = ninep_pane.fileOf(pane) orelse continue; + if (!std.mem.eql(u8, f.path, path)) continue; + return fileOf(pane, id); + } + return said(sam.File, why, "B: cannot open {s}", .{path}); + } + + fn read(ctx: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *sam.Why) ?[]const u8 { + const w: *World = @ptrCast(@alignCast(ctx)); + if (comptime pardes.hosted) if (filesystem.localPath(path)) |local| if (@import("exec.zig").isDirectory(local)) + return said([]const u8, why, "{s} is a directory", .{path}); + const bytes = filesystem.read(w.p, path) catch |err| { + const name = @errorName(err); + const words = if (std.mem.eql(u8, name, "FileNotFound")) + "file does not exist" + else if (std.mem.eql(u8, name, "AccessDenied") or std.mem.eql(u8, name, "PermissionDenied")) + "permission denied" + else + name; + return said([]const u8, why, "can't open {s}: {s}", .{ path, words }); + }; + defer w.p.gpa.free(bytes); + return arena.dupe(u8, bytes) catch return said([]const u8, why, "can't read {s}: out of memory", .{path}); + } + + fn said(comptime T: type, why: *sam.Why, comptime fmt: []const u8, args: anytype) ?T { + why.len = if (std.fmt.bufPrint(&why.buf, fmt, args)) |s| s.len else |_| 0; + return null; + } +}; + +fn fileOf(pane: *panes.Pane, id: usize) sam.File { + const f = ninep_pane.fileOf(pane).?; + return .{ + .name = f.path, + .text = f.content, + .dot = ninep_pane.dotOf(pane), + .dirty = ninep_pane.dirtyOf(pane), + .scratch = f.output != null, + .id = id, + }; +} + +/// `Edit command` from pane `id`, a text pane. +pub fn run(p: *Pardes, id: usize, command: []const u8) void { + const pane = p.panes[id] orelse return; + if (ninep_pane.fileOf(pane) == null) return p.reportFailure(id, "Edit: only a text pane is edited"); + // acme's Edit blocks the editor while its commands run; here the + // editor goes on, and a second Edit waits its turn. + if (p.pipe.edit_run != null) return p.reportFailure(id, "Edit: another Edit's commands are still running"); + const pd = p.gpa.create(Pending) catch |err| return p.reportError(id, "Edit", err); + pd.* = .{ .arena = .init(p.gpa), .origin = id, .origin_serial = pane.serial }; + var keep = false; + defer if (!keep) pd.deinit(p.gpa); + const arena = pd.arena.allocator(); + + // Every text pane, column by column as acme's allwindows goes, then any + // not in a column; the Edit starts in its own. + var files: std.ArrayList(sam.File) = .empty; + var cur: usize = 0; + var seen: [pardes.MAX_PANES]bool = @splat(false); + for (0..p.ncol) |c| { + for (p.col_panes[c][0..p.col_n[c]]) |slot| addFile(p, &files, arena, slot, id, &cur, &seen) catch |err| return p.reportError(id, "Edit", err); + } + for (0..pardes.MAX_PANES) |slot| addFile(p, &files, arena, slot, id, &cur, &seen) catch |err| return p.reportError(id, "Edit", err); + + var world: World = .{ .p = p, .from = id }; + var why: sam.Why = .{}; + var text: [260]u8 = undefined; + const res = sam.run(arena, files.items, cur, command, .{ .ctx = &world, .open = World.open, .read = World.read }, &why) catch |err| switch (err) { + error.Edit => return p.reportFailure(id, std.fmt.bufPrint(&text, "Edit: {s}", .{why.text()}) catch "Edit: failed"), + error.OutOfMemory => return p.reportError(id, "Edit", err), + }; + if (res.undo != 0) { + for (0..@abs(res.undo)) |_| if (res.undo > 0) panes.File.undo(p, pane) else panes.File.redo(p, pane); + return; + } + pd.res = res; + // What each file was, to know at the end that it still is. + pd.serials = arena.alloc(u32, res.files.len) catch |err| return p.reportError(id, "Edit", err); + pd.revisions = arena.alloc(u32, res.files.len) catch |err| return p.reportError(id, "Edit", err); + for (res.files, 0..) |f, i| { + const q = p.panes[f.id].?; + pd.serials[i] = q.serial; + pd.revisions[i] = q.file.?.revision; + } + if (res.jobs.len == 0) return commit(p, pd, &.{}); + + // The commands, as one pipe request: each with its input copied (the + // text may change while they run, and the Edit is then refused), in + // its file's directory. + const n = res.jobs.len; + const commands = arena.alloc([]const u8, n) catch |err| return p.reportError(id, "Edit", err); + const cwds = arena.alloc([]const u8, n) catch |err| return p.reportError(id, "Edit", err); + const inputs = arena.alloc(selection_pipe.Input, n) catch |err| return p.reportError(id, "Edit", err); + for (res.jobs, 0..) |job, i| { + const f = res.files[job.file]; + commands[i] = job.command; + cwds[i] = Pardes.paneDir(p.panes[f.id].?); + inputs[i] = .{ .bytes = if (job.c == '<') "" else arena.dupe(u8, f.text[job.q0..job.q1]) catch |err| return p.reportError(id, "Edit", err) }; + } + p.pipe.seq +%= 1; + pd.id = p.pipe.seq; + pd.request = .{ + .id = pd.id, + .command = commands[0], + .cwd = cwds[0], + .inputs = inputs, + .commands = commands, + .cwds = cwds, + .shell = arena.dupe(u8, p.shellBin()) catch |err| return p.reportError(id, "Edit", err), + }; + keep = true; + p.pipe.edit_run = pd; + p.emit(.{ .pipe = .{ .id = pd.id } }); + // A 9P write that ran it is answered once it is done. + if (p.fs.serving) p.fs.edit_answer_at = pardes.turn.edit_answers; +} + +fn addFile(p: *Pardes, files: *std.ArrayList(sam.File), arena: std.mem.Allocator, slot: usize, from: usize, cur: *usize, seen: *[pardes.MAX_PANES]bool) !void { + if (seen[slot]) return; + seen[slot] = true; + const pane = p.panes[slot] orelse return; + if (pane.file == null) return; + if (slot == from) cur.* = files.items.len; + try files.append(arena, fileOf(pane, slot)); +} + +/// The commands answered (pipe_resp): the Edit applied, or why not. +pub fn finish(p: *Pardes, success: bool, outputs: []const []const u8, failure: ?selection_pipe.Failure) void { + const pd = p.pipe.edit_run orelse return; + p.pipe.edit_run = null; + defer pd.deinit(p.gpa); + defer pardes.turn.editAnswered(); + const at = if (p.panes[pd.origin]) |pane| (if (pane.serial == pd.origin_serial) pd.origin else p.active) else p.active; + // Whatever fails from here fails the 9P write that ran it too. + const failures = p.fs.failures; + defer if (p.fs.failures != failures) p.noteLateFailure(at); + if (success and outputs.len == pd.res.jobs.len) return commit(p, pd, outputs); + + // Which command, in +Errors with its own words; the Edit changed nothing. + const job = if (failure) |f| (if (f.index < pd.res.jobs.len) pd.res.jobs[f.index] else pd.res.jobs[0]) else pd.res.jobs[0]; + var out: std.Io.Writer.Allocating = .init(p.gpa); + defer out.deinit(); + const w = &out.writer; + var line: [256]u8 = undefined; + report: { + w.print("Edit: {c} {s}\n\n", .{ job.c, job.command }) catch break :report; + if (pd.res.jobs.len > 1) if (failure) |f| w.print("command {d} of {d}: ", .{ f.index + 1, pd.res.jobs.len }) catch break :report; + const why_at = out.written().len; + Pipe.writeFailure(w, failure) catch break :report; + const why = std.mem.sliceTo(out.written()[why_at..], '\n'); + const said = std.fmt.bufPrint(&line, "Edit: {c} {s}: {s}", .{ job.c, job.command[0..@min(job.command.len, 120)], why }) catch "Edit: a command failed"; + _ = ninep_pane.appendErrors(p, at, out.written()); + return p.reportFailure(at, said); + } + p.reportFailure(at, "Edit: a command failed"); +} + +/// Apply what the Edit came to, `outputs` its jobs' answers: refused, all +/// of it, if a pane it changes is not the one it read any more. +fn commit(p: *Pardes, pd: *Pending, outputs: []const []const u8) void { + const res = pd.res; + const at = if (p.panes[pd.origin]) |pane| (if (pane.serial == pd.origin_serial) pd.origin else p.active) else p.active; + var text: [320]u8 = undefined; + for (res.files, 0..) |f, i| { + if (f.ops.items.len == 0 and !f.close and !f.renamed and !f.moved) continue; + const pane = p.panes[f.id] orelse return p.reportFailure(at, std.fmt.bufPrint(&text, "Edit: {s} closed while its commands ran; nothing changed", .{f.name}) catch "Edit: a pane closed"); + if (pane.serial != pd.serials[i]) return p.reportFailure(at, std.fmt.bufPrint(&text, "Edit: {s} closed while its commands ran; nothing changed", .{f.name}) catch "Edit: a pane closed"); + if (f.ops.items.len > 0 and pane.file.?.revision != pd.revisions[i]) + return p.reportFailure(at, std.fmt.bufPrint(&text, "Edit: {s} changed while its commands ran; nothing changed", .{f.name}) catch "Edit: a file changed"); + } + // `w`'s bytes, written after this step, before anything else is. + for (res.writes) |wr| { + const f = res.files[wr.file]; + const pane = p.panes[f.id].?; + const path = p.gpa.dupe(u8, wr.path) catch |err| return p.reportError(at, "Edit", err); + const bytes = p.gpa.dupe(u8, wr.bytes) catch |err| { + p.gpa.free(path); + return p.reportError(at, "Edit", err); + }; + const own = std.mem.eql(u8, wr.path, pane.file.?.path); + p.pipe.writes.append(p.gpa, .{ + .pane = @intCast(f.id), + .serial = pane.serial, + .path = path, + .bytes = bytes, + // Its own name, all of it, and nothing after the w changes it: + // clean, as acme's putfile leaves it. + .clean = if (own and wr.whole and !f.scratch and f.ops.items.len == 0) pane.file.?.revision else null, + .promote = wr.whole and f.scratch, + }) catch |err| { + p.gpa.free(path); + p.gpa.free(bytes); + return p.reportError(at, "Edit", err); + }; + } + if (res.writes.len > 0) p.emit(.edit_write); + for (res.files) |f| { + const pane = p.panes[f.id] orelse continue; + const pf = ninep_pane.fileOf(pane) orelse continue; + const ops = f.ops.items; + for (ops) |*o| if (o.job) |j| { + o.text = outputs[j]; + }; + if (ops.len > 0) { + const new = sam.apply(p.gpa, pf.content, ops) catch |err| return p.reportError(at, "Edit", err); + // `s/a/a/` changes nothing: no undo step, no new revision. + if (std.mem.eql(u8, new, pf.content)) p.gpa.free(new) else { + panes.File.pushUndo(p, pane); + panes.File.setContent(p, pf, new); + } + // e read its own file over it: what is on disk again. + if (f.clean) { + pf.saved_revision = pf.revision; + pf.disk_gone = false; + } + } + if (ops.len > 0 or f.moved) ninep_pane.setDot(pane, sam.moveDot(f.dot, ops)); + if (f.renamed) ninep_pane.nameBuffer(p, f.id, f.name, false) catch |err| p.reportError(f.id, "Edit", err); + } + // What was printed, `>`'s output in its place among it. + if (res.printed.len > 0 or outputs.len > 0) { + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var from: usize = 0; + for (res.jobs, 0..) |job, j| { + if (job.c != '>') continue; + out.appendSlice(p.gpa, res.printed[from..job.at]) catch return; + out.appendSlice(p.gpa, outputs[j]) catch return; + from = job.at; + } + out.appendSlice(p.gpa, res.printed[from..]) catch return; + if (out.items.len > 0) _ = ninep_pane.appendErrors(p, at, out.items); + } + // D's panes last, each as Del closes one: an edited one is warned about + // once, and closes on the next. + for (res.files) |f| { + if (!f.close) continue; + const pane = p.panes[f.id] orelse continue; + if (builtins.warnModifiedIn(.{ .p = p, .pane = pane, .id = f.id, .txt = "", .arg = null }, .Del, .{ .pane = f.id })) continue; + p.removePane(f.id, null) catch |err| p.reportError(f.id, "Edit", err); + } +} + +const testing = std.testing; +const th = @import("ninep/testing.zig"); +const tree = @import("ninep/tree.zig"); + +/// The answer of the Edit waiting on its commands: as a host's worker +/// brings it home, run for real when `real`. +fn answer(p: *Pardes, outputs: []const []const u8) void { + const pd = p.pipe.edit_run.?; + p.update(.{ .pipe_resp = .{ .id = pd.id, .success = true, .outputs = outputs } }); +} + +fn runReal(p: *Pardes) !void { + const pd = p.pipe.edit_run.?; + const job = try selection_pipe.Job.copy(testing.allocator, pd.request); + defer job.deinit(testing.allocator); + var response = selection_pipe.runJob(testing.allocator, testing.io, job); + defer response.deinit(testing.allocator); + p.update(.{ .pipe_resp = .{ .id = pd.id, .success = response.success, .outputs = response.outputs, .failure = response.failure } }); +} + +fn errorsText(p: *Pardes) ?[]const u8 { + for (p.panes) |slot| { + const q = slot orelse continue; + const qf = q.file orelse continue; + const o = qf.output orelse continue; + if (std.meta.activeTag(o.from) == .errors) return qf.content; + } + return null; +} + +test "Edit , | sort runs off the loop, through the session's shell in the file's directory, and is one undo step" { + const p = try th.withFile(testing.allocator, "b\na\nc\n"); + defer p.deinit(); + const serial = th.serialOf(p); + const answers = pardes.turn.edit_answers; + try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(serial, .ctl), "Edit , | sort\n").reply.status); + // Nothing changed yet: the command is out. + try testing.expectEqualStrings("b\na\nc\n", p.panes[0].?.file.?.content); + const req = p.pipe.pipeRequest(p.pipe.edit_run.?.id).?; + try testing.expectEqualStrings("sort", req.commands[0]); + try testing.expectEqualStrings("b\na\nc\n", req.inputs[0].bytes); + try testing.expectEqualStrings("/", req.cwds[0]); + try testing.expectEqualStrings(p.shellBin(), req.shell); + // A second Edit waits its turn rather than run beside it. + try testing.expectEqual(tree.E.IO, th.wr(p, tree.Node.of(serial, .ctl), "Edit ,d\n").errno()); + answer(p, &.{"a\nb\nc\n"}); + try testing.expect(p.pipe.edit_run == null); + try testing.expectEqual(answers +% 1, pardes.turn.edit_answers); + try testing.expectEqualStrings("a\nb\nc\n", p.panes[0].?.file.?.content); + try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(serial, .ctl), "Undo\n").reply.status); + try testing.expectEqualStrings("b\na\nc\n", p.panes[0].?.file.?.content); + // What follows it in the same write would run before its commands + // answer: refused, and the Edit goes on. + const after = th.wr(p, tree.Node.of(serial, .ctl), "Edit , | sort\nSave\n"); + try testing.expectEqual(tree.E.INVAL, after.errno()); + try testing.expectEqualStrings(@import("ninep/ctl.zig").e_after_edit, after.reply.ename); + answer(p, &.{"a\nb\nc\n"}); + try testing.expectEqualStrings("a\nb\nc\n", p.panes[0].?.file.?.content); +} + +test "Edit's < | and > with a real shell: a command per address, > printed to +Errors" { + if (comptime !pardes.hosted) return error.SkipZigTest; + const p = try th.withFile(testing.allocator, "one two\nthree\n"); + defer p.deinit(); + const ctl = tree.Node.of(th.serialOf(p), .ctl); + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit ,x/[a-z]+/ | tr a-z A-Z\n").reply.status); + try testing.expectEqual(@as(usize, 3), p.pipe.edit_run.?.request.inputs.len); + try runReal(p); + try testing.expectEqualStrings("ONE TWO\nTHREE\n", p.panes[0].?.file.?.content); + try testing.expectEqual(@as(usize, 1), p.panes[0].?.file.?.history.undo_len); + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit 2 < printf new\n").reply.status); + try runReal(p); + try testing.expectEqualStrings("ONE TWO\nnew", p.panes[0].?.file.?.content); + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit , > wc -l\n").reply.status); + try runReal(p); + try testing.expectEqualStrings("ONE TWO\nnew", p.panes[0].?.file.?.content); + try testing.expectEqualStrings("1", std.mem.trim(u8, errorsText(p).?, " \n")); +} + +test "a failing command changes nothing and says why, its stderr in +Errors" { + if (comptime !pardes.hosted) return error.SkipZigTest; + const p = try th.withFile(testing.allocator, "keep\n"); + defer p.deinit(); + const ctl = tree.Node.of(th.serialOf(p), .ctl); + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit , | echo boom >&2; exit 3\n").reply.status); + p.fs.late_failure_len = 0; + try runReal(p); + try testing.expectEqualStrings("keep\n", p.panes[0].?.file.?.content); + try testing.expectEqual(@as(usize, 0), p.panes[0].?.file.?.history.undo_len); + try testing.expectEqualStrings("Edit: | echo boom >&2; exit 3: exit status 3", p.fs.late_failure[0..p.fs.late_failure_len]); + const report = errorsText(p).?; + try testing.expect(std.mem.indexOf(u8, report, "Edit: | echo boom") != null); + try testing.expect(std.mem.indexOf(u8, report, "boom\n") != null); +} + +test "an Edit whose file is edited while its commands run is refused whole" { + const p = try th.withFile(testing.allocator, "abc\n"); + defer p.deinit(); + try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(th.serialOf(p), .ctl), "Edit , | cat\n").reply.status); + panes.File.setContent(p, &p.panes[0].?.file.?, try testing.allocator.dupe(u8, "typed\n")); + p.fs.late_failure_len = 0; + answer(p, &.{"ABC\n"}); + try testing.expectEqualStrings("typed\n", p.panes[0].?.file.?.content); + try testing.expectEqualStrings("Edit: /test.txt changed while its commands ran; nothing changed", p.fs.late_failure[0..p.fs.late_failure_len]); +} + +test "X over open files, w, e, r, f, B and D on panes and the disk" { + if (comptime !pardes.hosted or !filesystem.platform_has_fs) return error.SkipZigTest; + const gpa = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.c", .data = "int foo;\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.h", .data = "foo\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "c.c", .data = "foo bar\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "data", .data = "DATA\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + const p = try th.withFile(gpa, "scratch\n"); + defer p.deinit(); + var path: [4200]u8 = undefined; + look.lookAt(p, 0, try std.fmt.bufPrint(&path, "{s}/a.c", .{dir})); + const a = p.active; + look.lookAt(p, 0, try std.fmt.bufPrint(&path, "{s}/b.h", .{dir})); + p.active = 0; + const ctl = tree.Node.of(th.serialOf(p), .ctl); + // X: every open file whose line matches, each from its own dot. + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit X/\\.[ch]$/ ,s/foo/FOO/g\n").reply.status); + try testing.expectEqualStrings("int FOO;\n", p.panes[a].?.file.?.content); + try testing.expectEqualStrings("scratch\n", p.panes[0].?.file.?.content); + // B opens a file, which a `"re"` address then edits, from pane 0. + var cmd: [4400]u8 = undefined; + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, try std.fmt.bufPrint(&cmd, "Edit B {s}/c.c\n", .{dir})).reply.status); + try testing.expectEqual(@as(usize, 0), p.active); + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit \"c\\.c$\" 1 s/bar/BAR/\n").reply.status); + const c = for (p.panes, 0..) |slot, i| { + if (slot) |q| if (q.file) |f| if (std.mem.endsWith(u8, f.path, "/c.c")) break i; + } else return error.NotOpened; + try testing.expectEqualStrings("foo BAR\n", p.panes[c].?.file.?.content); + // w of all of a file to its own name leaves it clean; r reads into dot. + try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(p.panes[a].?.serial, .ctl), "Edit w\n").reply.status); + p.perform(.edit_write); // the effect th.wr took off the queue + try testing.expectEqualStrings("int FOO;\n", p.fallback.get(p.panes[a].?.file.?.path).?); + try testing.expect(!ninep_pane.dirtyOf(p.panes[a].?)); + try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(p.panes[c].?.serial, .ctl), "Edit 1 r data\n").reply.status); + try testing.expectEqualStrings("DATA\n", p.panes[c].?.file.?.content); + // e of an edited file is refused; f names one and prints it. + try testing.expectEqual(tree.E.IO, th.wr(p, tree.Node.of(p.panes[c].?.serial, .ctl), "Edit e\n").errno()); + try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(p.panes[c].?.serial, .ctl), "Edit f d.c\n").reply.status); + try testing.expect(std.mem.endsWith(u8, p.panes[c].?.file.?.path, "/d.c")); + try testing.expect(std.mem.indexOf(u8, errorsText(p).?, "'+. ") != null); + // D closes a pane by name, an edited one (b.h, by the X) on the + // second asking, as Del does. + const b_serial = for (p.panes) |slot| { + if (slot) |q| if (q.file) |f| if (std.mem.endsWith(u8, f.path, "/b.h")) break q.serial; + } else return error.NotOpened; + const a_ctl = tree.Node.of(p.panes[a].?.serial, .ctl); + try testing.expect(th.wr(p, a_ctl, "Edit D b.h\n").reply.status == .err); + try testing.expect(p.paneBySerial(b_serial) != null); + try testing.expectEqual(tree.Status.ok, th.wr(p, a_ctl, "Edit D b.h\n").reply.status); + try testing.expect(p.paneBySerial(b_serial) == null); +} diff --git a/src/fs.zig b/src/fs.zig index 7a56d387..2a5102f4 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1613,6 +1613,9 @@ pub const Namespace = struct { /// A 9P write asked a language server something: the answer count it /// waits to change (`turn.lsp_answers`), so its failure is the write's. lsp_answer_at: ?u64 = null, + /// A write ran an Edit whose `<`, `|` or `>` commands are running: it is + /// answered once `turn.edit_answers` passes this, the Edit done. + edit_answer_at: ?u64 = null, /// The pane a language answer filled (a Rename's preview): what the /// waiting 9P write answers once it is in (9p_io). lsp_result: ?u32 = null, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 599dd0d6..ac5d64d8 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -203,6 +203,7 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep for (text) |c| if ((c < ' ' and c != '\t' and c != '\n') or c == 0x7f) return tree.failText(req.tag, E.INVAL, e_control); if (exec) if (tooLong(req, text)) |refusal| return refusal; if (!apply) continue; + if (p.fs.edit_answer_at != null) return tree.failText(req.tag, E.INVAL, e_after_edit); var id = if (serial) |s| p.paneBySerial(s) orelse break else p.active; // No pane at all: the root's look and exec act in the session's // directory. An exec runs as the workspace tag's; a look from a @@ -259,6 +260,11 @@ pub fn tooLong(req: Req, line: []const u8) ?Reply { pub const e_control = "invalid command line: it holds a control character (or DEL) other than a tab"; +/// An Edit whose `<`, `|` or `>` commands are running answers its write +/// when they are done (edit_cmd.zig); a line after it in the same write +/// would run before them, on the text they are about to change. +pub const e_after_edit = "invalid command line: an Edit running commands ends its write; write what follows after it"; + /// Runs one click (`run`) as a 9P write's: a builtin that fails there fails /// the write, with its words and an err record, and no msg, as a ctl line /// does (runBuiltin). The refusal, or null. @@ -959,6 +965,7 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { var it = Messages.init(p, req.data); while (it.next()) |line_in| { if (line_in.len == 0 or exec_line.isComment(line_in)) continue; + if (apply and p.fs.edit_answer_at != null) return tree.failText(req.tag, E.INVAL, e_after_edit); // A line before this one may have closed the pane (`Del`). if (apply and p.paneBySerial(serial) == null) return Reply.fail(req.tag, E.NOENT); // acme's ctl words: done by the file that replaces each, or the diff --git a/src/pardes.zig b/src/pardes.zig index 7ae73636..cf3d5128 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -123,6 +123,9 @@ pub const Turn = struct { /// Bumped each time a language server's answer (or its lack) is taken /// in (`lspResponse`): a write that asked one waits for this. lsp_answers: u64 = 0, + /// Bumped each time an Edit's commands (`< | >`) have answered and the + /// Edit is done, or failed (edit_cmd.zig): a write that ran one waits. + edit_answers: u64 = 0, /// All of the above, and `out` reaching zero. settled: std.Io.Condition = .init, @@ -220,6 +223,16 @@ pub const Turn = struct { while (t.lsp_answers == answers) t.settled.wait(t.io.?, &t.mutex) catch return; } + pub fn editAnswered(t: *Turn) void { + t.edit_answers +%= 1; + const io = t.io orelse return; + t.settled.broadcast(io); + } + + pub fn awaitEdit(t: *Turn, answers: u64) void { + while (t.edit_answers == answers) t.settled.wait(t.io.?, &t.mutex) catch return; + } + pub fn awaitRestored(t: *Turn, restores: u64) void { while (t.restores == restores) t.settled.wait(t.io.?, &t.mutex) catch return; } @@ -483,6 +496,7 @@ test { _ = @import("exec.zig"); _ = @import("look.zig"); _ = @import("sam_edit.zig"); + _ = @import("edit_cmd.zig"); _ = @import("mouse.zig"); _ = @import("normal.zig"); _ = @import("regexp.zig"); @@ -3702,6 +3716,8 @@ pub const Effect = union(enum) { /// Snapshot the matching request with pipeRequest(id), then run it away /// from the UI/event loop and answer with pipe_resp. pipe: struct { id: u32 }, + /// Write what an Edit's `w` took (`Pipe.writes`), in order. + edit_write, watch: struct { pane: u8, on: bool, mode: WatchMode = .reconcile }, theme_file: struct { generation: u32, on: bool }, /// Write the build-time theme ring below the per-user config directory. @@ -4907,7 +4923,7 @@ pub const Pardes = struct { if (p.custom_theme) |theme_value| std.zon.parse.free(gpa, theme_value); if (p.chord_arg) |a| gpa.free(a); for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); - if (p.pipe.wait) |*wait| wait.deinit(gpa); + p.pipe.deinit(gpa); p.locations_cache.deinit(p.tree_sitter_gpa); p.fs.deinit(gpa); p.shell_rows.reset(gpa); @@ -5795,6 +5811,37 @@ pub const Pardes = struct { f(p.host.ctx, q.id) else p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }), + .edit_write => { + // Each write takes the bytes `w` took when it ran: the text + // as it was before the Edit's changes. + var writes = p.pipe.writes; + p.pipe.writes = .empty; + defer { + for (writes.items) |*w| w.deinit(p.gpa); + writes.deinit(p.gpa); + } + for (writes.items) |w| { + const was = if (p.panes[w.pane]) |pane| (if (pane.file) |f| f.saved_revision else 0) else 0; + const failures = p.fs.failures; + makeParents(w.path); + p.hostWriteFile(w.pane, w.path, w.bytes); + const pane = p.panes[w.pane] orelse continue; + if (pane.serial != w.serial) continue; + const f = if (pane.file) |*file| file else continue; + // Failed, it changes nothing, as save_text's does not. + if (p.fs.failures != failures) { + f.saved_revision = was; + continue; + } + if (w.promote) { + p.promoteSaved(w.pane, w.path); + } else if (w.clean != null and w.clean.? == f.revision) { + f.saved_revision = f.revision; + f.disk_gone = false; + ctlfs.events.noteLog(p, .save, pane); + } else ctlfs.events.noteLogAs(p, .save, pane, w.path); + } + }, .watch => |w| if (v.watch_file) |f| f(p.host.ctx, w.pane, p.watchPath(w.pane) orelse "", w.on, w.mode) else { @@ -5881,6 +5928,7 @@ pub const Pardes = struct { look.cancelLookHover(p); p.fs.serving = true; p.fs.lsp_answer_at = null; + p.fs.edit_answer_at = null; const reply = ctlfs.handle(p, req); p.fs.serving = false; // The one-failure rule is a write's: a refused open (its OTRUNC's diff --git a/src/sam_edit.zig b/src/sam_edit.zig index 9b055ef9..3f23aeff 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -1,18 +1,29 @@ //! acme's Edit (editors/acme/edit.c, ecmd.c, elog.c): sam's command -//! language over one pane's body. The commands are parsed as edit.c parses -//! them, run as ecmd.c runs them against the text as it was before the Edit, -//! and their changes collected in order, as elog.c logs them, then applied -//! at once: an Edit is one undo step, and one that fails changes nothing. +//! language over the open text panes. The commands are parsed as edit.c +//! parses them, run as ecmd.c runs them against the text as it was before +//! the Edit, and their changes collected in order, a log a file, as elog.c +//! logs them, then applied at once: an Edit is one undo step in each file it +//! changes, and one that fails changes nothing. //! //! Addresses are the `addr` file's (src/ninep/addr.zig), so they take //! pardes's `line:col` too; regular expressions are src/regexp.zig's, mvzr //! searched as sam searches, with its step budget. //! -//! Left out: the file commands (`b B D e r w f X Y`), the pipes (`< | >`), -//! the `'` and `"` addresses, and `\1`..`\9` in `s` (mvzr has no -//! submatches). `u` undoes or redoes only as a whole Edit. acme warns about -//! changes out of sequence (elog.c:130) and applies them anyway; here the -//! Edit is refused. +//! What touches more than the text is the caller's (src/EditCmd.zig): `<`, +//! `|` and `>` are collected as jobs, a command to run per address, whose +//! output fills the change they hold the place of; `w` as the bytes to +//! write; `D`, and the names `e` and `f` set, as marks on the file; `B` and +//! the reads of `e` and `r` through `World`, at once, as acme does them. +//! +//! Left out: the `'` address, `B `) refuses the whole Edit, where sam +//! warns and puts in what it wrote; `D` of a file the Edit changed is +//! refused rather than drop the changes; `e` of an edited file is refused +//! every time, not once. const std = @import("std"); const regexp = @import("regexp.zig"); const addr_lang = @import("ninep/addr.zig"); @@ -26,14 +37,62 @@ fn stepRune(text: []const u8, p: usize) usize { pub const Range = addr_lang.Range; -pub const Op = struct { q0: u32, q1: u32, text: []const u8 }; +/// A change to the text as it was: `job`, when set, is a `<` or `|` whose +/// command's output is the text, known once it has run. +pub const Op = struct { q0: u32, q1: u32, text: []const u8, job: ?u32 = null }; + +/// One open text pane, as an Edit sees and leaves it. +pub const File = struct { + /// Its absolute path; after `e` or `f`, the name they gave it. + name: []const u8, + text: []const u8, + dot: Range = .{}, + /// Edited since it was saved: the `'` of acme's file line. + dirty: bool = false, + /// No file of its own (a +Errors, a +New): `e`, `r` and `w` want a name. + scratch: bool = false, + /// The caller's: which pane it is. + id: usize = 0, + ops: std.ArrayList(Op) = .empty, + /// `e` or `f` named it `name`. + renamed: bool = false, + /// `D` closes it once the Edit is done. + close: bool = false, + /// `e` read its own file whole: it is clean again once applied. + clean: bool = false, + /// A command left a dot in it. + moved: bool = false, +}; + +/// A command for `<`, `|` or `>` (`c`), run in `file`'s directory, its +/// stdin `file`'s text in `q0..q1` (none for `<`). `>`'s output is printed +/// at `at` in `Result.printed`. +pub const Job = struct { c: u8, command: []const u8, file: u32, q0: u32, q1: u32, at: usize }; -/// What an Edit came to: the changes in order, the dot it leaves (in the -/// text before them), and what `p` and `=` printed. +/// `w`: `bytes` to `path`, `whole` when they are all of `file`'s text. +pub const Write = struct { file: u32, path: []const u8, bytes: []const u8, whole: bool }; + +/// What the editor does for `B`, `e` and `r` while an Edit runs. +pub const World = struct { + ctx: *anyopaque, + /// The text pane holding the absolute `path`, opened if it is not open: + /// `B`. Null, and `why` set, when it cannot be. + open: *const fn (ctx: *anyopaque, path: []const u8, why: *Why) ?File, + /// The bytes of the absolute `path`, in `arena`: `e` and `r`. + read: *const fn (ctx: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *Why) ?[]const u8, +}; + +/// What an Edit came to: every file (those `B` opened after the ones it +/// was given), each with its changes in order and the dot it leaves (in the +/// text before them); the jobs and writes; and what `p`, `=`, `b`, `f` and +/// `X` printed. pub const Result = struct { - ops: []const Op, - dot: Range, - printed: []const u8, + files: []File, + /// The current file at the end (`b` moves it). + cur: usize, + jobs: []const Job = &.{}, + writes: []const Write = &.{}, + printed: []const u8 = "", /// A bare `u`/`u-3`: undo (positive) or redo (negative) that many. undo: i32 = 0, }; @@ -49,9 +108,17 @@ pub const Why = struct { } }; +/// The most commands an Edit's `<`, `|` and `>` may run: each is a process. +pub const max_jobs = 1024; + const Cmd = struct { c: u8, addr: ?[]const u8 = null, + /// A `"re"` address: the file whose line matches. + file_re: ?[]const u8 = null, + /// A `,` after it, whose right side acme evaluates in the current file + /// (ecmd.c cmdaddress): only `;` carries the file over. + file_comma: bool = false, re: ?[]const u8 = null, text: []const u8 = "", sub: ?*Cmd = null, @@ -61,9 +128,10 @@ const Cmd = struct { to: ?[]const u8 = null, }; -/// Runs `command` over `text` from `dot`, the file named `name` (for `=`). +/// Runs `command` over `files` from `files[cur]`, whose dots are where +/// each starts. `world` answers `B`, `e` and `r`; with none they fail. /// Everything returned lives in `arena`. -pub fn run(arena: std.mem.Allocator, text: []const u8, dot: Range, name: []const u8, command: []const u8, why: *Why) Failure!Result { +pub fn run(arena: std.mem.Allocator, files: []const File, cur: usize, command: []const u8, world: ?World, why: *Why) Failure!Result { var src = try arena.alloc(u8, command.len + 1); @memcpy(src[0..command.len], command); src[command.len] = '\n'; @@ -80,23 +148,32 @@ pub fn run(arena: std.mem.Allocator, text: []const u8, dot: Range, name: []const // reaches Edit unfinished was cut short (a write, an open closed), and // half of it inserted is worse than none. if (ps.open_text) return fail(why, "a, c or i text not ended by a . line", .{}); - const cmds = first orelse return .{ .ops = &.{}, .dot = dot, .printed = "" }; + var ex: Exec = .{ .arena = arena, .why = why, .world = world, .cur = cur }; + try ex.files.appendSlice(arena, files); + const cmds = first orelse return .{ .files = ex.files.items, .cur = cur }; // acme's u runs at once (ecmd.c:532), outside the edit log; here it is // an Edit of its own. if (cmds.c == 'u') { if (cmds.next != null) return fail(why, "u is only an Edit of its own here", .{}); - return .{ .ops = &.{}, .dot = dot, .printed = "", .undo = cmds.num }; + return .{ .files = ex.files.items, .cur = cur, .undo = cmds.num }; } - var ex: Exec = .{ .arena = arena, .text = text, .name = name, .why = why }; - var d = dot; + // editthread: each command from the current file, which `b` changes. var it: ?*Cmd = cmds; - while (it) |c| : (it = c.next) d = try ex.exec(c, d); - return .{ .ops = ex.ops.items, .dot = d, .printed = ex.out.items }; + while (it) |c| : (it = c.next) { + const fi = ex.cur; + const d = try ex.exec(c, fi, ex.files.items[fi].dot); + ex.files.items[fi].dot = d; + ex.files.items[fi].moved = true; + } + return .{ + .files = ex.files.items, + .cur = ex.cur, + .jobs = ex.jobs.items, + .writes = ex.writes.items, + .printed = ex.out.items, + }; } -/// Whether `command` stops inside a `{` group or an `a`, `c` or `i` text -/// block still waiting for its `.` line: a writer of lines (a ctl, exec) -/// hands an Edit the lines after it until it does not. /// What an Edit command still waits for: nothing, the `.` line that ends /// an a, c or i text block, or the `}` of a group. pub const Wait = enum { none, text, group }; @@ -131,6 +208,9 @@ fn groupOpen(command: []const u8) bool { return depth > 0; } +/// Whether `command` stops inside a `{` group or an `a`, `c` or `i` text +/// block still waiting for its `.` line: a writer of lines (a ctl, exec) +/// hands an Edit the lines after it until it does not. pub fn needsMore(arena: std.mem.Allocator, command: []const u8) bool { var why: Why = .{}; const src = std.fmt.allocPrint(arena, "{s}\n", .{command}) catch return false; @@ -158,6 +238,8 @@ const Parser = struct { braced: bool = false, /// A text block of `a`, `c` or `i` ran out before its `.` line. open_text: bool = false, + /// The address being read had a `,` after a `"re"`. + file_comma: bool = false, why: *Why, fn getch(ps: *Parser) ?u8 { @@ -207,8 +289,9 @@ const Parser = struct { } /// An address's text, blanks dropped, or null: the syntax of edit.c's - /// compoundaddr and simpleaddr, evaluated later by addr.zig. - fn address(ps: *Parser) Failure!?[]const u8 { + /// compoundaddr and simpleaddr, evaluated later by addr.zig. A `"re"` + /// first is the file the rest addresses, kept in `file_re`. + fn address(ps: *Parser, file_re: ?*?[]const u8) Failure!?[]const u8 { var out: std.ArrayList(u8) = .empty; while (true) { const c = ps.skipbl() orelse break; @@ -216,6 +299,7 @@ const Parser = struct { '0'...'9', '#', '.', '$', '+', '-', ',', ';' => { ps.i += 1; try out.append(ps.arena, c); + if (c == ',' and file_re != null and file_re.?.* != null) ps.file_comma = true; // pardes's line:col if (c >= '0' and c <= '9' and ps.nextc() == ':' and ps.i + 1 < ps.src.len and ps.src[ps.i + 1] >= '0' and ps.src[ps.i + 1] <= '9') @@ -242,7 +326,13 @@ const Parser = struct { } }, '\'' => return fail(ps.why, "can't handle '", .{}), - '"' => return fail(ps.why, "a file address is no address pardes's Edit takes", .{}), + '"' => { + // Only first, as the file the rest of it addresses. + const into = file_re orelse return fail(ps.why, "bad address", .{}); + if (out.items.len > 0 or into.* != null) return fail(ps.why, "bad address", .{}); + ps.i += 1; + into.* = try ps.getregexp('"'); + }, else => break, } } @@ -322,13 +412,33 @@ const Parser = struct { return s; } + /// edit.c:404, collecttoken: up to a byte of `end`, blanks before it + /// kept (the command trims them); a word wants its newline after it. + fn collecttoken(ps: *Parser, end: []const u8) Failure![]const u8 { + const start = ps.i; + while (ps.nextc()) |c| : (ps.i += 1) { + if (c != ' ' and c != '\t') break; + } + while (ps.nextc()) |c| : (ps.i += 1) { + if (std.mem.indexOfScalar(u8, end, c) != null) break; + } + const s = ps.src[start..ps.i]; + if (ps.nextc() == '\n') ps.i += 1 else try ps.atnl(); + return s; + } + /// edit.c:467, parsecmd. fn parse(ps: *Parser, nest: u32) Failure!?*Cmd { - const a = try ps.address(); + var file_re: ?[]const u8 = null; + ps.file_comma = false; + const a = try ps.address(&file_re); _ = ps.skipbl() orelse return null; const c = ps.getch() orelse return null; const cmd = try ps.arena.create(Cmd); - cmd.* = .{ .c = c, .addr = a }; + cmd.* = .{ .c = c, .addr = a, .file_re = file_re, .file_comma = ps.file_comma }; + // aNo in edit.c's cmdtab. + if ((a != null or file_re != null) and std.mem.indexOfScalar(u8, "bBDefuXY", c) != null) + return fail(ps.why, "command takes no address", .{}); switch (c) { '\n' => {}, 'a', 'c', 'i' => cmd.text = try ps.collecttext(), @@ -362,10 +472,11 @@ const Parser = struct { } try ps.atnl(); }, - 'x', 'y', 'g', 'v' => { - // x without a pattern is every line (ecmd.c:568, linelooper). + 'x', 'y', 'g', 'v', 'X', 'Y' => { + // x without a pattern is every line (ecmd.c:568, + // linelooper), X every file. const n = ps.nextc(); - if (c != 'x' or (n != ' ' and n != '\t' and n != '\n')) { + if ((c != 'x' and c != 'X') or (n != ' ' and n != '\t' and n != '\n')) { _ = ps.skipbl(); const delim = ps.getch() orelse '\n'; if (delim == '\n') return fail(ps.why, "no address", .{}); @@ -375,21 +486,23 @@ const Parser = struct { if (ps.skipbl() == '\n') { ps.i += 1; const p = try ps.arena.create(Cmd); - p.* = .{ .c = 'p' }; + p.* = .{ .c = if (c == 'X' or c == 'Y') 'f' else 'p' }; cmd.sub = p; } else { cmd.sub = (try ps.parse(nest)) orelse return fail(ps.why, "defcmd", .{}); } }, 'm', 't' => { - cmd.to = (try ps.address()) orelse return fail(ps.why, "bad address", .{}); + cmd.to = (try ps.address(null)) orelse return fail(ps.why, "bad address", .{}); try ps.atnl(); }, 'u' => { - if (a != null) return fail(ps.why, "command takes no address", .{}); cmd.num = ps.getnum(2); try ps.atnl(); }, + // edit.c's cmdtab: a line for these, a word for those. + 'b', 'B', 'D', '<', '|', '>' => cmd.text = try ps.collecttoken("\n"), + 'e', 'f', 'r', 'w' => cmd.text = try ps.collecttoken(" \t\n"), '{' => { var last: ?*Cmd = null; while (true) { @@ -410,7 +523,6 @@ const Parser = struct { if (nest == 0) return fail(ps.why, "right brace with no left brace", .{}); return null; }, - 'b', 'B', 'D', 'e', 'r', 'w', 'f', 'X', 'Y', '<', '|', '>' => return fail(ps.why, "{c} is a sam command pardes's Edit leaves out (it has no file or shell commands)", .{c}), else => return fail(ps.why, "unknown command {c}", .{c}), } return cmd; @@ -419,23 +531,35 @@ const Parser = struct { // ---- running: ecmd.c, logging: elog.c ---- +const e_noname = "no file name given"; + const Exec = struct { arena: std.mem.Allocator, - text: []const u8, - name: []const u8, why: *Why, - ops: std.ArrayList(Op) = .empty, + world: ?World, + files: std.ArrayList(File) = .empty, + /// The current file: where the next top-level command runs. + cur: usize, + jobs: std.ArrayList(Job) = .empty, + writes: std.ArrayList(Write) = .empty, out: std.ArrayList(u8) = .empty, nest: u32 = 0, + /// Inside an X or Y, which do not nest (ecmd.c Glooping). + looping: bool = false, fn clip(n: usize) u32 { return std.math.cast(u32, n) orelse std.math.maxInt(u32); } - /// An address from `dot`, or `dot` when there is none (aDot). - fn address(ex: *Exec, expr: ?[]const u8, dot: Range) Failure!Range { + fn text(ex: *const Exec, fi: usize) []const u8 { + return ex.files.items[fi].text; + } + + /// An address in file `fi` from `dot`, or `dot` when there is none + /// (aDot). + fn address(ex: *Exec, fi: usize, expr: ?[]const u8, dot: Range) Failure!Range { const e = expr orelse return dot; - var a: addr_lang.Addr = .{ .text = ex.text, .lim = null, .expr = e }; + var a: addr_lang.Addr = .{ .text = ex.text(fi), .lim = null, .expr = e }; // A miss names the pattern that missed, not the whole Edit line. const r = a.address(dot) orelse return if (std.mem.eql(u8, a.err, addr_lang.e_no_match)) fail(ex.why, "no match for regexp {s}", .{e}) @@ -448,13 +572,14 @@ const Exec = struct { /// elog.c's order: each change at or after the end of the one before, /// since they all address the text as it was. - fn log(ex: *Exec, q0: u32, q1: u32, text: []const u8) Failure!void { - if (q0 == q1 and text.len == 0) return; - if (ex.ops.items.len > 0) { - const prev = ex.ops.items[ex.ops.items.len - 1]; + fn log(ex: *Exec, fi: usize, q0: u32, q1: u32, bytes: []const u8, job: ?u32) Failure!void { + if (q0 == q1 and bytes.len == 0 and job == null) return; + const ops = &ex.files.items[fi].ops; + if (ops.items.len > 0) { + const prev = ops.items[ops.items.len - 1]; if (q0 < prev.q1 or q0 < prev.q0) return fail(ex.why, "changes out of sequence", .{}); } - try ex.ops.append(ex.arena, .{ .q0 = q0, .q1 = q1, .text = text }); + try ops.append(ex.arena, .{ .q0 = q0, .q1 = q1, .text = bytes, .job = job }); } fn compile(ex: *Exec, pat: []const u8, c: u8) Failure!regexp.Regex { @@ -464,7 +589,10 @@ const Exec = struct { error.WideRange => fail(ex.why, "{s}", .{regexp.Regex.e_wide}), error.NegatedRunes => fail(ex.why, "{s}", .{regexp.Regex.e_negated}), error.Mixed => fail(ex.why, "{s}", .{regexp.Regex.e_mixed}), - error.Bad => fail(ex.why, "bad regexp in {c} command", .{c}), + error.Bad => if (c == '"' or c == 'X' or c == 'Y') + fail(ex.why, "bad regexp in file match", .{}) + else + fail(ex.why, "bad regexp in {c} command", .{c}), }; } @@ -472,84 +600,175 @@ const Exec = struct { /// (addr.zig): mvzr matches bytes, so `.` would take one byte of `é` /// and x, y and s would split it. From `from` on only, so a match never /// reaches back into what the last one took. - fn find(ex: *Exec, rx: *regexp.Regex, from: usize, hi: usize) Failure!?regexp.Regex.Match { + fn find(ex: *Exec, rx: *regexp.Regex, in: []const u8, from: usize, hi: usize) Failure!?regexp.Regex.Match { if (from > hi) return null; // The budget is each search's own: an x over 100k lines makes 100k // searches, none of which is the slow one. rx.steps = regexp.Regex.budget; - const m = (rx.find(ex.text, from, hi, hi) catch return fail(ex.why, "{s}", .{addr_lang.e_slow})) orelse return null; - var start = modal.runeStart(ex.text, m.start); - if (start < from) start = modal.runeEnd(ex.text, m.start); - return .{ .start = start, .end = @max(start, modal.runeEnd(ex.text, m.end)) }; + const m = (rx.find(in, from, hi, hi) catch return fail(ex.why, "{s}", .{addr_lang.e_slow})) orelse return null; + var start = modal.runeStart(in, m.start); + if (start < from) start = modal.runeEnd(in, m.start); + return .{ .start = start, .end = @max(start, modal.runeEnd(in, m.end)) }; + } + + /// ecmd.c pfilename: `'` if edited, `+`, `.` if current, and the name. + fn fileLine(ex: *Exec, fi: usize) Failure![]const u8 { + const f = &ex.files.items[fi]; + return std.fmt.allocPrint(ex.arena, "{c}+{c} {s}\n", .{ + @as(u8, if (f.dirty and !f.scratch) '\'' else ' '), + @as(u8, if (fi == ex.cur) '.' else ' '), + f.name, + }); + } + + /// ecmd.c filematch: the file's line matches `pat`. + fn fileMatch(ex: *Exec, fi: usize, pat: []const u8) Failure!bool { + var rx = try ex.compile(pat, 'X'); + const line = try ex.fileLine(fi); + return (try ex.find(&rx, line, 0, line.len)) != null; + } + + /// ecmd.c matchfile: the one open file whose line matches `pat`. + fn matchFile(ex: *Exec, pat: []const u8) Failure!usize { + var found: ?usize = null; + for (ex.files.items, 0..) |f, i| { + if (f.close or f.scratch) continue; + if (!try ex.fileMatch(i, pat)) continue; + if (found != null) return fail(ex.why, "too many files match \"{s}\"", .{pat}); + found = i; + } + return found orelse fail(ex.why, "no file matches \"{s}\"", .{pat}); + } + + /// `name` as a path: itself when absolute, else in `fi`'s directory + /// (acme's dirname). + fn pathIn(ex: *Exec, fi: usize, name: []const u8) Failure![]const u8 { + if (name.len > 0 and name[0] == '/') return name; + const dir = std.fs.path.dirnamePosix(ex.files.items[fi].name) orelse "/"; + return std.fs.path.resolvePosix(ex.arena, &.{ dir, name }); + } + + /// The open file named `path`, a scratch too. + fn lookFile(ex: *Exec, path: []const u8) ?usize { + for (ex.files.items, 0..) |f, i| if (!f.close and std.mem.eql(u8, f.name, path)) return i; + return null; + } + + /// ecmd.c cmdname: the name a file command means: the one given, in the + /// file's directory, else the file's own (none for a scratch). `set` + /// names the file so (`e`, `f`), as an unnamed one always is. + fn cmdName(ex: *Exec, fi: usize, given: []const u8, set: bool) Failure!?[]const u8 { + const s = std.mem.trim(u8, given, " \t"); + const f = &ex.files.items[fi]; + if (s.len == 0) return if (f.scratch) null else f.name; + const full = try ex.pathIn(fi, s); + if (set and !std.mem.eql(u8, full, f.name)) { + if (ex.lookFile(full)) |other| if (other != fi) + try ex.out.print(ex.arena, "warning: duplicate file name \"{s}\"\n", .{full}); + f.name = full; + f.renamed = true; + f.scratch = false; + } + return full; + } + + fn readFile(ex: *Exec, path: []const u8) Failure![]const u8 { + const w = ex.world orelse return fail(ex.why, "can't open {s}: no files here", .{path}); + return w.read(w.ctx, ex.arena, path, ex.why) orelse error.Edit; + } + + /// ecmd.c:62, cmdexec: runs `c` in file `fi` from `dot`, answering the + /// dot it leaves there. + fn exec(ex: *Exec, c: *Cmd, fi_in: usize, dot_in: Range) Failure!Range { + var fi = fi_in; + var dot = dot_in; + if (ex.files.items[fi].close) return fail(ex.why, "no current window", .{}); + // A `"re"` address: the command runs in that file, from its dot. + if (c.file_re) |pat| { + fi = try ex.matchFile(pat); + dot = ex.files.items[fi].dot; + if (c.file_comma and fi != fi_in) return fail(ex.why, "addresses in different files", .{}); + } + // w's default address is the whole file (aAll). + const r = if (c.c == 'w' and c.addr == null) + Range{ .q0 = 0, .q1 = clip(ex.text(fi).len) } + else + try ex.address(fi, c.addr, dot); + const d = try ex.execIn(c, fi, r); + if (fi == fi_in) return d; + ex.files.items[fi].dot = d; + ex.files.items[fi].moved = true; + return dot_in; } - /// ecmd.c:62, cmdexec: runs `c` from `dot`, answering the dot it leaves. - fn exec(ex: *Exec, c: *Cmd, dot: Range) Failure!Range { - const r = try ex.address(c.addr, dot); + /// The command itself, at `r` in file `fi`. + fn execIn(ex: *Exec, c: *Cmd, fi: usize, r: Range) Failure!Range { + const txt = ex.text(fi); switch (c.c) { '\n' => return r, 'a' => { - try ex.log(r.q1, r.q1, c.text); + try ex.log(fi, r.q1, r.q1, c.text, null); return .{ .q0 = r.q1, .q1 = r.q1 }; }, 'i' => { - try ex.log(r.q0, r.q0, c.text); + try ex.log(fi, r.q0, r.q0, c.text, null); return .{ .q0 = r.q0, .q1 = r.q0 }; }, 'c' => { - try ex.log(r.q0, r.q1, c.text); + try ex.log(fi, r.q0, r.q1, c.text, null); return .{ .q0 = r.q0, .q1 = r.q0 }; }, 'd' => { - try ex.log(r.q0, r.q1, ""); + try ex.log(fi, r.q0, r.q1, "", null); return .{ .q0 = r.q0, .q1 = r.q0 }; }, 'p' => { - try ex.out.appendSlice(ex.arena, ex.text[r.q0..r.q1]); + try ex.out.appendSlice(ex.arena, txt[r.q0..r.q1]); return r; }, '=' => { // ecmd.c:665, printposn + const name = ex.files.items[fi].name; if (c.text.len > 0) { - try ex.out.print(ex.arena, "{s}:#{d}", .{ ex.name, r.q0 }); + try ex.out.print(ex.arena, "{s}:#{d}", .{ name, r.q0 }); if (r.q1 != r.q0) try ex.out.print(ex.arena, ",#{d}", .{r.q1}); } else { - const l1 = 1 + std.mem.count(u8, ex.text[0..r.q0], "\n"); - var l2 = l1 + std.mem.count(u8, ex.text[r.q0..r.q1], "\n"); - if (r.q1 > r.q0 and ex.text[r.q1 - 1] == '\n') l2 -= 1; - try ex.out.print(ex.arena, "{s}:{d}", .{ ex.name, l1 }); + const l1 = 1 + std.mem.count(u8, txt[0..r.q0], "\n"); + var l2 = l1 + std.mem.count(u8, txt[r.q0..r.q1], "\n"); + if (r.q1 > r.q0 and txt[r.q1 - 1] == '\n') l2 -= 1; + try ex.out.print(ex.arena, "{s}:{d}", .{ name, l1 }); if (l2 != l1) try ex.out.print(ex.arena, ",{d}", .{l2}); } try ex.out.append(ex.arena, '\n'); return r; }, - 's' => return ex.substitute(c, r), + 's' => return ex.substitute(c, fi, r), 'x', 'y' => { - const ranges = if (c.re) |pat| try ex.looper(pat, r, c.c == 'x') else try ex.lines(r); + const ranges = if (c.re) |pat| try ex.looper(pat, fi, r, c.c == 'x') else try ex.lines(fi, r); ex.nest += 1; defer ex.nest -= 1; var d = r; - for (ranges) |each| d = try ex.exec(c.sub.?, each); + for (ranges) |each| d = try ex.exec(c.sub.?, fi, each); return d; }, 'g', 'v' => { var rx = try ex.compile(c.re.?, c.c); - const hit = (try ex.find(&rx, r.q0, r.q1)) != null; - if (hit != (c.c == 'v')) return ex.exec(c.sub.?, r); + const hit = (try ex.find(&rx, txt, r.q0, r.q1)) != null; + if (hit != (c.c == 'v')) return ex.exec(c.sub.?, fi, r); return r; }, 'm', 't' => { - const to = try ex.address(c.to, dot); - const bytes = ex.text[r.q0..r.q1]; + const to = try ex.address(fi, c.to, r); + const bytes = txt[r.q0..r.q1]; if (c.c == 't') { - try ex.log(to.q1, to.q1, bytes); + try ex.log(fi, to.q1, to.q1, bytes, null); } else if (r.q1 <= to.q0) { // ecmd.c:408, move - try ex.log(r.q0, r.q1, ""); - try ex.log(to.q1, to.q1, bytes); + try ex.log(fi, r.q0, r.q1, "", null); + try ex.log(fi, to.q1, to.q1, bytes, null); } else if (r.q0 >= to.q1) { - try ex.log(to.q1, to.q1, bytes); - try ex.log(r.q0, r.q1, ""); + try ex.log(fi, to.q1, to.q1, bytes, null); + try ex.log(fi, r.q0, r.q1, "", null); } else if (!(r.q0 == to.q0 and r.q1 == to.q1)) { return fail(ex.why, "move overlaps itself", .{}); } @@ -558,28 +777,142 @@ const Exec = struct { 'u' => return fail(ex.why, "u is only an Edit of its own here", .{}), '{' => { var it = c.sub; - while (it) |each| : (it = each.next) _ = try ex.exec(each, r); + while (it) |each| : (it = each.next) _ = try ex.exec(each, fi, r); + return r; + }, + 'b' => { + // ecmd.c b_cmd, tofile: the file named so, exactly or in + // the current file's directory. + const name = std.mem.trim(u8, c.text, " \t"); + const at = ex.lookFile(name) orelse ex.lookFile(try ex.pathIn(fi, name)); + const to = if (at) |i| (if (ex.files.items[i].scratch) null else i) else null; + const target = to orelse return fail(ex.why, "no such file \"{s}\"", .{name}); + // The `.` goes with it in the line printed. + ex.cur = target; + if (ex.nest == 0) try ex.out.appendSlice(ex.arena, try ex.fileLine(target)); + return r; + }, + 'B' => { + const list = std.mem.trim(u8, c.text, " \t"); + if (list.len > 0 and list[0] == '<') return fail(ex.why, "B { + const list = std.mem.trim(u8, c.text, " \t"); + if (list.len > 0 and list[0] == '<') return fail(ex.why, "D { + // ecmd.c e_cmd: e reads a file over all of this one, r over + // dot; e names this file after it. + const f = &ex.files.items[fi]; + if (c.c == 'e' and f.dirty and !f.scratch) return fail(ex.why, "{s} modified", .{f.name}); + const own = f.name; + const path = (try ex.cmdName(fi, c.text, c.c == 'e')) orelse return fail(ex.why, e_noname, .{}); + const bytes = try ex.readFile(path); + const q: Range = if (c.c == 'e') .{ .q0 = 0, .q1 = clip(txt.len) } else r; + try ex.log(fi, q.q0, q.q1, bytes, null); + if (c.c == 'e' and std.mem.eql(u8, path, own)) ex.files.items[fi].clean = true; + return r; + }, + 'w' => { + if (ex.files.items[fi].ops.items.len > 0) return fail(ex.why, "can't write file with pending modifications", .{}); + const path = (try ex.cmdName(fi, c.text, false)) orelse return fail(ex.why, "no name specified for 'w' command", .{}); + try ex.writes.append(ex.arena, .{ + .file = @intCast(fi), + .path = path, + .bytes = try ex.arena.dupe(u8, txt[r.q0..r.q1]), + .whole = r.q0 == 0 and r.q1 == txt.len, + }); + return r; + }, + 'f' => { + _ = try ex.cmdName(fi, c.text, true); + try ex.out.appendSlice(ex.arena, try ex.fileLine(fi)); + return r; + }, + 'X', 'Y' => { + // ecmd.c filelooper: the files whose line matches (X) or + // does not (Y), each from its own dot; X alone is every + // file with a name. + if (ex.looping) return fail(ex.why, "can't nest {c} command", .{c.c}); + ex.looping = true; + defer ex.looping = false; + ex.nest += 1; + defer ex.nest -= 1; + var chosen: std.ArrayList(usize) = .empty; + for (ex.files.items, 0..) |f, i| { + if (f.close) continue; + if (c.re == null and f.scratch) continue; + if (c.re == null or (try ex.fileMatch(i, c.re.?)) == (c.c == 'X')) try chosen.append(ex.arena, i); + } + for (chosen.items) |i| { + const d = try ex.exec(c.sub.?, i, ex.files.items[i].dot); + ex.files.items[i].dot = d; + ex.files.items[i].moved = true; + } + return r; + }, + '<', '|', '>' => { + // ecmd.c runpipe: the command's output replaces dot (`<`, + // `|`), dot is its input (`|`, `>`), and `>`'s output is + // printed. + const command = std.mem.trim(u8, c.text, " \t"); + if (command.len == 0) return fail(ex.why, "no command specified for {c}", .{c.c}); + if (ex.jobs.items.len >= max_jobs) return fail(ex.why, "too many commands: more than {d} for one Edit", .{max_jobs}); + const job: u32 = @intCast(ex.jobs.items.len); + try ex.jobs.append(ex.arena, .{ .c = c.c, .command = command, .file = @intCast(fi), .q0 = r.q0, .q1 = r.q1, .at = ex.out.items.len }); + if (c.c != '>') try ex.log(fi, r.q0, r.q1, "", job); return r; }, else => return fail(ex.why, "unknown command {c}", .{c.c}), } } + /// ecmd.c D1: closed once the Edit is done. One with changes pending + /// in this Edit is refused rather than have them dropped. + fn closeFile(ex: *Exec, fi: usize) Failure!void { + const f = &ex.files.items[fi]; + if (f.ops.items.len > 0) return fail(ex.why, "D: {s} has changes pending in this Edit", .{f.name}); + f.close = true; + } + /// ecmd.c:443, s_cmd. - fn substitute(ex: *Exec, c: *Cmd, r: Range) Failure!Range { + fn substitute(ex: *Exec, c: *Cmd, fi: usize, r: Range) Failure!Range { + const txt = ex.text(fi); var rx = try ex.compile(c.re.?, 's'); var n = c.num; var op: ?usize = null; var p1: usize = r.q0; var did = false; while (p1 <= r.q1) { - const m = (try ex.find(&rx, p1, r.q1)) orelse break; + const m = (try ex.find(&rx, txt, p1, r.q1)) orelse break; if (m.start == m.end) { if (op != null and m.start == op.?) { - p1 = stepRune(ex.text, p1); + p1 = stepRune(txt, p1); continue; } - p1 = stepRune(ex.text, m.end); + p1 = stepRune(txt, m.end); } else p1 = m.end; op = m.end; n -= 1; @@ -594,10 +927,10 @@ const Exec = struct { if (e >= '1' and e <= '9') return fail(ex.why, "no \\{c}: mvzr keeps no submatches", .{e}); try buf.append(ex.arena, e); } else if (ch == '&') { - try buf.appendSlice(ex.arena, ex.text[m.start..m.end]); + try buf.appendSlice(ex.arena, txt[m.start..m.end]); } else try buf.append(ex.arena, ch); } - try ex.log(clip(m.start), clip(m.end), buf.items); + try ex.log(fi, clip(m.start), clip(m.end), buf.items, null); did = true; if (!c.global) break; } @@ -609,7 +942,8 @@ const Exec = struct { } /// ecmd.c:796, looper: the matches (x) or what lies between them (y). - fn looper(ex: *Exec, pat: []const u8, r: Range, xy: bool) Failure![]Range { + fn looper(ex: *Exec, pat: []const u8, fi: usize, r: Range, xy: bool) Failure![]Range { + const txt = ex.text(fi); var rx = try ex.compile(pat, if (xy) 'x' else 'y'); var out: std.ArrayList(Range) = .empty; var op: ?usize = if (xy) null else r.q0; @@ -617,13 +951,13 @@ const Exec = struct { while (p <= r.q1) { var tr: Range = undefined; var sel_end: usize = undefined; - if (try ex.find(&rx, p, r.q1)) |m| { + if (try ex.find(&rx, txt, p, r.q1)) |m| { if (m.start == m.end) { if (op != null and m.start == op.?) { - p = stepRune(ex.text, p); + p = stepRune(txt, p); continue; } - p = stepRune(ex.text, m.end); + p = stepRune(txt, m.end); } else p = m.end; tr = if (xy) .{ .q0 = clip(m.start), .q1 = clip(m.end) } else .{ .q0 = clip(op.?), .q1 = clip(m.start) }; sel_end = m.end; @@ -642,12 +976,13 @@ const Exec = struct { /// ecmd.c:840, linelooper: each line in the range, the first from where /// the range starts, the last cut where it ends. - fn lines(ex: *Exec, r: Range) Failure![]Range { + fn lines(ex: *Exec, fi: usize, r: Range) Failure![]Range { + const txt = ex.text(fi); var out: std.ArrayList(Range) = .empty; var p: usize = r.q0; while (p < r.q1) { - const nl = std.mem.indexOfScalarPos(u8, ex.text, p, '\n'); - const e = @min(if (nl) |i| i + 1 else ex.text.len, r.q1); + const nl = std.mem.indexOfScalarPos(u8, txt, p, '\n'); + const e = @min(if (nl) |i| i + 1 else txt.len, r.q1); if (e <= p) break; try out.append(ex.arena, .{ .q0 = clip(p), .q1 = clip(e) }); p = e; @@ -656,7 +991,8 @@ const Exec = struct { } }; -/// The text after `ops`, which are in order and do not overlap. +/// The text after `ops`, which are in order and do not overlap (a job's +/// with its output in place). pub fn apply(gpa: std.mem.Allocator, text: []const u8, ops: []const Op) ![]u8 { var n: usize = text.len; for (ops) |o| n = n - (o.q1 - o.q0) + o.text.len; @@ -675,9 +1011,9 @@ pub fn apply(gpa: std.mem.Allocator, text: []const u8, ops: []const Op) ![]u8 { return out; } -/// Where `dot` lands after `ops`: each end moved by the changes before it; -/// an empty dot where a change starts selects what it put there, as -/// elogapply does (elog.c:283). +/// Where `dot` lands after `ops` (their texts final): each end moved by the +/// changes before it; an empty dot where a change starts selects what it +/// put there, as elogapply does (elog.c:283). pub fn moveDot(dot: Range, ops: []const Op) Range { var shift: i64 = 0; for (ops) |o| { @@ -702,11 +1038,11 @@ fn edited(text: []const u8, command: []const u8) ![]u8 { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); var why: Why = .{}; - const res = run(arena_state.allocator(), text, .{}, "t", command, &why) catch |err| { + const res = run(arena_state.allocator(), &.{.{ .name = "t", .text = text }}, 0, command, null, &why) catch |err| { if (err == error.Edit) std.debug.print("Edit: {s}\n", .{why.text()}); return err; }; - return apply(std.testing.allocator, text, res.ops); + return apply(std.testing.allocator, text, res.files[0].ops.items); } fn expectEdit(text: []const u8, command: []const u8, want: []const u8) !void { @@ -768,13 +1104,21 @@ test "an Edit that fails halfway changes nothing, and says why in acme's words" .{ "}", "right brace with no left brace" }, .{ ",x/foo/{", "unmatched `{'" }, .{ ",x/foo/{\nd", "unmatched `{'" }, - .{ "w /tmp/x", "w is a sam command pardes's Edit leaves out (it has no file or shell commands)" }, + .{ "B are jobs: a command per address, its output the change" { + var fx: Fixture = .init(); + defer fx.deinit(); + const res = try fx.edit(0, ",x/foo|bar/ | tr a-z A-Z\n$ > wc -c\n$ < date"); + try std.testing.expectEqual(@as(usize, 4), res.jobs.len); + try std.testing.expectEqual(@as(u8, '|'), res.jobs[0].c); + try std.testing.expectEqualStrings("tr a-z A-Z", res.jobs[0].command); + try std.testing.expectEqualStrings("foo", res.files[0].text[res.jobs[0].q0..res.jobs[0].q1]); + try std.testing.expectEqualStrings("bar", res.files[0].text[res.jobs[1].q0..res.jobs[1].q1]); + try std.testing.expectEqual(@as(u8, '>'), res.jobs[2].c); + try std.testing.expectEqual(@as(u8, '<'), res.jobs[3].c); + // `>` changes nothing; `|` and `<` hold their output's place. + const ops = res.files[0].ops.items; + try std.testing.expectEqual(@as(usize, 3), ops.len); + try std.testing.expectEqual(@as(?u32, 0), ops[0].job); + try std.testing.expectEqual(@as(?u32, 1), ops[1].job); + try std.testing.expectEqual(@as(?u32, 3), ops[2].job); + // ...out of order with the x before it: `1 <` reaches back. + try std.testing.expectError(error.Edit, fx.edit(0, ",x/bar/ | cat\n1 < date")); + try std.testing.expectEqualStrings("changes out of sequence", fx.why.text()); + // Across files with X: each job is its file's. + const x = try fx.edit(0, "X/\\.c$/ , | sort"); + try std.testing.expectEqual(@as(usize, 2), x.jobs.len); + try std.testing.expectEqual(@as(u32, 2), x.jobs[1].file); +} diff --git a/src/selection_pipe.zig b/src/selection_pipe.zig index 44cc1709..4fb024bb 100644 --- a/src/selection_pipe.zig +++ b/src/selection_pipe.zig @@ -18,11 +18,18 @@ pub const command_timeout_seconds: u64 = 10; pub const Input = struct { bytes: []const u8 }; /// Borrowed view exposed by the core while an effect is being drained. +/// An Edit's `<`, `|` and `>` (src/edit_cmd.zig) run a command of their own +/// per input, each in its file's directory: `commands` and `cwds`, when +/// given, name input i's, and `shell` (the session's Shell) runs them, +/// /bin/sh when it is empty. pub const Request = struct { id: u32, command: []const u8, cwd: []const u8, inputs: []const Input, + commands: []const []const u8 = &.{}, + cwds: []const []const u8 = &.{}, + shell: []const u8 = "", }; /// Worker-owned snapshot. `copy` is intentionally called synchronously while @@ -33,6 +40,10 @@ pub const Job = struct { command: []u8, cwd: []u8, inputs: [][]u8, + /// Input i's own command and directory, when the request gave them. + commands: [][]u8 = &.{}, + cwds: [][]u8 = &.{}, + shell: []u8 = &.{}, pub fn copy(gpa: std.mem.Allocator, request: Request) !*Job { const job = try gpa.create(Job); @@ -46,22 +57,45 @@ pub const Job = struct { errdefer gpa.free(job.command); job.cwd = try gpa.dupe(u8, filesystem.localPath(request.cwd) orelse request.cwd); errdefer gpa.free(job.cwd); - job.inputs = try gpa.alloc([]u8, request.inputs.len); - errdefer gpa.free(job.inputs); + job.inputs = try dupeAll(gpa, request.inputs.len, request.inputs, false); + errdefer freeAll(gpa, job.inputs); + job.commands = try dupeAll(gpa, request.commands.len, request.commands, false); + errdefer freeAll(gpa, job.commands); + job.cwds = try dupeAll(gpa, request.cwds.len, request.cwds, true); + errdefer freeAll(gpa, job.cwds); + job.shell = try gpa.dupe(u8, request.shell); + return job; + } + + /// Owned copies of `items` (Inputs or strings); a directory as the + /// host's own path, as `cwd` is. + fn dupeAll(gpa: std.mem.Allocator, n: usize, items: anytype, dirs: bool) ![][]u8 { + const out = try gpa.alloc([]u8, n); var made: usize = 0; - errdefer for (job.inputs[0..made]) |input| gpa.free(input); - for (request.inputs, 0..) |input, i| { - job.inputs[i] = try gpa.dupe(u8, input.bytes); + errdefer { + for (out[0..made]) |item| gpa.free(item); + gpa.free(out); + } + for (items) |item| { + const bytes: []const u8 = if (@TypeOf(item) == Input) item.bytes else item; + out[made] = try gpa.dupe(u8, if (dirs) filesystem.localPath(bytes) orelse bytes else bytes); made += 1; } - return job; + return out; + } + + fn freeAll(gpa: std.mem.Allocator, items: [][]u8) void { + for (items) |item| gpa.free(item); + gpa.free(items); } pub fn deinit(job: *Job, gpa: std.mem.Allocator) void { gpa.free(job.command); gpa.free(job.cwd); - for (job.inputs) |input| gpa.free(input); - gpa.free(job.inputs); + freeAll(gpa, job.inputs); + freeAll(gpa, job.commands); + freeAll(gpa, job.cwds); + gpa.free(job.shell); gpa.destroy(job); } }; @@ -193,6 +227,18 @@ pub fn runOne( command: []const u8, cwd: []const u8, input: []const u8, +) Outcome { + return runIn(gpa, io, "", command, cwd, input); +} + +/// `runOne` through `shell -c` (/bin/sh when it is empty). +pub fn runIn( + gpa: std.mem.Allocator, + io: std.Io, + shell: []const u8, + command: []const u8, + cwd: []const u8, + input: []const u8, ) Outcome { const fail = struct { fn k(kind: Failure.Kind) Outcome { @@ -200,7 +246,8 @@ pub fn runOne( } }; if (std.mem.indexOfScalar(u8, command, 0) != null or - std.mem.indexOfScalar(u8, cwd, 0) != null) return fail.k(.spawn); + std.mem.indexOfScalar(u8, cwd, 0) != null or + std.mem.indexOfScalar(u8, shell, 0) != null) return fail.k(.spawn); // std's spawn runs no code in the child: this thread's mask, which the // child inherits, is cleared across the fork (only the tty's SIGWINCH is @@ -211,7 +258,7 @@ pub fn runOne( std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, &kept); defer std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null); var child = std.process.spawn(io, .{ - .argv = &.{ "/bin/sh", "-c", command }, + .argv = &.{ if (shell.len == 0) "/bin/sh" else shell, "-c", command }, .cwd = if (cwd.len == 0) .inherit else .{ .path = cwd }, .stdin = .pipe, .stdout = .pipe, @@ -301,7 +348,9 @@ pub fn runJob(gpa: std.mem.Allocator, io: std.Io, job: *const Job) Response { var made: usize = 0; var total: usize = 0; for (job.inputs, 0..) |input, i| { - const output = switch (runOne(gpa, io, job.command, job.cwd, input)) { + const command = if (job.commands.len > 0) job.commands[i] else job.command; + const cwd = if (job.cwds.len > 0) job.cwds[i] else job.cwd; + const output = switch (runIn(gpa, io, job.shell, command, cwd, input)) { .ok => |bytes| bytes, .failed => |f| { // WHICH selection, because with several cursors "it failed" is @@ -400,3 +449,22 @@ test "native pipe runner preserves stdin/stdout bytes and reports how it failed" .failed => return error.EarlyStdinCloseShouldNotFail, } } + +test "a request may give each input its own command and directory, run by the shell it names" { + const gpa = std.testing.allocator; + const job = try Job.copy(gpa, .{ + .id = 3, + .command = "", + .cwd = "", + .inputs = &.{ .{ .bytes = "" }, .{ .bytes = "abc" } }, + .commands = &.{ "pwd", "tr a-z A-Z" }, + .cwds = &.{ "/tmp", "/" }, + .shell = "/bin/sh", + }); + defer job.deinit(gpa); + var response = runJob(gpa, std.testing.io, job); + defer response.deinit(gpa); + try std.testing.expect(response.success); + try std.testing.expectEqualStrings("/tmp\n", response.outputs[0]); + try std.testing.expectEqualStrings("ABC", response.outputs[1]); +} diff --git a/test/fs.py b/test/fs.py index 65b354d9..1303db0d 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1008,9 +1008,68 @@ def cut_writes(binary): assert (screen['cols'], screen['rows']) == (132, 40), (screen['cols'], screen['rows']) +def edit_commands(binary): + """Edit's `< | >` run off the loop and answer the write that ran them + once applied; a failing one changes nothing and fails the write in its + words; X edits every open file it matches; w writes. The editor answers + other requests while a slow command runs.""" + with tempfile.TemporaryDirectory(prefix='pardes-edit-') as directory: + root = Path(directory) + (root / 'a.txt').write_bytes(b'pear\napple\nfig\n') + (root / 'b.txt').write_bytes(b'apple pie\n') + with session(binary, root, 'edit') as (client, address): + a = look(client, str(root / 'a.txt')) + b = look(client, str(root / 'b.txt')) + # The write returns with the text sorted, through the session's + # shell in the file's directory. + client.write(f'/pane/{a}/ctl', b'Edit , | sort\n') + assert client.read(f'/pane/{a}/body') == b'apple\nfig\npear\n' + client.write(f'/pane/{a}/ctl', b'Edit $ < pwd\n') + assert client.read(f'/pane/{a}/body') == f'apple\nfig\npear\n{root}\n'.encode() + client.write(f'/pane/{a}/ctl', b'Undo\n') + assert client.read(f'/pane/{a}/body') == b'apple\nfig\npear\n' + # A per-match command, one undo step. + client.write(f'/pane/{a}/ctl', b'Edit ,x/[a-z]+/ | tr a-z A-Z\n') + assert client.read(f'/pane/{a}/body') == b'APPLE\nFIG\nPEAR\n' + # A failing command: nothing changed, the write fails in words, + # its stderr in +Errors. + try: + client.write(f'/pane/{a}/ctl', b'Edit , | echo nope >&2; exit 4\n') + raise AssertionError('a failing Edit command was taken') + except OSError as why: + assert 'exit status 4' in str(why), why + assert client.read(f'/pane/{a}/body') == b'APPLE\nFIG\nPEAR\n' + index = client.read('/index').decode() + errors = [line.split()[0] for line in index.splitlines() if line.endswith(('+Errors', f'{root}/+Errors')) or '+Errors' in line] + assert errors and any(b'nope' in client.read(f'/pane/{e}/body') for e in errors), index + # While a slow command runs, the editor answers. + done = threading.Event() + + def slow(): + with Client(address) as other: + other.write(f'/pane/{b}/ctl', b'Edit , | sleep 1; cat\n') + done.set() + worker = threading.Thread(target=slow) + worker.start() + time.sleep(.2) + began = time.monotonic() + client.read('/index') + assert time.monotonic() - began < .5 and not done.is_set(), 'the editor waited on the command' + worker.join(timeout=15) + assert done.is_set() + # X: each open file whose line matches; w writes it. + client.write(f'/pane/{a}/ctl', b'Edit X/b\\.txt$/ ,s/apple/APPLE/\n') + assert client.read(f'/pane/{b}/body') == b'APPLE pie\n' + client.write(f'/pane/{b}/ctl', b'Edit w\n') + assert (root / 'b.txt').read_bytes() == b'APPLE pie\n' + client.write(f'/pane/{a}/ctl', b'Edit 1 w first.txt\n') + assert (root / 'first.txt').read_bytes() == b'APPLE\n' + + def test(binary, quic=False): started = time.monotonic() cut_writes(binary) + edit_commands(binary) odd_paths(binary) delcol_last_keeps_window(binary) run_file(binary) -- cgit v1.3 From 406f483288c7689bdd2e1f3f68b276c61ca9412a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 20:50:48 -0300 Subject: An Edit's held write: < | > commands no longer block their 9P connection (answered like a held read, so a status read or a filter reading the session's own mount runs beside it), a Tflush or hang-up of the write kills the commands' process groups and changes nothing; e loads by Get's way (asked once, clean after, undo puts the name back); ~ in e r w f B; B checks every name first; an Edit that runs commands is a write of its own, refused up front with other lines; Edit's +Errors output keeps the keyboard where it was; X goes in pane order; a refused write open says its errno; the reference's Coming from acme rows say what Get file's undo, failure and directory refusal, Putall's answer, Zerox across Dump and Incl's directories now do Co-Authored-By: Claude Opus 5.5 --- docs/typ/reference.typ | 39 +++++---- src/9p_io.zig | 73 ++++++++++++++-- src/Pipe.zig | 6 +- src/edit_cmd.zig | 225 +++++++++++++++++++++++++++++++++++++++---------- src/fs.zig | 65 +++++++++++++- src/ninep/ctl.zig | 27 ++++-- src/pardes.zig | 20 ++--- src/sam_edit.zig | 138 ++++++++++++++++++++++++------ src/selection_pipe.zig | 120 +++++++++++++++++++++++++- test/fs.py | 31 +++++++ test/selfmount.py | 26 ++++++ 11 files changed, 649 insertions(+), 121 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 321860d6..efc08a9b 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -689,21 +689,30 @@ open file whose line matches. Commands: - `x y g v c a i d s p = m t u` and `{ }`. - `X`/`Y` run a command in each open file whose line (` +. /path`, `'` when - edited) matches, or does not: `X/'/w` writes every edited file. -- `b` makes a file current, `B` opens files, `D` closes panes (an edited one - on the second asking, as #word("Del")). -- `e` reads a file over the whole text and names the pane after it, `r` - over dot. `w` writes all of it, or the address, to its file or a name; - all of it to its own name leaves it clean. `f` names the pane and prints - its line. + edited) matches, or does not, in the order the panes were opened (as + #file("index") lists them): `X/'/w` writes every edited file. +- `b` makes a file current; `B` opens files, every name checked before any + opens; `D` closes panes (an edited one on the second asking, as + #word("Del")). +- `e` loads a file over the whole text as #word("Get") `file` does, once the + rest of the Edit is done: the pane takes its name and is clean, one undo + step puts both back, and unsaved edits are asked about once; the file + takes no other command in that Edit. `r` reads a file over dot. `w` writes + all of it, or the address, to its file or a name; all of it to its own + name leaves it clean. `f` names the pane and prints its line. File names + are relative to the file's directory, and `~` is the home directory. - `cmd` sends dot to it and prints what it writes. Each command runs in its file's directory through #word("Shell"), off the -loop, so the editor goes on; the write that ran the Edit is answered when -they are done, and a line after it in the same write is refused. A command -that fails (an exit status, 10 seconds, 1 MiB of output) fails the Edit, its -stderr in `+Errors`. Each file's changes are one undo step, applied only if +loop, so the editor goes on. The write that ran the Edit is held and +answered when they are done, its connection serving other requests +meanwhile (a command may read the session through its mount); a flush of +that write (an interrupted writer) kills the commands and changes nothing. +Such an Edit is a write of its own: one with other lines is refused before +any runs. One Edit's commands run at a time in a session, at most 1024 of +them. A command that fails (an exit status, 10 seconds, 1 MiB of output) +fails the Edit, its stderr in `+Errors`. Each file's changes are one undo step, applied only if every command succeeds; a failure changes nothing and fails the write with acme's words (`Edit: no substitution`), as does a file edited while the commands ran. An `x` that finds nothing succeeds silently. `p`, `=` and `>` @@ -1049,12 +1058,12 @@ with Client(sys.argv[1]) as c: # a socket path, or (ip, port) [`addr` reset on first open], [#file("addr") is the pane's; no open resets it (write `0`)], [OTRUNC on `data` ignored], [`: > data` deletes the addressed text; OTRUNC on #file("body") (`9p write`) replaces it all], [event flags 1, 2, 4, 8], [1, 4 and 8; never 2, so no expansion record follows], - [`Get`], [#word("Get") reads the file again, refusing unsaved edits once; `Get file` loads that file into the pane; in a directory pane it reads the directory again (also `get` on #file("ctl"))], + [`Get`], [#word("Get") reads the file again, refusing unsaved edits once; `Get file` loads that file into the pane, which takes its name, and one that fails changes nothing; #word("Undo") after it, or after #word("Edit")'s `e`, puts the old name back with the old text and its saved state; in a directory pane #word("Get") reads the directory again and `Get file` is refused (#word("Look") opens the file) (also `get` on #file("ctl"))], [`Put`, `Delete`, `Load`], [#word("Save"); a #word("Del") that does not ask; #word("Restore")], - [`Putall`], [#word("Putall"): every pane with unsaved edits to a file is saved, a refused one said], - [`Zerox`], [#word("Zerox"): a second pane on the buffer, one text, undo and unsaved state, its own scroll and cursor; an event reader on one hears no edit made through the other], + [`Putall`], [#word("Putall"): every pane with unsaved edits to a file is saved, a refused one said; with a refusal, its write is answered once the other saves have landed], + [`Zerox`], [#word("Zerox"): a second pane on the buffer, one text, undo and unsaved state, its own scroll and cursor; an event reader on one hears no edit made through the other; the twins are kept across #word("Dump") and #word("Restore")], [`Tab`], [#word("Tab") `N`, 1-16: for every pane, not per window; bare, it says the width], - [`Incl`], [#word("Incl"): for the session, not per window, seeded with `/usr/include` and `/usr/local/include`; a name found nowhere else (`stdio.h`, ``) is tried there], + [`Incl`], [#word("Incl"): for the session, not per window, seeded with `/usr/include` and `/usr/local/include`; it takes absolute (or `~`) directories that exist, and `Incl -` alone clears the list; a name found nowhere else (`stdio.h`, ``) is tried there], [`Indent`], [always on: #key("Enter"), #key("o") and #key("O") keep the line's indent as it is], [`Snarf`, `Cut`, `Paste`], [refused: the chords, #key("y"), #key("p")], [`Font`, `Send`, `ID`], [#word("Font"); #word("Repl") and #word("Exec"); `$winid`], diff --git a/src/9p_io.zig b/src/9p_io.zig index 46bbb2ba..a01eb491 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -180,6 +180,10 @@ pub const Listener = struct { restore_writer: std.atomic.Value(bool) = .init(false), /// Clients turned away with every slot taken, since the log last said so. refused: std.atomic.Value(u32) = .init(0), + /// Writes being served right now, a retry of a parked one included: a + /// held Edit write a retry has taken out of its park is not flushed + /// (watchEdit). + writes_out: std.atomic.Value(u32) = .init(0), /// Connections accepted so far, and the count each slot's connection /// was accepted at: a Restore cuts those accepted before it (`reset`), /// and a new client in a freed slot has a later stamp. Written on the @@ -241,6 +245,10 @@ pub const Listener = struct { fn onServe(ctx: ?*anyopaque, conn: *Runner.Conn, req: pardes.ctlfs.Req) void { const l = of(ctx); + if (req.op == .write) _ = l.writes_out.fetchAdd(1, .acq_rel); + defer if (req.op == .write) { + _ = l.writes_out.fetchSub(1, .acq_rel); + }; // Once `stop` has begun the editor is tearing down and may never // rest again: answer without waiting on it. if (l.stopping.load(.acquire)) { @@ -268,9 +276,11 @@ pub const Listener = struct { const changes = pardes.ctlfs.changesPane(core, req); const fills = pardes.ctlfs.handsOff(core, req); const reply = core.serveFs(req); - // Taken now: a request served while this one waits starts afresh. - const edit_at = core.fs.edit_answer_at; - core.fs.edit_answer_at = null; + const edit_started = core.fs.edit_started; + core.fs.edit_started = false; + // The held Edit write asked again by a retry, its Edit still + // running: parked again, as it was. + if (reply.status == .again and req.op == .write) return conn.reply(&reply, ""); if (req.op == .release and quiet) l.collectOs(); // A close's held last line runs now when no step is out, so its err // is logged before the close is answered, as before; with a step @@ -335,6 +345,19 @@ pub const Listener = struct { // is on its way out and will settle nothing this could wait for, // and `deinit` lets the answer out before it cuts the connections. if (core.quit) return conn.reply(&reply, ""); + // An Edit whose `<`, `|` or `>` commands run off the loop: the write + // is held, as a read with nothing yet is, and answered when the Edit + // is done (answerHeld), so the connection serves on meanwhile -- a + // filter that reads this session through a mount among what it + // serves. A flush of it, or a hang-up, stops the Edit (watchEdit). + if (edit_started and core.pipe.edit_run != null) { + const later: pardes.ctlfs.Reply = .{ .tag = req.tag, .status = .again }; + const ticket = conn.hold(&later) orelse return; + core.fs.edit_hold = .{ .asker = conn, .slot = ticket.slot, .seq = ticket.seq, .tag = req.tag, .node = req.node, .handle = req.handle, .written = reply.written }; + const watcher = std.Thread.spawn(.{}, watchEdit, .{ l, conn, ticket }) catch return; + watcher.detach(); + return; + } const restoring = core.restore_req != null; // Set with the turn still held, so `reset` sees it and waits. if (restoring) l.restore_writer.store(true, .release); @@ -360,10 +383,6 @@ pub const Listener = struct { } }; } - // An Edit whose `<`, `|` or `>` commands run off the loop: the write - // is answered once they have and the Edit is applied, or failed - // (late_failure), as `echo Edit , | sort > ctl` must return sorted. - if (edit_at) |n| if (l.core == core) pardes.turn.awaitEdit(n); core.fs.write_waits = false; // ponytail: one slot, so a failure of another client's effects that // settle in the same wait is told to this write too. @@ -418,6 +437,46 @@ pub const Listener = struct { const conn: *Runner.Conn = @ptrCast(@alignCast(held.asker)); if (!conn.answerWith(held.ticket, Held{ .core = core, .req = held.req }, Held.make)) o.held = null; } + // An Edit's held write, its Edit done. Not waiting: a retry has it + // out, and its asking answers it (Pardes.serveFs); or it was + // flushed, and watchEdit lets the record go. + if (core.fs.edit_hold) |h| if (h.done) { + const conn: *Runner.Conn = @ptrCast(@alignCast(h.asker)); + _ = conn.answerWith(.{ .slot = h.slot, .seq = h.seq }, core, struct { + fn make(c: *pardes.Pardes) ?Runner.Conn.Answer { + return .{ .reply = pardes.filesystem.EditHold.answer(&c.fs) }; + } + }.make); + }; + } + + /// While an Edit's write is held: when nobody waits for it any more -- + /// flushed (an interrupted writer), its fid clunked, its connection + /// hung up -- the Edit is stopped, its commands killed, nothing + /// changed (edit_cmd.cancel). The engine tells the backend nothing of a + /// flush, so it is looked for, every 100 ms; a park out for a retry is + /// not waiting either, so only three looks in a row with no write being + /// served count. + fn watchEdit(l: *Listener, conn: *Runner.Conn, ticket: cloud9.fs.Ticket) void { + const io = pardes.turn.io orelse return; + var misses: u8 = 0; + while (!l.stopping.load(.acquire)) { + io.sleep(.fromMilliseconds(100), .awake) catch return; + _ = pardes.turn.take(); + defer pardes.turn.give(); + const core = l.core; + const h = core.fs.edit_hold orelse return; + if (h.slot != ticket.slot or h.seq != ticket.seq or h.asker != @as(*anyopaque, conn)) return; + if (conn.waiting(ticket) or l.writes_out.load(.acquire) != 0) { + misses = 0; + continue; + } + misses += 1; + if (misses < 3) continue; + if (h.done) core.fs.edit_hold = null else @import("edit_cmd.zig").cancel(core); + l.kick(); + return; + } } /// A held read asked again, to make its answer while its park waits. diff --git a/src/Pipe.zig b/src/Pipe.zig index 6981c023..850f9c64 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -26,11 +26,7 @@ writes: std.ArrayList(edit_cmd.Write) = .empty, pub fn deinit(pipe: *Pipe, gpa: std.mem.Allocator) void { if (pipe.wait) |*wait| wait.deinit(gpa); - if (pipe.edit_run) |pending| { - pending.deinit(gpa); - // A 9P write waiting on it is answered (the core is going). - pardes.turn.editAnswered(); - } + if (pipe.edit_run) |pending| pending.deinit(gpa); for (pipe.writes.items) |*w| w.deinit(gpa); pipe.writes.deinit(gpa); } diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig index 7f5c6279..4e2c09fd 100644 --- a/src/edit_cmd.zig +++ b/src/edit_cmd.zig @@ -11,7 +11,8 @@ //! Shell, and the Edit is applied when they have all answered -- or not at //! all, when one fails or a file it changes was edited meanwhile. One Edit //! waits at a time; a 9P write that ran it is answered when it is done -//! (9p_io, `fs.edit_answer_at`). +//! (9p_io, `fs.edit_hold`), the connection serving on meanwhile; a flush +//! of that write stops the commands and changes nothing. const std = @import("std"); const pardes = @import("pardes.zig"); const sam = @import("sam_edit.zig"); @@ -67,6 +68,27 @@ const World = struct { p: *Pardes, from: usize, + fn check(ctx: *anyopaque, path: []const u8, why: *sam.Why) bool { + const w: *World = @ptrCast(@alignCast(ctx)); + for (w.p.panes) |slot| { + const pane = slot orelse continue; + const f = ninep_pane.fileOf(pane) orelse continue; + if (std.mem.eql(u8, f.path, path)) return true; + } + if (comptime !pardes.hosted) return true; + const local = filesystem.localPath(path) orelse return true; + if (@import("exec.zig").isDirectory(local)) return said(bool, why, "B: {s} is a directory", .{path}) orelse false; + var buf: [4096]u8 = undefined; + if (filesystem.resolveOs(local, &buf) == null) return said(bool, why, "B: {s}: no such file", .{path}) orelse false; + return true; + } + + fn refuseGet(ctx: *anyopaque, id: usize, why: *sam.Why) bool { + const w: *World = @ptrCast(@alignCast(ctx)); + const words = @import("ninep/ctl.zig").getRefused(w.p, w.p.panes[id] orelse return false, "e") orelse return false; + return said(bool, why, "{s}", .{words}) orelse true; + } + fn open(ctx: *anyopaque, path: []const u8, why: *sam.Why) ?sam.File { const w: *World = @ptrCast(@alignCast(ctx)); const p = w.p; @@ -135,20 +157,27 @@ pub fn run(p: *Pardes, id: usize, command: []const u8) void { defer if (!keep) pd.deinit(p.gpa); const arena = pd.arena.allocator(); - // Every text pane, column by column as acme's allwindows goes, then any - // not in a column; the Edit starts in its own. + // Every text pane in the order they were made, as /index lists them, + // so X goes the same way whatever the layout; the Edit starts in its own. var files: std.ArrayList(sam.File) = .empty; - var cur: usize = 0; - var seen: [pardes.MAX_PANES]bool = @splat(false); - for (0..p.ncol) |c| { - for (p.col_panes[c][0..p.col_n[c]]) |slot| addFile(p, &files, arena, slot, id, &cur, &seen) catch |err| return p.reportError(id, "Edit", err); + for (p.panes, 0..) |slot, i| { + const q = slot orelse continue; + if (q.file == null) continue; + files.append(arena, fileOf(q, i)) catch |err| return p.reportError(id, "Edit", err); } - for (0..pardes.MAX_PANES) |slot| addFile(p, &files, arena, slot, id, &cur, &seen) catch |err| return p.reportError(id, "Edit", err); + std.mem.sort(sam.File, files.items, p, struct { + fn before(core: *Pardes, a: sam.File, b: sam.File) bool { + return core.panes[a.id].?.serial < core.panes[b.id].?.serial; + } + }.before); + const cur = for (files.items, 0..) |f, i| { + if (f.id == id) break i; + } else unreachable; var world: World = .{ .p = p, .from = id }; var why: sam.Why = .{}; var text: [260]u8 = undefined; - const res = sam.run(arena, files.items, cur, command, .{ .ctx = &world, .open = World.open, .read = World.read }, &why) catch |err| switch (err) { + const res = sam.run(arena, files.items, cur, command, .{ .ctx = &world, .check = World.check, .open = World.open, .read = World.read, .refuseGet = World.refuseGet }, &why) catch |err| switch (err) { error.Edit => return p.reportFailure(id, std.fmt.bufPrint(&text, "Edit: {s}", .{why.text()}) catch "Edit: failed"), error.OutOfMemory => return p.reportError(id, "Edit", err), }; @@ -190,21 +219,45 @@ pub fn run(p: *Pardes, id: usize, command: []const u8) void { .commands = commands, .cwds = cwds, .shell = arena.dupe(u8, p.shellBin()) catch |err| return p.reportError(id, "Edit", err), + .token = selection_pipe.newToken(), }; keep = true; p.pipe.edit_run = pd; p.emit(.{ .pipe = .{ .id = pd.id } }); - // A 9P write that ran it is answered once it is done. - if (p.fs.serving) p.fs.edit_answer_at = pardes.turn.edit_answers; + // A 9P write that ran it is held, and answered once it is done + // (9p_io, fs.edit_hold); the connection serves on meanwhile. + if (p.fs.serving) p.fs.edit_started = true; +} + +/// The Edit waiting on its commands, stopped: its write was flushed, or +/// its connection hung up (9p_io). Its commands are killed, and nothing +/// changes. +pub fn cancel(p: *Pardes) void { + p.fs.edit_hold = null; + const pd = p.pipe.edit_run orelse return; + p.pipe.edit_run = null; + selection_pipe.stop(pd.request.token); + if (p.panes[pd.origin]) |pane| if (pane.serial == pd.origin_serial) + p.setMessage(pd.origin, "Edit: interrupted; nothing changed"); + pd.deinit(p.gpa); } -fn addFile(p: *Pardes, files: *std.ArrayList(sam.File), arena: std.mem.Allocator, slot: usize, from: usize, cur: *usize, seen: *[pardes.MAX_PANES]bool) !void { - if (seen[slot]) return; - seen[slot] = true; - const pane = p.panes[slot] orelse return; - if (pane.file == null) return; - if (slot == from) cur.* = files.items.len; - try files.append(arena, fileOf(pane, slot)); +/// The held 9P write that ran the Edit has its answer: done, failed in the +/// words said on pane `at` when `failed`. +fn answerHold(p: *Pardes, at: usize, failed: bool) void { + const h = if (p.fs.edit_hold) |*held| held else return; + h.done = true; + p.fs.news = true; + if (!failed) return; + const words = if (p.fs.said_at == p.fs.failures and p.fs.said_len > 0) + p.fs.said[0..p.fs.said_len] + else if (p.panes[at]) |pane| pane.msg[0..pane.msg_len] else "Edit: failed"; + const kept = @import("Messages.zig").clip(words, h.said.len); + @memcpy(h.said[0..kept.len], kept); + h.said_len = @intCast(kept.len); + h.errno = @import("ninep/ctl.zig").failureErrno(kept); + // The write's err record, as a refusal answered at once has. + pardes.ctlfs.events.noteError(p, .{ .tag = h.tag, .op = .write, .node = h.node, .handle = h.handle }, @import("ninep/tree.zig").failText(h.tag, h.errno, h.said[0..h.said_len])); } /// The commands answered (pipe_resp): the Edit applied, or why not. @@ -212,11 +265,10 @@ pub fn finish(p: *Pardes, success: bool, outputs: []const []const u8, failure: ? const pd = p.pipe.edit_run orelse return; p.pipe.edit_run = null; defer pd.deinit(p.gpa); - defer pardes.turn.editAnswered(); const at = if (p.panes[pd.origin]) |pane| (if (pane.serial == pd.origin_serial) pd.origin else p.active) else p.active; // Whatever fails from here fails the 9P write that ran it too. const failures = p.fs.failures; - defer if (p.fs.failures != failures) p.noteLateFailure(at); + defer answerHold(p, at, p.fs.failures != failures); if (success and outputs.len == pd.res.jobs.len) return commit(p, pd, outputs); // Which command, in +Errors with its own words; the Edit changed nothing. @@ -232,7 +284,9 @@ pub fn finish(p: *Pardes, success: bool, outputs: []const []const u8, failure: ? Pipe.writeFailure(w, failure) catch break :report; const why = std.mem.sliceTo(out.written()[why_at..], '\n'); const said = std.fmt.bufPrint(&line, "Edit: {c} {s}: {s}", .{ job.c, job.command[0..@min(job.command.len, 120)], why }) catch "Edit: a command failed"; + const was = p.active; _ = ninep_pane.appendErrors(p, at, out.written()); + if (p.panes[was] != null) p.active = was; return p.reportFailure(at, said); } p.reportFailure(at, "Edit: a command failed"); @@ -245,12 +299,21 @@ fn commit(p: *Pardes, pd: *Pending, outputs: []const []const u8) void { const at = if (p.panes[pd.origin]) |pane| (if (pane.serial == pd.origin_serial) pd.origin else p.active) else p.active; var text: [320]u8 = undefined; for (res.files, 0..) |f, i| { - if (f.ops.items.len == 0 and !f.close and !f.renamed and !f.moved) continue; + if (f.ops.items.len == 0 and !f.close and !f.renamed and !f.moved and f.get == null) continue; const pane = p.panes[f.id] orelse return p.reportFailure(at, std.fmt.bufPrint(&text, "Edit: {s} closed while its commands ran; nothing changed", .{f.name}) catch "Edit: a pane closed"); if (pane.serial != pd.serials[i]) return p.reportFailure(at, std.fmt.bufPrint(&text, "Edit: {s} closed while its commands ran; nothing changed", .{f.name}) catch "Edit: a pane closed"); - if (f.ops.items.len > 0 and pane.file.?.revision != pd.revisions[i]) + if ((f.ops.items.len > 0 or f.get != null) and pane.file.?.revision != pd.revisions[i]) return p.reportFailure(at, std.fmt.bufPrint(&text, "Edit: {s} changed while its commands ran; nothing changed", .{f.name}) catch "Edit: a file changed"); } + // e first, Get's way: read before anything is changed, so one that + // cannot be read changes nothing; its own undo step puts the old name + // back with the old text, and it leaves the pane clean. + for (res.files) |f| { + const path = f.get orelse continue; + var failed: anyerror = error.Unexpected; + const errno = @import("ninep/ctl.zig").getFile(p, p.panes[f.id].?, path, &failed); + if (errno != 0) return p.reportFailure(at, std.fmt.bufPrint(&text, "Edit: e {s}: {s}", .{ path, if (errno == @import("ninep/tree.zig").E.NOENT) "no such file" else "cannot be read" }) catch "Edit: e failed"); + } // `w`'s bytes, written after this step, before anything else is. for (res.writes) |wr| { const f = res.files[wr.file]; @@ -291,11 +354,6 @@ fn commit(p: *Pardes, pd: *Pending, outputs: []const []const u8) void { panes.File.pushUndo(p, pane); panes.File.setContent(p, pf, new); } - // e read its own file over it: what is on disk again. - if (f.clean) { - pf.saved_revision = pf.revision; - pf.disk_gone = false; - } } if (ops.len > 0 or f.moved) ninep_pane.setDot(pane, sam.moveDot(f.dot, ops)); if (f.renamed) ninep_pane.nameBuffer(p, f.id, f.name, false) catch |err| p.reportError(f.id, "Edit", err); @@ -312,7 +370,11 @@ fn commit(p: *Pardes, pd: *Pending, outputs: []const []const u8) void { from = job.at; } out.appendSlice(p.gpa, res.printed[from..]) catch return; + // Printed, the keyboard stays where it was: a +Errors made for it + // does not take it, so the next Edit lands where this one did. + const was = p.active; if (out.items.len > 0) _ = ninep_pane.appendErrors(p, at, out.items); + if (p.panes[was] != null) p.active = was; } // D's panes last, each as Del closes one: an edited one is warned about // once, and closes on the next. @@ -344,6 +406,17 @@ fn runReal(p: *Pardes) !void { p.update(.{ .pipe_resp = .{ .id = pd.id, .success = response.success, .outputs = response.outputs, .failure = response.failure } }); } +/// Whether any +Errors holds `needle`. +fn errorsHas(p: *Pardes, needle: []const u8) bool { + for (p.panes) |slot| { + const q = slot orelse continue; + const qf = q.file orelse continue; + const o = qf.output orelse continue; + if (std.meta.activeTag(o.from) == .errors and std.mem.indexOf(u8, qf.content, needle) != null) return true; + } + return false; +} + fn errorsText(p: *Pardes) ?[]const u8 { for (p.panes) |slot| { const q = slot orelse continue; @@ -358,8 +431,9 @@ test "Edit , | sort runs off the loop, through the session's shell in the file's const p = try th.withFile(testing.allocator, "b\na\nc\n"); defer p.deinit(); const serial = th.serialOf(p); - const answers = pardes.turn.edit_answers; try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(serial, .ctl), "Edit , | sort\n").reply.status); + // The listener is told to hold the write. + try testing.expect(p.fs.edit_started); // Nothing changed yet: the command is out. try testing.expectEqualStrings("b\na\nc\n", p.panes[0].?.file.?.content); const req = p.pipe.pipeRequest(p.pipe.edit_run.?.id).?; @@ -371,17 +445,55 @@ test "Edit , | sort runs off the loop, through the session's shell in the file's try testing.expectEqual(tree.E.IO, th.wr(p, tree.Node.of(serial, .ctl), "Edit ,d\n").errno()); answer(p, &.{"a\nb\nc\n"}); try testing.expect(p.pipe.edit_run == null); - try testing.expectEqual(answers +% 1, pardes.turn.edit_answers); try testing.expectEqualStrings("a\nb\nc\n", p.panes[0].?.file.?.content); try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(serial, .ctl), "Undo\n").reply.status); try testing.expectEqualStrings("b\na\nc\n", p.panes[0].?.file.?.content); - // What follows it in the same write would run before its commands - // answer: refused, and the Edit goes on. - const after = th.wr(p, tree.Node.of(serial, .ctl), "Edit , | sort\nSave\n"); - try testing.expectEqual(tree.E.INVAL, after.errno()); - try testing.expectEqualStrings(@import("ninep/ctl.zig").e_after_edit, after.reply.ename); - answer(p, &.{"a\nb\nc\n"}); - try testing.expectEqualStrings("a\nb\nc\n", p.panes[0].?.file.?.content); + // Another line in its write would run before its commands answer: the + // whole write is refused before any line runs, the one before it too. + for ([_][]const u8{ "Edit , | sort\nSave\n", "Msg before\nEdit , | sort\nMsg after\n" }) |two| { + const after = th.wr(p, tree.Node.of(serial, .ctl), two); + try testing.expectEqual(tree.E.INVAL, after.errno()); + try testing.expectEqualStrings(@import("ninep/ctl.zig").e_after_edit, after.reply.ename); + try testing.expect(p.pipe.edit_run == null and !th.logHas(p, "before")); + } + try testing.expectEqual(tree.E.INVAL, th.wr(p, @intFromEnum(tree.TopFile.exec), "Msg before\nEdit , | sort\n").errno()); +} + +test "the held write asked again is parked again, then answered once, and a flush stops the Edit" { + const p = try th.withFile(testing.allocator, "b\na\n"); + defer p.deinit(); + const ctl = tree.Node.of(th.serialOf(p), .ctl); + const req: tree.Req = .{ .tag = 7, .op = .write, .node = ctl, .handle = 0, .data = "Edit , | sort\n" }; + try testing.expectEqual(tree.Status.ok, p.serveFs(req).status); + // As 9p_io holds it. + p.fs.edit_hold = .{ .asker = @ptrCast(p), .slot = 0, .seq = 1, .tag = 7, .node = ctl, .handle = 0, .written = @intCast(req.data.len) }; + // A retry of its park: still waiting, never run a second time. + try testing.expectEqual(tree.Status.again, p.serveFs(req).status); + try testing.expect(p.pipe.edit_run != null); + answer(p, &.{"a\nb\n"}); + try testing.expect(p.fs.edit_hold.?.done); + const done = p.serveFs(req); + try testing.expectEqual(tree.Status.ok, done.status); + try testing.expectEqual(@as(u32, @intCast(req.data.len)), done.written); + try testing.expect(p.fs.edit_hold == null); + try testing.expectEqualStrings("a\nb\n", p.panes[0].?.file.?.content); + // A failure is the held write's answer, in the Edit's words. + _ = p.serveFs(.{ .tag = 8, .op = .write, .node = ctl, .data = "Edit , | false\n" }); + p.fs.edit_hold = .{ .asker = @ptrCast(p), .slot = 0, .seq = 2, .tag = 8, .node = ctl, .handle = 0, .written = 15 }; + p.update(.{ .pipe_resp = .{ .id = p.pipe.edit_run.?.id, .success = false, .outputs = &.{}, .failure = .{ .kind = .exit, .code = 1 } } }); + const failed = filesystem.EditHold.answer(&p.fs); + try testing.expectEqual(tree.Status.err, failed.status); + try testing.expectEqualStrings("Edit: | false: exit status 1", failed.ename); + // Flushed (or hung up): its commands stopped, nothing changed, and the + // next Edit is free to run; the stopped one's late answer is no one's. + _ = p.serveFs(.{ .tag = 9, .op = .write, .node = ctl, .data = "Edit , | sort -r\n" }); + const stale = p.pipe.edit_run.?.id; + p.fs.edit_hold = .{ .asker = @ptrCast(p), .slot = 0, .seq = 3, .tag = 9, .node = ctl, .handle = 0, .written = 18 }; + cancel(p); + try testing.expect(p.pipe.edit_run == null and p.fs.edit_hold == null); + p.update(.{ .pipe_resp = .{ .id = stale, .success = true, .outputs = &.{"b\na\n"} } }); + try testing.expectEqualStrings("a\nb\n", p.panes[0].?.file.?.content); + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit , | cat\n").reply.status); } test "Edit's < | and > with a real shell: a command per address, > printed to +Errors" { @@ -399,6 +511,8 @@ test "Edit's < | and > with a real shell: a command per address, > printed to +E try testing.expectEqualStrings("ONE TWO\nnew", p.panes[0].?.file.?.content); try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit , > wc -l\n").reply.status); try runReal(p); + // The +Errors it opened did not take the keyboard. + try testing.expectEqual(@as(usize, 0), p.active); try testing.expectEqualStrings("ONE TWO\nnew", p.panes[0].?.file.?.content); try testing.expectEqualStrings("1", std.mem.trim(u8, errorsText(p).?, " \n")); } @@ -409,11 +523,12 @@ test "a failing command changes nothing and says why, its stderr in +Errors" { defer p.deinit(); const ctl = tree.Node.of(th.serialOf(p), .ctl); try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit , | echo boom >&2; exit 3\n").reply.status); - p.fs.late_failure_len = 0; + p.fs.edit_hold = .{ .asker = @ptrCast(p), .slot = 0, .seq = 1, .tag = 2, .node = ctl, .handle = 0, .written = 1 }; try runReal(p); try testing.expectEqualStrings("keep\n", p.panes[0].?.file.?.content); try testing.expectEqual(@as(usize, 0), p.panes[0].?.file.?.history.undo_len); - try testing.expectEqualStrings("Edit: | echo boom >&2; exit 3: exit status 3", p.fs.late_failure[0..p.fs.late_failure_len]); + // The held write's answer is the failure, in its words. + try testing.expectEqualStrings("Edit: | echo boom >&2; exit 3: exit status 3", filesystem.EditHold.answer(&p.fs).ename); const report = errorsText(p).?; try testing.expect(std.mem.indexOf(u8, report, "Edit: | echo boom") != null); try testing.expect(std.mem.indexOf(u8, report, "boom\n") != null); @@ -422,12 +537,13 @@ test "a failing command changes nothing and says why, its stderr in +Errors" { test "an Edit whose file is edited while its commands run is refused whole" { const p = try th.withFile(testing.allocator, "abc\n"); defer p.deinit(); - try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(th.serialOf(p), .ctl), "Edit , | cat\n").reply.status); + const ctl = tree.Node.of(th.serialOf(p), .ctl); + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit , | cat\n").reply.status); + p.fs.edit_hold = .{ .asker = @ptrCast(p), .slot = 0, .seq = 1, .tag = 2, .node = ctl, .handle = 0, .written = 1 }; panes.File.setContent(p, &p.panes[0].?.file.?, try testing.allocator.dupe(u8, "typed\n")); - p.fs.late_failure_len = 0; answer(p, &.{"ABC\n"}); try testing.expectEqualStrings("typed\n", p.panes[0].?.file.?.content); - try testing.expectEqualStrings("Edit: /test.txt changed while its commands ran; nothing changed", p.fs.late_failure[0..p.fs.late_failure_len]); + try testing.expectEqualStrings("Edit: /test.txt changed while its commands ran; nothing changed", filesystem.EditHold.answer(&p.fs).ename); } test "X over open files, w, e, r, f, B and D on panes and the disk" { @@ -439,6 +555,7 @@ test "X over open files, w, e, r, f, B and D on panes and the disk" { try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.h", .data = "foo\n" }); try tmp.dir.writeFile(testing.io, .{ .sub_path = "c.c", .data = "foo bar\n" }); try tmp.dir.writeFile(testing.io, .{ .sub_path = "data", .data = "DATA\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "n.c", .data = "new\n" }); var dir_buf: [4096]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; const p = try th.withFile(gpa, "scratch\n"); @@ -453,6 +570,11 @@ test "X over open files, w, e, r, f, B and D on panes and the disk" { try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit X/\\.[ch]$/ ,s/foo/FOO/g\n").reply.status); try testing.expectEqualStrings("int FOO;\n", p.panes[a].?.file.?.content); try testing.expectEqualStrings("scratch\n", p.panes[0].?.file.?.content); + // X alone lists them in the order they were opened, as /index does. + try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, "Edit X\n").reply.status); + const listed = errorsText(p).?; + try testing.expect(std.mem.indexOf(u8, listed, "/test.txt").? < std.mem.indexOf(u8, listed, "/a.c").?); + try testing.expect(std.mem.indexOf(u8, listed, "/a.c").? < std.mem.indexOf(u8, listed, "/b.h").?); // B opens a file, which a `"re"` address then edits, from pane 0. var cmd: [4400]u8 = undefined; try testing.expectEqual(tree.Status.ok, th.wr(p, ctl, try std.fmt.bufPrint(&cmd, "Edit B {s}/c.c\n", .{dir})).reply.status); @@ -469,11 +591,26 @@ test "X over open files, w, e, r, f, B and D on panes and the disk" { try testing.expect(!ninep_pane.dirtyOf(p.panes[a].?)); try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(p.panes[c].?.serial, .ctl), "Edit 1 r data\n").reply.status); try testing.expectEqualStrings("DATA\n", p.panes[c].?.file.?.content); - // e of an edited file is refused; f names one and prints it. - try testing.expectEqual(tree.E.IO, th.wr(p, tree.Node.of(p.panes[c].?.serial, .ctl), "Edit e\n").errno()); + // e of an edited file is asked about once, as Get asks; again, it is + // read in Get's way, which leaves the pane clean and named after it. + const c_ctl = tree.Node.of(p.panes[c].?.serial, .ctl); + try testing.expect(th.wr(p, c_ctl, "Edit e data\n").reply.status == .err); + try testing.expectEqualStrings("DATA\n", p.panes[c].?.file.?.content); + try testing.expect(ninep_pane.dirtyOf(p.panes[c].?)); + try testing.expectEqual(tree.Status.ok, th.wr(p, c_ctl, "Edit e data\n").reply.status); + try testing.expect(std.mem.endsWith(u8, p.panes[c].?.file.?.path, "/data")); + try testing.expect(!ninep_pane.dirtyOf(p.panes[c].?)); + // B checks every name first: a directory among them opens none. + const before = p.next_serial; + try testing.expect(th.wr(p, ctl, try std.fmt.bufPrint(&cmd, "Edit B {s}/n.c {s}\n", .{ dir, dir })).reply.status == .err); + try testing.expectEqual(before, p.next_serial); + // f names one and prints it. + try testing.expectEqual(tree.Status.ok, th.wr(p, c_ctl, "Edit 1 c/edited/\n").reply.status); try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(p.panes[c].?.serial, .ctl), "Edit f d.c\n").reply.status); try testing.expect(std.mem.endsWith(u8, p.panes[c].?.file.?.path, "/d.c")); - try testing.expect(std.mem.indexOf(u8, errorsText(p).?, "'+. ") != null); + // In its directory's +Errors, or the log when the screen has no room + // left for one. + try testing.expect(errorsHas(p, "'+. ") or th.logHas(p, "'+. ")); // D closes a pane by name, an edited one (b.h, by the X) on the // second asking, as Del does. const b_serial = for (p.panes) |slot| { diff --git a/src/fs.zig b/src/fs.zig index 2a5102f4..db07672e 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -85,6 +85,14 @@ pub const WriteError = error{ NoSpaceLeft, OpenFailed, WriteFailed, + // The rest are open(2)'s errno, named so errorWords says them. + NoSuchFileOrDirectory, + NotDir, + InvalidArgument, + FileBusy, + SymLinkLoop, + NoSuchDeviceOrAddress, + FileTooBig, }; /// The host takes the bytes. The caller has given the turn up (`write`), @@ -102,6 +110,13 @@ pub fn writeFile(path: []const u8, bytes: []const u8) WriteError!void { .ROFS => error.ReadOnlyFilesystem, .NOSPC, .DQUOT => error.NoSpaceLeft, .NAMETOOLONG => error.PathTooLong, + .NOENT => error.NoSuchFileOrDirectory, + .NOTDIR => error.NotDir, + .INVAL => error.InvalidArgument, + .BUSY, .TXTBSY => error.FileBusy, + .LOOP => error.SymLinkLoop, + .NXIO, .NODEV => error.NoSuchDeviceOrAddress, + .FBIG => error.FileTooBig, else => error.OpenFailed, }; var off: usize = 0; @@ -1554,6 +1569,36 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { return buf; } +/// A 9P write of an Edit held while its commands run (Namespace.edit_hold). +pub const EditHold = struct { + /// The listener's: the connection that asked, and its park. + asker: *anyopaque, + slot: u16, + seq: u64, + tag: u64, + node: u64, + handle: u32, + written: u32, + /// The Edit is done: applied, or failed with `said`. + done: bool = false, + errno: u16 = 0, + said: [256]u8 = undefined, + said_len: u16 = 0, + + pub fn names(h: *const EditHold, req: tree.Req) bool { + return req.op == .write and req.tag == h.tag and req.node == h.node and req.handle == h.handle; + } + + /// Its answer, the held record let go: the words copied out first. + pub fn answer(ns: *Namespace) tree.Reply { + const h = ns.edit_hold.?; + ns.edit_hold = null; + if (h.errno == 0) return .{ .tag = h.tag, .written = h.written }; + @memcpy(ns.edit_said[0..h.said_len], h.said[0..h.said_len]); + return tree.failText(h.tag, h.errno, ns.edit_said[0..h.said_len]); + } +}; + pub const Namespace = struct { socket_path: []const u8 = "", tcp_address: ?std.Io.net.IpAddress = null, @@ -1613,9 +1658,15 @@ pub const Namespace = struct { /// A 9P write asked a language server something: the answer count it /// waits to change (`turn.lsp_answers`), so its failure is the write's. lsp_answer_at: ?u64 = null, - /// A write ran an Edit whose `<`, `|` or `>` commands are running: it is - /// answered once `turn.edit_answers` passes this, the Edit done. - edit_answer_at: ?u64 = null, + /// The request being served started an Edit whose `<`, `|` or `>` + /// commands run off the loop (edit_cmd.zig): the listener holds it. + edit_started: bool = false, + /// That write, held: answered once `done` (9p_io answerHeld), or + /// asked again by a retry of its park (Pardes.serveFs); a flush or a + /// hang-up stops the Edit (9p_io watchEdit). + edit_hold: ?EditHold = null, + /// The words a held Edit write was refused with, kept for its answer. + edit_said: [256]u8 = undefined, /// The pane a language answer filled (a Rename's preview): what the /// waiting 9P write answers once it is in (9p_io). lsp_result: ?u32 = null, @@ -1757,3 +1808,11 @@ test { test "the tree's README lists src/ only when the build serves it" { try std.testing.expectEqual(limits.embedded_sources, std.mem.indexOf(u8, help, "src/") != null); } + +test "a write open(2) refuses says its errno in words" { + if (comptime @import("builtin").os.tag != .linux or !pardes.hosted) return error.SkipZigTest; + // /proc takes no new file: ENOENT, which used to read "open failed". + try std.testing.expectError(error.NoSuchFileOrDirectory, writeFile("/proc/pardes-no-such-file", "x")); + var words: [128]u8 = undefined; + try std.testing.expectEqualStrings("no such file or directory", pardes.Messages.errorWords(error.NoSuchFileOrDirectory, &words)); +} diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 274caf88..8ece7ead 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -193,6 +193,7 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep // The root's lines run at the keyboard's pane: a refusal before any runs // is that pane's too, in its err record. p.fs.ran_at = if (serial == null) (if (p.panes[p.active]) |pane| pane.serial else 0) else 0; + if (editNotAlone(p, req.data)) return tree.failText(req.tag, E.INVAL, e_after_edit); for ([2]bool{ false, true }) |apply| { if (apply) p.fs.results_len = 0; var it = Messages.init(p, req.data); @@ -203,7 +204,6 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep for (text) |c| if ((c < ' ' and c != '\t' and c != '\n') or c == 0x7f) return tree.failText(req.tag, E.INVAL, e_control); if (exec) if (tooLong(req, text)) |refusal| return refusal; if (!apply) continue; - if (p.fs.edit_answer_at != null) return tree.failText(req.tag, E.INVAL, e_after_edit); var id = if (serial) |s| p.paneBySerial(s) orelse break else p.active; // No pane at all: the root's look and exec act in the session's // directory. An exec runs as the workspace tag's; a look from a @@ -260,10 +260,25 @@ pub fn tooLong(req: Req, line: []const u8) ?Reply { pub const e_control = "invalid command line: it holds a control character (or DEL) other than a tab"; -/// An Edit whose `<`, `|` or `>` commands are running answers its write -/// when they are done (edit_cmd.zig); a line after it in the same write -/// would run before them, on the text they are about to change. -pub const e_after_edit = "invalid command line: an Edit running commands ends its write; write what follows after it"; +/// An Edit whose `<`, `|` or `>` commands run answers its write when they +/// are done (edit_cmd.zig); a line after it in the same write would run +/// before them, on the text they are about to change. Refused up front, +/// before any line runs. +pub const e_after_edit = "invalid command line: an Edit that runs commands is a write of its own"; + +/// Whether `data` holds an Edit that runs commands and any other line. +fn editNotAlone(p: *Pardes, data: []const u8) bool { + const sam = @import("../sam_edit.zig"); + var lines: usize = 0; + var runs = false; + var it = Messages.init(p, data); + while (it.next()) |line| { + if (line.len == 0 or exec_line.isComment(line)) continue; + lines += 1; + if (std.mem.startsWith(u8, line, "Edit") and sam.runsCommands(p.scratch.allocator(), line["Edit".len..])) runs = true; + } + return runs and lines > 1; +} /// Runs one click (`run`) as a 9P write's: a builtin that fails there fails /// the write, with its words and an err record, and no msg, as a ctl line @@ -959,13 +974,13 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { const serial = pane.serial; // Checked whole before anything applies, so a write that must wait for // the lock has done nothing yet when it goes again. + if (editNotAlone(p, req.data)) return tree.failText(req.tag, E.INVAL, e_after_edit); for ([2]bool{ false, true }) |apply| { if (apply) p.fs.results_len = 0; var held = !other and pane.fs.lock != null; var it = Messages.init(p, req.data); while (it.next()) |line_in| { if (line_in.len == 0 or exec_line.isComment(line_in)) continue; - if (apply and p.fs.edit_answer_at != null) return tree.failText(req.tag, E.INVAL, e_after_edit); // A line before this one may have closed the pane (`Del`). if (apply and p.paneBySerial(serial) == null) return Reply.fail(req.tag, E.NOENT); // acme's ctl words: done by the file that replaces each, or the diff --git a/src/pardes.zig b/src/pardes.zig index cf3d5128..e92f9623 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -123,9 +123,6 @@ pub const Turn = struct { /// Bumped each time a language server's answer (or its lack) is taken /// in (`lspResponse`): a write that asked one waits for this. lsp_answers: u64 = 0, - /// Bumped each time an Edit's commands (`< | >`) have answered and the - /// Edit is done, or failed (edit_cmd.zig): a write that ran one waits. - edit_answers: u64 = 0, /// All of the above, and `out` reaching zero. settled: std.Io.Condition = .init, @@ -223,15 +220,6 @@ pub const Turn = struct { while (t.lsp_answers == answers) t.settled.wait(t.io.?, &t.mutex) catch return; } - pub fn editAnswered(t: *Turn) void { - t.edit_answers +%= 1; - const io = t.io orelse return; - t.settled.broadcast(io); - } - - pub fn awaitEdit(t: *Turn, answers: u64) void { - while (t.edit_answers == answers) t.settled.wait(t.io.?, &t.mutex) catch return; - } pub fn awaitRestored(t: *Turn, restores: u64) void { while (t.restores == restores) t.settled.wait(t.io.?, &t.mutex) catch return; @@ -5918,6 +5906,12 @@ pub const Pardes = struct { /// that changes a pane costs a frame, which is why a round trip on a /// local socket costs microseconds and not a vsync. pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { + // The held write of an Edit whose commands run, asked again by a + // retry of its park: still waiting, or its answer, never run twice. + if (p.fs.edit_hold) |*h| if (h.names(req)) { + if (!h.done) return .{ .tag = req.tag, .status = .again }; + return filesystem.EditHold.answer(&p.fs); + }; defer panes.File.syncTwins(p); if (!ctlfs.changesPane(p, req)) return ctlfs.handle(p, req); // An address, a limit or the mark flag is nothing drawn: a script's @@ -5928,7 +5922,7 @@ pub const Pardes = struct { look.cancelLookHover(p); p.fs.serving = true; p.fs.lsp_answer_at = null; - p.fs.edit_answer_at = null; + p.fs.edit_started = false; const reply = ctlfs.handle(p, req); p.fs.serving = false; // The one-failure rule is a write's: a refused open (its OTRUNC's diff --git a/src/sam_edit.zig b/src/sam_edit.zig index 3f23aeff..d0c51bdb 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -12,8 +12,8 @@ //! What touches more than the text is the caller's (src/EditCmd.zig): `<`, //! `|` and `>` are collected as jobs, a command to run per address, whose //! output fills the change they hold the place of; `w` as the bytes to -//! write; `D`, and the names `e` and `f` set, as marks on the file; `B` and -//! the reads of `e` and `r` through `World`, at once, as acme does them. +//! write; `D`, `e`'s load and the name `f` sets, as marks on the file; `B` +//! and the reads of `e` and `r` through `World`, at once, as acme does them. //! //! Left out: the `'` address, `B `) refuses the whole Edit, where sam //! warns and puts in what it wrote; `D` of a file the Edit changed is -//! refused rather than drop the changes; `e` of an edited file is refused -//! every time, not once. +//! refused rather than drop the changes; `e` loads its file once the Edit +//! is done, by Get's way (ninep/ctl.zig getFile), so the file takes no +//! other command in the same Edit. const std = @import("std"); const regexp = @import("regexp.zig"); const addr_lang = @import("ninep/addr.zig"); @@ -58,8 +59,10 @@ pub const File = struct { renamed: bool = false, /// `D` closes it once the Edit is done. close: bool = false, - /// `e` read its own file whole: it is clean again once applied. - clean: bool = false, + /// `e` loads this file into it once the Edit is done (the editor's Get + /// path, which renames the pane and leaves it clean); the file takes no + /// more commands in the Edit. + get: ?[]const u8 = null, /// A command left a dot in it. moved: bool = false, }; @@ -75,11 +78,17 @@ pub const Write = struct { file: u32, path: []const u8, bytes: []const u8, whole /// What the editor does for `B`, `e` and `r` while an Edit runs. pub const World = struct { ctx: *anyopaque, + /// Whether `B` could open the absolute `path`: false, and `why` set, + /// when it could not, before any is opened. + check: *const fn (ctx: *anyopaque, path: []const u8, why: *Why) bool, /// The text pane holding the absolute `path`, opened if it is not open: /// `B`. Null, and `why` set, when it cannot be. open: *const fn (ctx: *anyopaque, path: []const u8, why: *Why) ?File, /// The bytes of the absolute `path`, in `arena`: `e` and `r`. read: *const fn (ctx: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *Why) ?[]const u8, + /// `e` over unsaved edits in the pane `id`: asked once, as Get asks; + /// true, and `why` set, when it is refused this time. + refuseGet: *const fn (ctx: *anyopaque, id: usize, why: *Why) bool, }; /// What an Edit came to: every file (those `B` opened after the ones it @@ -221,6 +230,28 @@ pub fn needsMore(arena: std.mem.Allocator, command: []const u8) bool { } } +/// Whether `command` holds a `<`, `|` or `>`: its write is answered only +/// when they have run (ninep/ctl.zig refuses other lines beside it). +pub fn runsCommands(arena: std.mem.Allocator, command: []const u8) bool { + var why: Why = .{}; + const src = std.fmt.allocPrint(arena, "{s}\n", .{command}) catch return false; + var ps: Parser = .{ .arena = arena, .src = src, .why = &why }; + const Walk = struct { + fn any(c: ?*Cmd) bool { + var it = c; + while (it) |each| : (it = each.next) { + if (std.mem.indexOfScalar(u8, "<|>", each.c) != null) return true; + if (any(each.sub)) return true; + } + return false; + } + }; + while (true) { + const c = (ps.parse(0) catch return false) orelse return false; + if (Walk.any(c)) return true; + } +} + fn fail(why: *Why, comptime fmt: []const u8, args: anytype) Failure { why.len = if (std.fmt.bufPrint(&why.buf, fmt, args)) |s| s.len else |_| 0; return error.Edit; @@ -642,7 +673,10 @@ const Exec = struct { /// `name` as a path: itself when absolute, else in `fi`'s directory /// (acme's dirname). - fn pathIn(ex: *Exec, fi: usize, name: []const u8) Failure![]const u8 { + fn pathIn(ex: *Exec, fi: usize, name_in: []const u8) Failure![]const u8 { + // `~` and `~user` as Get, Incl and Save read them. + var home: [4096]u8 = undefined; + const name = try ex.arena.dupe(u8, @import("fs.zig").expandHome(name_in, &home)); if (name.len > 0 and name[0] == '/') return name; const dir = std.fs.path.dirnamePosix(ex.files.items[fi].name) orelse "/"; return std.fs.path.resolvePosix(ex.arena, &.{ dir, name }); @@ -683,6 +717,7 @@ const Exec = struct { var fi = fi_in; var dot = dot_in; if (ex.files.items[fi].close) return fail(ex.why, "no current window", .{}); + if (ex.files.items[fi].get) |path| return fail(ex.why, "{s} is read in by e at the Edit's end: no more commands in it", .{path}); // A `"re"` address: the command runs in that file, from its dot. if (c.file_re) |pat| { fi = try ex.matchFile(pat); @@ -797,6 +832,9 @@ const Exec = struct { if (list.len > 0 and list[0] == '<') return fail(ex.why, "B { - // ecmd.c e_cmd: e reads a file over all of this one, r over - // dot; e names this file after it. + 'r' => { + // ecmd.c e_cmd: r reads a file over dot. + const path = (try ex.cmdName(fi, c.text, false)) orelse return fail(ex.why, e_noname, .{}); + try ex.log(fi, r.q0, r.q1, try ex.readFile(path), null); + return r; + }, + 'e' => { + // ecmd.c e_cmd: a file read over all of this one, which takes + // its name: Get's way (ctl.getFile), once the Edit is done, + // asking first, once, over unsaved edits. const f = &ex.files.items[fi]; - if (c.c == 'e' and f.dirty and !f.scratch) return fail(ex.why, "{s} modified", .{f.name}); - const own = f.name; - const path = (try ex.cmdName(fi, c.text, c.c == 'e')) orelse return fail(ex.why, e_noname, .{}); - const bytes = try ex.readFile(path); - const q: Range = if (c.c == 'e') .{ .q0 = 0, .q1 = clip(txt.len) } else r; - try ex.log(fi, q.q0, q.q1, bytes, null); - if (c.c == 'e' and std.mem.eql(u8, path, own)) ex.files.items[fi].clean = true; + if (f.ops.items.len > 0) return fail(ex.why, "e: {s} has changes pending in this Edit", .{f.name}); + const given = std.mem.trim(u8, c.text, " \t"); + const path = if (given.len == 0) + (if (f.scratch) return fail(ex.why, e_noname, .{}) else f.name) + else + try ex.pathIn(fi, given); + const w = ex.world orelse return fail(ex.why, "can't open {s}: no files here", .{path}); + if (w.refuseGet(w.ctx, f.id, ex.why)) return error.Edit; + _ = try ex.readFile(path); + f.get = path; + f.name = path; return r; }, 'w' => { @@ -893,7 +942,7 @@ const Exec = struct { /// in this Edit is refused rather than have them dropped. fn closeFile(ex: *Exec, fi: usize) Failure!void { const f = &ex.files.items[fi]; - if (f.ops.items.len > 0) return fail(ex.why, "D: {s} has changes pending in this Edit", .{f.name}); + if (f.ops.items.len > 0 or f.get != null) return fail(ex.why, "D: {s} has changes pending in this Edit", .{f.name}); f.close = true; } @@ -1166,7 +1215,23 @@ const Fixture = struct { .{ .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; @@ -1188,7 +1253,7 @@ const Fixture = struct { fn edit(fx: *Fixture, from: usize, command: []const u8) !Result { var ctx: u8 = 0; - const world: World = .{ .ctx = &ctx, .open = open, .read = read }; + 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); } @@ -1247,17 +1312,23 @@ test "b moves the current file, \"re\" addresses another, and f names one" { test "e and r read a file into the text, w writes it, D and B close and open panes" { var fx: Fixture = .init(); defer fx.deinit(); - // r replaces dot; e the whole text, and names the file after it. + // r replaces dot; e loads a file over all of it at the end, by Get's + // way, which names the pane after it. const r = try fx.edit(0, "2 r data"); try std.testing.expectEqualStrings("int foo;\nDATA\n", try fx.after(r, 0)); try std.testing.expect(!r.files[0].renamed); - const e = try fx.edit(0, "e /src/data"); - try std.testing.expectEqualStrings("DATA\n", try fx.after(e, 0)); - try std.testing.expectEqualStrings("/src/data", e.files[0].name); - try std.testing.expect(!e.files[0].clean); - // e of an edited file is refused, as acme's winclean refuses it. + const e = try fx.edit(0, "e data"); + try std.testing.expectEqualStrings("/src/data", e.files[0].get.?); + try std.testing.expectEqual(@as(usize, 0), e.files[0].ops.items.len); + // ...and takes no more commands, nor follows another change. + try std.testing.expectError(error.Edit, fx.edit(0, "e data\n,d")); + try std.testing.expectError(error.Edit, fx.edit(0, "1d\ne data")); + // e of an edited file is asked about, as Get asks. try std.testing.expectError(error.Edit, fx.edit(1, "e")); - try std.testing.expectEqualStrings("/src/b.h modified", fx.why.text()); + try std.testing.expectEqualStrings("/src/b.h: Modified (e again to discard)", fx.why.text()); + // `~` is the home directory, as Get and Save read it. + const home = try fx.edit(0, "w ~/t.txt"); + try std.testing.expect(home.writes[0].path[0] == '/' and std.mem.indexOfScalar(u8, home.writes[0].path, '~') == null); try std.testing.expectError(error.Edit, fx.edit(0, "r nothing")); try std.testing.expectEqualStrings("can't open /src/nothing: file does not exist", fx.why.text()); // w: all of it by default, to its own name; an address and a name. @@ -1282,6 +1353,10 @@ test "e and r read a file into the text, w writes it, D and B close and open pan try std.testing.expectEqualStrings("old foo\n", try fx.after(b, 4)); try std.testing.expectError(error.Edit, fx.edit(0, "B gone.c")); try std.testing.expectEqualStrings("B: cannot open /src/gone.c", fx.why.text()); + // Every name is checked first: one that cannot open opens none. + Fixture.opened = 0; + try std.testing.expectError(error.Edit, fx.edit(0, "B new.c gone.c")); + try std.testing.expectEqual(@as(usize, 0), Fixture.opened); } test "<, | and > are jobs: a command per address, its output the change" { @@ -1309,3 +1384,14 @@ test "<, | and > are jobs: a command per address, its output the change" { try std.testing.expectEqual(@as(usize, 2), x.jobs.len); try std.testing.expectEqual(@as(u32, 2), x.jobs[1].file); } + +test "an Edit that runs commands is told from one that does not" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + try std.testing.expect(runsCommands(a, ", | sort")); + try std.testing.expect(runsCommands(a, ",x/a/{\n< date\n}")); + try std.testing.expect(runsCommands(a, "X/c/ , > wc")); + try std.testing.expect(!runsCommands(a, ",s/|/>/g")); + try std.testing.expect(!runsCommands(a, ",x/ max_stdout_bytes or stderr_reader.buffered().len > max_stderr_bytes) return fail.k(.too_large); multi_reader.checkAnyError() catch return fail.k(.io); + if (token != 0) Running.remove(pid); const term = child.wait(io) catch return fail.k(.io); writer.?.join(); writer = null; @@ -339,6 +414,12 @@ pub fn runIn( return .{ .ok = stdout }; } +fn tokenStopped(token: u32) bool { + Running.take(); + defer Running.lock.unlock(); + return Running.isStopped(token); +} + /// Invoke the command independently for every selection. The response is all /// or nothing: one failure frees every earlier stdout and returns a failed, /// empty answer for the core to ignore. @@ -350,7 +431,11 @@ pub fn runJob(gpa: std.mem.Allocator, io: std.Io, job: *const Job) Response { for (job.inputs, 0..) |input, i| { const command = if (job.commands.len > 0) job.commands[i] else job.command; const cwd = if (job.cwds.len > 0) job.cwds[i] else job.cwd; - const output = switch (runIn(gpa, io, job.shell, command, cwd, input)) { + if (job.token != 0 and tokenStopped(job.token)) { + response.failure = .{ .kind = .signal, .index = @intCast(i) }; + break; + } + const output = switch (runIn(gpa, io, job.shell, command, cwd, input, job.token)) { .ok => |bytes| bytes, .failed => |f| { // WHICH selection, because with several cursors "it failed" is @@ -468,3 +553,34 @@ test "a request may give each input its own command and directory, run by the sh try std.testing.expectEqualStrings("/tmp\n", response.outputs[0]); try std.testing.expectEqualStrings("ABC", response.outputs[1]); } + +test "stop kills a running request's commands, the whole group, and starts none after" { + const gpa = std.testing.allocator; + const token = newToken(); + const job = try Job.copy(gpa, .{ + .id = 1, + .command = "", + .cwd = "", + .inputs = &.{ .{ .bytes = "" }, .{ .bytes = "" } }, + .commands = &.{ "sleep 30; echo late", "echo never" }, + .token = token, + }); + defer job.deinit(gpa); + const Run = struct { + fn go(j: *const Job, out: *Response) void { + out.* = runJob(std.testing.allocator, std.testing.io, j); + } + }; + var response: Response = undefined; + const started = std.Io.Clock.awake.now(std.testing.io); + const thread = try std.Thread.spawn(.{}, Run.go, .{ job, &response }); + std.Io.sleep(std.testing.io, .fromMilliseconds(300), .awake) catch {}; + stop(token); + thread.join(); + defer response.deinit(gpa); + try std.testing.expect(!response.success); + try std.testing.expectEqual(Failure.Kind.signal, response.failure.?.kind); + try std.testing.expectEqual(@as(u32, 0), response.failure.?.index); + const took = started.durationTo(std.Io.Clock.awake.now(std.testing.io)); + try std.testing.expect(took.toMilliseconds() < 5000); +} diff --git a/test/fs.py b/test/fs.py index 59668c57..b593981c 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1085,6 +1085,37 @@ def edit_commands(binary): assert time.monotonic() - began < .5 and not done.is_set(), 'the editor waited on the command' worker.join(timeout=15) assert done.is_set() + # On the same connection: the Edit's write is held, and a read sent + # after it is answered first; a Tflush of it stops it, changes + # nothing, and frees the way for the next Edit. + def send(kind, tag, payload): + client.socket.sendall(struct.pack(' {mount}/pane/{edited}/ctl & sleep .5; " + f"s=$(date +%s%N); timeout 5 cat {mount}/status > /dev/null; e=$(date +%s%N); " + f"echo $(( (e - s) / 1000000 )) > {took}; wait\n").encode()) + ms = int(took.read_text()) if took.exists() else -1 + took.unlink(missing_ok=True) + check(ran == '0' and 0 <= ms < 1000, f'a status read beside a slow Edit answers at once ({ms} ms)') + check(client.read(f'/pane/{edited}/body') == b'apple\npear\n', 'and the slow Edit applied') + ran = run(f"echo 'Edit $ < cat {mount}/pane/{edited}/body' > {mount}/pane/{edited}/ctl\n".encode()) + check(ran == '0' and client.read(f'/pane/{edited}/body') == b'apple\npear\napple\npear\n', + f'an Edit whose command reads the session through its mount ({ran!r})') + # An interrupted Edit write is flushed: its command is stopped and + # nothing changes, and the next Edit runs. + flushed = Path(f'/tmp/{name}.flushed') + ran = run((f"timeout -s INT 1 sh -c \"echo 'Edit , | sleep 4; tr a-z A-Z' > {mount}/pane/{edited}/ctl\"; " + f"echo $? > {flushed}; sleep 1; echo 'Edit 1 | tr p P' > {mount}/pane/{edited}/ctl; echo $? >> {flushed}\n").encode()) + codes = flushed.read_text().split() if flushed.exists() else [] + flushed.unlink(missing_ok=True) + time.sleep(4.5) + check(codes == ['124', '0'] and client.read(f'/pane/{edited}/body') == b'aPPle\npear\napple\npear\n', + f'an interrupted Edit changes nothing, and the next runs ({codes!r}, {client.read(f"/pane/{edited}/body")!r})') client.write('/exec', b'Msg still here\n') text = ''.join(cell[0] for cell in client.screen()['cells']) check('still here' in text, 'the editor answers after all of that') -- cgit v1.3 From dd6a3c2c367cee12a8e2da81e7da6a2c8f3103d5 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 23:20:19 -0300 Subject: Round 39's small ones: a name write past its one line is refused by that write; Get and Edit's e load over a scratch under 100 bytes unasked, as Del closes it; Putall saves a Zerox pair once; bare Tab on the root ctl says the width as from a pane, and a ctl check of Tab no longer sets it; a directory read is "is a directory" (EISDIR), an unreadable file "permission denied" (EACCES), Incl of a file "not a directory" (ENOTDIR), and a device "not a regular file", never read to the stream limit Co-Authored-By: Claude Opus 5.5 --- src/Messages.zig | 3 +++ src/builtins.zig | 13 ++++++++-- src/config.zig | 1 - src/dump.zig | 1 + src/exec.zig | 2 ++ src/fs.zig | 7 ++++++ src/ninep/ctl.zig | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- src/ninep/tree.zig | 10 ++++++++ 8 files changed, 104 insertions(+), 5 deletions(-) (limited to 'src/fs.zig') diff --git a/src/Messages.zig b/src/Messages.zig index 366445c7..2314939f 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -498,6 +498,9 @@ pub fn errorWords(err: anyerror, buf: []u8) []const u8 { return switch (err) { error.FileTooLarge => "too large", error.NotAFile => "not a regular file", + // In the words a mount turns into EISDIR and EACCES (cloud9.fs.enameErrno). + error.IsDirectory => "is a directory", + error.PermissionDenied, error.AccessDenied => "permission denied", error.ReadFailed => "could not be read", error.ParseZon => "not valid ZON", error.ThemeFileTooLarge => "too large: a theme file is at most 1 MiB", diff --git a/src/builtins.zig b/src/builtins.zig index 70ca93a1..c42d4978 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1157,7 +1157,9 @@ pub const Get = struct { const errno = if (typed.len == 0) ctl.get(c.p, c.pane, &failed) else ctl.getFile(c.p, c.pane, path, &failed); if (errno != 0) { var said: [320]u8 = undefined; - c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Get: {s}: {s}", .{ path[0..@min(path.len, 256)], if (failed == error.FileNotFound) "no such file" else "cannot be read" }) catch "Get: cannot be read"); + var words: [128]u8 = undefined; + const why = if (failed == error.FileNotFound) "no such file" else pardes.Messages.errorWords(failed, &words); + c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Get: {s}: {s}", .{ path[0..@min(path.len, 256)], why }) catch "Get: cannot be read"); } } }; @@ -1172,6 +1174,10 @@ pub const Putall = struct { const pane = slot orelse continue; const f = pane.file orelse continue; if (f.output != null or f.listing != null or f.revision == f.saved_revision) continue; + // A Zerox pair is one buffer: saved once, by its first pane. + if (f.twin != 0) if (for (c.p.panes[0..id]) |earlier| { + if ((earlier orelse continue).file) |ef| if (ef.twin == f.twin) break true; + } else false) continue; exec.saveFile(c.p, id); } } @@ -1203,7 +1209,10 @@ pub const Incl = struct { var home_buf: [4096]u8 = undefined; const expanded = @import("fs.zig").expandHome(dir_word, &home_buf); if (comptime pardes.hosted) if (@import("fs.zig").localPath(expanded)) |local| if (!exec.isDirectory(local)) - return p.reportFailure(c.id, std.fmt.bufPrint(&said, "Incl: no such directory: {s}", .{shown}) catch "Incl: no such directory"); + return p.reportFailure(c.id, if (exec.kindOf(local) != null) + std.fmt.bufPrint(&said, "Incl: not a directory: {s}", .{shown}) catch "Incl: not a directory" + else + std.fmt.bufPrint(&said, "Incl: no such directory: {s}", .{shown}) catch "Incl: no such directory"); } var words = std.mem.tokenizeAny(u8, typed, " \t"); while (words.next()) |dir_word| { diff --git a/src/config.zig b/src/config.zig index 26e1de2c..d6ea7358 100644 --- a/src/config.zig +++ b/src/config.zig @@ -1299,7 +1299,6 @@ pub const Runtime = struct { const width = std.fmt.parseInt(u16, text, 10) catch return false; if (width < 1 or width > 16) return false; state.tab = width; - tab_now = width; }, .theme, .font => return false, } diff --git a/src/dump.zig b/src/dump.zig index 1ded9989..201f5bf2 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -864,6 +864,7 @@ fn applySettings(p: *Pardes, lines: []const []const u8) void { } const setting = config.Runtime.find(line[0 .. sp orelse line.len]) orelse continue; _ = p.settings.apply(setting, if (sp) |s| line[s + 1 ..] else null); + if (setting.action == .tab) config.tab_now = p.settings.tab; } } diff --git a/src/exec.zig b/src/exec.zig index d6834797..a5b6e506 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -1124,6 +1124,8 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] return p.setMessage(p.active, std.fmt.bufPrint(&said, "Tab {d}", .{p.settings.tab}) catch "Tab"); } else if (!p.settings.apply(setting, arg)) { p.reportFailure(p.active, "Tab: invalid tab width: takes " ++ comptime config.Runtime.takes(.tab).?); + } else { + config.tab_now = p.settings.tab; }, // Said with what it takes: its words, its range. else => if (!p.settings.apply(setting, arg)) { diff --git a/src/fs.zig b/src/fs.zig index db07672e..fb76cee3 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1521,6 +1521,13 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { }; defer _ = libc.close(fd); + // A device (/dev/zero, a tty) is no file to read whole: said so, not + // read to the stream limit and called too large. + if (ninep_io.statNoFollow(path_z)) |facts| { + const kind = facts.mode & 0o170000; + if (kind == 0o040000) return error.IsDirectory; + if (kind == 0o020000 or kind == 0o060000) return error.NotAFile; + } const end = libc.lseek(fd, 0, libc.SEEK.END); // Not seekable: a pipe or a FIFO is no file; a regular file that is a // stream (a 9ns mount's log or screen, opened nonseekable) is read to diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index c6b76d51..dc5e8386 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -322,6 +322,10 @@ pub fn failureErrno(failure: []const u8) u16 { // word 9ns reads as it. if (std.mem.indexOf(u8, failure, "busy: ") != null) return E.BUSY; if (std.mem.indexOf(u8, failure, "no such") != null or std.mem.indexOf(u8, failure, "not found") != null) return E.NOENT; + // As 9ns reads the same words (cloud9.fs.enameErrno). + if (std.mem.indexOf(u8, failure, "not a dir") != null) return E.NOTDIR; + if (std.mem.indexOf(u8, failure, "is a dir") != null) return E.ISDIR; + if (std.mem.indexOf(u8, failure, "permission denied") != null) return 13; // EACCES // A pattern refused (Edit's too) is malformed input, as 9ns reads it; // so is a word this build has not (`invalid: acme's Put ...`). if (std.mem.indexOf(u8, failure, "bad regular expression") != null or std.mem.indexOf(u8, failure, "invalid") != null or @@ -548,6 +552,8 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? return refuse(p, req, std.fmt.bufPrint(&why, head ++ "{s}" ++ tail, .{pardes.colors.themesNear(near[0..@min(room, near.len)], arg)}) catch "bad value in control message", arg); }, .font => config.Runtime.FontSpec.parse(arg) != null, + // Bare, it says the width, as from a pane's exec. + .tab => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 16, else => probe: { var probe = p.settings; break :probe probe.apply(setting, if (arg.len > 0) arg else null); @@ -1158,6 +1164,9 @@ const e_locked = tree.e_in_use ++ ": another open of this ctl holds the lock"; pub fn getRefused(p: *Pardes, pane: *Pane, word: []const u8) ?[]const u8 { const f = pane_files.fileOf(pane) orelse return null; if (!panes.Output.fileTraits(f.output).saves or f.revision == f.saved_revision) return null; + // A scratch under 100 bytes is not asked about, as Del and Exit do not + // ask (builtins.warnModifiedIn): nothing worth a question to lose. + if (f.output != null and f.content.len < 100) return null; // Dirty by a rename alone is no text to lose: only edits are asked about. const saved = f.saved_hash orelse return null; if (std.hash.Wyhash.hash(0, f.content) == saved) return null; @@ -2106,6 +2115,64 @@ test "Undo to unsaved text under its old name says nothing changed on disk when } } +test "round 39's small refusals: one name an open, small scratches unasked, twins saved once, bare Tab on ctl, and errnos in words a mount reads" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "f.txt", .data = "f\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "noread.txt", .data = "secret\n" }); + try tmp.dir.createDirPath(testing.io, "sub"); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[0].?; + var line: [4300]u8 = undefined; + // One name an open: a second line, in the write or after, is refused. + try testing.expectEqual(E.INVAL, wr(p, Node.of(serial, .name), "/tmp/pardes-a\nb").errno()); + const before = try testing.allocator.dupe(u8, pane.file.?.path); + defer testing.allocator.free(before); + const h = call(p, .{ .tag = 1, .op = .open, .node = Node.of(serial, .name), .omode = 1 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = Node.of(serial, .name), .handle = h, .data = "/tmp/pardes-one.txt\n" }).reply.status); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 3, .op = .write, .node = Node.of(serial, .name), .handle = h, .data = "b" }).errno()); + _ = call(p, .{ .tag = 4, .op = .release, .node = Node.of(serial, .name), .handle = h, .opened = true }); + tree.runClosedLines(p); + try testing.expectEqualStrings("/tmp/pardes-one.txt", pane.file.?.path); + // Bare Tab on the root ctl says the width, as from a pane. + try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "Tab\n").reply.status); + // Errnos a mount reads from the words. + _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&line, "{s}/f.txt\n", .{dir})); + try testing.expect(p.executeBuiltinLine(0, "Get")); + try testing.expectEqual(E.ISDIR, wr(p, Node.of(serial, .exec), "Get sub\n").errno()); + if (comptime pardes.hosted) { + var noread_buf: [4300]u8 = undefined; + _ = std.c.chmod(try std.fmt.bufPrintSentinel(&noread_buf, "{s}/noread.txt", .{dir}, 0), 0); + try testing.expectEqual(@as(u16, 13), wr(p, Node.of(serial, .exec), "Get noread.txt\n").errno()); + try testing.expectEqual(E.NOTDIR, wr(p, Node.of(serial, .exec), try std.fmt.bufPrint(&line, "Incl {s}/f.txt\n", .{dir})).errno()); + const zero = wr(p, Node.of(serial, .look), "/dev/zero\n"); + _ = zero; + try testing.expect(th.logHas(p, "not a regular file")); + } + // Twins saved once by Putall. + _ = wr(p, Node.of(serial, .body), "edited\n"); + try testing.expect(p.executeBuiltinLine(0, "Zerox")); + while (p.nextEffect()) |_| {} + try testing.expect(p.executeBuiltinLine(0, "Putall")); + var saves: usize = 0; + while (p.nextEffect()) |e| if (e == .save_file) { + saves += 1; + }; + try testing.expectEqual(@as(usize, 1), saves); + // A scratch of 2 bytes is loaded over unasked. + try testing.expect(p.executeBuiltinLine(0, "New")); + const scratch = p.panes[p.active].?; + _ = pane_files.spliceBody(p, scratch, 0, 0, "hi") orelse return error.NoScratch; + const failures = p.fs.failures; + try testing.expect(p.executeBuiltinLine(p.active, try std.fmt.bufPrint(&line, "Get {s}/f.txt", .{dir}))); + try testing.expectEqual(failures, p.fs.failures); + try testing.expectEqualStrings("f\n", scratch.file.?.content); +} + test "a body write to a terminal is typed input, not a paste, even to a program that asked for bracketed paste" { const p = try Pardes.init(testing.allocator, .{ .cols = 90, .rows = 30 }); defer p.deinit(); @@ -2761,7 +2828,8 @@ test "Shell refuses a path that is no executable, and bare it goes back to the d try testing.expectEqual(Status.err, refused.reply.status); try testing.expect(std.mem.indexOf(u8, refused.reply.ename, "Shell: shell \"/nonexistent/zzsh\" not found") != null); try testing.expect(th.logHas(p, "shell \"/nonexistent/zzsh\" not found")); - try testing.expectEqual(E.IO, wr(p, root_ctl, "Shell /etc\n").errno()); + // Its words say a directory, which a mount reads as EISDIR too. + try testing.expectEqual(E.ISDIR, wr(p, root_ctl, "Shell /etc\n").errno()); try testing.expect(th.logHas(p, "Shell: not a shell: /etc is a directory")); try testing.expectEqualStrings("", p.settings.shell.requested.get()); try testing.expectEqual(Status.ok, wr(p, root_ctl, "Shell /bin/sh\n").reply.status); @@ -3073,7 +3141,7 @@ test "pty/ctl exec in a directory that is gone fails ENOENT; a shell that cannot // The host's own failure is the waiting write's (late_failure). p.fs.late_failure_len = 0; p.shellFailed(@intCast(p.paneBySerial(serial).?), error.AccessDenied); - try testing.expectEqualStrings("shell: access denied", p.fs.late_failure[0..p.fs.late_failure_len]); + try testing.expectEqualStrings("shell: permission denied", p.fs.late_failure[0..p.fs.late_failure_len]); } test "a script whose interpreter is not there: Tty refuses it up front, only an err logged, and pty/ctl exec keeps the running shell" { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 1990d09e..c78a1aa2 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1270,6 +1270,16 @@ fn writeLines(p: *Pardes, req: Req, target: Target) Reply { data = data[nl + 1 ..]; if (data.len == 0) return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } + // One name an open, on one line: anything after its newline, in this + // write or a later one, is refused by the write that brings it, never + // left to rename the pane again at the close (`printf 'a\nb' > name`). + if (target == .pane and target.pane.file == .name) { + const past_newline = if (std.mem.indexOfScalar(u8, data, '\n')) |nl| nl + 1 < data.len else false; + if (o.named or past_newline) { + o.pending.clearRetainingCapacity(); + return failText(req.tag, E.INVAL, "invalid file name: one name a write, on one line"); + } + } o.pending.appendSlice(p.gpa, data) catch return Reply.fail(req.tag, E.NOMEM); // A line runs when its newline comes, or, the last one, when its open // is let go (release). Nothing is inferred from a write's size: a mount -- cgit v1.3 From bc3d18d27f9fc1155db7fac3946c4d38774f9e65 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 21 Oct 2026 14:35:15 -0300 Subject: Build with Zig 0.17 ghostty, libvaxis and uucode move to ghostty's 0.17 pins, cloud9 to its 0.17 main, SDL to castholm's release-3.4.x (3.4.18), zstbi and tree-sitter to forks with 0.17 build files (see build.zig.zon). A bare zig build copies the binaries into ~/.local/bin (-Dhome-install=false leaves it out): 0.17 keeps the prefix from build scripts. A terminal's edited copy goes when the program clears the screen. tinywin.snap is gone; perf baselines are re-recorded. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- build.zig | 289 +++++++++++++++----------------- build.zig.zon | 45 ++--- build/snap.zig | 6 +- docs/typ/building.typ | 12 +- docs/typ/install.typ | 2 +- mupdf.zig | 6 +- src/9p_io.zig | 14 +- src/CHANGELOG.md | 8 + src/Layer.zig | 4 +- src/Messages.zig | 14 +- src/TerminalImages.zig | 82 ++++++++- src/builtins.zig | 26 +-- src/colors.zig | 70 ++++---- src/config.zig | 21 ++- src/detached/client.zig | 8 +- src/detached/wire.zig | 39 +++-- src/draw.zig | 22 +-- src/dump.zig | 24 +-- src/esp32p4.zig | 2 +- src/esp32p4/input_rescue.zig | 2 +- src/esp32p4/selftest.zig | 2 +- src/fs.zig | 8 +- src/gui/Post.zig | 14 +- src/gui/gui.zig | 20 +-- src/host_io.zig | 14 +- src/image.zig | 6 +- src/linux/v9fs.zig | 4 +- src/locations.zig | 24 +-- src/look.zig | 6 +- src/lsp/lsp.zig | 2 +- src/lsp/lsp_client.zig | 2 +- src/macos.zig | 26 +-- src/main.zig | 6 + src/memory.zig | 2 +- src/modal.zig | 2 +- src/ninep/addr.zig | 2 +- src/ninep/cols.zig | 10 +- src/ninep/ctl.zig | 14 +- src/ninep/events.zig | 10 +- src/ninep/pane.zig | 11 +- src/ninep/pty.zig | 6 +- src/ninep/screen.zig | 2 +- src/ninep/tree.zig | 16 +- src/normal.zig | 2 +- src/pager.zig | 2 +- src/panes.zig | 2 +- src/pardes.zig | 32 ++-- src/pdf.zig | 10 +- src/regexp.zig | 12 +- src/sam_edit.zig | 2 +- src/syntax.zig | 2 +- src/terminal.zig | 30 +++- src/tty/tty.zig | 22 +-- test/deck/replay.zig | 5 +- test/deck/schema.zig | 10 +- test/e2e_harness.zig | 2 +- test/fs_bench.zig | 4 +- test/history.zig | 10 +- test/hxdiff.zig | 14 +- test/image_harness.zig | 2 +- test/lspbench.zig | 2 +- test/monkey.zig | 2 +- test/panes.zig | 50 +++--- test/pdf.zig | 8 +- test/pdf_scroll_bench.zig | 2 +- test/pdf_sections_bench.zig | 2 +- test/perf-baseline-gui-Debug.json | 1 - test/perf-baseline-gui-debug.json | 1 + test/perf-baseline-tty-Debug.json | 1 - test/perf-baseline-tty-ReleaseFast.json | 1 - test/perf-baseline-tty-debug.json | 1 + test/perf-baseline-tty-fast.json | 1 + test/perf.zig | 15 +- test/snapshot.zig | 40 ++--- test/snapshots/exec.golden | 8 +- test/snapshots/tinywin.golden | 83 --------- test/snapshots/tinywin.snap | 31 ---- test/unit_profile_test.zig | 7 +- tools/gen_themes.zig | 15 +- 80 files changed, 664 insertions(+), 677 deletions(-) delete mode 100644 test/perf-baseline-gui-Debug.json create mode 100644 test/perf-baseline-gui-debug.json delete mode 100644 test/perf-baseline-tty-Debug.json delete mode 100644 test/perf-baseline-tty-ReleaseFast.json create mode 100644 test/perf-baseline-tty-debug.json create mode 100644 test/perf-baseline-tty-fast.json delete mode 100644 test/snapshots/tinywin.golden delete mode 100644 test/snapshots/tinywin.snap (limited to 'src/fs.zig') diff --git a/README.md b/README.md index 3a566d2a..0a03bdba 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ looks; the keys are helix's; every session is a virtual filesystem, served over 9P, that any program can drive. Get the source with `git clone https://git.sr.ht/~gbrls/pardes && cd pardes` -(also at https://git.0x4200.cafe/pardes). Install with Zig 0.16: +(also at https://git.0x4200.cafe/pardes). Install with Zig 0.17: `zig build -Dplatform=tty --prefix ~/.local` for `pardes` in a terminal, or `-Dplatform=gui` for the `pardes-gui` window. The terminal should report the mouse; Shift-Esc needs the kitty keyboard diff --git a/build.zig b/build.zig index 0246d55f..ddd41a03 100644 --- a/build.zig +++ b/build.zig @@ -59,13 +59,14 @@ pub fn build(b: *std.Build) void { const requested_platform = b.option(Platform, "platform", "which shell to build (tty, gui, web, macos, esp32p4); absent builds the tty cli and the SDL gui together"); const platform = requested_platform orelse .tty; const also_gui = requested_platform == null; - const home_install = also_gui and prefixIsUntouched(b); - if (home_install) { - if (b.graph.environ_map.get("HOME")) |home| { - b.resolveInstallPrefix(b.pathJoin(&.{ home, ".local" }), .{}); - std.debug.print("pardes: installing into {s} (override with --prefix)\n", .{b.install_prefix}); - } - } + // A bare `zig build` also copies the binaries into ~/.local/bin. Zig + // 0.17 keeps the prefix in the maker process, out of this script's + // reach, so `--prefix` no longer turns it off: -Dhome-install=false does. + const home_bin: ?[]const u8 = if (also_gui and (b.option(bool, "home-install", "a bare `zig build` also copies the binaries into ~/.local/bin (default: true)") orelse true)) + if (b.graph.environ_map.get("HOME")) |home| b.pathJoin(&.{ home, ".local", "bin" }) else null + else + null; + const home_install = home_bin != null; const esp32p4_target: std.Target.Query = .{ .cpu_arch = .riscv32, .os_tag = .freestanding, @@ -114,18 +115,18 @@ pub fn build(b: *std.Build) void { const is_web_target = target.result.cpu.arch == .wasm32 and target.result.os.tag == .freestanding; const is_esp32p4_target = target.result.cpu.arch == .riscv32 and target.result.os.tag == .freestanding; const optimize = if (is_web) - .ReleaseSmall - else if (is_esp32p4_target and requested_optimize == .Debug) - .ReleaseFast + .small + else if (is_esp32p4_target and requested_optimize == .debug) + .fast else requested_optimize; const test_build = b.step("test-build", "compile unit-test programs without running them"); const doc_typ_opts = b.addOptions(); - doc_typ_opts.addOption([]const u8, "dir", b.pathFromRoot("docs/typ")); + doc_typ_opts.addOptionPathUntracked("dir", b.path("docs/typ")); // The docs (docs/typ, docs/site): each output is one typst run, and each // reads docs/typ/builtins-*.json; `builtins-json` refreshes this build's from the // registry first (the tool is wired below, once the core module is). - const typst_bin: ?[]const u8 = b.findProgram(&.{"typst"}, &.{}) catch null; + const typst_bin: ?[]const u8 = b.findProgram(.{ .names = &.{"typst"} }); var doc_renders: [3]?*std.Build.Step.Run = @splat(null); const cheatsheet_step = b.step("cheatsheet", "render docs/typ/cheatsheet-a4.typ to /share/doc/pardes/cheatsheet.pdf (needs typst)"); const book_step = b.step("book", "render docs/typ/book.typ to /share/doc/pardes/pardes.pdf (needs typst)"); @@ -139,11 +140,13 @@ pub fn build(b: *std.Build) void { sheet.addFileArg(b.path("docs/typ/cheatsheet-a4.typ")); sheet.has_side_effects = true; cheatsheet_step.dependOn(&b.addInstallFile(sheet.addOutputFileArg("cheatsheet.pdf"), "share/doc/pardes/cheatsheet.pdf").step); - const book = b.addSystemCommand(&.{ typst, "compile", "--ignore-system-fonts", "--root", b.pathFromRoot(".") }); + const book = b.addSystemCommand(&.{ typst, "compile", "--ignore-system-fonts", "--root", "." }); + book.setCwd(b.path(".")); book.addFileArg(b.path("docs/typ/book.typ")); book.has_side_effects = true; book_step.dependOn(&b.addInstallFile(book.addOutputFileArg("pardes.pdf"), "share/doc/pardes/pardes.pdf").step); - const site = b.addSystemCommand(&.{ typst, "compile", "--format", "bundle", "--features", "bundle,html", "--root", b.pathFromRoot(".") }); + const site = b.addSystemCommand(&.{ typst, "compile", "--format", "bundle", "--features", "bundle,html", "--root", "." }); + site.setCwd(b.path(".")); site.addFileArg(b.path("docs/site/site.typ")); const site_dir = site.addOutputDirectoryArg("site"); site.has_side_effects = true; @@ -168,7 +171,7 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("test/unit_profile.zig"), }), }); - const c_optimize: std.builtin.OptimizeMode = if (optimize == .Debug) .ReleaseFast else optimize; + const c_optimize: std.lang.Optimize = if (optimize == .debug) .fast else optimize; const default_grammars: TreeSitterGrammars = if (is_web) .zig else if (is_esp32p4) .disabled else .full; const requested_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full"); const tree_sitter_grammars = requested_grammars orelse default_grammars; @@ -321,7 +324,7 @@ pub fn build(b: *std.Build) void { .name = "pardes-gen-themes", .root_module = b.createModule(.{ .target = b.graph.host, - .optimize = .Debug, + .optimize = .debug, .root_source_file = b.path("tools/gen_themes.zig"), }), }); @@ -353,7 +356,7 @@ pub fn build(b: *std.Build) void { // `pardes ` alone, like a tarball build; -Dstamp-commit=true // stamps one anyway. const stamp_commit = b.option(bool, "stamp-commit", "embed the git commit in --version and crash records (default: release builds and the ~/.local install)") orelse - (optimize != .Debug or home_install); + (optimize != .debug or home_install); const shell_cfg: ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars, .tracy = tracy != null, @@ -391,9 +394,7 @@ pub fn build(b: *std.Build) void { if (tree_sitter_grammars != .disabled) { const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter"); if (is_web) { - const web_libc_include: std.Build.LazyPath = .{ - .cwd_relative = b.path("src/web/libc/include").getPath(b), - }; + const web_libc_include = b.path("src/web/libc/include"); for (tree_sitter_mod.link_objects.items) |link_object| switch (link_object) { .other_step => |lib| { lib.root_module.link_libc = false; @@ -417,12 +418,11 @@ pub fn build(b: *std.Build) void { (tree_sitter_grammars == .zig and g.tier == .zig)) { const dep = b.dependency(g.dep, .{}); - const query_path = dep.path(g.query); - const query = std.Io.Dir.cwd().readFileAlloc(io, query_path.getPath(b), b.allocator, .limited(0x100000)) catch @panic("read " ++ g.name ++ " highlights"); + const query = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights"); ts_queries.addOption([]const u8, g.name ++ "_highlights", query); // helix's textobject queries, vendored (vendor/queries); a // grammar without one gets none - const objects = std.Io.Dir.cwd().readFileAlloc(io, b.pathFromRoot("vendor/queries/" ++ g.name ++ "/textobjects.scm"), b.allocator, .limited(0x100000)) catch ""; + const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch ""; ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects); const lib = b.addLibrary(.{ @@ -438,8 +438,9 @@ pub fn build(b: *std.Build) void { const ts_cflags = [_][]const u8{ "-fno-sanitize=function", "-DTREE_SITTER_REUSE_ALLOCATOR", + // Relative to the build root, the compiler's working directory. "-include", - b.path("src/tree_sitter_heap.h").getPath(b), + "src/tree_sitter_heap.h", }; lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/parser.c"), .flags = &ts_cflags }); if (g.scanner) lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/scanner.c"), .flags = &ts_cflags }); @@ -467,7 +468,7 @@ pub fn build(b: *std.Build) void { // (src/regexp.zig). A bump that moves the anchor stops the build. const mvzr_mod = mvzr: { const dep = b.dependency("mvzr", .{ .target = target, .optimize = optimize }); - const src = std.Io.Dir.cwd().readFileAlloc(io, dep.path("src/mvzr.zig").getPath(b), b.allocator, .limited(1 << 20)) catch @panic("read mvzr"); + const src = configureRead(b, io, dep.builder.root, "src/mvzr.zig", 1 << 20) catch @panic("read mvzr"); const anchor = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n"; const at = (std.mem.indexOf(u8, src, anchor) orelse @panic("mvzr's matchPattern changed: redo its step budget in build.zig")) + anchor.len; const spend = @@ -536,7 +537,17 @@ pub fn build(b: *std.Build) void { \\ ; if (std.mem.count(u8, backed, end_anchor) != 1) @panic("mvzr's parser changed: redo its `$` before `|` in build.zig"); - const patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM"); + var patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM"); + // Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it upstream). + for ([_][3][]const u8{ + .{ "[1]RegOp{.{ .unused = {} }} ** ops", "@splat(.{ .unused = {} })", "1" }, + .{ "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", "@splat(.{ .low = 0, .hi = 0 })", "1" }, + .{ "\"a\" ** 2048", "&@as([2048]u8, @splat('a'))", "2" }, + .{ "\"12345,\" ** 255", "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))", "1" }, + }) |edit| { + if (std.mem.count(u8, patched, edit[0]) != std.fmt.parseInt(usize, edit[2], 10) catch unreachable) std.debug.panic("mvzr changed at `{s}`: redo its `**` patch in build.zig", .{edit[0]}); + patched = std.mem.replaceOwned(u8, b.allocator, patched, edit[0], edit[1]) catch @panic("OOM"); + } break :mvzr b.createModule(.{ .root_source_file = b.addWriteFiles().add("mvzr.zig", patched), .target = target, .optimize = optimize }); }; @@ -582,6 +593,7 @@ pub fn build(b: *std.Build) void { }); mupdf.linkTo(mupdf_mod); mupdf_mod.addImport("c_heap", c_heap_mod); + mupdf_mod.addImport("pdf_c", b.addTranslateC(.{ .root_source_file = b.path("src/pdf_bridge.h"), .target = target, .optimize = optimize }).createModule()); mupdf_mod.addIncludePath(b.path("src")); mupdf_mod.addCSourceFile(.{ .file = b.path("src/pdf_bridge.c"), @@ -599,12 +611,13 @@ pub fn build(b: *std.Build) void { const pdf_bench_mod = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("src/pdf.zig"), .link_libc = true, }); mupdf.linkTo(pdf_bench_mod); pdf_bench_mod.addImport("c_heap", c_heap_mod); + pdf_bench_mod.addImport("pdf_c", b.addTranslateC(.{ .root_source_file = b.path("src/pdf_bridge.h"), .target = target, .optimize = .fast }).createModule()); pdf_bench_mod.addIncludePath(b.path("src")); pdf_bench_mod.addCSourceFile(.{ .file = b.path("src/pdf_bridge.c"), @@ -614,14 +627,14 @@ pub fn build(b: *std.Build) void { .name = "pardes-pdf-bench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/pdf_bench.zig"), .link_libc = true, }), }); pdf_bench.root_module.addImport("mupdf", pdf_bench_mod); const run_pdf_bench = b.addRunArtifact(pdf_bench); - if (b.args) |args| run_pdf_bench.addArgs(args); + run_pdf_bench.addPassthruArgs(); run_pdf_bench.setCwd(b.path(".")); pdf_bench_step.dependOn(&run_pdf_bench.step); @@ -629,7 +642,7 @@ pub fn build(b: *std.Build) void { .name = "pardes-pdf-sections-bench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/pdf_sections_bench.zig"), .link_libc = true, }), @@ -637,10 +650,10 @@ pub fn build(b: *std.Build) void { pdf_sections_bench.root_module.addImport("pardes", core_module); pdf_sections_bench.root_module.addImport("mupdf", mupdf_mod); const sections_bench_opts = b.addOptions(); - sections_bench_opts.addOption(bool, "release_fast_core", optimize == .ReleaseFast); + sections_bench_opts.addOption(bool, "release_fast_core", optimize == .fast); pdf_sections_bench.root_module.addOptions("pdf_sections_bench_config", sections_bench_opts); const run_pdf_sections_bench = b.addRunArtifact(pdf_sections_bench); - if (b.args) |args| run_pdf_sections_bench.addArgs(args); + run_pdf_sections_bench.addPassthruArgs(); run_pdf_sections_bench.setCwd(b.path(".")); pdf_sections_bench_step.dependOn(&run_pdf_sections_bench.step); @@ -648,7 +661,7 @@ pub fn build(b: *std.Build) void { .name = "pardes-pdf-pointer-bench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/pdf_pointer_bench.zig"), .link_libc = true, }), @@ -656,7 +669,7 @@ pub fn build(b: *std.Build) void { pdf_pointer_bench.root_module.addImport("pardes", core_module); pdf_pointer_bench.root_module.addImport("mupdf", mupdf_mod); const run_pdf_pointer_bench = b.addRunArtifact(pdf_pointer_bench); - if (b.args) |args| run_pdf_pointer_bench.addArgs(args); + run_pdf_pointer_bench.addPassthruArgs(); run_pdf_pointer_bench.setCwd(b.path(".")); pdf_pointer_bench_step.dependOn(&run_pdf_pointer_bench.step); @@ -672,11 +685,11 @@ pub fn build(b: *std.Build) void { pdf_scroll_bench.root_module.addImport("pardes", core_module); pdf_scroll_bench.root_module.addImport("mupdf", mupdf_mod); const scroll_bench_opts = b.addOptions(); - scroll_bench_opts.addOption(bool, "release_fast_core", optimize == .ReleaseFast); + scroll_bench_opts.addOption(bool, "release_fast_core", optimize == .fast); scroll_bench_opts.addOption([]const u8, "core_optimize", @tagName(optimize)); pdf_scroll_bench.root_module.addOptions("pdf_scroll_bench_config", scroll_bench_opts); const run_pdf_scroll_bench = b.addRunArtifact(pdf_scroll_bench); - if (b.args) |args| run_pdf_scroll_bench.addArgs(args); + run_pdf_scroll_bench.addPassthruArgs(); run_pdf_scroll_bench.setCwd(b.path(".")); pdf_scroll_bench_step.dependOn(&run_pdf_scroll_bench.step); } @@ -712,15 +725,13 @@ pub fn build(b: *std.Build) void { // - An X10 mouse report and a kitty graphics reply cut short by a read // wait for their rest: the first became three bytes of text, the // second sliced past its input. - // - A malformed color or clipboard reply is dropped instead of failing - // the parse, which stopped input; so is a byte no UTF-8 starts with. - // - An OSC reply ends at its first terminator: one ended by BEL ran on to - // the next sequence's ESC and left what lay between as text. + // - A byte no UTF-8 starts with is dropped instead of failing the parse, + // which stopped input. (vaxis itself now drops a malformed color or + // clipboard reply and ends an OSC at its first terminator.) // - A device report's fields are sought in the sequence, not past it. // A bump that moves an anchor stops the build. { - const parser_path = vaxis_dep.path("src/Parser.zig").getPath(b); - var src = std.Io.Dir.cwd().readFileAlloc(io, parser_path, b.allocator, .limited(1 << 20)) catch @panic("read vaxis Parser.zig"); + var src = configureRead(b, io, vaxis_dep.builder.root, "src/Parser.zig", 1 << 20) catch @panic("read vaxis Parser.zig"); const edits = [_]struct { anchor: []const u8, with: []const u8, count: usize = 1 }{ .{ .anchor = @@ -731,7 +742,7 @@ pub fn build(b: *std.Build) void { \\ 0x5F => return parseApc(input), \\ // pardes's patch (its build.zig): ESC before a key's sequence is Alt on the key. \\ 0x1B => if (input.len > 2 and (input[2] == '[' or input[2] == 'O')) { - \\ var inner = if (input[2] == '[') parseCsi(input[1..], &self.buf) else parseSs3(input[1..]); + \\ var inner = if (input[2] == '[') parseCsi(input[1..], &self.buf, self.cursor_position_requests) else parseSs3(input[1..]); \\ if (inner.n == 0) return inner; \\ if (inner.event) |*event| switch (event.*) { \\ .key_press, .key_release => |*key| key.mods.alt = true, @@ -765,71 +776,17 @@ pub fn build(b: *std.Build) void { \\ switch (input[2]) { , }, - .{ - .anchor = - \\ const esc_result = skipUntilST(input); - \\ if (esc_result.n > 0) break :blk esc_result.n; - \\ - \\ // No escape, could be BEL terminated - \\ const bel = std.mem.indexOfScalarPos(u8, input, 2, 0x07) orelse return .{ - \\ .event = null, - \\ .n = 0, - \\ }; - \\ bel_terminated = true; - \\ break :blk bel + 1; - , - .with = - \\ // pardes's patch (its build.zig): whichever terminator comes first ends it. - \\ const esc = std.mem.indexOfScalarPos(u8, input, 2, 0x1b); - \\ const bel = std.mem.indexOfScalarPos(u8, input, 2, 0x07); - \\ if (bel != null and (esc == null or bel.? < esc.?)) { - \\ bel_terminated = true; - \\ break :blk bel.? + 1; - \\ } - \\ const esc_result = skipUntilST(input); - \\ if (esc_result.n > 0) break :blk esc_result.n; - \\ return .{ .event = null, .n = 0 }; - , - }, - .{ - .anchor = " const color = try Color.rgbFromSpec(color_spec);\n", - .with = " const color = Color.rgbFromSpec(color_spec) catch return null_event; // pardes's patch (its build.zig)\n", - .count = 2, - }, - .{ - .anchor = - \\ if (input[semicolon_idx + 1] != 'c') return null_event; - \\ const payload = if (bel_terminated) - \\ input[semicolon_idx + 3 .. sequence.len - 1] - \\ else - \\ input[semicolon_idx + 3 .. sequence.len - 2]; - \\ const decoder = std.base64.standard.Decoder; - \\ const text = try paste_allocator.?.alloc(u8, try decoder.calcSizeForSlice(payload)); - \\ try decoder.decode(text, payload); - , - .with = - \\ // pardes's patch (its build.zig): a malformed reply is dropped. - \\ const body_end = if (bel_terminated) sequence.len - 1 else sequence.len - 2; - \\ if (semicolon_idx + 3 > body_end or input[semicolon_idx + 1] != 'c') return null_event; - \\ const payload = input[semicolon_idx + 3 .. body_end]; - \\ const decoder = std.base64.standard.Decoder; - \\ const gpa = paste_allocator orelse return null_event; - \\ const text = gpa.alloc(u8, decoder.calcSizeForSlice(payload) catch return null_event) catch return null_event; - \\ decoder.decode(text, payload) catch { - \\ gpa.free(text); - \\ return null_event; - \\ }; - , - }, .{ .anchor = \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => { + \\ // Legacy keys \\ , .with = \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => { \\ // pardes's patch (its build.zig): a cursor position report is no key. \\ if (final == 'R' and cursorReport(sequence)) return null_event; + \\ // Legacy keys \\ , }, @@ -882,8 +839,7 @@ pub fn build(b: *std.Build) void { // (InactiveDim on a focus change) sent every blank of every pane it // touched again: 7 KB a click for three shell panes. The terminal // keeps the old ink there, and so does vaxis's last frame. - const render_path = vaxis_dep.path("src/Vaxis.zig").getPath(b); - var render_src = std.Io.Dir.cwd().readFileAlloc(io, render_path, b.allocator, .limited(1 << 20)) catch @panic("read vaxis Vaxis.zig"); + var render_src = configureRead(b, io, vaxis_dep.builder.root, "src/Vaxis.zig", 1 << 20) catch @panic("read vaxis Vaxis.zig"); const render_anchor = \\ if ((!self.refresh and \\ last.eql(cell) and @@ -941,7 +897,7 @@ pub fn build(b: *std.Build) void { var ghostty_vt_for_snap: ?*std.Build.Module = null; const ghostty_simd = !freestanding_core and (!target.result.os.tag.isDarwin() or b.graph.host.result.os.tag.isDarwin()); - const ghostty_optimize: std.builtin.OptimizeMode = if (optimize == .Debug) .ReleaseSafe else optimize; + const ghostty_optimize: std.lang.Optimize = if (optimize == .debug) .safe else optimize; const ghostty_dep = if (is_esp32p4) null else b.lazyDependency("ghostty", .{ .target = target, .optimize = ghostty_optimize, .simd = ghostty_simd, .@"app-runtime" = .none, .@"emit-xcframework" = false }); if (ghostty_dep) |dep| { const ghostty_vt = dep.module("ghostty-vt"); @@ -1017,6 +973,17 @@ pub fn build(b: *std.Build) void { const sdl_lib = dep.artifact("SDL3"); gm.linkLibrary(sdl_lib); gm.addIncludePath(dep.path("include")); + // gui.zig's `c`: SDL and the font shim, which @cImport gave it before Zig 0.17. + const header = b.addWriteFiles().add("gui_c.h", + \\#define SDL_DISABLE_OLD_NAMES 1 + \\#include + \\#include "font.h" + \\ + ); + const gui_c = b.addTranslateC(.{ .root_source_file = header, .target = target, .optimize = optimize }); + gui_c.addIncludePath(dep.path("include")); + gui_c.addIncludePath(b.path("src/gui")); + gm.addImport("gui_c", gui_c.createModule()); } gm.linkLibrary(freetype.?); // HarfBuzz from source, like FreeType: its FreeType integration @@ -1105,7 +1072,7 @@ pub fn build(b: *std.Build) void { }) |file| web_step.dependOn(&b.addInstallFileWithDir(b.path(file[0]), .{ .custom = "web" }, file[1]).step); const run_web_harness = b.addSystemCommand(&.{ "node", "test/web_harness.mjs" }); - run_web_harness.addArg(b.getInstallPath(.{ .custom = "web" }, "")); + run_web_harness.addDirectoryArg(installed("web")); run_web_harness.step.dependOn(web_step); b.step("web-harness", "run the dependency-free JS/WASM DOM harness").dependOn(&run_web_harness.step); b.getInstallStep().dependOn(web_step); @@ -1149,9 +1116,9 @@ pub fn build(b: *std.Build) void { const min_version = b.fmt("{d}.{d}", .{ macos_min_version.major, macos_min_version.minor }); const swift_mode: []const u8 = switch (optimize) { - .Debug => "-Onone", - .ReleaseSmall => "-Osize", - .ReleaseFast, .ReleaseSafe => "-O", + .debug => "-Onone", + .small => "-Osize", + .fast, .safe => "-O", }; const link = b.addSystemCommand(&.{ "swiftc", swift_mode, "-target", triple, "-import-objc-header" }); @@ -1218,7 +1185,8 @@ pub fn build(b: *std.Build) void { const sign = b.addSystemCommand(&.{ "codesign", "--force", "--sign", macos_identity }); if (!std.mem.eql(u8, macos_identity, "-")) sign.addArgs(&.{ "--options", "runtime", "--timestamp" }); - sign.addArg(b.getInstallPath(.prefix, "pardes.app")); + sign.setCwd(installed("")); + sign.addArg("pardes.app"); sign.has_side_effects = true; sign.step.dependOn(&install_app_bin.step); sign.step.dependOn(&install_plist.step); @@ -1227,8 +1195,8 @@ pub fn build(b: *std.Build) void { app_step.dependOn(&sign.step); const dmg = b.addSystemCommand(&.{ "hdiutil", "create", "-volname", "pardes", "-ov", "-format", "UDZO", "-srcfolder" }); - dmg.addArg(b.getInstallPath(.prefix, "pardes.app")); - dmg.addArg(b.getInstallPath(.prefix, "pardes.dmg")); + dmg.setCwd(installed("")); + dmg.addArgs(&.{ "pardes.app", "pardes.dmg" }); dmg.has_side_effects = true; dmg.step.dependOn(&sign.step); dmg_step.dependOn(&dmg.step); @@ -1267,7 +1235,7 @@ pub fn build(b: *std.Build) void { const run_e2e = std.Build.Step.Run.create(b, "run macos-e2e"); run_e2e.addFileArg(runnable); run_e2e.setCwd(b.path(".")); - if (b.args) |args| run_e2e.addArgs(args); + run_e2e.addPassthruArgs(); run_e2e.has_side_effects = true; e2e_step.dependOn(&run_e2e.step); } else e2e_step.dependOn(&b.addFail("macos-e2e needs a Darwin host and target").step); @@ -1290,7 +1258,7 @@ pub fn build(b: *std.Build) void { .linkage = if (static) .static else null, .root_module = root_mod, }); - b.installArtifact(exe); + installHome(b, exe, home_bin); if (gui_mod) |gm| { var gui_name: []const u8 = "pardes-gui"; if (target.result.os.tag != .linux or target.result.cpu.arch != .x86_64) @@ -1300,7 +1268,7 @@ pub fn build(b: *std.Build) void { .linkage = if (static) .static else null, .root_module = gm, }); - b.installArtifact(gui_exe); + installHome(b, gui_exe, home_bin); } const run = b.addRunArtifact(exe); b.step("run", "descend to the pardes").dependOn(&run.step); @@ -1312,7 +1280,7 @@ pub fn build(b: *std.Build) void { }); const run_iso = b.addRunArtifact(iso_exe); // Something to look at on arrival, read out of the binary itself. - if (b.args) |args| run_iso.addArgs(args) else run_iso.addArg("src/pardes.zig"); + run_iso.addPassthruArgs(); const iso_step = b.step("run-isolated", "descend to a pardes with no host but the terminal"); iso_step.dependOn(&run_iso.step); } @@ -1370,15 +1338,9 @@ pub fn build(b: *std.Build) void { hxdiff.root_module.addImport("pardes", core_module); const run_hxdiff = b.addRunArtifact(hxdiff); run_hxdiff.has_side_effects = true; - if (b.args) |args| run_hxdiff.addArgs(args) else { - run_hxdiff.addArgs(&.{ - "--strict", - "test/hxcases/cases.jsonl", - "test/hxcases/goldens.jsonl", - "test/hxcases/waivers.jsonl", - }); - run_hxdiff.setCwd(b.path(".")); - } + // Bare, it runs the checked-in suite (test/hxdiff.zig). + run_hxdiff.addPassthruArgs(); + run_hxdiff.setCwd(b.path(".")); const hxdiff_step = b.step("hxdiff", "compare Helix results (-- --strict cases reference [waivers]; cases alone emits)"); hxdiff_step.dependOn(&run_hxdiff.step); @@ -1403,16 +1365,8 @@ pub fn build(b: *std.Build) void { const run_hxparity = b.addRunArtifact(hxdiff); run_hxparity.has_side_effects = true; run_hxparity.addArg("--parity"); - if (b.args) |args| run_hxparity.addArgs(args) else { - run_hxparity.addArgs(&.{ - "--strict", - "--waivers", - "test/hxcases/parity-waivers.jsonl", - "test/hxcases/cases.jsonl", - "test/hxcases/parity.jsonl", - }); - run_hxparity.setCwd(b.path(".")); - } + run_hxparity.addPassthruArgs(); + run_hxparity.setCwd(b.path(".")); const hxparity_step = b.step("hxparity", "run the file-vs-pty editing parity suite (-- [--waivers w.jsonl] ...)"); hxparity_step.dependOn(&run_hxparity.step); @@ -1427,21 +1381,21 @@ pub fn build(b: *std.Build) void { .name = "pardes-lspbench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/lspbench.zig"), .link_libc = true, }), }); lspbench.root_module.addImport("pardes", core_module); const run_lspbench = b.addRunArtifact(lspbench); - if (b.args) |args| run_lspbench.addArgs(args); + run_lspbench.addPassthruArgs(); run_lspbench.setCwd(b.path(".")); run_lspbench.has_side_effects = true; const lspbench_step = b.step("lspbench", "language-backend latency + feature matrix (-- [--json] [--check] [repo-root]), or one query (-- probe : [arg] [--reps N])"); lspbench_step.dependOn(&run_lspbench.step); const run_lspbench_check = b.addRunArtifact(lspbench); run_lspbench_check.addArg("--check"); - if (b.args) |args| run_lspbench_check.addArgs(args); + run_lspbench_check.addPassthruArgs(); run_lspbench_check.setCwd(b.path(".")); run_lspbench_check.has_side_effects = true; const lspbench_check_step = b.step("lspbench-check", "require every configured language probe to complete correctly"); @@ -1449,12 +1403,12 @@ pub fn build(b: *std.Build) void { const locations_bench_step = b.step("locations-bench", "measure cold/warm result formatting (-Doptimize=ReleaseFast; CSV on stderr)"); - if (optimize != .ReleaseFast) { + if (optimize != .fast) { locations_bench_step.dependOn(&b.addFail("locations-bench requires -Doptimize=ReleaseFast").step); } else { const locations_bench_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/locations_bench.zig"), .link_libc = true, }); @@ -1465,7 +1419,7 @@ pub fn build(b: *std.Build) void { locations_bench_step.dependOn(&run_locations_bench.step); } - const perf_optimize: std.builtin.OptimizeMode = .ReleaseFast; + const perf_optimize: std.lang.Optimize = .fast; const perf_options = b.addOptions(); const perf_target = std.Target.Query.fromTarget(&target.result); perf_options.addOption(PerfBuild, "identity", .{ @@ -1499,7 +1453,7 @@ pub fn build(b: *std.Build) void { perf.root_module.addOptions("perf_options", perf_options); const run_perf = b.addRunArtifact(perf); run_perf.has_side_effects = true; - if (b.args) |args| run_perf.addArgs(args); + run_perf.addPassthruArgs(); run_perf.setCwd(b.path(".")); const perf_step = b.step("perf", "gesture latency or bounded terminal stress (-- [--json] [--reps N] [--base old.json] [--terminal-mib N])"); perf_step.dependOn(&run_perf.step); @@ -1536,7 +1490,7 @@ pub fn build(b: *std.Build) void { .name = "pardes-fs-bench", .root_module = b.createModule(.{ .target = target, - .optimize = .ReleaseFast, + .optimize = .fast, .root_source_file = b.path("test/fs_bench.zig"), .link_libc = true, }), @@ -1544,7 +1498,7 @@ pub fn build(b: *std.Build) void { fs_bench.root_module.addImport("pardes", core_module); const run_fs_bench = b.addRunArtifact(fs_bench); run_fs_bench.has_side_effects = true; - if (b.args) |args| run_fs_bench.addArgs(args); + run_fs_bench.addPassthruArgs(); run_fs_bench.setCwd(b.path(".")); const fs_bench_step = b.step("fs-bench", "9P filesystem request cost and allocation count (-- [--json] [--reps N])"); fs_bench_step.dependOn(&run_fs_bench.step); @@ -1581,11 +1535,11 @@ pub fn build(b: *std.Build) void { }); syntax_runner.root_module.addImport("syntax", syntax_module); const run_syntax = b.addRunArtifact(syntax_runner); - if (b.args) |args| run_syntax.addArgs(args); + run_syntax.addPassthruArgs(); b.step("syntax", "emit deterministic syntax snapshots").dependOn(&run_syntax.step); const run_syntax_bench = b.addRunArtifact(syntax_runner); run_syntax_bench.addArg("--bench"); - if (b.args) |args| run_syntax_bench.addArgs(args); + run_syntax_bench.addPassthruArgs(); run_syntax_bench.has_side_effects = true; b.step("syntax-bench", "measure highlighting latency and allocations").dependOn(&run_syntax_bench.step); const syntax_test = b.addTest(.{ @@ -1611,7 +1565,7 @@ pub fn build(b: *std.Build) void { // part of fs-test; the long run is manual. const run_monkey9p = b.addSystemCommand(&.{ "python3", "-B", "test/monkey9p.py" }); run_monkey9p.addArtifactArg(exe); - if (b.args) |args| run_monkey9p.addArgs(args); + run_monkey9p.addPassthruArgs(); run_monkey9p.setCwd(b.path(".")); run_monkey9p.has_side_effects = true; b.step("monkey-9p", "random 9P operations checking the documented rules (-- [--seed N]... [--steps M] [--replay F] [--shrink F] [--no-shrink])").dependOn(&run_monkey9p.step); @@ -1622,7 +1576,7 @@ pub fn build(b: *std.Build) void { if (platform == .gui) { const run_monkey_gui = b.addSystemCommand(&.{ "python3", "-B", "test/gui_monkey.py" }); run_monkey_gui.addArtifactArg(exe); - if (b.args) |args| run_monkey_gui.addArgs(args); + run_monkey_gui.addPassthruArgs(); run_monkey_gui.setCwd(b.path(".")); run_monkey_gui.has_side_effects = true; monkey_gui_step.dependOn(&run_monkey_gui.step); @@ -1653,7 +1607,7 @@ pub fn build(b: *std.Build) void { }), }); // Ordinary executable; each launch asks sudo inside its own PTY. - b.installArtifact(v9fs_helper); + installHome(b, v9fs_helper, home_bin); const run_v9fs = b.addSystemCommand(&.{ "python3", "-B", "test/v9fs.py" }); run_v9fs.addArtifactArg(exe); run_v9fs.addArtifactArg(v9fs_helper); @@ -1688,7 +1642,7 @@ pub fn build(b: *std.Build) void { }), }); const run_history = b.addRunArtifact(history); - if (b.args) |args| run_history.addArgs(args); + run_history.addPassthruArgs(); run_history.has_side_effects = true; b.step("history", "compare command output and test/build runtime across jj revisions").dependOn(&run_history.step); @@ -1843,7 +1797,7 @@ pub fn build(b: *std.Build) void { if (unit_match) |check| check.addArtifactArg(shell_test); const run_profile = b.addRunArtifact(unit_profile); run_profile.addArtifactArg(shell_test); - if (b.args) |args| run_profile.addArgs(args); + run_profile.addPassthruArgs(); run_profile.has_side_effects = true; b.step("unit-profile", "report test request time and process memory as JSONL (-- optional filter, --timeout-ms=N)").dependOn(&run_profile.step); const profile_test = b.addExecutable(.{ @@ -1876,19 +1830,38 @@ fn testMatch(b: *std.Build, profiler: *std.Build.Step.Compile, filters: []const return check; } -fn prefixIsUntouched(b: *std.Build) bool { - if (b.dest_dir != null) return false; - const zig_out = b.build_root.join(b.allocator, &.{"zig-out"}) catch @panic("OOM"); - if (!std.mem.eql(u8, b.install_prefix, zig_out)) return false; - return std.mem.eql(u8, b.exe_dir, b.pathJoin(&.{ b.install_path, "bin" })) and - std.mem.eql(u8, b.lib_dir, b.pathJoin(&.{ b.install_path, "lib" })) and - std.mem.eql(u8, b.h_dir, b.pathJoin(&.{ b.install_path, "include" })); +/// Installs `artifact` in the prefix and, given `home_bin`, copies it there +/// too (`install` unlinks first, so a running binary is replaced). +fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]const u8) void { + b.installArtifact(artifact); + const dir = home_bin orelse return; + const copy = b.addSystemCommand(&.{ "install", "-Dm755" }); + copy.addArtifactArg(artifact); + copy.addArg(b.pathJoin(&.{ dir, artifact.name })); + copy.has_side_effects = true; + b.getInstallStep().dependOn(©.step); +} + +/// A file read while configuring, under a package's root. A dependency's is +/// hash-addressed and never changes under the same pin; this repo's are not +/// tracked one by one, since the configure runs again on every build anyway +/// (findProgram and gitCommit poison its cache). +// ponytail: untracked repo reads; b.dependOnFileContents each one if the configure cache ever stays pure. +fn configureRead(b: *std.Build, io: std.Io, root: std.Build.Cache.Path, sub: []const u8, limit: usize) ![]u8 { + return root.root_dir.handle.readFileAlloc(io, b.pathJoin(&.{ root.subPathOrDot(), sub }), b.allocator, .limited(limit)); +} + +/// `sub` under the install prefix, known only when the build runs. +fn installed(sub: []const u8) std.Build.LazyPath { + return .{ .relative = .{ .base = .install_prefix, .sub_path = sub } }; } fn gitCommit(b: *std.Build) ?[]const u8 { + // HEAD is not a file the configure cache can track. + b.graph.poisonCache(); var code: u8 = 0; const out = b.runAllowFail( - &.{ "git", "-C", b.build_root.path orelse ".", "rev-parse", "--short=12", "HEAD" }, + &.{ "git", "rev-parse", "--short=12", "HEAD" }, &code, .ignore, ) catch return null; @@ -1985,7 +1958,7 @@ fn compileGlsl(b: *std.Build, name: []const u8) std.Build.LazyPath { fn vendoredThemes(b: *std.Build, io: std.Io) []const []const u8 { var count: usize = 0; { - var dir = b.build_root.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); + var dir = b.root.root_dir.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); defer dir.close(io); var it = dir.iterate(); while (it.next(io) catch @panic("read vendor/themes")) |e| { @@ -1995,7 +1968,7 @@ fn vendoredThemes(b: *std.Build, io: std.Io) []const []const u8 { } const names = b.allocator.alloc([]const u8, count) catch @panic("OOM"); - var dir = b.build_root.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); + var dir = b.root.root_dir.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); defer dir.close(io); var it = dir.iterate(); var index: usize = 0; diff --git a/build.zig.zon b/build.zig.zon index b1f501fe..a2fc90dd 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,52 +9,59 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#fe9772b178575fcab93de09fc61c2f13db7db1a8", - .hash = "cloud9-0.1.0-yt86qh4qHgC6OpG4gZE9yoQaO8huc5mnQCaqGwuJ0OU1", + .url = "git+https://git.sr.ht/~gbrls/cloud9#d5c37d9122240fe95d308fbe15874e14dd786c5a", + .hash = "cloud9-0.1.0-yt86qnAvHgB1dEWGakukcJ54GZ7J3mv_lm_kApzAuEOY", }, // Pinned to the exact libvaxis commit ghostty is built against, so it // is compatible with ghostty's uucode configuration (the one we share // with it via `external_uucode` in build.zig). .vaxis = .{ - .url = "git+https://github.com/rockorager/libvaxis.git#1dbbe575dff4586fe51e3217aa5c3fecdcbb6089", - .hash = "vaxis-0.6.0-BWNV_CrbCQCscGpzsAlR402rYQ_tV3aAl081c2iRRkka", + .url = "git+https://github.com/rockorager/libvaxis.git#6fd944a27fb3d6f596e981076381a3131f2448b4", + .hash = "vaxis-0.6.0-BWNV_MafDAAEzkVUvrW9NFUqnnMUoeHqrs2mecnD6D7w", }, .ghostty = .{ - .url = "git+https://github.com/ghostty-org/ghostty.git#82e53e3f6e219e0cf0499fe29c82d925ea26cd5e", - .hash = "ghostty-1.3.2-dev-5UdBCzeJJQXw_vG5Hsfx0DYUmF7Exs_9yctijqOIfp7W", + .url = "git+https://github.com/ghostty-org/ghostty.git#521cf2c5d30bd48028ca61546c64e7913764073d", + .hash = "ghostty-1.3.2-dev-5UdBC6WZfwXgQ6HmA5DH6dGNAUqtDMLrhhrHiBX-99J0", }, // Same uucode commit ghostty and vaxis both depend on. We build it // ourselves (with uucode_config.zig) so ghostty-vt and vaxis can share // a single uucode module. See build.zig for the why. .uucode = .{ - .url = "git+https://github.com/jacobsandlund/uucode#2826a37a4562284fdacd8fa029d49509cc9bffcd", - .hash = "uucode-0.2.0-ZZjBPlK5VADj7fdoq7G8LIHzD5o6FSkcBXXrRWr4jnrA", + .url = "git+https://github.com/jacobsandlund/uucode#ea62149739404a73c202b48a33bf6dd2af4bd9b0", + .hash = "uucode-0.2.0-ZZjBPoGFVgCiflJNFc6Io8xzC67B6PA5bUkk4LT0kCxg", }, + // Pivok7's fork: zig-gamedev/zstbi PR #16, "Upgrade to zig 0.17.0" + // (two lines of build.zig). Back to upstream once it is merged. .zstbi = .{ - .url = "git+https://github.com/zig-gamedev/zstbi#3813f5f113b26f644cfa01a30155cc76b3526e91", - .hash = "zstbi-0.11.0-dev-L0Ea_3GWBwAh7m54XX055vwLKPTPij5hyqyeq92MXPE2", + .url = "git+https://github.com/Pivok7/zstbi#bc96f28d341f9c7fb9cbc5dc65aa4c5cf0c8f007", + .hash = "zstbi-0.11.0-dev-L0Ea_3GWBwCpNHVwGU4MPR_oDd0FoQOYNrGodwvJ6Z45", }, - // SDL3 (castholm/SDL zig bindings) — only fetched/compiled when `-Dsdl` - // is set. Lazy so the default vaxis build never touches it. The sdl + // SDL3 (castholm/SDL zig bindings, its release-3.4.x branch for Zig + // 0.17; david-vanderson's fork, pinned before, has no 0.17 build) — only + // fetched/compiled when `-Dsdl` is set. Lazy so the default vaxis build never touches it. The sdl // package resolves its own linux deps from its own build.zig.zon. .sdl = .{ - .url = "git+https://github.com/david-vanderson/SDL#5bbcf665494fe14acadf50601edf6d5f74ebf96a", - .hash = "sdl-0.4.2+3.4.4-SDL--tB1pQFLgwvCakiiOSoZIuVaz6a6-_gOZC66AGRD", + .url = "git+https://github.com/castholm/SDL#dbcb19aa3583c318556ecae3ecbeb29b102d37c5", + .hash = "sdl-0.6.0+3.4.18-SDL--p-gqAGWpnfTLlhs0dgjDtc4P4_CHeNLGY_SX_Fv", .lazy = true, }, // tree-sitter: Zig bindings + the C runtime, plus grammars (parser.c // we link, highlights.scm we read at build time into the ts_queries module). + // pierrelgol's forks of zig-tree-sitter (here) and tree-sitter-c + // (ts_c), which pin a fork of the tree-sitter core: upstream's + // build.zig files still use APIs Zig 0.17 removed. Their diffs touch + // only the build files and tests. Back to upstream once it moves. .tree_sitter = .{ - .url = "git+https://github.com/tree-sitter/zig-tree-sitter#b55d4977d61330390fc733944da06106ff972660", - .hash = "tree_sitter-0.26.0-8heIf3CaAQB4SSumoGzq3gLSz2rkvXxcKFyskRWqDGBz", + .url = "git+https://github.com/pierrelgol/zig-tree-sitter#2ffef82a12d0305e646ade0e67c693cabc661e05", + .hash = "tree_sitter-0.26.0-8heIf1HEAQCVBaR2wlDhGTw16Ttn1bzERVIwlzNcyO6b", }, .ts_rust = .{ .url = "git+https://github.com/tree-sitter/tree-sitter-rust#77a3747266f4d621d0757825e6b11edcbf991ca5", .hash = "N-V-__8AAHJYbgAipcanYj2A6rnj9wtGzjGzANkrOsqiFAxm", }, .ts_c = .{ - .url = "git+https://github.com/tree-sitter/tree-sitter-c#b780e47fc780ddc8da13afa35a3f4ed5c157823d", - .hash = "tree_sitter_c-0.24.2-y5boS-ptQADHoCoVfjGT_nFtFQ5LbomIkW0fxG3_cmdB", + .url = "git+https://github.com/pierrelgol/tree-sitter-c#67949e4c8dc630c18a522919f2bde2e025a0d025", + .hash = "tree_sitter_c-0.24.2-y5boS-htQACe3pz6jHq4tpS8dB6WIo4-zk_ct7lAjvQT", }, .ts_typst = .{ .url = "git+https://github.com/uben0/tree-sitter-typst#13863ddcbaa7b68ee6221cea2e3143415e64aea4", @@ -185,7 +192,7 @@ .lazy = true, }, }, - .minimum_zig_version = "0.16.0", + .minimum_zig_version = "0.17.0", .paths = .{""}, .fingerprint = 0x41dc46101fc764d8, } diff --git a/build/snap.zig b/build/snap.zig index 7aa06884..35a246ad 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -44,7 +44,7 @@ pub fn addTty(b: *std.Build, opts: struct { const run_snap = b.addRunArtifact(snap); run_snap.addArtifactArg(opts.exe); run_snap.addPrefixedFileArg("--lspmock=", lspmock.getEmittedBin()); - if (b.args) |args| run_snap.addArgs(args); + run_snap.addPassthruArgs(); // scripts fork children and drive real ptys: never cached, never "up to date" run_snap.has_side_effects = true; const snap_step = b.step("snap", "run the snapshot parity suite (-- --update regenerates goldens)"); @@ -63,7 +63,7 @@ pub fn addTty(b: *std.Build, opts: struct { const run_monkey = b.addRunArtifact(monkey); run_monkey.addArtifactArg(snap); run_monkey.addArtifactArg(opts.exe); - if (b.args) |args| run_monkey.addArgs(args); + run_monkey.addPassthruArgs(); run_monkey.has_side_effects = true; b.step("monkey", "random snapshot scripts hunting panics (-- [steps] [--from=N] [--out=DIR])").dependOn(&run_monkey.step); const monkey_tests = b.addTest(.{ .root_module = monkey.root_module }); @@ -101,7 +101,7 @@ pub fn addWeb(b: *std.Build) void { run_web_snap.step.dependOn(&build_web_snap.step); run_web_snap.step.dependOn(&driver_test.step); run_web_snap.has_side_effects = true; - if (b.args) |args| run_web_snap.addArgs(args); + run_web_snap.addPassthruArgs(); b.step("web-snap", "run browser highlighting, touch, Look, resize and scroll checks").dependOn(&run_web_snap.step); b.step("web-e2e", "run the Chrome-driven DOM end-to-end suite").dependOn(&run_web_snap.step); } diff --git a/docs/typ/building.typ b/docs/typ/building.typ index ae2f3a60..8d7524f9 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -9,7 +9,7 @@ pieces fit. To install it, see #doc("setup", section: "install"). = Platforms -Zig *0.16.0* (`build.zig.zon` pins `minimum_zig_version`). Dependencies are +Zig *0.17.0* (`build.zig.zon` pins `minimum_zig_version`). Dependencies are fetched and pinned by the manifest; the terminal build needs no system package. The SDL shell builds SDL3 and FreeType from source. PDF support builds MuPDF and is on by default (`-Dmupdf=false` drops it). 9P over QUIC @@ -24,10 +24,11 @@ builds MuPDF and is on by default (`-Dmupdf=false` drops it). 9P over QUIC [`zig build -Dplatform=esp32p4`], [a freestanding riscv32 editor object for the ESP32-P4, with a 384 KiB heap], ) -A bare `zig build` installs into `~/.local`; `--prefix ` installs -elsewhere, except `--prefix zig-out`, which counts as no prefix. With -`-Dplatform` the default prefix is `zig-out`, so always pass `-Dplatform` -while developing. Test, benchmark and run steps build what they need +A bare `zig build` installs into the prefix (`zig-out`, or `--prefix +`) and copies the binaries into `~/.local/bin`; `-Dhome-install=false` +leaves that copy out. Zig 0.17 keeps the prefix from the build script, so +`--prefix` alone no longer stops it. With `-Dplatform` nothing is copied, +so always pass `-Dplatform` while developing. Test, benchmark and run steps build what they need without installing. `pardes --version` prints `pardes ` (from `build.zig.zon`), plus the commit for release builds and the `~/.local` install; `pardes --help` lists every flag. @@ -50,6 +51,7 @@ there; its namespace is in `src/esp32p4_gpio.zig`. [`-Djpx`], [bool, `true`: JPEG 2000, and with it scanned PDFs], [`-Dtree-sitter`], [`disabled`, `zig`, `minimal`, `full`; `full` natively, `zig` for web, `disabled` for esp32p4], [`-Dembed-sources`], [bool, `false`: serve the sources under #file("/src")], + [`-Dhome-install`], [bool: a bare `zig build` also copies the binaries into `~/.local/bin`; default true], [`-Dstamp-commit`], [bool: the git commit in `--version` and crash records; on for release builds and the `~/.local` install], [`-Dtheme-animation`], [bool; on except for esp32p4], [`-Dworkspace-tag`], [bool: draw the workspace tag row; on except for macOS, whose menu bar carries it], diff --git a/docs/typ/install.typ b/docs/typ/install.typ index 9758777d..d97d30f7 100644 --- a/docs/typ/install.typ +++ b/docs/typ/install.typ @@ -18,7 +18,7 @@ #let first = project.mirrors.first() #cmd("git clone " + first.clone + " && cd pardes") -With Zig 0.16 (the build fetches everything else; once that is +With Zig 0.17 (the build fetches everything else; once that is downloaded, a first build from a clean cache took 62 seconds on 16 cores): #cmd("# pardes, in a terminal\nzig build -Dplatform=tty --prefix ~/.local") #cmd("# pardes-gui, its own window\nzig build -Dplatform=gui --prefix ~/.local") diff --git a/mupdf.zig b/mupdf.zig index eeadaa5d..761fef92 100644 --- a/mupdf.zig +++ b/mupdf.zig @@ -293,7 +293,7 @@ fn configureModule(module: *std.Build.Module, dependency: *std.Build.Dependency, } fn flatCSources(b: *std.Build, io: std.Io, dependency: *std.Build.Dependency, relative_dir: []const u8) []const []const u8 { - var dir = std.Io.Dir.cwd().openDir(io, dependency.path(relative_dir).getPath(b), .{ .iterate = true }) catch + var dir = dependency.builder.root.root_dir.handle.openDir(io, relative_dir, .{ .iterate = true }) catch std.debug.panic("MuPDF source directory is missing: {s}", .{relative_dir}); defer dir.close(io); @@ -317,9 +317,9 @@ fn flatCSources(b: *std.Build, io: std.Io, dependency: *std.Build.Dependency, re } fn readMakelists(b: *std.Build, io: std.Io, dependency: *std.Build.Dependency) []const u8 { - return std.Io.Dir.cwd().readFileAlloc( + return dependency.builder.root.root_dir.handle.readFileAlloc( io, - dependency.path("Makelists").getPath(b), + "Makelists", b.allocator, .limited(1024 * 1024), ) catch @panic("read MuPDF Makelists"); diff --git a/src/9p_io.zig b/src/9p_io.zig index 18c51ece..27d79b93 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1553,7 +1553,7 @@ test "a socket path too long for sun_path is no listener, and leaves the editor' } else { _ = unsetenv("XDG_RUNTIME_DIR"); }; - const long = "n" ** 120; + const long = &@as([120]u8, @splat('n')); try testing.expect(listen(testing.io, testing.allocator, p, long, "", null, null) == null); try testing.expect(pardes.turn.answer_held == null); try testing.expect(pardes.turn.wake_parked == null); @@ -1567,7 +1567,7 @@ test "a listening editor posts itself into the 9P registry and unposts on stop" _ = try std.fmt.bufPrintSentinel(&directory, "/tmp/pardes-post-XXXXXX", .{}, 0); if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; const dir = std.mem.span(@as([*:0]const u8, &directory)); - const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer { if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); @@ -1628,7 +1628,7 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; // What the listener posted and left inside goes with it. defer std.Io.Dir.cwd().deleteTree(testing.io, std.mem.sliceTo(&directory, 0)) catch |err| std.debug.print("deleteTree: {s}\n", .{@errorName(err)}); - const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer { if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); @@ -1749,7 +1749,7 @@ test "a change waits while the editor is out mid-step, a read does not, and the if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; // What the listener posted and left inside goes with it. defer std.Io.Dir.cwd().deleteTree(testing.io, std.mem.sliceTo(&directory, 0)) catch |err| std.debug.print("deleteTree: {s}\n", .{@errorName(err)}); - const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer { if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); @@ -1824,7 +1824,7 @@ test "a held read is answered when the log has news, and a flushed one spends no if (mkdtemp(&directory) == null) return error.TempDirectoryFailed; // What the listener posted and left inside goes with it. defer std.Io.Dir.cwd().deleteTree(testing.io, std.mem.sliceTo(&directory, 0)) catch |err| std.debug.print("deleteTree: {s}\n", .{@errorName(err)}); - const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeZ(u8, std.mem.span(v)) else null; + const old_runtime = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; defer { if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); @@ -2051,7 +2051,7 @@ test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and u 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.dupeZ(u8, std.mem.span(old)); + 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| { @@ -2073,7 +2073,7 @@ 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.dupeZ(u8, std.mem.span(old)); + 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| { diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 4fe0760c..c6c2eadd 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -17,6 +17,14 @@ - A diff paged into a session (`git show | pardes -`) opens its `+Diff` alone; the `+Pager` no longer stays folded under it. +- Built with Zig 0.17. A bare `zig build` still puts the binaries in + `~/.local/bin`, now as a copy beside the prefix, which `--prefix` no + longer prevents; `-Dhome-install=false` does. ghostty, libvaxis, uucode + and SDL (3.4.18) move to their Zig 0.17 versions, and tree-sitter to a + 0.28 development snapshot. +- A terminal's edited copy goes when the program clears the screen, + instead of staying where its rows were. + - n/N follow Helix search registers, counts, wrapping and select mode. `*` sets a search from the selection; `Alt-*` omits word boundaries. The location ring remains as LookNext/LookPrev (Space j n/p). diff --git a/src/Layer.zig b/src/Layer.zig index 7a5fcf7e..ba45bc88 100644 --- a/src/Layer.zig +++ b/src/Layer.zig @@ -51,7 +51,7 @@ cols: u16 = 0, rows: u16 = 0, /// A body's compact rows, from its top. context_rows: u16 = 0, -context_separators: std.bit_set.StaticBitSet(limits.wrap_rows) = .initEmpty(), +context_separators: std.bit_set.StaticBitSet(limits.wrap_rows) = .empty, /// `rows * cols`, row after row. cells: []pardes.Cell = &.{}, cursor: ?struct { x: u16, y: u16, bar: bool = false } = null, @@ -72,7 +72,7 @@ pub fn capacity(layer: *const Layer, metrics: Metrics) u16 { } pub fn setContextLines(layer: *Layer, lines: []const i32) void { - layer.context_separators = .initEmpty(); + layer.context_separators = .empty; const count = @min(lines.len, layer.context_rows); var index: usize = 0; while (index + 1 < count and index < limits.wrap_rows) : (index += 1) { diff --git a/src/Messages.zig b/src/Messages.zig index 2314939f..b67a8402 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -519,20 +519,20 @@ pub fn errorWords(err: anyerror, buf: []u8) []const u8 { /// A ZON parse failure in a person's words: the first error the parser /// found and its line, `line 3: expected ','`. pub fn zonWhy(diag: *const std.zon.parse.Diagnostics, buf: []u8) []const u8 { - var errors = diag.iterateErrors(); - const first = errors.next() orelse return "not valid ZON"; - const loc = first.getLocation(diag); - return std.fmt.bufPrint(buf, "line {d}: {f}", .{ loc.line + 1, first.fmtMessage(diag) }) catch "not valid ZON"; + if (diag.errors.len == 0) return "not valid ZON"; + const first = diag.errors[0]; + return std.fmt.bufPrint(buf, "line {d}: {s}", .{ first.loc.line + 1, first.msg }) catch "not valid ZON"; } 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 diag: std.zon.parse.Diagnostics = .{}; - defer diag.deinit(std.testing.allocator); + 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.fromSliceAlloc(T, std.testing.allocator, ".{\n .a = 1,\n .b = 2 }", &diag, .{})); + 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: ")); } diff --git a/src/TerminalImages.zig b/src/TerminalImages.zig index bc1b2ea8..4140813f 100644 --- a/src/TerminalImages.zig +++ b/src/TerminalImages.zig @@ -38,6 +38,72 @@ const GlyphKey = struct { id: u32, generation: u64, src: PixelRect, cols: u16 }; /// left corner (above or left of it is negative). const Rect = struct { x: i64, y: i64, w: i64, h: i64 }; +/// The runs of Kitty placeholder cells between two pins, one row's run at a +/// time, as ghostty's own `kitty.graphics.unicode.placementIterator` gave +/// them before it moved into its RenderState, which pardes does not keep. +const PlaceholderRuns = struct { + rows: ghostty_vt.PageList.RowIterator, + row: ?ghostty_vt.Pin, + /// Where the scan of `row` resumes: a run ended by an incompatible + /// placeholder starts the next one there. + x: usize = 0, + + fn init(top: ghostty_vt.Pin, bottom: ghostty_vt.Pin) PlaceholderRuns { + var rows = top.rowIterator(.right_down, bottom); + const row = rows.next(); + return .{ .rows = rows, .row = row }; + } + + fn next(self: *PlaceholderRuns) ?gfx.unicode.Placement { + while (self.row) |row| { + if (!row.rowAndCell().row.kitty_virtual_placeholder) { + self.advance(); + continue; + } + var run: ?gfx.unicode.IncompletePlacement = null; + var start: usize = 0; + const cells = row.cells(.all); + while (self.x < cells.len) : (self.x += 1) { + const cell = &cells[self.x]; + if (cell.codepoint() != gfx.unicode.placeholder) { + if (run) |done| return complete(row, start, done); + continue; + } + const style = row.style(cell); + const curr: gfx.unicode.IncompletePlacement = .init(&style, row.grapheme(cell) orelse &.{}); + if (run) |*prev| { + if (!prev.append(&curr)) return complete(row, start, prev.*); + } else { + run = curr.start(); + start = self.x; + } + } + self.advance(); + if (run) |done| return complete(row, start, done); + } + return null; + } + + fn advance(self: *PlaceholderRuns) void { + self.row = self.rows.next(); + self.x = 0; + } + + fn complete(row: ghostty_vt.Pin, x: usize, run: gfx.unicode.IncompletePlacement) gfx.unicode.Placement { + var pin = row; + pin.x = @intCast(x); + return .{ + .pin = pin, + .image_id = run.imageId(), + .placement_id = run.placement_id orelse 0, + .col = run.col.?, + .row = run.row.?, + .width = run.width, + .height = 1, + }; + } +}; + pub fn deinit(ti: *TerminalImages, gpa: std.mem.Allocator) void { var conv = ti.converted.valueIterator(); while (conv.next()) |c| gpa.free(c.rgba); @@ -91,7 +157,7 @@ pub fn draw( // Virtual placements: shown through the placeholder cells, one run of // them on a row at a time. The placeholders themselves are not text. - var runs = gfx.unicode.placementIterator(top, bottom); + var runs: PlaceholderRuns = .init(top, bottom); while (runs.next()) |run| { const at = pages.pointFromPin(.viewport, run.pin) orelse continue; const v = at.viewport.y; @@ -104,7 +170,8 @@ pub fn draw( cell.len = 1; } const img = storage.imageById(run.image_id) orelse continue; - const rp = run.renderPlacement(storage, &img, cw, ch) catch continue; + const target = storage.placeholderTarget(run.image_id, run.placement_id) orelse continue; + const rp = run.renderPlacement(&target.placement, &img, cw, ch) catch continue; if (rp.dest_width == 0 or rp.dest_height == 0 or rp.source_width == 0 or rp.source_height == 0) continue; ctx.place(img, .{ .x = rp.source_x, .y = rp.source_y, .w = rp.source_width, .h = rp.source_height }, .{ .x = @as(i64, at.viewport.x) * cw + rp.offset_x, @@ -122,7 +189,8 @@ pub fn draw( const placed = entry.value_ptr.*; const pin = switch (placed.location) { .pin => |pin| pin, - .virtual => continue, + // ponytail: a placement relative to another (P=/Q=, new in ghostty) is not drawn; resolve its chain if a program needs it. + .virtual, .relative => continue, }; const img = storage.images.get(entry.key_ptr.image_id) orelse continue; const at = pages.pointFromPin(.screen, pin.*) orelse continue; @@ -221,7 +289,8 @@ const Ctx = struct { fn pixelsOf(ti: *TerminalImages, gpa: std.mem.Allocator, img: gfx.Image) ?[]const u8 { const n = @as(usize, img.width) * img.height; if (n == 0) return null; - if (img.format == .rgba) return if (img.data.len == n * 4) img.data else null; + const data = img.data.bytes() orelse return null; + if (img.format == .rgba) return if (data.len == n * 4) data else null; const gop = ti.converted.getOrPut(gpa, img.id) catch return null; if (gop.found_existing) { if (gop.value_ptr.generation == img.generation) { @@ -247,10 +316,11 @@ fn convert(gpa: std.mem.Allocator, img: gfx.Image, n: usize) ?[]u8 { .gray => 1, else => return null, }; - if (img.data.len != n * depth) return null; + const data = img.data.bytes() orelse return null; + if (data.len != n * depth) return null; const out = gpa.alloc(u8, n * 4) catch return null; for (0..n) |i| { - const px = img.data[i * depth ..][0..depth]; + const px = data[i * depth ..][0..depth]; out[i * 4 ..][0..4].* = switch (depth) { 3 => .{ px[0], px[1], px[2], 255 }, 2 => .{ px[0], px[0], px[0], px[1] }, diff --git a/src/builtins.zig b/src/builtins.zig index f73c5982..d9cef8c9 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -98,11 +98,11 @@ fn isEnabled(comptime T: type) bool { /// word that is one here, or in no build. pub fn absentWhy(name: []const u8) ?[]const u8 { @setEvalBranchQuota(20000); - inline for (@typeInfo(@This()).@"struct".decls) |d| { - if (comptime @TypeOf(@field(@This(), d.name)) == type) { - const T = @field(@This(), d.name); + inline for (@typeInfo(@This()).@"struct".decl_names) |d| { + if (comptime @TypeOf(@field(@This(), d)) == type) { + const T = @field(@This(), d); if (comptime @typeInfo(T) == .@"struct" and @hasDecl(T, "run") and !isEnabled(T)) { - if (std.mem.eql(u8, d.name, name)) return if (@hasDecl(T, "gui_only")) "GUI-only" else "not in this build"; + if (std.mem.eql(u8, d, name)) return if (@hasDecl(T, "gui_only")) "GUI-only" else "not in this build"; } } } @@ -112,12 +112,12 @@ pub fn absentWhy(name: []const u8) ?[]const u8 { fn manualBuiltinCount() comptime_int { comptime { var count = 0; - for (@typeInfo(@This()).@"struct".decls) |d| { - if (@TypeOf(@field(@This(), d.name)) != type) continue; - const T = @field(@This(), d.name); + for (@typeInfo(@This()).@"struct".decl_names) |d| { + if (@TypeOf(@field(@This(), d)) != type) continue; + const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; if (@TypeOf(T.run) != fn (Ctx) void) - @compileError(d.name ++ ".run must have signature fn (Ctx) void"); + @compileError(d ++ ".run must have signature fn (Ctx) void"); count += 1; } return count; @@ -129,9 +129,9 @@ fn manualBuiltinList() [manualBuiltinCount()]type { @setEvalBranchQuota(4000); var list: [manualBuiltinCount()]type = undefined; var count = 0; - for (@typeInfo(@This()).@"struct".decls) |d| { - if (@TypeOf(@field(@This(), d.name)) != type) continue; - const T = @field(@This(), d.name); + for (@typeInfo(@This()).@"struct".decl_names) |d| { + if (@TypeOf(@field(@This(), d)) != type) continue; + const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; list[count] = T; count += 1; @@ -317,7 +317,7 @@ test "Exit over a ctl write or a click names every pane it asks about, a second first.file.?.saved_hash = 0; // edited: what it had is not what it has p.newScratchBelow(p.active); const second = p.panes[p.active].?; - panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, "x" ** 120)); + 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; @@ -341,7 +341,7 @@ test "Exit over a ctl write or a click names every pane it asks about, a second 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, "y" ** 120)); + panes.File.setContent(p, &second.file.?, try std.testing.allocator.dupe(u8, &@as([120]u8, @splat('y')))); try std.testing.expect(p.executeBuiltinLine(p.active, "Exit")); try std.testing.expect(!p.quit); const again = p.fs.failure[0..p.fs.failure_len]; diff --git a/src/colors.zig b/src/colors.zig index 379d1301..dd0d8938 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -205,7 +205,7 @@ const name_tint_chroma: f32 = 0.06; /// ink where that hue holds, the name reads on its ground (nameTintFloor) /// and it stands off the ink. Null when no colour of the theme will do. fn derivedNameTint(th: *const Theme, ink: [3]u8, ground: [3]u8) ?[3]u8 { - const pal = th.palette orelse [_][3]u8{th.kw} ** 16; + const pal = th.palette orelse @as([16][3]u8, @splat(th.kw)); const sources = [_][3]u8{ th.kw, pal[4], pal[5], pal[6], pal[3], pal[2], pal[1], th.num, th.str, th.box } ++ [_][3]u8{ th.column_box orelse th.num, th.box_dirty orelse th.num, th.sel_bg, th.search_bg orelse th.num } ++ [_][3]u8{ th.diagnostic_info orelse th.num, th.diagnostic_hint orelse th.num, th.diagnostic_warning orelse th.num } ++ @@ -468,28 +468,29 @@ const curated = struct { pub const dark = @import("themes/dark.zig"); }; -fn fold(comptime C: type) [@typeInfo(C).@"struct".decls.len]Theme { +fn fold(comptime C: type) [@typeInfo(C).@"struct".decl_names.len]Theme { comptime { @setEvalBranchQuota(400000); - var out: [@typeInfo(C).@"struct".decls.len]Theme = undefined; - for (@typeInfo(C).@"struct".decls, 0..) |d, i| { + var out: [@typeInfo(C).@"struct".decl_names.len]Theme = undefined; + const theme_info = @typeInfo(Theme).@"struct"; + for (@typeInfo(C).@"struct".decl_names, 0..) |d, i| { var t: Theme = undefined; - const source = @field(C, d.name).theme; - for (@typeInfo(Theme).@"struct".fields) |f| { - @field(t, f.name) = if (f.type == ?Decor and @hasField(@TypeOf(source), f.name)) decor: { + const source = @field(C, d).theme; + for (theme_info.field_names, theme_info.field_types, theme_info.field_attrs) |name, T, attrs| { + @field(t, name) = if (T == ?Decor and @hasField(@TypeOf(source), name)) decor: { // A nested literal is folded field by field too. var decor: Decor = .{}; - const given = @field(source, f.name); - for (@typeInfo(Decor).@"struct".fields) |g| if (@hasField(@TypeOf(given), g.name)) { - @field(decor, g.name) = @field(given, g.name); + const given = @field(source, name); + for (@typeInfo(Decor).@"struct".field_names) |g| if (@hasField(@TypeOf(given), g)) { + @field(decor, g) = @field(given, g); }; break :decor decor; - } else if (@hasField(@TypeOf(source), f.name)) - @field(source, f.name) - else if (f.default_value_ptr) |ptr| - @as(*const f.type, @ptrCast(@alignCast(ptr))).* + } else if (@hasField(@TypeOf(source), name)) + @field(source, name) + else if (attrs.defaultValue(T)) |value| + value else - @compileError("theme " ++ d.name ++ " is missing " ++ f.name); + @compileError("theme " ++ d ++ " is missing " ++ name); } out[i] = t; } @@ -501,7 +502,7 @@ fn fold(comptime C: type) [@typeInfo(C).@"struct".decls.len]Theme { /// takes: a faithful port (`dracula`) keeps the plain name, and helix's /// looser copy of it is still there as `dracula_helix` (the zed ones already /// carry `_zed`). -fn foldImports(comptime ours: anytype, comptime C: type) [@typeInfo(C).@"struct".decls.len]Theme { +fn foldImports(comptime ours: anytype, comptime C: type) [@typeInfo(C).@"struct".decl_names.len]Theme { comptime { @setEvalBranchQuota(400000); var out = fold(C); @@ -514,7 +515,7 @@ fn foldImports(comptime ours: anytype, comptime C: type) [@typeInfo(C).@"struct" pub const themes = fold(curated) ++ foldImports(fold(curated), @import("generated_themes")); /// The first `native_count` of `themes` are pardes's own; the rest imported. -pub const native_count = @typeInfo(curated).@"struct".decls.len; +pub const native_count = @typeInfo(curated).@"struct".decl_names.len; /// The picker's sections (`Themes`), in ring order, each running from /// the theme it names to the next section's; `NextColor` and `Theme` still @@ -677,8 +678,8 @@ pub const ChromeTheme = struct { pub fn interpolate(from: ChromeTheme, to: ChromeTheme, step: u16, steps: u16) ChromeTheme { var out: ChromeTheme = undefined; const t = @as(f32, @floatFromInt(@min(step, steps))) / @as(f32, @floatFromInt(@max(1, steps))); - inline for (@typeInfo(ChromeTheme).@"struct".fields) |field| - @field(out, field.name) = if (step == 0) @field(from, field.name) else if (step >= steps) @field(to, field.name) else mixOklab(@field(from, field.name), @field(to, field.name), t); + inline for (@typeInfo(ChromeTheme).@"struct".field_names) |name| + @field(out, name) = if (step == 0) @field(from, name) else if (step >= steps) @field(to, name) else mixOklab(@field(from, name), @field(to, name), t); return out; } }; @@ -801,14 +802,16 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo themeFileError(p, request, error.ThemeFileTooLarge); return false; } - const source = p.gpa.dupeZ(u8, bytes) catch |err| { + const source = p.gpa.dupeSentinel(u8, bytes, 0) catch |err| { themeFileError(p, request, err); return false; }; defer p.gpa.free(source); - var diagnostics: std.zon.parse.Diagnostics = .{}; - defer diagnostics.deinit(p.gpa); - const parsed = std.zon.parse.fromSliceAlloc(Theme, p.gpa, source, &diagnostics, .{}) catch |err| { + // The parse's results live in `arena`; the theme kept owns only its name. + var arena: std.heap.ArenaAllocator = .init(p.gpa); + defer arena.deinit(); + var diagnostics: std.zon.parse.Diagnostics = undefined; + var parsed = std.zon.parse.fromSlice(Theme, .{ .gpa = p.gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics }) catch |err| { if (err != error.ParseZon) themeFileError(p, request, err) else { // Which line, and what the parser wanted there. var why: [200]u8 = undefined; @@ -817,10 +820,13 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo return false; }; if (parsed.name.len == 0 or parsed.name.len > 255) { - std.zon.parse.free(p.gpa, parsed); themeFileError(p, request, error.InvalidThemeName); return false; } + parsed.name = p.gpa.dupe(u8, parsed.name) catch |err| { + themeFileError(p, request, err); + return false; + }; const target_chrome = ChromeTheme.fromTheme(&parsed); if (animate and p.animate_theme_changes) @@ -829,7 +835,7 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo p.chrome_animation.snap(target_chrome); const old = p.custom_theme; p.custom_theme = parsed; - if (old) |theme_value| std.zon.parse.free(p.gpa, theme_value); + if (old) |theme_value| p.gpa.free(theme_value.name); var settled: [limits.host_path_cap]u8 = undefined; @memcpy(settled[0..request.path.len], request.path); _ = p.theme_file_loaded.set(settled[0..request.path.len]); @@ -847,7 +853,7 @@ pub fn carryTheme(p: *Pardes, old: *const Pardes, index: bool) !void { const t = old.custom_theme orelse return; var copy = t; copy.name = try p.gpa.dupe(u8, t.name); - if (p.custom_theme) |mine| std.zon.parse.free(p.gpa, mine); + if (p.custom_theme) |mine| p.gpa.free(mine.name); p.custom_theme = copy; _ = p.theme_file_loaded.set(old.theme_file_loaded.get()); } @@ -931,7 +937,7 @@ fn likeness(theme_name: []const u8, name: []const u8) usize { in_order += 1; pos = at + 1; } - const inside: usize = if (name.len > 0 and std.ascii.indexOfIgnoreCase(theme_name, name) != null) name.len * 4 else 0; + const inside: usize = if (name.len > 0 and std.ascii.findIgnoreCase(theme_name, name) != null) name.len * 4 else 0; return prefix * 3 + in_order + inside; } @@ -952,7 +958,7 @@ pub fn setThemeIndex(p: *Pardes, index: usize) void { p.chrome_animation.snap(target_chrome); if (p.custom_theme) |theme_value| { p.custom_theme = null; - std.zon.parse.free(p.gpa, theme_value); + p.gpa.free(theme_value.name); } p.theme_file_loaded.clear(); if (p.theme_file_path.get().len > 0) { @@ -1264,10 +1270,12 @@ test "legacy ThemeFile documents inherit Pardes UI roles without new fields" { rest = rest[at + std.mem.indexOfScalar(u8, rest[at..], '}').? + 1 ..]; rest = std.mem.trimStart(u8, rest, " ,"); } - const source = try std.testing.allocator.dupeZ(u8, legacy.items); + const source = try std.testing.allocator.dupeSentinel(u8, legacy.items, 0); defer std.testing.allocator.free(source); - const parsed = try std.zon.parse.fromSliceAlloc(Theme, std.testing.allocator, source, null, .{}); - defer std.zon.parse.free(std.testing.allocator, parsed); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var diagnostics: std.zon.parse.Diagnostics = undefined; + const parsed = try std.zon.parse.fromSlice(Theme, .{ .gpa = std.testing.allocator, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics }); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_bg); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_name_fg); try std.testing.expectEqual(@as(?[3]u8, null), parsed.tag_active_name_fg); diff --git a/src/config.zig b/src/config.zig index 50009660..8166954d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -2170,10 +2170,12 @@ pub const User = struct { defer gpa.free(one_path); const bytes = try std.Io.Dir.cwd().readFileAlloc(io, one_path, gpa, .limited(4096)); defer gpa.free(bytes); - const source = try gpa.dupeZ(u8, bytes); + const source = try gpa.dupeSentinel(u8, bytes, 0); defer gpa.free(source); - const parsed = try std.zon.parse.fromSliceAlloc(Sample, gpa, source, null, .{}); - defer std.zon.parse.free(gpa, parsed); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var diagnostics: std.zon.parse.Diagnostics = undefined; + const parsed = try std.zon.parse.fromSlice(Sample, .{ .gpa = gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diagnostics }); try std.testing.expectEqualStrings("one", parsed.name); try std.testing.expectEqual([3]u8{ 1, 2, 3 }, parsed.rgb); } @@ -2239,25 +2241,26 @@ const doc_typ = struct { fn hasChordField(T: type) bool { if (@typeInfo(T) != .array or @typeInfo(@typeInfo(T).array.child) != .@"struct") return false; - for (@typeInfo(@typeInfo(T).array.child).@"struct".fields) |f| if (f.type == Chord) return true; + for (@typeInfo(@typeInfo(T).array.child).@"struct".field_types) |F| if (F == Chord) return true; return false; } /// Bound somewhere in this file: a binding, a prefix or a key list. fn bound(c: Chord) bool { const config = @import("config.zig"); - inline for (@typeInfo(config).@"struct".decls) |d| { - const v = @field(config, d.name); + inline for (@typeInfo(config).@"struct".decl_names) |d| { + const v = @field(config, d); const T = @TypeOf(v); if (T == []const Chord) { for (v) |b| if (same(b, c)) return true; } else if (T == comptime_int or T == u21 or T == u8) { // a prefix or a bare key; only the tty toggle carries Ctrl - const plain = !c.alt and !c.shift and (!c.ctrl or comptime std.mem.indexOf(u8, d.name, "toggle") != null); + const plain = !c.alt and !c.shift and (!c.ctrl or comptime std.mem.indexOf(u8, d, "toggle") != null); if (plain and v >= 0x20 and v < 0x7f and v == c.cp) return true; } else if (comptime hasChordField(T)) { - for (v) |e| inline for (@typeInfo(@TypeOf(e)).@"struct".fields) |f| - if (f.type == Chord and same(@field(e, f.name), c)) return true; + const info = @typeInfo(@TypeOf(v[0])).@"struct"; + for (v) |e| inline for (info.field_names, info.field_types) |name, F| + if (F == Chord and same(@field(e, name), c)) return true; } } return false; diff --git a/src/detached/client.zig b/src/detached/client.zig index 69ab2fdd..cf1842d9 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -1182,12 +1182,12 @@ test "detached session: a frontend is never asked to fork, write, or watch" { // One: the union a frontend decodes into has no other variant. Named // rather than counted, so re-adding `spawn` fails with the name in it. - const fields = @typeInfo(wire.ServerMsg).@"union".fields; - inline for (fields) |f| { + const fields = @typeInfo(wire.ServerMsg).@"union".field_names; + inline for (fields) |name| { for (allowed) |ok| { - if (std.mem.eql(u8, f.name, ok)) break; + if (std.mem.eql(u8, name, ok)) break; } else { - std.debug.print("ServerMsg.{s} is not an effect a frontend may perform\n", .{f.name}); + std.debug.print("ServerMsg.{s} is not an effect a frontend may perform\n", .{name}); return error.MachineLocalEffectOnTheWire; } } diff --git a/src/detached/wire.zig b/src/detached/wire.zig index c9d9b578..f1b7a1b3 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -20,9 +20,10 @@ const chrome_layout: u64 = 0x5e758b47fb0cf8da; comptime { @setEvalBranchQuota(10_000); var hash = std.hash.Fnv1a_64.init(); - for (@typeInfo(pardes.Chrome).@"struct".fields) |field| { - hash.update(field.name); - hash.update(@typeName(field.type)); + const info = @typeInfo(pardes.Chrome).@"struct"; + for (info.field_names, info.field_types) |name, T| { + hash.update(name); + hash.update(@typeName(T)); } if (hash.final() != chrome_layout) @compileError(std.fmt.comptimePrint("pardes.Chrome changed (layout 0x{x}): bump wire.version, then chrome_layout", .{hash.final()})); } @@ -285,21 +286,22 @@ pub const Frame = struct { region.clip > region.rect.w or region.thumb_y > region.rect.h or region.thumb_h > region.rect.h - region.thumb_y) return error.BadValue; regions.appendAssumeCapacity(region); } - inline for (@typeInfo(pardes.Chrome).@"struct".fields) |field| { - const rgb = &@field(chrome, field.name); - if (field.type == ?[3]u8) { + const info = @typeInfo(pardes.Chrome).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const rgb = &@field(chrome, name); + if (T == ?[3]u8) { if (try r.getBool()) { rgb.* = .{ 0, 0, 0 }; for (&rgb.*.?) |*channel| channel.* = try r.getByte(); } - } else if (field.type == u8) { + } else if (T == u8) { rgb.* = try r.getByte(); - } else if (field.type == u32) { + } else if (T == u32) { rgb.* = try r.getU32(); - } else if (field.type == f32) { + } else if (T == f32) { rgb.* = @bitCast(try r.getU32()); if (!std.math.isFinite(rgb.*)) return error.BadValue; - } else if (field.type == [8]f32) { + } else if (T == [8]f32) { for (rgb) |*value| { value.* = @bitCast(try r.getU32()); if (!std.math.isFinite(value.*)) return error.BadValue; @@ -781,7 +783,7 @@ pub fn layersBound(layers: []const pardes.Layer, tags: []const pardes.Layer, reg const region_len = 1 + 1 + 4 + 8 + 1 + 2 + 2 + 1 + 2 + 4 + 4; /// The palette: each colour three bytes, a theme's optional ones a flag /// before them. -const chrome_len = @typeInfo(pardes.Chrome).@"struct".fields.len * 4 + 8 * 4; +const chrome_len = @typeInfo(pardes.Chrome).@"struct".field_names.len * 4 + 8 * 4; pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, pointer_shape: pardes.Surface.PointerShape, cells: []const pardes.Cell, prev: []const pardes.Cell, layers: []const pardes.Layer, tags: []const pardes.Layer, regions: []const pardes.Region, chrome: pardes.Chrome) Error![]const u8 { // The protocol's ceiling, enforced by the ENCODER too, and BEFORE the @@ -865,18 +867,19 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point try w.putU32(@bitCast(region.lift)); try w.putU32(@bitCast(region.line)); } - inline for (@typeInfo(pardes.Chrome).@"struct".fields) |field| { - const rgb = @field(chrome, field.name); - if (field.type == ?[3]u8) { + const info = @typeInfo(pardes.Chrome).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const rgb = @field(chrome, name); + if (T == ?[3]u8) { try w.putBool(rgb != null); if (rgb) |value| for (value) |channel| try w.putByte(channel); - } else if (field.type == u8) { + } else if (T == u8) { try w.putByte(rgb); - } else if (field.type == u32) { + } else if (T == u32) { try w.putU32(rgb); - } else if (field.type == f32) { + } else if (T == f32) { try w.putU32(@bitCast(rgb)); - } else if (field.type == [8]f32) { + } else if (T == [8]f32) { for (rgb) |value| try w.putU32(@bitCast(value)); } else for (rgb) |channel| try w.putByte(channel); } diff --git a/src/draw.zig b/src/draw.zig index b35d55e8..e6420ed4 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -1598,7 +1598,7 @@ test "a tag of three rows has its grip on the first, and band under it that stil test "place puts every part where the painters and layers put it, in every layout" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); - _ = try p.setTestFile("placed\n" ** 80); + _ = try p.setTestFile(std.mem.asBytes(&@as([80][7]u8, @splat("placed\n".*)))); p.newColumn(0); p.newScratchIn(0, p.activeColumn().?); p.newScratchBelow(0); @@ -1713,7 +1713,7 @@ test "a notice wider than its band, as a shader's compile error is, draws its en _ = try p.setTestFile("text\n"); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); - const long = "Shader /home/someone/shaders/test_shadertoy_invalid.glsl: error: Linking fragment stage: No function definition (body) found: " ** 3; + const long = std.mem.asBytes(&@as([3][126]u8, @splat("Shader /home/someone/shaders/test_shadertoy_invalid.glsl: error: Linking fragment stage: No function definition (body) found: ".*))); for ([_][]const u8{ "Msg " ++ long, "" }) |line| { // The Msg builtin, and the path a failed compile takes (Post.zig). if (line.len > 0) try std.testing.expect(p.executeBuiltinLine(p.active, line)) else p.setMessage(p.active, long); @@ -1952,7 +1952,7 @@ test "the focused cursor glides a jump, lands a step at once, and is exact at re if (!builtins.capabilities.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 30 }); defer p.deinit(); - _ = try p.setTestFile("some text on a line\n" ** 20); + _ = try p.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); p.settings.cursor_blink = false; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -2078,7 +2078,7 @@ test "a terminal's cursor lands with scrolling output, never gliding against it" defer arena.deinit(); const ms = std.time.ns_per_ms; var now: u64 = std.time.ns_per_s; - p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "line\r\n" ** 20 ++ "$ some command typed" } }); + p.update(.{ .output = .{ .pane = @intCast(term), .bytes = std.mem.asBytes(&@as([20][6]u8, @splat("line\r\n".*))) ++ "$ some command typed" } }); p.advance(now); _ = try p.render(arena.allocator()); // Enter: three lines of output scroll up, the cursor to a new prompt. @@ -2101,10 +2101,10 @@ test "a monkey over notices, prompts, tags and tiny panes at a gui's metrics nev const random = prng.random(); const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); - _ = try p.setTestFile("fuzz\n\u{754c}\u{754c} wide\n" ** 20); + _ = try p.setTestFile(std.mem.asBytes(&@as([20][17]u8, @splat("fuzz\n\u{754c}\u{754c} wide\n".*)))); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); - const words = [_][]const u8{ "error:", "\u{754c}", "x", "Shader /tmp/a.glsl:", "e\u{301}", "\t", "long-" ** 20, " " }; + const words = [_][]const u8{ "error:", "\u{754c}", "x", "Shader /tmp/a.glsl:", "e\u{301}", "\t", std.mem.asBytes(&@as([20][5]u8, @splat("long-".*))), " " }; const commands = [_][]const u8{ "New", "Newcol", "Collapse", "Tagbottom", "TreeContext", "Wrap", "Find", "Del", "FocusTint", "Debug" }; var text: std.ArrayListUnmanaged(u8) = .empty; defer text.deinit(std.testing.allocator); @@ -2143,7 +2143,7 @@ test "a monkey over notices, prompts, tags and tiny panes at a gui's metrics nev // A tag of several rows. 5 => if (p.panes[p.active]) |pane| { text.clearRetainingCapacity(); - for (0..random.uintAtMost(usize, 5)) |_| try text.appendSlice(std.testing.allocator, if (random.boolean()) " Look\nmore \u{754c}" else "\n" ++ "x" ** 150); + for (0..random.uintAtMost(usize, 5)) |_| try text.appendSlice(std.testing.allocator, if (random.boolean()) " Look\nmore \u{754c}" else "\n" ++ &@as([150]u8, @splat('x'))); if (pane.tag.own) |own| std.testing.allocator.free(own); pane.tag.own = try std.testing.allocator.dupe(u8, text.items); }, @@ -2173,7 +2173,7 @@ test "a wide glyph cut by a tag's or a notice's edge is joined into the grid as defer arena.deinit(); const pane = p.panes[p.active].?; // Both alignments, so one of them puts a wide glyph across each edge. - for ([_][]const u8{ "\u{754c}" ** 30, "x" ++ "\u{754c}" ** 30 }) |wide| { + for ([_][]const u8{ std.mem.asBytes(&@as([30][3]u8, @splat("\u{754c}".*))), "x" ++ std.mem.asBytes(&@as([30][3]u8, @splat("\u{754c}".*))) }) |wide| { if (pane.tag.own) |own| std.testing.allocator.free(own); pane.tag.own = try std.testing.allocator.dupe(u8, wide); var message: [200]u8 = undefined; @@ -2201,7 +2201,7 @@ test "a body with context rows is painted once, and the grid's rows are what a p if (comptime !@import("syntax.zig").enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer p.deinit(); - const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (" // body line\n" ** 30) ++ " }\n};\n"); + const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][21]u8, @splat(" // body line\n".*)))) ++ " }\n};\n"); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/test.zig"); if (!panes.File.supportsContext(pane)) return error.SkipZigTest; @@ -2250,7 +2250,7 @@ test "a body with context rows is painted once, and the grid's rows are what a p /// Two columns, the file in the left one and a shell in the right, the /// right one focused with its cursor settled. fn twoColumns(p: *Pardes, arena: *std.heap.ArenaAllocator) !void { - _ = try p.setTestFile("some text on a line\n" ** 6); + _ = try p.setTestFile(std.mem.asBytes(&@as([6][20]u8, @splat("some text on a line\n".*)))); _ = try p.newShell(1, ""); try std.testing.expect(layout.splitColumn(p, 0, 1, false)); p.sync(); @@ -2386,7 +2386,7 @@ test "a pane focus reaches brightens on the same spring the one it leaves dims o if (!builtins.capabilities.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); - _ = try p.setTestFile("some text on a line\n" ** 4); + _ = try p.setTestFile(std.mem.asBytes(&@as([4][20]u8, @splat("some text on a line\n".*)))); p.newScratchBelow(0); p.settings.inactive_dim = 40; p.settings.motion = .smooth; diff --git a/src/dump.zig b/src/dump.zig index 402918c4..545d09ec 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -421,9 +421,9 @@ pub const Parsed = struct { pub fn check(gpa: std.mem.Allocator, bytes: []const u8, why: []u8) !void { var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); - const source = try arena.allocator().dupeZ(u8, bytes); - var diag: std.zon.parse.Diagnostics = .{}; - const state = std.zon.parse.fromSliceAlloc(State, arena.allocator(), source, &diag, .{ .free_on_error = false }) catch |err| { + const source = try arena.allocator().dupeSentinel(u8, bytes, 0); + var diag: std.zon.parse.Diagnostics = undefined; + const state = std.zon.parse.fromSlice(State, .{ .gpa = gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diag }) catch |err| { const said = pardes.Messages.zonWhy(&diag, why[0 .. why.len - 1]); if (said.ptr != why.ptr) @memcpy(why[0..said.len], said); why[said.len] = 0; @@ -436,21 +436,13 @@ pub fn readZon(gpa: std.mem.Allocator, bytes: []const u8, label: []const u8) !Pa var parsed: Parsed = .{ .value = undefined, .arena = .init(gpa) }; errdefer parsed.deinit(); const arena = parsed.arena.allocator(); - const source = try gpa.dupeZ(u8, bytes); + const source = try gpa.dupeSentinel(u8, bytes, 0); defer gpa.free(source); - parsed.value = if (builtin.os.tag == .emscripten or builtin.os.tag == .freestanding) - std.zon.parse.fromSliceAlloc(State, arena, source, null, .{ .free_on_error = false }) catch |err| { - if (err == error.ParseZon) log.err("parse dump {s}: {s}", .{ label, @errorName(err) }); - return err; - } - else blk: { - var diag: std.zon.parse.Diagnostics = .{}; - defer diag.deinit(arena); - break :blk std.zon.parse.fromSliceAlloc(State, arena, source, &diag, .{ .free_on_error = false }) catch |err| { - if (err == error.ParseZon) log.err("parse dump {s}: {f}", .{ label, diag }); - return err; - }; + var diag: std.zon.parse.Diagnostics = undefined; + parsed.value = std.zon.parse.fromSlice(State, .{ .gpa = gpa, .arena = arena, .source = source, .diagnostics = &diag }) catch |err| { + if (err == error.ParseZon) log.err("{f}", .{diag.fmt(label)}); + return err; }; try validate(parsed.value); return parsed; diff --git a/src/esp32p4.zig b/src/esp32p4.zig index 6772e75d..ed18efd9 100644 --- a/src/esp32p4.zig +++ b/src/esp32p4.zig @@ -506,7 +506,7 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { c.update(.pointer_leave); dirty = true; }, - .focus_in, .mouse_leave => {}, + .focus_in, .mouse_leave, .cursor_position => {}, // Capability replies. vaxis's own Loop sets these fields directly (`Loop.zig:377-403`); // with no Loop, this is where they land. DA1 is the terminator: every terminal answers it // last, so it is the signal that the whole handshake is in and the detected features can be diff --git a/src/esp32p4/input_rescue.zig b/src/esp32p4/input_rescue.zig index ba6974d2..d7556d46 100644 --- a/src/esp32p4/input_rescue.zig +++ b/src/esp32p4/input_rescue.zig @@ -245,7 +245,7 @@ test "a long transmit does not lose the input that arrives during it" { defer port.sent.deinit(std.testing.allocator); var ring: Ring = .{}; - const frame = "\x1b[1;1H" ++ "x" ** 400; + const frame = "\x1b[1;1H" ++ &@as([400]u8, @splat('x')); try std.testing.expectEqual(@as(u32, 0), pump(&port, &ring, frame, 1_000_000)); // Every output byte went out, in order. diff --git a/src/esp32p4/selftest.zig b/src/esp32p4/selftest.zig index 97b43059..19b71e90 100644 --- a/src/esp32p4/selftest.zig +++ b/src/esp32p4/selftest.zig @@ -270,7 +270,7 @@ export fn zig_main() noreturn { const typed = "the quick brown fox jumps over the lazy dog, and then some more besides"; var port: FakePort = .{ .tx_cap = 2, .incoming = typed }; var ring: input_rescue.Ring = .{}; - const frame = "\x1b[1;1H" ++ "x" ** 300; + const frame = "\x1b[1;1H" ++ &@as([300]u8, @splat('x')); const abandoned = input_rescue.pump(&port, &ring, frame, 1_000_000); check("the frame went out whole", abandoned == 0 and port.sent == frame.len); diff --git a/src/fs.zig b/src/fs.zig index fb76cee3..061d4225 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -677,7 +677,7 @@ pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOption } test "a path with a part over 255 bytes is NameTooLong, never a panic" { - const long = "/tmp/" ++ "x" ** 300 ++ "/f"; + const long = "/tmp/" ++ &@as([300]u8, @splat('x')) ++ "/f"; try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); } @@ -1152,7 +1152,7 @@ pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u notes.skipped += 1; continue; }) orelse break; - if (std.ascii.indexOfIgnoreCase(e.basename, pat) != null) { + if (std.ascii.findIgnoreCase(e.basename, pat) != null) { hits[hits_len] = try arena.dupe(u8, e.path); hits_len += 1; } @@ -1167,7 +1167,7 @@ pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u } else { for (sources) |s| { if (hits_len >= hits.len) break; - if (std.ascii.indexOfIgnoreCase(std.fs.path.basename(s.path), pat) != null) { + if (std.ascii.findIgnoreCase(std.fs.path.basename(s.path), pat) != null) { hits[hits_len] = s.path; hits_len += 1; } @@ -1201,7 +1201,7 @@ fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budg while (it.next()) |raw| { line += 1; if (result.hits >= budget) break; - const at = std.ascii.indexOfIgnoreCase(raw, pat) orelse continue; + const at = std.ascii.findIgnoreCase(raw, pat) orelse continue; const ln = std.mem.trimEnd(u8, raw, " \t\r"); var cut = @min(ln.len, 200); while (cut > 0 and cut < ln.len and ln[cut] & 0xc0 == 0x80) cut -= 1; diff --git a/src/gui/Post.zig b/src/gui/Post.zig index fc256135..8d0e14d9 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -610,13 +610,13 @@ const GhosttyUniforms = extern struct { }; test "the uniform block is ghostty's, offset for offset, and the prefix names it in that order" { - const ours = @typeInfo(Uniforms).@"struct".fields; - const theirs = @typeInfo(GhosttyUniforms).@"struct".fields; - try std.testing.expectEqual(theirs.len, ours.len); + const ours = @typeInfo(Uniforms).@"struct"; + const theirs = @typeInfo(GhosttyUniforms).@"struct"; + try std.testing.expectEqual(theirs.field_names.len, ours.field_names.len); try std.testing.expectEqual(@sizeOf(GhosttyUniforms), @sizeOf(Uniforms)); - inline for (ours, theirs) |a, b| { - try std.testing.expectEqual(@offsetOf(GhosttyUniforms, b.name), @offsetOf(Uniforms, a.name)); - try std.testing.expectEqual(b.type, a.type); + inline for (ours.field_names, ours.field_types, theirs.field_names, theirs.field_types) |a, a_type, b, b_type| { + try std.testing.expectEqual(@offsetOf(GhosttyUniforms, b), @offsetOf(Uniforms, a)); + try std.testing.expectEqual(b_type, a_type); } // By NAME: iSelectionForegroundColor sits where ghostty's Zig says // selection_background, which is where its GLSL puts the foreground. @@ -633,7 +633,7 @@ test "the uniform block is ghostty's, offset for offset, and the prefix names it .{ "vec3", "iBackgroundColor" }, .{ "vec3", "iForegroundColor" }, .{ "vec3", "iCursorColor" }, .{ "vec3", "iCursorText" }, .{ "vec3", "iSelectionForegroundColor" }, .{ "vec3", "iSelectionBackgroundColor" }, }; - try std.testing.expectEqual(ours.len, glsl.len); + try std.testing.expectEqual(ours.field_names.len, glsl.len); // Its three blocks (Globals, Palette, Colors) read as one, in order. const start = std.mem.indexOf(u8, prefix, "uniform Globals {").?; const end = std.mem.indexOf(u8, prefix, "uniform PardesPost {").?; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 5a026664..b8687fd3 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -25,11 +25,7 @@ const ninep_io = @import("../9p_io.zig"); const detached_client = @import("../detached/client.zig"); const tracy = @import("../tracy.zig"); -pub const c = @cImport({ - @cDefine("SDL_DISABLE_OLD_NAMES", "1"); - @cInclude("SDL3/SDL.h"); - @cInclude("font.h"); -}); +pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig const host_io = @import("../host_io.zig"); extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; @@ -4806,7 +4802,7 @@ fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { } fn putClipboard(gpa: std.mem.Allocator, text: []const u8) void { - const z = gpa.dupeZ(u8, text) catch return; + const z = gpa.dupeSentinel(u8, text, 0) catch return; defer gpa.free(z); _ = c.SDL_SetClipboardText(z.ptr); } @@ -5131,7 +5127,7 @@ test "a wheel over codex in a terminal reaches its pty as the mouse reports it a 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("\x1b[<65;6;4M" ** 3, try Sent.take(core, &sent)); + 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. @@ -7157,7 +7153,7 @@ test "every pixel of a grip column is band, button or ring, and the button sits const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 20 }); defer core.deinit(); - const pane = try core.setTestFile("text\n" ** 60); + 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 ([_]bool{ false, true }) |bottom| for ([_]usize{ 0, 1 }) |focus| for ([_]bool{ false, true }) |dirty| { @@ -10156,7 +10152,7 @@ test "the selection glows round its block, on the body only, fading in over 100 const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 30); + _ = try core.setTestFile(std.mem.asBytes(&@as([30][20]u8, @splat("some text on a line\n".*)))); core.settings.selection_glow = true; pardes.test_api.sync(core); const s = try core.render(core.scratch.allocator()); @@ -10206,7 +10202,7 @@ test "a hovered word glows along its foot, never over the cursor, fading in over const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 30); + _ = try core.setTestFile(std.mem.asBytes(&@as([30][20]u8, @splat("some text on a line\n".*)))); core.settings.hover_glow = true; pardes.test_api.sync(core); const s = try core.render(core.scratch.allocator()); @@ -10256,7 +10252,7 @@ test "occlusion shades each body's edges, inside it, never a tag, a grip or the const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 30); + _ = try core.setTestFile(std.mem.asBytes(&@as([30][20]u8, @splat("some text on a line\n".*)))); core.settings.occlusion = true; pardes.test_api.sync(core); const s = try core.render(core.scratch.allocator()); @@ -10295,7 +10291,7 @@ test "a body tells its first line, and lapis's dots under it move a quarter as f const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - const pane = try core.setTestFile("line\n" ** 80); + const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); pane.scrollBy(8); try std.testing.expect(core.executeBuiltinLine(0, "Theme lapis")); core.settings.parallax = true; diff --git a/src/host_io.zig b/src/host_io.zig index a90c903d..d789a77d 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -172,7 +172,7 @@ pub const Lsp = struct { const declared_path = if (file) |f| f.path else ""; const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path); errdefer gpa.free(path); - const source = try gpa.dupeZ(u8, if (file) |f| f.content else ""); + const source = try gpa.dupeSentinel(u8, if (file) |f| f.content else "", 0); errdefer gpa.free(source); const arg = try gpa.dupe(u8, req.arg); errdefer gpa.free(arg); @@ -210,7 +210,7 @@ pub const Lsp = struct { if (f.output != null) continue; const local = filesystem.localPath(f.path) orelse continue; const other_path = try gpa.dupe(u8, local); - const other_source = gpa.dupeZ(u8, f.content) catch |err| { + const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { gpa.free(other_path); return err; }; @@ -785,7 +785,7 @@ pub const Shell = struct { var dir_buf: [4096]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; var path: [4200:0]u8 = undefined; - const p = try std.fmt.bufPrintZ(&path, "{s}/mysh", .{dir}); + const p = try std.fmt.bufPrintSentinel(&path, "{s}/mysh", .{dir}, 0); try std.testing.expectEqual(Family.bash, familyOf(p.ptr)); try std.testing.expectEqual(Family.none, familyOf("/bin/sh")); } @@ -1662,7 +1662,7 @@ pub fn forkShell( 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, null)); - const too_long = [_]u8{'x'} ** 4096; + const too_long = @as([4096]u8, @splat('x')); try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80, null)); var tmp = std.testing.tmpDir(.{}); @@ -1675,7 +1675,7 @@ test "shell spawn rejects invalid directories before creating a child" { try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80, null)); 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, null)); - const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ ("child/" ** 50), .{directory}); + 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, null)); } @@ -1720,7 +1720,7 @@ 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 = "nested-directory-with-more-than-forty-characters/" ** 7; + 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)]; @@ -1801,7 +1801,7 @@ test "shell cwd rejects truncation and preserves an owned child path longer than const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); - const nested = "nested-directory-with-more-than-forty-characters/" ** 24; + 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)]; diff --git a/src/image.zig b/src/image.zig index 72520ad6..8bf9de08 100644 --- a/src/image.zig +++ b/src/image.zig @@ -242,11 +242,11 @@ pub const GlyphArt = struct { const glyphs_ascii = glyphs ++ ascii_glyphs; fn matchCell(cell: *const [64][3]u8, pal: Palette, gset: []const Glyph) Cell { - var counts = [_]u16{0} ** 16; + var counts = @as([16]u16, @splat(0)); for (cell) |px| counts[nearest(px, pal)] += 1; var cand: [4]u4 = undefined; var ncand: usize = 0; - var used = [_]bool{false} ** 16; + var used = @as([16]bool, @splat(false)); while (ncand < 4) : (ncand += 1) { var best: ?usize = null; for (counts, 0..) |c, i| { @@ -432,7 +432,7 @@ pub const GlyphArt = struct { test "render: tiny image produces a grid within bounds" { const a = std.testing.allocator; // 2x2 checker, RGBA - var img = [_]u8{0} ** (2 * 2 * 4); + var img = @as([2 * 2 * 4]u8, @splat(0)); img[0] = 255; img[1] = 255; img[2] = 255; diff --git a/src/linux/v9fs.zig b/src/linux/v9fs.zig index 5e031bfe..15945e7b 100644 --- a/src/linux/v9fs.zig +++ b/src/linux/v9fs.zig @@ -64,11 +64,11 @@ pub fn helperPath(buf: []u8) ![:0]u8 { const path = if (std.c.getenv("PARDES_V9FS_HELPER")) |env| blk: { const override = std.mem.span(env); if (!std.fs.path.isAbsolute(override)) return error.AbsoluteHelperPathRequired; - break :blk try std.fmt.bufPrintZ(buf, "{s}", .{override}); + break :blk try std.fmt.bufPrintSentinel(buf, "{s}", .{override}, 0); } else blk: { var own: [4096]u8 = undefined; const parent = std.fs.path.dirname(try selfPath(&own)) orelse return error.ExecutablePathUnavailable; - break :blk try std.fmt.bufPrintZ(buf, "{s}/{s}", .{ parent, executable }); + break :blk try std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ parent, executable }, 0); }; if (std.c.access(path.ptr, 1) != 0) return error.V9fsHelperNotFound; return path; diff --git a/src/locations.zig b/src/locations.zig index 745393e5..2828566d 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -587,12 +587,13 @@ pub const Config = struct { const key = token[0..colon]; const value = token[colon + 1 ..]; var found = false; - inline for (@typeInfo(Config).@"struct".fields) |field| { - if (std.mem.eql(u8, key, field.name)) { - @field(result, field.name) = switch (@typeInfo(field.type)) { + const info = @typeInfo(Config).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + if (std.mem.eql(u8, key, name)) { + @field(result, name) = switch (@typeInfo(T)) { .bool => if (std.mem.eql(u8, value, "on")) true else if (std.mem.eql(u8, value, "off")) false else return error.ExpectedOnOrOff, - .int => std.fmt.parseInt(field.type, value, 10) catch return error.InvalidContext, - .@"enum" => std.meta.stringToEnum(field.type, value) orelse return error.InvalidLayout, + .int => std.fmt.parseInt(T, value, 10) catch return error.InvalidContext, + .@"enum" => std.meta.stringToEnum(T, value) orelse return error.InvalidLayout, else => @compileError("unsupported location setting type"), }; found = true; @@ -604,11 +605,12 @@ pub const Config = struct { } pub fn write(config: Config, writer: *std.Io.Writer) !void { - inline for (@typeInfo(Config).@"struct".fields, 0..) |field, index| { + const info = @typeInfo(Config).@"struct"; + inline for (info.field_names, info.field_types, 0..) |name, T, index| { if (index > 0) try writer.writeByte(' '); - try writer.writeAll(field.name ++ ":"); - const value = @field(config, field.name); - switch (@typeInfo(field.type)) { + try writer.writeAll(name ++ ":"); + const value = @field(config, name); + switch (@typeInfo(T)) { .bool => try writer.writeAll(if (value) "on" else "off"), .int => try writer.print("{d}", .{value}), .@"enum" => try writer.writeAll(@tagName(value)), @@ -809,11 +811,11 @@ test "locations cache bounds memory and entries and evicts least recently used" try std.testing.expectEqual(@as(usize, 2), cache.len); try std.testing.expect(cache.bytes <= 40); try std.testing.expectEqualStrings("b.unknown", cache.entries[0].path); - try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.unknown", "x" ** 41, false, false, 40)); + try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.unknown", &@as([41]u8, @splat('x')), false, false, 40)); try std.testing.expectEqual(@as(usize, 2), cache.len); if (syntax.supportsPath("large.zig")) { const before = cache.analyses; - try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.zig", "x" ** 25, true, true, 40)); + try std.testing.expectError(error.SourceTooLarge, cache.getBounded(gpa, "large.zig", &@as([25]u8, @splat('x')), true, true, 40)); try std.testing.expectEqual(before, cache.analyses); } cache.deinit(gpa); diff --git a/src/look.zig b/src/look.zig index 1065cb02..f9c470cf 100644 --- a/src/look.zig +++ b/src/look.zig @@ -671,7 +671,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start const cl: usize = @intCast(@max(0, pane.body.cur_row)); const cc: usize = @intCast(@max(0, pane.body.cur_col)); for (lines, 0..) |ln, i| { - const at = std.ascii.indexOfIgnoreCase(ln, pat) orelse continue; + const at = std.ascii.findIgnoreCase(ln, pat) orelse continue; const row = try std.fmt.allocPrint(arena, "{s}:{d}:{d}{c}{d} {s}\n", .{ loc, i + 1, at + 1, config.range_sep, at + pat.len, std.mem.trimEnd(u8, ln, " \t"), }); @@ -1273,7 +1273,7 @@ fn missText(text: []const u8, buf: *[miss_path_cap + "…".len]u8) []const u8 { 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/" ++ "deep/" ** 80 ++ "the-file.zig"; + 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/")); @@ -2185,7 +2185,7 @@ test "Look ignores missing and out of bounds pane addresses" { test "a pointer resting where a look-hover found nothing does not wake the core every frame" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); - _ = try p.setTestFile(" \n" ** 30); + _ = try p.setTestFile(std.mem.asBytes(&@as([30][6]u8, @splat(" \n".*)))); p.sync(); const r = p.rects[p.active]; // Resting on blanks in the body: a wait, then nothing to open. diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 96d42bbd..4a70efe5 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -92,7 +92,7 @@ else pub const backend_name = "lsp-client"; pub const supports: std.EnumSet(Kind) = blk: { - var s: std.EnumSet(Kind) = .initEmpty(); + var s: std.EnumSet(Kind) = .empty; for (0..backends.len) |i| s.setUnion(backends[i].supports); break :blk s; }; diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index 54bbaa79..b396879b 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -159,7 +159,7 @@ pub const specs = [_]Spec{ /// answered per connection; a kind its server never advertised simply returns /// no rows, which the harness reports as CLAIMED-EMPTY per language — honest, /// since the claim here is about the protocol, not about every server. -pub const supports: std.EnumSet(lsp.Kind) = .initFull(); +pub const supports: std.EnumSet(lsp.Kind) = .full; /// Routing: an extension in the table whose spec is not disabled by its env /// var. Deliberately does NOT probe for the binary — this runs on the Tab diff --git a/src/macos.zig b/src/macos.zig index 20463481..37db0abd 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -724,7 +724,7 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { // in Debug, libc's malloc otherwise. libc's measured at least as fast as // std.heap.smp_allocator everywhere and faster on MuPDF's page-sized // rasters, so this shell no longer differs. - const gpa = if (builtin.mode == .Debug) debug_gpa.allocator() else std.heap.c_allocator; + const gpa = if (builtin.mode == .debug) debug_gpa.allocator() else std.heap.c_allocator; const allocs = pardes.memory.init(gpa); errdefer pardes.memory.deinit(); @@ -858,7 +858,7 @@ export fn pardes_deinit() void { st.gpa.destroy(st.threaded); pardes.memory.deinit(); // Leaks are logged and do not fail, as std.start treats the others'. - if (builtin.mode == .Debug) { + if (builtin.mode == .debug) { _ = debug_gpa.deinit(); debug_gpa = .init; } @@ -2871,22 +2871,22 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@offsetOf(c.pardes_cell_s, "len"), @offsetOf(Cell, "len")); try expectEqual(@offsetOf(c.pardes_cell_s, "flags"), @offsetOf(Cell, "flags")); try expectEqual(@sizeOf(c.pardes_scene_s), @sizeOf(Scene)); - inline for (@typeInfo(Scene).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_scene_s, field.name), @offsetOf(Scene, field.name)); + inline for (@typeInfo(Scene).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_scene_s, name), @offsetOf(Scene, name)); try expectEqual(@sizeOf(c.pardes_panel_box_s), @sizeOf(PanelBox)); - inline for (@typeInfo(PanelBox).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_panel_box_s, field.name), @offsetOf(PanelBox, field.name)); + inline for (@typeInfo(PanelBox).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_panel_box_s, name), @offsetOf(PanelBox, name)); try expectEqual(@sizeOf(c.pardes_panel_track_s), @sizeOf(PanelTrack)); - inline for (@typeInfo(PanelTrack).@"struct".fields) |field| { - const c_name = comptime if (std.mem.eql(u8, field.name, "motion")) + inline for (@typeInfo(PanelTrack).@"struct".field_names) |name| { + const c_name = comptime if (std.mem.eql(u8, name, "motion")) "reserved0" else - field.name; - try expectEqual(@offsetOf(c.pardes_panel_track_s, c_name), @offsetOf(PanelTrack, field.name)); + name; + try expectEqual(@offsetOf(c.pardes_panel_track_s, c_name), @offsetOf(PanelTrack, name)); } try expectEqual(@sizeOf(c.pardes_image_s), @sizeOf(Image)); - inline for (@typeInfo(Image).@"struct".fields) |field| - try expectEqual(@offsetOf(c.pardes_image_s, field.name), @offsetOf(Image, field.name)); + inline for (@typeInfo(Image).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_image_s, name), @offsetOf(Image, name)); try expectEqual(@sizeOf(c.pardes_runtime_s), @sizeOf(Runtime)); try expectEqual(@as(u32, c.PARDES_COLOR_DEFAULT), color_default); @@ -3177,7 +3177,7 @@ test "mac tag layer ABI preserves logical capacity and physical grip" { }); try std.testing.expectEqual(@as(u32, 11), pardes_tag_layer_value(0, 8)); try std.testing.expectEqual(@as(u8, 'Z'), pardes_tag_layer_cells(0).?[11].text[0]); - var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{'G'} ++ .{0} ** 6, .len = 1, .default = false })); + var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{ 'G', 0, 0, 0, 0, 0, 0 }, .len = 1, .default = false })); var source: [24]pardes.Cell = @splat(.{}); blankTagCells(&canonical, 8, 3, &source, &core.surface.tag_layers); try std.testing.expectEqual(@as(u8, 'G'), canonical[9].text[0]); diff --git a/src/main.zig b/src/main.zig index 26259b43..e3bae75f 100644 --- a/src/main.zig +++ b/src/main.zig @@ -464,6 +464,12 @@ fn nativeMain(init: std.process.Init) !void { } opts.tty_only = explicit_tty or session_only; opts.mounts = mounts[0..mounts_len]; + // `zig build run-isolated` with nothing named: something to look at on + // arrival, read out of the binary itself. + if (pardes.isolated and positional == null) { + session_only = false; + positional = "src/pardes.zig"; + } if (detach != null and attach != null) badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); // --wait waits on the pane a FILE opens: with none there is nothing to diff --git a/src/memory.zig b/src/memory.zig index abfd40f6..48403c55 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -38,7 +38,7 @@ pub const limits = struct { }; const Allocator = std.mem.Allocator; -const debug_enabled = builtin.mode == .Debug; +const debug_enabled = builtin.mode == .debug; pub const Allocators = struct { pardes: Allocator, diff --git a/src/modal.zig b/src/modal.zig index 50e0ddf4..82f1a3a0 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -163,7 +163,7 @@ pub const Normal = struct { }; pub const Input = struct { - roles: std.EnumSet(Role) = .initEmpty(), + roles: std.EnumSet(Role) = .empty, cp: u21, ctrl: bool = false, alt: bool = false, diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index b78c46e7..3feda5a2 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -646,7 +646,7 @@ test "the address language, form by form" { try testing.expectEqualStrings(c[1], th.wr(p, addr, c[0]).reply.ename); } - const nested = "," ** 4096; + const nested = &@as([4096]u8, @splat(',')); _ = th.wr(p, addr, "#0"); try testing.expectEqual(E.INVAL, th.wr(p, addr, nested).errno()); } diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index e3b456ba..59f6ae42 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -288,18 +288,18 @@ test "exactly 4096 bytes written with echo's newline after a truncation fit ever const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = th.serialOf(p); - const text = "w" ** 4096 ++ "\n"; + const text = &@as([4096]u8, @splat('w')) ++ "\n"; for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @intFromEnum(tree.TopFile.tag) }) |node| { _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = node, .truncate = true }); const h = th.call(p, .{ .tag = 2, .op = .open, .node = node, .omode = 1 }).reply.handle; const r = th.call(p, .{ .tag = 3, .op = .write, .node = node, .handle = h, .data = text }); try testing.expectEqual(tree.Status.ok, r.reply.status); _ = th.call(p, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true }); - try testing.expect(std.mem.endsWith(u8, th.rd(p, node, 0, 1 << 16).bytes, "w" ** 4096)); + try testing.expect(std.mem.endsWith(u8, th.rd(p, node, 0, 1 << 16).bytes, &@as([4096]u8, @splat('w')))); // One more byte is over. _ = th.call(p, .{ .tag = 5, .op = .setattr, .node = node, .truncate = true }); const h2 = th.call(p, .{ .tag = 6, .op = .open, .node = node, .omode = 1 }).reply.handle; - try testing.expectEqual(E.NOSPC, th.call(p, .{ .tag = 7, .op = .write, .node = node, .handle = h2, .data = "w" ** 4097 ++ "\n" }).errno()); + try testing.expectEqual(E.NOSPC, th.call(p, .{ .tag = 7, .op = .write, .node = node, .handle = h2, .data = &@as([4097]u8, @splat('w')) ++ "\n" }).errno()); _ = th.call(p, .{ .tag = 8, .op = .release, .node = node, .handle = h2, .opened = true }); } } @@ -316,7 +316,7 @@ test "a Newcol refused because the tags would not fit logs its err alone and spe for (p.col_panes[col][0..p.col_n[col]]) |k| { const each = p.panes[k].?; if (each.tag.own) |old| p.gpa.free(old); - each.tag.own = try p.gpa.dupe(u8, "word " ** 60); + each.tag.own = try p.gpa.dupe(u8, std.mem.asBytes(&@as([60][5]u8, @splat("word ".*)))); } try testing.expect(p.col_n[col] >= 2); p.sync(); @@ -588,7 +588,7 @@ test "a refused write after a truncation leaves every kind of tag as it was, and defer p.deinit(); const serial = th.serialOf(p); const col = layout.columnSerial(p, 0); - const big = "w" ** (limits.max_tag_tail + 1); + const big = &@as([limits.max_tag_tail + 1]u8, @splat('w')); // Each tag: a truncating open, then a write too long: nothing changes. for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @intFromEnum(tree.TopFile.tag) }) |node| { _ = th.wr(p, node, " Mine"); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f6457b83..6b4bbafb 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1682,9 +1682,9 @@ test "a look's miss repeats the path whole up to 256 bytes, then gives up its mi var line: [512]u8 = undefined; _ = wr(p, root, try std.fmt.bufPrint(&line, "{s}\n", .{long})); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&line, "look: no match for \"{s}\"\n", .{long}))); - const huge = "é" ** 150; // 300 bytes: its middle cut to fit 256, between characters + const huge = std.mem.asBytes(&@as([150][2]u8, @splat("é".*))); // 300 bytes: its middle cut to fit 256, between characters _ = wr(p, root, huge ++ "\n"); - try testing.expect(th.logHas(p, "look: no match for \"" ++ "é" ** 63 ++ "…" ++ "é" ** 63 ++ "\"\n")); + try testing.expect(th.logHas(p, "look: no match for \"" ++ std.mem.asBytes(&@as([63][2]u8, @splat("é".*))) ++ "…" ++ std.mem.asBytes(&@as([63][2]u8, @splat("é".*))) ++ "\"\n")); } test "exec runs a builtin at the pane and records the pane it acted on" { @@ -2041,7 +2041,7 @@ test "Zerox twins dump their text once and come back on one buffer from a Restor defer p.deinit(); const first = serialOf(p); _ = wr(p, Node.of(first, .name), "/tmp/pardes-zerox-dump.txt\n"); - _ = wr(p, Node.of(first, .body), "unsaved " ** 64 ++ "\n"); + _ = wr(p, Node.of(first, .body), std.mem.asBytes(&@as([64][8]u8, @splat("unsaved ".*))) ++ "\n"); try testing.expect(p.executeBuiltinLine(0, "Zerox")); try testing.expect(p.executeBuiltinLine(0, "Zerox")); try pardes.dump.dumpState(p); @@ -2888,7 +2888,7 @@ test "a builtin that fails a ctl write logs only its err, so the same failure ag test "an exec line over the command limit fails the write and says the limit; a builtin's may be longer" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const long = "echo " ++ "y" ** pardes.exec.command_max ++ "\n"; + const long = "echo " ++ &@as([pardes.exec.command_max]u8, @splat('y')) ++ "\n"; const refused = wr(p, root_exec, long); try testing.expectEqual(E.INVAL, refused.errno()); try testing.expectEqualStrings(e_too_long, refused.reply.ename); @@ -2896,7 +2896,7 @@ test "an exec line over the command limit fails the write and says the limit; a try testing.expect(th.logHas(p, try std.fmt.bufPrint(&rec, "err {d} exec: invalid command line: a command line is at most 1024 bytes", .{serialOf(p)}))); try testing.expectEqualStrings(e_control, wr(p, root_exec, "echo a\x01b\n").reply.ename); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&rec, "err {d} exec: invalid command line: it holds", .{serialOf(p)}))); - try testing.expectEqual(Status.ok, wr(p, root_exec, "Msg " ++ "z" ** 1100 ++ "\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, root_exec, "Msg " ++ &@as([1100]u8, @splat('z')) ++ "\n").reply.status); } test "Edit's p and = never fail for want of room for +Errors: the text is logged instead" { @@ -4012,8 +4012,8 @@ test "Back and Forward written to exec keep to the focused file, and JumpScope a defer p.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "row\n" ** 100 }); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.txt", .data = "row\n" ** 100 }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = std.mem.asBytes(&@as([100][4]u8, @splat("row\n".*))) }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.txt", .data = std.mem.asBytes(&@as([100][4]u8, @splat("row\n".*))) }); var dir_buf: [4096]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line: [4200]u8 = undefined; diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 3910ac05..7b73dc0e 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -938,7 +938,7 @@ test "event records are acme's bytes, one per read, and .again when empty" { try testing.expectEqualStrings("ML0 ", rd(p, event, 0, 4).bytes); try testing.expectEqualStrings("3 4 3 one\n", rd(p, event, 0, 4096).bytes); - const big = "z" ** max_record_text; + const big = &@as([max_record_text]u8, @splat('z')); _ = noteAction(p, 0, .body_exec, 0, max_record_text, 0, big); try testing.expectEqualStrings("MX0 256 0 0 \n", rd(p, event, 0, 4096).bytes); @@ -1388,7 +1388,7 @@ test "opens of the log share the open records, and a closed one frees its record test "a click in the body reports the offsets of the word it takes, so the record can be written back" { const config = @import("../config.zig"); const gpa = testing.allocator; - const text = "alpha qty beta\n qty\n\tqty\ndef f(qty): return qty.x\n" ++ "w" ** 100 ++ " qty\n"; + const text = "alpha qty beta\n qty\n\tqty\ndef f(qty): return qty.x\n" ++ &@as([100]u8, @splat('w')) ++ " qty\n"; const p = try withFile(gpa, text); defer p.deinit(); // A scratch made over 9P, clicked while another pane has the keyboard. @@ -1459,7 +1459,7 @@ test "follow new skips what the log held and waits for what comes after" { test "a long msg record is cut between words at its cap, with an ellipsis" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const long = "word " ** 60; // 300 bytes + const long = std.mem.asBytes(&@as([60][5]u8, @splat("word ".*))); // 300 bytes _ = wr(p, Node.of(serialOf(p), .ctl), "Msg " ++ long ++ "\n"); const log = @intFromEnum(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; @@ -1485,7 +1485,7 @@ test "a record is one line of UTF-8: DEL and C1 are spaces, bytes not UTF-8 are test "a long err record keeps its end, its middle given up to an ellipsis" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus" ++ "abcdefgh" ** 40 ++ "\n"); + _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus" ++ std.mem.asBytes(&@as([40][8]u8, @splat("abcdefgh".*))) ++ "\n"); const log = @intFromEnum(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; @@ -1500,7 +1500,7 @@ test "a long err record keeps its end, its middle given up to an ellipsis" { test "two failures that agree only in what their records cut are two records, not one counted" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const long = "why " ** 80; + const long = std.mem.asBytes(&@as([80][4]u8, @splat("why ".*))); p.setMessage(0, long ++ "first"); p.setMessage(0, long ++ "second"); try testing.expect(!th.logHas(p, "(x2)")); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3b70d62f..8605cab8 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1427,7 +1427,7 @@ test "a tag write past the limit is refused whole, naming the limit" { const tag = Node.of(serialOf(p), .tag); const before = try testing.allocator.dupe(u8, rd(p, tag, 0, 1 << 16).bytes); defer testing.allocator.free(before); - const big = "w" ** (limits.max_tag_tail + 10); + const big = &@as([limits.max_tag_tail + 10]u8, @splat('w')); const r = wr(p, tag, big); try testing.expectEqual(E.NOSPC, r.errno()); // `no space` is what 9ns maps to ENOSPC, so a shell through a mount @@ -1549,20 +1549,21 @@ test "a name with a component over 255 bytes is refused, and a long path's faile const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); - const refused = wr(p, Node.of(serial, .name), "/tmp/" ++ "c" ** 256 ++ "/f.txt\n"); + const refused = wr(p, Node.of(serial, .name), "/tmp/" ++ &@as([256]u8, @splat('c')) ++ "/f.txt\n"); try testing.expectEqual(E.INVAL, refused.errno()); try testing.expectEqualStrings("invalid file name: a component over 255 bytes", refused.reply.ename); - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/" ++ "c" ** 255 ++ "\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/" ++ &@as([255]u8, @splat('c')) ++ "\n").reply.status); // Held with no newline, it is refused by that write, not at the close. const held = call(p, .{ .tag = 1, .op = .open, .node = Node.of(serial, .name), .omode = 1 }).reply.handle; - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 2, .op = .write, .node = Node.of(serial, .name), .handle = held, .data = "/tmp/" ++ "e" ** 256 }).errno()); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 2, .op = .write, .node = Node.of(serial, .name), .handle = held, .data = "/tmp/" ++ &@as([256]u8, @splat('e')) }).errno()); _ = call(p, .{ .tag = 3, .op = .release, .node = Node.of(serial, .name), .handle = held, .opened = true }); try testing.expectEqual(@as(usize, 0), p.fs.closed_lines.items.len); // A Save of a 3000-byte path the host refuses: the waiting write's // reason is at the end, the path giving up its middle. // (Under /tmp: under / a user's Save is refused permission, not // missing.) - const long = "/tmp/nonexistent-pardes-root/" ++ ("d" ** 200 ++ "/") ** 15 ++ "f.txt"; + const segment = &@as([200]u8, @splat('d')) ++ "/"; + const long = "/tmp/nonexistent-pardes-root/" ++ std.mem.asBytes(&@as([15][201]u8, @splat(segment.*))) ++ "f.txt"; const id = p.paneBySerial(serial).?; try nameBuffer(p, id, long, false); p.fs.late_failure_len = 0; diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index c58cf676..aeb57a00 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -1044,12 +1044,12 @@ test "a run's answer says cut when its output's start is gone, and reads a bound const q = try withTerm(gpa); defer q.deinit(); const kept = q.panes[0].?; - kept.terminal.?.vt.screens.get(.primary).?.pages.explicit_max_size = 1; + kept.terminal.?.vt.screens.get(.primary).?.pages.limits.set(.bytes, 1); const run = Node.of(serialOf(q), .pty_run); sh.put(q, prompt); h = sh.send(q, run); sh.put(q, c); - const lines = "pruned\r\n" ** 64; + const lines = std.mem.asBytes(&@as([64][8]u8, @splat("pruned\r\n".*))); var fed: usize = 0; while (!kept.terminal.?.stream.handler.out_start.?.garbage) : (fed += 1) { if (fed == 1000) return error.TestUnexpectedResult; @@ -1146,7 +1146,7 @@ test "a run's answer longer than its room is cut, its newline kept" { var slot: Run = .{}; const p = try th.withTerm(testing.allocator); defer p.deinit(); - answer(p, &slot, "busy: {s} is running", .{"x" ** 200}); + answer(p, &slot, "busy: {s} is running", .{&@as([200]u8, @splat('x'))}); try testing.expectEqual(slot.answer.len, slot.len); try testing.expectEqual(@as(u8, '\n'), slot.answer[slot.len - 1]); } diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index b991c3e4..8d4707e0 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -333,7 +333,7 @@ test "a terminal's body is its logical lines: a row the terminal wrapped is join const p = try th.withTerm(testing.allocator); defer p.deinit(); const pane = p.panes[0].?; - const long = "w" ** 50 ++ "x" ** 150; // wider than the pane: it wraps + const long = &@as([50]u8, @splat('w')) ++ &@as([150]u8, @splat('x')); // wider than the pane: it wraps try testing.expect(long.len > pane.cols); p.update(.{ .output = .{ .pane = 0, .bytes = long ++ "\r\nnext" } }); while (p.nextEffect()) |_| {} diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index eedab43b..5678832b 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -509,7 +509,7 @@ pub fn fitErr(text: []const u8, out: []u8) []const u8 { 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/" ++ "deep/" ** 30 ++ "file.txt: no such directory"; + 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/")); @@ -517,7 +517,7 @@ test "a reason past 128 bytes keeps its end: the path in it gives up its middle" 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 = "why " ** 40 ++ "the reason"; + 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 @@ -525,7 +525,7 @@ test "a reason past 128 bytes keeps its end: the path in it gives 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", .{"no-such-dir/" ** 20})); + 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")); } @@ -1492,17 +1492,17 @@ test "README names every file the tree serves" { return false; } }; - inline for (@typeInfo(TopFile).@"enum".fields) |f| { - const t: TopFile = @enumFromInt(f.value); + inline for (@typeInfo(TopFile).@"enum".field_values) |value| { + const t: TopFile = @enumFromInt(value); if (t != .root and !words.has(t.fileName())) { std.debug.print("README does not mention /{s}\n", .{t.fileName()}); return error.Undocumented; } } - inline for (@typeInfo(PaneFile).@"enum".fields) |f| { - const t: PaneFile = @enumFromInt(f.value); + inline for (@typeInfo(PaneFile).@"enum".field_values) |value| { + const t: PaneFile = @enumFromInt(value); const ok = if (t == .dir) true else if (t.inPty() and t != .pty) - std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @enumFromInt(f.value)).fileName()) != null + std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @enumFromInt(value)).fileName()) != null else words.has(t.fileName()); if (!ok) { diff --git a/src/normal.zig b/src/normal.zig index 77feb7cf..8de23d1c 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -1015,7 +1015,7 @@ test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} - const long = "a" ** 400; + const long = &@as([400]u8, @splat('a')); const pane = try p.setTestFile(long ++ "\nsecond\n"); p.settings.wrap = true; const width = panes.File.wrapWidth(pane, true); diff --git a/src/pager.zig b/src/pager.zig index 30418623..feabd194 100644 --- a/src/pager.zig +++ b/src/pager.zig @@ -38,7 +38,7 @@ pub fn parse(gpa: std.mem.Allocator, raw: []const u8, colour: bool) !Page { errdefer h.text.deinit(gpa); errdefer h.spans.deinit(gpa); try h.text.ensureTotalCapacity(gpa, raw.len); - var stream: ghostty_vt.Stream(*Handler) = .init(&h); + var stream: ghostty_vt.Stream(*Handler) = .init(.{ .handler = &h }); defer stream.deinit(); stream.nextSlice(raw); if (h.failed) return error.OutOfMemory; diff --git a/src/panes.zig b/src/panes.zig index ba1dedb5..07d5ccb1 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -318,7 +318,7 @@ pub const Pane = struct { /// `older` is an earlier message line still on screen; `index` says /// which (`Pane.msg_older`). pub const Kind = enum { older, message, leader, prompt }; - pub const max = @typeInfo(Kind).@"enum".fields.len - 1 + message_stack; + pub const max = @typeInfo(Kind).@"enum".field_names.len - 1 + message_stack; kinds: [max]Kind = undefined, index: [max]u8 = @splat(0), diff --git a/src/pardes.zig b/src/pardes.zig index 5f330712..8da0922d 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -807,7 +807,7 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest if (comptime !syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer p.deinit(); - const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (" // body\n" ** 30) ++ " }\n};\n"); + const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n"); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/test.zig"); if (!panes.File.supportsContext(pane)) return error.SkipZigTest; @@ -1247,7 +1247,9 @@ test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all r const r = p.rects[0]; const x0 = r.x + config.GUTTER + panes.File.gutterWidth(pane); const use_y = p.bodyTop(pane, r) + 1; - const tag = try tagline.tagText(p, p.scratch.allocator(), pane); + // Copied out of the scratch arena, which each p.update resets. + const tag = try std.testing.allocator.dupe(u8, try tagline.tagText(p, p.scratch.allocator(), pane)); + defer std.testing.allocator.free(tag); for ([_]struct { word: []const u8, kind: lsp.Kind }{ .{ .word = " Def ", .kind = .definition }, .{ .word = " Refs", .kind = .references } }) |w| { // B1 sweeps the use of `alpha` on the second line (bytes 30..35), // leaving the cursor at its far end. @@ -1348,7 +1350,7 @@ test "acme placement: under a pane's text when it has many blank rows, else halv try std.testing.expectEqual(text_end, p.rects[second].y); // Fill both with text: no blank space is big, so the biggest pane is // halved. - const full = "x\n" ** 80; + const full = std.mem.asBytes(&@as([80][2]u8, @splat("x\n".*))); for ([_]usize{ top, second }) |id| panes.File.setContent(p, &p.panes[id].?.file.?, try p.gpa.dupe(u8, full)); p.sync(); const big = if (p.rects[second].h >= p.rects[top].h) second else top; @@ -2006,7 +2008,7 @@ test "a command pane shows how its command ended, and the next command there run try std.testing.expectEqual(@as(usize, 0), Count.signals); p.host = host_before; // A command line longer than a command pane takes is refused. - const long = "x" ** (exec.command_max + 1); + const long = &@as([exec.command_max + 1]u8, @splat('x')); try std.testing.expectEqual(@as(?usize, null), exec.execute(p, 1, long)); } @@ -2970,9 +2972,9 @@ test "restored terminals keep monotonic nonzero pane identities" { fn chordName(comptime c: config.Chord) []const u8 { comptime { const mods = (if (c.ctrl) "C-" else "") ++ (if (c.alt) "A-" else "") ++ (if (c.shift) "S-" else ""); - for (@typeInfo(Key).@"struct".decls) |d| { - if (@TypeOf(@field(Key, d.name)) != u21) continue; - if (@field(Key, d.name) == c.cp) return mods ++ d.name; + for (@typeInfo(Key).@"struct".decl_names) |d| { + if (@TypeOf(@field(Key, d)) != u21) continue; + if (@field(Key, d) == c.cp) return mods ++ d; } if (c.cp < 0x20 or c.cp > 0x7e) @compileError("chord has no name for the index"); return mods ++ &[_]u8{@as(u8, @intCast(c.cp))}; @@ -3088,11 +3090,11 @@ pub const builtin_rows: [std.enums.values(Builtin).len]Row = blk: { for (std.enums.values(Builtin), 0..) |b, i| { const keys = if (config.leader_path.get(b)) |path| leaderKeys(path) else ""; const rest = shortcuts(b); - const named = @tagName(b) ++ (if (rest.len == 0) "" else (" " ** (namew - @tagName(b).len)) ++ " " ++ rest); + const named = @tagName(b) ++ (if (rest.len == 0) "" else (&@as([namew - @tagName(b).len]u8, @splat(' '))) ++ " " ++ rest); rows[i] = .{ .path = config.leader_path.get(b), .cmd = b, - .line = keys ++ (" " ** (4 + keyw - keys.len)) ++ " " ++ named, + .line = keys ++ (&@as([4 + keyw - keys.len]u8, @splat(' '))) ++ " " ++ named, }; } const last = "\x7f"; @@ -3111,8 +3113,8 @@ comptime { @setEvalBranchQuota(20000); // one branch per string byte, behind the decl walk that folds Builtin var it = std.mem.tokenizeScalar(u8, config.topbar_str, ' '); words: while (it.next()) |w| { - for (@typeInfo(Builtin).@"enum".fields) |f| - if (std.mem.eql(u8, f.name, w)) continue :words; + for (@typeInfo(Builtin).@"enum".field_names) |name| + if (std.mem.eql(u8, name, w)) continue :words; @compileError("topbar word is not a builtin: " ++ w); } } @@ -4499,7 +4501,7 @@ pub const Pardes = struct { /// Panes made this step that found no room in their column /// (exec.placeNew): closed at the step's end, once whatever made them /// is done with them. - unplaced: std.StaticBitSet(MAX_PANES) = .initEmpty(), + unplaced: std.StaticBitSet(MAX_PANES) = .empty, /// A look's word search is running (look.lookUnresolved): from a /// terminal its rows refill the directory's one +Search (Output). word_look: bool = false, @@ -5018,7 +5020,7 @@ pub const Pardes = struct { if (p.dump_out) |d| gpa.free(d); p.fallback.deinit(); if (p.last_dump) |d| gpa.free(d); - if (p.custom_theme) |theme_value| std.zon.parse.free(gpa, theme_value); + if (p.custom_theme) |theme_value| gpa.free(theme_value.name); if (p.chord_arg) |a| gpa.free(a); for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); p.pipe.deinit(gpa); @@ -8508,7 +8510,7 @@ test "raw tty Ctrl-B switches to editor mode without sending child input" { test "the jump list never holds two entries in a row the same, when the one between them goes" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 40 }); defer p.deinit(); - const pane = try p.setTestFile("a\n" ** 200); + const pane = try p.setTestFile(std.mem.asBytes(&@as([200][2]u8, @splat("a\n".*)))); const at: Loc = .{ .pane = 0, .serial = pane.serial, .line = 1, .col = 1 }; // A, a pane long closed with no file to keep it, A again, then far on. p.jumps[0] = at; @@ -9054,7 +9056,7 @@ const JumpsTest = struct { fn init(order: []const u8) !JumpsTest { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 80 }); errdefer p.deinit(); - const text = "row\n" ** 100; + const text = std.mem.asBytes(&@as([100][4]u8, @splat("row\n".*))); _ = try p.setTestFile(text); var t: JumpsTest = .{ .p = p }; for ([_][]const u8{ "/b.txt", "/test.txt", "" }, 1..) |path, n| { diff --git a/src/pdf.zig b/src/pdf.zig index d98d5ff2..5adc62d1 100644 --- a/src/pdf.zig +++ b/src/pdf.zig @@ -4,9 +4,7 @@ const std = @import("std"); const c_heap = @import("c_heap"); -const c = @cImport({ - @cInclude("pdf_bridge.h"); -}); +const c = @import("pdf_c"); // src/pdf_bridge.h, translated by build.zig /// What MuPDF allocates from, itself and the libraries it bundles (they all /// allocate through its context): `start`'s allocator, through the shared C @@ -1130,7 +1128,7 @@ pub const Document = struct { const page_number = try document.checkedPage(page); if (std.mem.indexOfScalar(u8, needle, 0) != null) return error.InvalidNeedle; - const needle_z = try gpa.dupeZ(u8, needle); + const needle_z = try gpa.dupeSentinel(u8, needle, 0); defer gpa.free(needle_z); var found: c.pardes_pdf_search_result = @@ -2067,7 +2065,7 @@ test "MuPDF search returns normalized oriented quads and word selection text" { const projected = try document.pageText(std.testing.allocator, 0); defer std.testing.allocator.free(projected); - try std.testing.expect(std.ascii.indexOfIgnoreCase(projected, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(projected, "Pardes") != null); // Exercise transactional cache replacement before searching page zero // again; a failed ownership handoff here tends to surface as a double drop. if (document.pages > 1) { @@ -2093,7 +2091,7 @@ test "MuPDF search returns normalized oriented quads and word selection text" { const text = try document.copySelection(std.testing.allocator, 0, selected.start, selected.end); defer std.testing.allocator.free(text); - try std.testing.expect(std.ascii.indexOfIgnoreCase(text, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(text, "Pardes") != null); } test "highlighted render changes pixels while plain render stays stable" { diff --git a/src/regexp.zig b/src/regexp.zig index 86132f60..4cbca57e 100644 --- a/src/regexp.zig +++ b/src/regexp.zig @@ -58,7 +58,7 @@ pub const Regex = struct { /// Timed on this machine's ReleaseSafe build: 10M steps of the worst /// patterns take 45-80 ms, and a Debug build is ten times slower. - pub const budget: u64 = if (builtin.mode == .Debug) 4_000_000 else 32_000_000; + pub const budget: u64 = if (builtin.mode == .debug) 4_000_000 else 32_000_000; pub const e_long = std.fmt.comptimePrint("bad regular expression: longer than mvzr's {d} operations (about {d} pattern characters)", .{ max_ops, max_ops }); pub const e_anchor = "bad regular expression: in a pattern with \\n, ^ can only come first and $ only just before a \\n"; @@ -503,10 +503,10 @@ test "a class with non-ASCII runes matches those runes: [éa-z], a range of them } test "a pattern past 64 characters compiles, and one past the limit says so" { - var long = try Regex.compile("a" ** 200); - const text = "x" ++ "a" ** 200 ++ "\n"; + var long = try Regex.compile(&@as([200]u8, @splat('a'))); + const text = "x" ++ &@as([200]u8, @splat('a')) ++ "\n"; try std.testing.expectEqual(@as(usize, 1), (try long.find(text, 0, text.len, text.len)).?.start); - try std.testing.expectError(error.TooLong, Regex.compile("a" ** (max_ops + 8))); + try std.testing.expectError(error.TooLong, Regex.compile(&@as([max_ops + 8]u8, @splat('a')))); try std.testing.expectError(error.Bad, Regex.compile("a[b")); } @@ -546,13 +546,13 @@ test "a search that would backtrack without end runs out of budget, promptly" { // As long a chain as mvzr compiles, over runs one `a` short of it: 2^20 // steps from every start. for (0..line.len / 20) |i| line[i * 20 + 19] = 'b'; - var chain = try Regex.compile("a?" ** 20 ++ "a" ** 20); + var chain = try Regex.compile(std.mem.asBytes(&@as([20][2]u8, @splat("a?".*))) ++ &@as([20]u8, @splat('a'))); try std.testing.expectError(error.TooSlow, chain.find(&line, 0, line.len, line.len)); } test "the match is the leftmost, however long the line" { // A window cut into the identifier would find `x... =` from its middle. - const text = "let " ++ "x" ** 100 ++ " = 1"; + const text = "let " ++ &@as([100]u8, @splat('x')) ++ " = 1"; var assign = try Regex.compile("\\s*(\\w+)\\s*="); const m = (try assign.find(text, 0, text.len, text.len)).?; try std.testing.expectEqual(@as(usize, 3), m.start); diff --git a/src/sam_edit.zig b/src/sam_edit.zig index d0c51bdb..f6253c89 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -1102,7 +1102,7 @@ fn expectEdit(text: []const u8, command: []const u8, want: []const u8) !void { test "an x over 100k lines is 100k searches, each with its own step budget" { const th = @import("ninep/testing.zig"); - const line = "x" ** 80 ++ "\n"; + const line = &@as([80]u8, @splat('x')) ++ "\n"; const text = try std.testing.allocator.alloc(u8, line.len * 100_000); defer std.testing.allocator.free(text); for (0..100_000) |k| @memcpy(text[line.len * k ..][0..line.len], line); diff --git a/src/syntax.zig b/src/syntax.zig index b2f5ea99..fa212ca7 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -1859,7 +1859,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte defer stop(); const header = "pub fn run() void {"; const content = "| \t" ++ header ++ "\n| \t const value = 42;\nfile.zig:3\t}\n"; - const snapshots = [_]u8{0xff} ** header.len; + const snapshots = @as([header.len]u8, @splat(0xff)); const Row = struct { path: []const u8 = "file.zig", code_start: usize, diff --git a/src/terminal.zig b/src/terminal.zig index 3190c6e3..a8e7931c 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -207,7 +207,7 @@ const LivePalette = struct { var seed = GColor.default; for (base, 0..) |rgb, i| seed[i] = rgb; - self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); + self.colors = GColor.generate256Color(seed, .empty, bg, fg, false); self.key = key; return &self.colors; } @@ -609,10 +609,10 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ .cols = cols, .rows = rows, - .max_scrollback = 16 * 1024 * 1024, + .max_scrollback_bytes = 16 * 1024 * 1024, .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, }); - state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); + state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa }); state.replay.head = 0; state.replay.len = 0; state.reply_len = 0; @@ -1055,7 +1055,11 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { } }; } else failed = true; + // Whether the program cleared the screen (ED 2, a switch of screens); + // pardes reads the flag nowhere else. + pane.terminal.?.vt.flags.dirty.clear = false; ingest(pane, bytes); + const cleared = pane.terminal.?.vt.flags.dirty.clear; // RIS can destroy the alternate screen and every pin it owned. const alive = if (screens.generation(key) == generation) pages else null; var moved = false; @@ -1065,7 +1069,15 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { if (pin.garbage) pointer_rows_lost = true; }; }; + // The program cleared the screen, or the rows the live copy stood on are + // gone (pruned, a reset): the copy goes with them, as what the program + // drew next. Kept, ghostty would move its rows to the top of what is + // left, over the program's new text. + var copy_lost = cleared or alive == null; for (spans[0..nspans]) |span| { + if (span.overlay == overlay) if (span.start.pin) |pin| if (alive != null and pin.garbage) { + copy_lost = true; + }; const start = pinnedRow(alive, span.start); const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); moved = moved or start != span.overlay.row or rows != span.overlay.rows; @@ -1096,6 +1108,11 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { pane.clearPointerSelection(button); pane.sel[button].state = .none; }; + if (copy_lost) if (pane.ovl) |copy| { + pane.gpa.free(copy.text); + pane.ovl = null; + moved = true; + }; if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. if (failed) { const message = "terminal edit position reset: out of memory"; @@ -1211,7 +1228,7 @@ pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !Comm .whole = whole, }; } else true; - return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; + return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = whole }; } /// At a prompt with nothing typed on its line: no input left of the @@ -2813,7 +2830,7 @@ pub fn redo(p: *Pardes, pane: *Pane) void { pane.ensureCursorVisible(); } -pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { +pub 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; const n = @min(room, data.len); @@ -2968,7 +2985,8 @@ test "a program that asked for focus reports hears CSI I and CSI O as its pane t /// over two cells). inline fn kittyTransmit(comptime extra: []const u8) []const u8 { return comptime blk: { - const pixels = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 } ** 2; + 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\\"; diff --git a/src/tty/tty.zig b/src/tty/tty.zig index ca2cb939..82cb40bd 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -129,7 +129,7 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { var parser: vaxis.Parser = .{}; var buf: [1024]u8 = undefined; var carried: usize = 0; - while (!loop.should_quit) { + while (true) { // stopInput cancels the task; the read then fails with Canceled if (carried == buf.len) return error.InputSequenceTooLong; const received = try tty.read(buf[carried..]); if (received == 0) return; @@ -295,7 +295,7 @@ test "terminal input preserves fragmented keys queries paste and text after EOF" fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { return self.next < self.parts.len; } fn read(self: *@This(), buf: []u8) !usize { @@ -380,7 +380,7 @@ test "terminal replies and malformed sequences never become typed text" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { return self.next < self.parts.len; } fn read(self: *@This(), buf: []u8) !usize { @@ -465,7 +465,7 @@ test "terminal input split at every byte with a gap reads as it does whole" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), ms: u32) bool { + pub fn inputFollows(self: *@This(), ms: u32) bool { return self.next < self.parts.len and self.gap_ms <= ms; } fn read(self: *@This(), buf: []u8) !usize { @@ -561,7 +561,7 @@ test "an ESC read by itself is the Escape key at once" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { self.asked = true; return self.next < self.parts.len; } @@ -609,7 +609,7 @@ test "a frame's answer is taken wherever the reads cut it, and never typed" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { return self.next < self.parts.len; } fn read(self: *@This(), buf: []u8) !usize { @@ -701,7 +701,7 @@ test "terminal input cancellation joins blocked reads and queued EOF" { fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(_: *@This(), _: u32) bool { + pub fn inputFollows(_: *@This(), _: u32) bool { return false; } fn read(self: *@This(), buf: []u8) !usize { @@ -2332,7 +2332,7 @@ test "a terminal pane gets function keys as their sequences and lone modifiers n fn getWinsize(_: *@This()) !vaxis.Winsize { return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; } - fn inputFollows(self: *@This(), _: u32) bool { + pub fn inputFollows(self: *@This(), _: u32) bool { return self.next < self.parts.len; } fn read(self: *@This(), buf: []u8) !usize { @@ -3033,7 +3033,7 @@ test "a jump leaves a trail of a few cells behind the cursor that fades in 120 m const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 20); + _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); core.settings.jump_trail = true; for (0..40) |_| core.update(.tick); @@ -3078,7 +3078,7 @@ test "a notice chip casts a cell's shadow right and down, inside its body, off t const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer core.deinit(); - _ = try core.setTestFile("some text on a line\n" ** 20); + _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); core.settings.chip_shadow = true; try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice")); @@ -3114,7 +3114,7 @@ test "a scrolled pane's thumb brightens and fades back in 250 ms" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer core.deinit(); - const pane = try core.setTestFile("some text on a line\n" ** 200); + const pane = try core.setTestFile(std.mem.asBytes(&@as([200][20]u8, @splat("some text on a line\n".*)))); try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); core.settings.thumb_flash = true; for (0..40) |_| core.update(.tick); diff --git a/test/deck/replay.zig b/test/deck/replay.zig index 475f7476..49614b46 100644 --- a/test/deck/replay.zig +++ b/test/deck/replay.zig @@ -20,8 +20,9 @@ const Tally = struct { fn replay(src: [:0]const u8) !Tally { const gpa = std.testing.allocator; - const rec = try schema.parse(gpa, src); - defer schema.free(gpa, rec); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const rec = try schema.parse(gpa, arena.allocator(), src); var d: deck.Deck = .{}; var tally: Tally = .{}; for (rec.events) |ev| { diff --git a/test/deck/schema.zig b/test/deck/schema.zig index 782c829a..401e15e8 100644 --- a/test/deck/schema.zig +++ b/test/deck/schema.zig @@ -61,10 +61,8 @@ pub const Event = struct { }; }; -pub fn parse(gpa: std.mem.Allocator, src: [:0]const u8) error{ OutOfMemory, ParseZon }!Recording { - return std.zon.parse.fromSliceAlloc(Recording, gpa, src, null, .{}); -} - -pub fn free(gpa: std.mem.Allocator, rec: Recording) void { - std.zon.parse.free(gpa, rec); +/// The recording's slices live in `arena`. +pub fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, src: [:0]const u8) error{ OutOfMemory, ParseZon }!Recording { + var diagnostics: std.zon.parse.Diagnostics = undefined; + return std.zon.parse.fromSlice(Recording, .{ .gpa = gpa, .arena = arena, .source = src, .diagnostics = &diagnostics }); } diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index 9e67c49f..a2010c19 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -104,7 +104,7 @@ pub const Harness = struct { term.* = try ghostty_vt.Terminal.init(std.Io.Threaded.global_single_threaded.io(), gpa, .{ .cols = cols, .rows = rows, - .max_scrollback = 1024 * 1024, + .max_scrollback_bytes = 1024 * 1024, }); errdefer term.deinit(gpa); // vtStream() captures a pointer to `term`; term is heap-allocated so the diff --git a/test/fs_bench.zig b/test/fs_bench.zig index 746fe737..4764049f 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -272,7 +272,7 @@ pub fn main(init: std.process.Init) !void { .tag = 9, .op = .write, .node = s.node(.body), - .data = "x" ** 1024, + .data = &@as([1024]u8, @splat('x')), .size = 1024, }, "append: whole-body swap + undo snapshot"); @@ -327,7 +327,7 @@ pub fn main(init: std.process.Init) !void { try w.writeAll("]}\n"); } else { try w.print("{s:<26} {s:>9} {s:>8} {s}\n", .{ "request", "ns/op", "allocs", "note" }); - try w.print("{s:<26} {s:>9} {s:>8} {s}\n", .{ "-" ** 26, "-" ** 9, "-" ** 8, "-" ** 20 }); + try w.print("{s:<26} {s:>9} {s:>8} {s}\n", .{ &@as([26]u8, @splat('-')), &@as([9]u8, @splat('-')), &@as([8]u8, @splat('-')), &@as([20]u8, @splat('-')) }); for (rows.items) |r| try w.print("{s:<26} {d:>9} {d:>8} {s}\n", .{ r.name, r.ns, r.allocs, r.note }); } diff --git a/test/history.zig b/test/history.zig index 5ce45239..d399f7aa 100644 --- a/test/history.zig +++ b/test/history.zig @@ -432,24 +432,24 @@ test "history benchmark cases are nonempty unique and matched by name" { try std.testing.expectError(error.MissingField, readBenchmarks(arena, "{\"case\":\"first\"}")); const before = try readBenchmarks(arena, benchmark_fixture); const missing = try readBenchmarks(arena, "{\"case\":\"first\",\"bytes\":10,\"median_ns\":100,\"cold_ns\":100,\"allocations\":10,\"allocated_bytes\":1000}"); - try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(.{before} ** 4, .{missing} ** 4, null, &report.writer)); + try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(@splat(before), @splat(missing), null, &report.writer)); const renamed = \\{"case":"first","bytes":10,"median_ns":100,"cold_ns":100,"allocations":10,"allocated_bytes":1000} \\{"case":"renamed","bytes":20,"median_ns":100,"cold_ns":100,"allocations":10,"allocated_bytes":1000} ; const different = try readBenchmarks(arena, renamed); - try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(.{before} ** 4, .{different} ** 4, null, &report.writer)); + try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(@splat(before), @splat(different), null, &report.writer)); const reordered = \\{"case":"last","bytes":20,"median_ns":100,"cold_ns":100,"allocations":10,"allocated_bytes":1000} \\{"case":"first","bytes":10,"median_ns":100,"cold_ns":100,"allocations":10,"allocated_bytes":1000} ; const same = try readBenchmarks(arena, reordered); - try std.testing.expect(!try compareBenchmarks(.{before} ** 4, .{same} ** 4, 1, &report.writer)); + try std.testing.expect(!try compareBenchmarks(@splat(before), @splat(same), 1, &report.writer)); var samples = [4][]Benchmark{ before, before, before, different }; - try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(.{before} ** 4, samples, null, &report.writer)); + try std.testing.expectError(error.DifferentBenchmarks, compareBenchmarks(@splat(before), samples, null, &report.writer)); samples[3] = try arena.dupe(Benchmark, before); samples[3][0].bytes += 1; - try std.testing.expectError(error.DifferentBenchmarkInputs, compareBenchmarks(.{before} ** 4, samples, null, &report.writer)); + try std.testing.expectError(error.DifferentBenchmarkInputs, compareBenchmarks(@splat(before), samples, null, &report.writer)); } test "history benchmark gate uses repeated process captures rather than the first process alone" { diff --git a/test/hxdiff.zig b/test/hxdiff.zig index 48c7ab93..b12bcd8e 100644 --- a/test/hxdiff.zig +++ b/test/hxdiff.zig @@ -39,7 +39,7 @@ pub fn main(init: std.process.Init) !void { var pane_override: ?[]const u8 = null; var goldens_path: ?[]const u8 = null; var waivers_path: ?[]const u8 = null; - const paths = try arena.alloc([]const u8, args.len - 1); + const paths = try arena.alloc([]const u8, @max(args.len - 1, 3)); // room for the defaults below var n_paths: usize = 0; var want_waivers = false; for (args[1..]) |a| { @@ -67,6 +67,18 @@ pub fn main(init: std.process.Init) !void { n_paths += 1; } } + // Named nothing (`zig build hxdiff` or `hxparity` bare): the checked-in + // suite, run from the repository root. + if (n_paths == 0 and !want_waivers) { + strict = true; + const defaults: []const []const u8 = if (parity) + &.{ "test/hxcases/cases.jsonl", "test/hxcases/parity.jsonl" } + else + &.{ "test/hxcases/cases.jsonl", "test/hxcases/goldens.jsonl", "test/hxcases/waivers.jsonl" }; + if (parity) waivers_path = waivers_path orelse "test/hxcases/parity-waivers.jsonl"; + @memcpy(paths[0..defaults.len], defaults); + n_paths = defaults.len; + } if (n_paths == 0 or want_waivers) fatal("usage: pardes-hxdiff [--parity] ... [goldens.jsonl [waivers.jsonl]]", .{}); const case_paths = paths[0..if (parity) n_paths else 1]; diff --git a/test/image_harness.zig b/test/image_harness.zig index 474ec48b..b45851cc 100644 --- a/test/image_harness.zig +++ b/test/image_harness.zig @@ -38,7 +38,7 @@ pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(arena); if (args.len != 3 and args.len != 4) return error.BadArgs; - const exe = try arena.dupeZ(u8, args[1]); + const exe = try arena.dupeSentinel(u8, args[1], 0); const backend = args[2]; const pdf_mode = args.len == 4 and std.mem.eql(u8, args[3], "pdf"); if (args.len == 4 and !pdf_mode) return error.BadArgs; diff --git a/test/lspbench.zig b/test/lspbench.zig index 02138d24..d0e25aee 100644 --- a/test/lspbench.zig +++ b/test/lspbench.zig @@ -216,7 +216,7 @@ fn reportText(rs: []const Result, rss: u64) void { const o = std.debug.print; o("backend: {s}\n\n", .{lsp.backend_name}); o("{s:<24} {s:>9} {s:>7} {s:>10} {s:>10} {s}\n", .{ "kind", "supports", "rows", "cold(us)", "warm(us)", "verdict" }); - o("{s}\n", .{"-" ** 78}); + o("{s}\n", .{&@as([78]u8, @splat('-'))}); var claimed: usize = 0; var working: usize = 0; var lies: usize = 0; diff --git a/test/monkey.zig b/test/monkey.zig index 83869ce4..dcea0b43 100644 --- a/test/monkey.zig +++ b/test/monkey.zig @@ -44,7 +44,7 @@ fn generate(gpa: std.mem.Allocator, seed: u64, steps: usize) ![]u8 { var s: Script = .{ .gpa = gpa }; try s.line("# pardes-monkey seed {d}, {d} steps", .{ seed, steps }); try s.line("file bad.txt hello \\xff\\xfe world\\nlatin-1 caf\\xe9 tail\\ntruncated \\xe6\\x97 here\\nend\\n", .{}); - try s.line("file wide.txt {s}tail\\nsecond line\\n", .{"\\xe6\\x97\\xa5\\xe6\\x9c\\xac\\xe8\\xaa\\x9e " ** 8}); + try s.line("file wide.txt {s}tail\\nsecond line\\n", .{std.mem.asBytes(&@as([8][37]u8, @splat("\\xe6\\x97\\xa5\\xe6\\x9c\\xac\\xe8\\xaa\\x9e ".*)))}); try s.line("lines long.txt 400 some words after the number, long enough to wrap in a narrow pane", .{}); try s.line("start 24 80 bad.txt", .{}); try s.line("wait 8000 Newcol Joincol", .{}); diff --git a/test/panes.zig b/test/panes.zig index 86e52838..54100f91 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -42,7 +42,7 @@ const TagLayerTests = struct { p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 5, .tagline_h = 10 }; p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/x"); - try setTag(pane, " " ++ "a" ** 38 ++ "\t界 END"); + try setTag(pane, " " ++ &@as([38]u8, @splat('a')) ++ "\t界 END"); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); _ = try p.render(frame.allocator()); @@ -135,7 +135,7 @@ const TagLayerTests = struct { try std.testing.expectEqual(@as(i32, 0), p.panes[second].?.input.cur_col); p.update(.{ .key = .{ .cp = Key.escape } }); const left = p.panes[0].?; - try setTag(left, " " ++ "a" ** 110); + try setTag(left, " " ++ &@as([110]u8, @splat('a'))); _ = try p.render(frame.allocator()); const left_layer = try findLayer(p, .pane, 0); const left_text = try pardes.tagline.tagText(p, frame.allocator(), left); @@ -149,7 +149,7 @@ const TagLayerTests = struct { try std.testing.expectEqual(panes.File.rawAtDisplay(left_text, end_col), @as(usize, @intCast(left.tag.cur_col))); try std.testing.expect(left.sel[0].state == .done and left.sel[0].r0 == 0); p.update(.{ .key = .{ .cp = Key.escape } }); - const long = "a" ** 60 ++ "界END"; + const long = &@as([60]u8, @splat('a')) ++ "界END"; p.global_tag.own = try p.gpa.dupe(u8, long); for (p.col_tags[0..p.ncol]) |*tag| tag.own = try p.gpa.dupe(u8, long); _ = try p.render(frame.allocator()); @@ -581,7 +581,7 @@ const BodyHitTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); defer p.deinit(); p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; - const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ " // body\n" ** 60 ++ " }\n};\n"); + const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([60][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); pane.scrollBy(10); var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -629,7 +629,7 @@ const LineNumberLookTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); defer p.deinit(); p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; - const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ " // body\n" ** 60 ++ " }\n};\n"); + const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([60][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); pane.scrollBy(30); var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -686,7 +686,7 @@ const TreeContextTests = struct { if (!syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); defer p.deinit(); - const pane = try setZigFile(p, "const Box = struct {\n\n // omitted member comment\n\n pub fn work(\n value: usize,\n ) void {\n" ++ " // body\n" ** 30 ++ " }\n};\n"); + const pane = try setZigFile(p, "const Box = struct {\n\n // omitted member comment\n\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); pane.scrollBy(10); @@ -717,7 +717,7 @@ const TreeContextTests = struct { if (context and !syntax.enabled) continue; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); defer p.deinit(); - const pane = try setZigFile(p, "pub fn work() void {\n" ++ " // body\n" ** 100 ++ "}\n"); + const pane = try setZigFile(p, "pub fn work() void {\n" ++ std.mem.asBytes(&@as([100][12]u8, @splat(" // body\n".*))) ++ "}\n"); if (context) try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); @@ -792,7 +792,7 @@ const TreeContextTests = struct { if (!syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 48, .rows = 14 }); defer p.deinit(); - const pane = try setZigFile(p, "pub fn @\"界name\"(\n\tvalue: usize,\n) void {\n" ++ " _ = value;\n" ** 12 ++ "}\n"); + const pane = try setZigFile(p, "pub fn @\"界name\"(\n\tvalue: usize,\n) void {\n" ++ std.mem.asBytes(&@as([12][15]u8, @splat(" _ = value;\n".*))) ++ "}\n"); pane.tag_expanded = false; // a one-row tag keeps this small screen's rows p.sync(); p.settings.wrap = false; @@ -820,7 +820,7 @@ const TreeContextTests = struct { // Read the body top again: the click cleared the announcement band the // builtin above put up, so the body moved with it. try std.testing.expectEqual(p.bodyTop(pane, p.rects[0]), cursor.y); - panes.File.setContent(p, &pane.file.?, try p.gpa.dupe(u8, "// no enclosing declaration\n" ** 18)); + panes.File.setContent(p, &pane.file.?, try p.gpa.dupe(u8, std.mem.asBytes(&@as([18][28]u8, @splat("// no enclosing declaration\n".*))))); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 0), pane.context_rows); try std.testing.expectEqual(pane.scroll(), pane.wrapAt(0).line); @@ -942,7 +942,7 @@ const TtySelectionTests = struct { try noChildInput(p); _ = try p.render(frame.allocator()); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;C\x07" ++ "\r\nnew output" ** 30 } }); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;C\x07" ++ std.mem.asBytes(&@as([30][12]u8, @splat("\r\nnew output".*))) } }); _ = try p.render(frame.allocator()); try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); @@ -1266,7 +1266,7 @@ const ClickCursorTests = struct { test "click operands and hover follow the scrolled source selection" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 14 }); defer p.deinit(); - const pane = try p.setTestFile("zero\none\ntwo\nthree\nalpha beta\nfive\ngamma delta\nseven\n" ++ "tail\n" ** 20); + const pane = try p.setTestFile("zero\none\ntwo\nthree\nalpha beta\nfive\ngamma delta\nseven\n" ++ std.mem.asBytes(&@as([20][5]u8, @splat("tail\n".*)))); p.presentation.enabled = false; p.settings.wrap = false; var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -1323,7 +1323,7 @@ const JumpSelectionTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 34, .rows = 10 }); defer p.deinit(); p.settings.wrap = wrap; - const text = try std.fmt.allocPrint(p.gpa, "{s}{s}", .{ prefix, "unrelated destination text\n" ** 80 }); + const text = try std.fmt.allocPrint(p.gpa, "{s}{s}", .{ prefix, std.mem.asBytes(&@as([80][27]u8, @splat("unrelated destination text\n".*))) }); defer p.gpa.free(text); const pane = try p.setTestFile(text); var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -1813,7 +1813,7 @@ test "a word the tag's wrapping breaks across rows is still one word to a click" var pad: usize = 1; const shown = while (pad < 80) : (pad += 1) { p.gpa.free(pane.file.?.path); - const path = try std.fmt.allocPrint(arena.allocator(), "/{s}/f.zig", .{("a" ** 80)[0..pad]}); + const path = try std.fmt.allocPrint(arena.allocator(), "/{s}/f.zig", .{(&@as([80]u8, @splat('a')))[0..pad]}); pane.file.?.path = try p.gpa.dupe(u8, path); p.sync(); const s = try pardes.tagline.shownTag(p, arena.allocator(), pane); @@ -1866,7 +1866,7 @@ test "terminal output keeps following new rows after scrollback eviction" { pane.body.mode = .tty; pane.tty_filter = false; const pages = &pane.terminal.?.vt.screens.active.pages; - pages.explicit_max_size = 64 * 1024; + pages.limits.set(.bytes, 64 * 1024); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); var evictions: usize = 0; @@ -1885,7 +1885,7 @@ test "terminal output keeps following new rows after scrollback eviction" { if (pages.scrollbar().total < previous) evictions += 1; } try std.testing.expect(evictions > phase); - try std.testing.expect(pages.page_size <= pages.maxSize()); + try std.testing.expect(pages.page_size <= pages.limits.max(.bytes)); const sb = pages.scrollbar(); try std.testing.expectEqual(sb.total - pane.rows, sb.offset); const full = try panes.terminal.screenTextAlloc(pane, gpa); @@ -1926,7 +1926,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { const pane = p.panes[0].?; pane.body.mode = .tty; const pages = &pane.terminal.?.vt.screens.active.pages; - pages.explicit_max_size = 64 * 1024; + pages.limits.set(.bytes, 64 * 1024); var next: usize = 0; while (next < 3000) { var buf: [32]u8 = undefined; @@ -1977,9 +1977,9 @@ test "terminal edits and undo survive partial history clearing and whole-screen pane.body.mode = .tty; if (action == .reset_alternate) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h" } }); - p.update(.{ .output = .{ .pane = 0, .bytes = "old row\r\n" ** 40 } }); + p.update(.{ .output = .{ .pane = 0, .bytes = std.mem.asBytes(&@as([40][9]u8, @splat("old row\r\n".*))) } }); const pages = &pane.terminal.?.vt.screens.active.pages; - pages.explicit_max_size = 64 * 1024; + pages.limits.set(.bytes, 64 * 1024); const row: i32 = @as(i32, @intCast(pages.total_rows - pane.rows)) + @as(i32, if (action == .partial_clear_history) -1 else 2); pane.body.mode = .normal; @@ -2005,7 +2005,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen const bytes = switch (action) { .clear_history, .partial_clear_history => "\x1b[3J", .reset_primary, .reset_alternate => "\x1bc", - .evict_all, .hidden_undo => "new row\r\n" ** 4000, + .evict_all, .hidden_undo => std.mem.asBytes(&@as([4000][9]u8, @splat("new row\r\n".*))), }; p.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); const expected: i32 = if (action == .clear_history) 2 else 0; @@ -2045,7 +2045,7 @@ test "terminal lower scroll regions do not move edits above them" { var setup: [64]u8 = undefined; const bytes = try std.fmt.bufPrint(&setup, "\x1b[4;{d}r\x1b[{d};1H", .{ pane.rows, pane.rows }); p.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); - p.update(.{ .output = .{ .pane = 0, .bytes = "tail\r\n" ** 50 } }); + p.update(.{ .output = .{ .pane = 0, .bytes = std.mem.asBytes(&@as([50][6]u8, @splat("tail\r\n".*))) } }); try std.testing.expectEqual(total, panes.terminal.scrollbar(pane).total); try std.testing.expectEqual(@as(i32, 1), pane.ovl.?.row); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); @@ -2064,7 +2064,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv const pane = p.panes[0].?; pane.body.mode = .tty; const pages = &pane.terminal.?.vt.screens.active.pages; - pages.explicit_max_size = 64 * 1024; + pages.limits.set(.bytes, 64 * 1024); var next: usize = 0; while (next < 3000) { var buf: [32]u8 = undefined; @@ -2229,7 +2229,7 @@ test "prompt cancellation restores the selection before regex previews" { } test "a prompt that cannot be opened leaves the open one as it was" { - const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[3].type.?; + const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".param_types[3].?; for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); @@ -2268,7 +2268,7 @@ test "Save's prompt starts from the pane's directory" { } test "a prompt opens with one allocation" { - const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[3].type.?; + const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".param_types[3].?; for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); @@ -3441,7 +3441,7 @@ const PdfTests = struct { defer probe.deinit(std.testing.allocator); try std.testing.expectEqual(@as(usize, 0), probe.page); try std.testing.expect(probe.quads.len > 0); - try std.testing.expect(std.ascii.indexOfIgnoreCase(probe.text, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(probe.text, "Pardes") != null); } test "PDF point mapping restores band origin and fractional placement" { @@ -4812,7 +4812,7 @@ test "growing a file pane colors every newly visible Zig keyword" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 8 }); defer p.deinit(); - const pane = try p.setTestFile("pub fn f() void { if (true) {} }\n" ** 100); + const pane = try p.setTestFile(std.mem.asBytes(&@as([100][33]u8, @splat("pub fn f() void { if (true) {} }\n".*)))); const file = &pane.file.?; gpa.free(file.path); file.path = try gpa.dupe(u8, "/resize.zig"); diff --git a/test/pdf.zig b/test/pdf.zig index a0eb8154..a51fd1a9 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -2080,14 +2080,14 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { @as(i32, r.y + r.h - 1), )); if (!panes.Pdf.beginSelection(p, pane, col, row)) continue; - if (std.ascii.indexOfIgnoreCase(pv.selection_text, "Pardes") != null) { + if (std.ascii.findIgnoreCase(pv.selection_text, "Pardes") != null) { selected_col = col; selected_row = row; break :find_word; } }; const word_col = selected_col orelse return error.PdfMouseMappingMissedWord; - try std.testing.expect(std.ascii.indexOfIgnoreCase( + try std.testing.expect(std.ascii.findIgnoreCase( pardes.test_api.heldSelection(p, 0).?, "Pardes", ) != null); @@ -2142,7 +2142,7 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { const hover = p.pdf_hover_preview orelse return error.MissingPdfHoverPreview; try std.testing.expectEqual(@as(usize, 0), hover.probe.page); try std.testing.expect(hover.probe.quads.len > 0); - try std.testing.expect(std.ascii.indexOfIgnoreCase(hover.probe.text, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(hover.probe.text, "Pardes") != null); try std.testing.expect(p.look_hover_preview == null); try std.testing.expect(p.look_hover_wait == null); @@ -2188,7 +2188,7 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { // search highlights without carrying an old selection into the result. p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = word_col, .row = selected_row } }); p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = word_col, .row = selected_row } }); - try std.testing.expect(std.ascii.indexOfIgnoreCase(pv.search_query, "Pardes") != null); + try std.testing.expect(std.ascii.findIgnoreCase(pv.search_query, "Pardes") != null); pv.resolveSearch(p.pdf_gpa); const highlights = (try panes.Pdf.buildHighlights( pv, diff --git a/test/pdf_scroll_bench.zig b/test/pdf_scroll_bench.zig index 166fa809..fdc42660 100644 --- a/test/pdf_scroll_bench.zig +++ b/test/pdf_scroll_bench.zig @@ -597,7 +597,7 @@ fn reportText(config: Config, travel: Travel, results: []const Result) void { "total_us", "rasters", "kept", "peak_kib", "visual", "transport", }); - std.debug.print("{s}\n", .{"-" ** 160}); + std.debug.print("{s}\n", .{&@as([160]u8, @splat('-'))}); for (results) |result| std.debug.print( "{s:<16} {d:>6} {d:>7} {d:>10} {d:>10} {d:>10} {d:>10} {d:>10} {d:>11} {d:>7} {d:>5} {d:>9} {x:0>16} {x:0>16}\n", .{ diff --git a/test/pdf_sections_bench.zig b/test/pdf_sections_bench.zig index 92c9ef7c..ee26e83d 100644 --- a/test/pdf_sections_bench.zig +++ b/test/pdf_sections_bench.zig @@ -454,7 +454,7 @@ fn reportText(config: Config, results: []const Result) void { std.debug.print("{s:<42} {s:>10} {s:>10} {s:>10} {s:>10} {s:>8} {s:>8} {s}\n", .{ "scenario", "min", "median", "p90", "max", "items", "bytes", "checksum", }); - std.debug.print("{s}\n", .{"-" ** 124}); + std.debug.print("{s}\n", .{&@as([124]u8, @splat('-'))}); for (results) |result| std.debug.print( "{s:<42} {d:>10} {d:>10} {d:>10} {d:>10} {d:>8} {d:>8} {x:0>16}\n", .{ diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json deleted file mode 100644 index 39f5913c..00000000 --- a/test/perf-baseline-gui-Debug.json +++ /dev/null @@ -1 +0,0 @@ -{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1818,"med_us":2104,"p90_us":2287,"max_us":2293},{"op":"render","fixture":"medium","min_us":78,"med_us":82,"p90_us":87,"max_us":87},{"op":"key-down","fixture":"medium","min_us":79,"med_us":81,"p90_us":89,"max_us":109},{"op":"key-right","fixture":"medium","min_us":79,"med_us":84,"p90_us":85,"max_us":89},{"op":"page-down","fixture":"medium","min_us":79,"med_us":81,"p90_us":84,"max_us":87},{"op":"wheel","fixture":"medium","min_us":77,"med_us":78,"p90_us":82,"max_us":82},{"op":"edit-char","fixture":"medium","min_us":1019,"med_us":1349,"p90_us":1597,"max_us":1632},{"op":"edit-twin","fixture":"medium","min_us":2029,"med_us":2353,"p90_us":2455,"max_us":2676},{"op":"body-2m","fixture":"medium","min_us":5978,"med_us":9708,"p90_us":11361,"max_us":11666},{"op":"body-appends","fixture":"medium","min_us":117933,"med_us":211247,"p90_us":268014,"max_us":275006},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":75,"p90_us":80,"max_us":84}]} diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json new file mode 100644 index 00000000..4b60520b --- /dev/null +++ b/test/perf-baseline-gui-debug.json @@ -0,0 +1 @@ +{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1732,"med_us":1881,"p90_us":2035,"max_us":2072},{"op":"render","fixture":"medium","min_us":89,"med_us":92,"p90_us":101,"max_us":102},{"op":"key-down","fixture":"medium","min_us":92,"med_us":94,"p90_us":100,"max_us":100},{"op":"key-right","fixture":"medium","min_us":91,"med_us":93,"p90_us":105,"max_us":109},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":99,"max_us":106},{"op":"wheel","fixture":"medium","min_us":90,"med_us":95,"p90_us":101,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1226,"med_us":1678,"p90_us":2093,"max_us":2323},{"op":"edit-twin","fixture":"medium","min_us":2275,"med_us":2697,"p90_us":2868,"max_us":2920},{"op":"body-2m","fixture":"medium","min_us":5213,"med_us":11333,"p90_us":18974,"max_us":18999},{"op":"body-appends","fixture":"medium","min_us":175012,"med_us":260087,"p90_us":317184,"max_us":317469},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":85,"p90_us":86,"max_us":98}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json deleted file mode 100644 index 9110398c..00000000 --- a/test/perf-baseline-tty-Debug.json +++ /dev/null @@ -1 +0,0 @@ -{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1881,"med_us":2148,"p90_us":2324,"max_us":2644},{"op":"render","fixture":"medium","min_us":79,"med_us":87,"p90_us":90,"max_us":93},{"op":"key-down","fixture":"medium","min_us":81,"med_us":84,"p90_us":86,"max_us":90},{"op":"key-right","fixture":"medium","min_us":80,"med_us":85,"p90_us":89,"max_us":102},{"op":"page-down","fixture":"medium","min_us":85,"med_us":86,"p90_us":88,"max_us":88},{"op":"wheel","fixture":"medium","min_us":79,"med_us":85,"p90_us":90,"max_us":91},{"op":"edit-char","fixture":"medium","min_us":1037,"med_us":1300,"p90_us":1639,"max_us":1647},{"op":"edit-twin","fixture":"medium","min_us":2046,"med_us":2378,"p90_us":2529,"max_us":2585},{"op":"body-2m","fixture":"medium","min_us":5790,"med_us":9510,"p90_us":12226,"max_us":12462},{"op":"body-appends","fixture":"medium","min_us":132421,"med_us":224849,"p90_us":257368,"max_us":274890},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":80,"p90_us":84,"max_us":86}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json deleted file mode 100644 index 4cbc8b95..00000000 --- a/test/perf-baseline-tty-ReleaseFast.json +++ /dev/null @@ -1 +0,0 @@ -{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1775,"med_us":1995,"p90_us":2092,"max_us":2094},{"op":"render","fixture":"medium","min_us":80,"med_us":86,"p90_us":89,"max_us":95},{"op":"key-down","fixture":"medium","min_us":81,"med_us":83,"p90_us":95,"max_us":101},{"op":"key-right","fixture":"medium","min_us":79,"med_us":84,"p90_us":85,"max_us":98},{"op":"page-down","fixture":"medium","min_us":80,"med_us":82,"p90_us":96,"max_us":97},{"op":"wheel","fixture":"medium","min_us":78,"med_us":80,"p90_us":87,"max_us":88},{"op":"edit-char","fixture":"medium","min_us":1036,"med_us":1377,"p90_us":1602,"max_us":1621},{"op":"edit-twin","fixture":"medium","min_us":2266,"med_us":2715,"p90_us":3695,"max_us":3927},{"op":"body-2m","fixture":"medium","min_us":4739,"med_us":8675,"p90_us":11518,"max_us":13657},{"op":"body-appends","fixture":"medium","min_us":111613,"med_us":214959,"p90_us":264859,"max_us":283506},{"op":"deep-sel","fixture":"medium","min_us":74,"med_us":76,"p90_us":89,"max_us":96}]} diff --git a/test/perf-baseline-tty-debug.json b/test/perf-baseline-tty-debug.json new file mode 100644 index 00000000..a01335bd --- /dev/null +++ b/test/perf-baseline-tty-debug.json @@ -0,0 +1 @@ +{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2169,"med_us":2697,"p90_us":3126,"max_us":3207},{"op":"render","fixture":"medium","min_us":89,"med_us":96,"p90_us":101,"max_us":115},{"op":"key-down","fixture":"medium","min_us":93,"med_us":98,"p90_us":104,"max_us":115},{"op":"key-right","fixture":"medium","min_us":96,"med_us":97,"p90_us":102,"max_us":108},{"op":"page-down","fixture":"medium","min_us":96,"med_us":98,"p90_us":102,"max_us":103},{"op":"wheel","fixture":"medium","min_us":89,"med_us":100,"p90_us":128,"max_us":168},{"op":"edit-char","fixture":"medium","min_us":1821,"med_us":2274,"p90_us":2404,"max_us":2610},{"op":"edit-twin","fixture":"medium","min_us":2710,"med_us":3180,"p90_us":3413,"max_us":3636},{"op":"body-2m","fixture":"medium","min_us":9090,"med_us":14438,"p90_us":18158,"max_us":22063},{"op":"body-appends","fixture":"medium","min_us":241367,"med_us":375874,"p90_us":470623,"max_us":528094},{"op":"deep-sel","fixture":"medium","min_us":88,"med_us":89,"p90_us":90,"max_us":90}]} diff --git a/test/perf-baseline-tty-fast.json b/test/perf-baseline-tty-fast.json new file mode 100644 index 00000000..04fc88d3 --- /dev/null +++ b/test/perf-baseline-tty-fast.json @@ -0,0 +1 @@ +{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1695,"med_us":2024,"p90_us":2180,"max_us":2292},{"op":"render","fixture":"medium","min_us":79,"med_us":82,"p90_us":92,"max_us":94},{"op":"key-down","fixture":"medium","min_us":81,"med_us":82,"p90_us":83,"max_us":84},{"op":"key-right","fixture":"medium","min_us":80,"med_us":82,"p90_us":91,"max_us":91},{"op":"page-down","fixture":"medium","min_us":81,"med_us":84,"p90_us":90,"max_us":171},{"op":"wheel","fixture":"medium","min_us":79,"med_us":80,"p90_us":90,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1332,"med_us":1691,"p90_us":1967,"max_us":1987},{"op":"edit-twin","fixture":"medium","min_us":2160,"med_us":2457,"p90_us":2718,"max_us":2757},{"op":"body-2m","fixture":"medium","min_us":5047,"med_us":13525,"p90_us":16257,"max_us":20323},{"op":"body-appends","fixture":"medium","min_us":155834,"med_us":261597,"p90_us":329936,"max_us":333538},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":76,"p90_us":84,"max_us":96}]} diff --git a/test/perf.zig b/test/perf.zig index c9235954..d01d1bb5 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -1054,7 +1054,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void .undo_output = undo_output, .history_rows = state.vt.screens.active.pages.scrollbar().total, .history_bytes = state.vt.screens.active.pages.page_size, - .history_limit_bytes = state.vt.screens.active.pages.maxSize(), + .history_limit_bytes = state.vt.screens.active.pages.limits.max(.bytes), .row_count_decreases = row_count_decreases, .allocator_calls = counter.calls, .allocator_live_after_output = live_after_output, @@ -1385,7 +1385,7 @@ fn reportText( for (fixtures) |fx| { if (base != null) o(" {s:>19}", .{fx.name}) else o(" {s:>12}", .{fx.name}); } - o("\n{s}\n", .{if (base != null) "-" ** (12 + fixtures.len * 20) else "-" ** (12 + fixtures.len * 13)}); + o("\n{s}\n", .{if (base != null) &@as([12 + fixtures.len * 20]u8, @splat('-')) else &@as([12 + fixtures.len * 13]u8, @splat('-'))}); var worst_jitter: f64 = 0; for (std.enums.values(Op), 0..) |op, oi| { o("{s:<12}", .{op.label()}); @@ -1412,7 +1412,7 @@ fn reportText( for (term_fixtures) |fx| { if (base != null) o(" {s:>19}", .{fx.name}) else o(" {s:>12}", .{fx.name}); } - o("\n{s}\n", .{if (base != null) "-" ** (12 + term_fixtures.len * 20) else "-" ** (12 + term_fixtures.len * 13)}); + o("\n{s}\n", .{if (base != null) &@as([12 + term_fixtures.len * 20]u8, @splat('-')) else &@as([12 + term_fixtures.len * 13]u8, @splat('-'))}); for (std.enums.values(TermOp), 0..) |op, oi| { o("{s:<12}", .{op.label()}); for (0..term_fixtures.len) |fi| { @@ -1524,10 +1524,11 @@ fn parseBase(src: []const u8, opts: Options, bytes: *const [fixtures.len]usize) defer parsed.deinit(); const report = parsed.value; if (!std.mem.eql(u8, report.harness, harness_id)) return error.BaselineHarnessMismatch; - inline for (std.meta.fields(BuildIdentity)) |field| { - const before = @field(report.build, field.name); - const after = @field(build_identity, field.name); - const same = if (field.type == []const u8) std.mem.eql(u8, before, after) else before == after; + const info = @typeInfo(BuildIdentity).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + const before = @field(report.build, name); + const after = @field(build_identity, name); + const same = if (T == []const u8) std.mem.eql(u8, before, after) else before == after; if (!same) return error.BaselineBuildMismatch; } if (report.cols != opts.cols or report.rows != opts.rows or report.reps != opts.reps or diff --git a/test/snapshot.zig b/test/snapshot.zig index 5522fbb9..2d8a8664 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -157,8 +157,8 @@ pub fn main(init: std.process.Init) !void { script_i += 1; } if (exe == null) fatal("usage: pardes-snap [scripts...] [--update] [--jobs=N]", .{}); - const exe_z = try arena.dupeZ(u8, exe.?); - lspmock_bin = if (lspmock) |p| try arena.dupeZ(u8, p) else null; + const exe_z = try arena.dupeSentinel(u8, exe.?, 0); + lspmock_bin = if (lspmock) |p| try arena.dupeSentinel(u8, p, 0) else null; if (scripts.len == 0) { scripts = try listSnaps(arena, try absPath(arena, orig_cwd, "test/snapshots")); @@ -443,7 +443,7 @@ fn runBatch( fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8, update: bool) u8 { if (careful) beCareful(); const stem = std.fs.path.stem(script_path); - const report_z = arena.dupeZ(u8, reportPath(arena, script_path) catch return 1) catch return 1; + const report_z = arena.dupeSentinel(u8, reportPath(arena, script_path) catch return 1, 0) catch return 1; const fd = libc.open(report_z, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); if (fd >= 0) { _ = libc.dup2(fd, 1); @@ -457,7 +457,7 @@ fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8 // dirty to every manual `cmp` audit. Unlink only this script's exact path // before it starts; a new mismatch below writes it back. const actual_path = std.fmt.allocPrint(arena, "{s}.actual", .{base_path}) catch return 1; - const actual_path_z = arena.dupeZ(u8, actual_path) catch return 1; + const actual_path_z = arena.dupeSentinel(u8, actual_path, 0) catch return 1; if (record_dir == null) _ = libc.unlink(actual_path_z); const golden: ?[]u8 = if (record_dir == null) readFileAlloc(arena, golden_path) catch null else null; const started = eh.nowMs(); @@ -473,7 +473,7 @@ fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8 return 0; } if (update) { - eh.writeFile(arena.dupeZ(u8, golden_path) catch return 1, out) catch return 1; + eh.writeFile(arena.dupeSentinel(u8, golden_path, 0) catch return 1, out) catch return 1; std.debug.print("UPDATED {s} ({d} bytes)\n", .{ stem, out.len }); return 0; } @@ -485,7 +485,7 @@ fn runOne(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const u8 std.debug.print("PASS {s} ({d}ms)\n", .{ stem, took }); return 0; } - eh.writeFile(arena.dupeZ(u8, actual_path) catch return 1, out) catch |err| { + eh.writeFile(arena.dupeSentinel(u8, actual_path, 0) catch return 1, out) catch |err| { std.debug.print("FAIL {s}: differs from golden; cannot write {s}: {s} ({d}ms)\n", .{ stem, actual_path, @errorName(err), took }); printFirstDiff(golden.?, out); return 1; @@ -557,7 +557,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const try mkdir(arena, work, false); // deterministic shell: fixed prompt, no history, no user rc leakage try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/.bashrc", .{home}, 0), "PS1='$ '\nHISTFILE=\n"); - _ = setenv("HOME", try arena.dupeZ(u8, home), 1); + _ = setenv("HOME", try arena.dupeSentinel(u8, home, 0), 1); // Keep startup configuration hermetic even when the developer exports an // XDG directory that points outside this per-snapshot fake home. const config_home = try std.fmt.allocPrintSentinel(arena, "{s}/.config", .{home}, 0); @@ -602,8 +602,8 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // take turns — which cost more wall clock than the other 51 scripts put // together. Scripts name it `$DUMP`. const dump_path = try std.fmt.allocPrint(arena, "{s}/dump.zon", .{base}); - _ = setenv("PARDES_DUMP", try arena.dupeZ(u8, dump_path), 1); - if (chdirRc(try arena.dupeZ(u8, work)) < 0) return error.ChdirFailed; + _ = setenv("PARDES_DUMP", try arena.dupeSentinel(u8, dump_path, 0), 1); + if (chdirRc(try arena.dupeSentinel(u8, work, 0)) < 0) return error.ChdirFailed; const chunks = try arena.alloc([]const u8, countCaptures(src)); var chunk_len: usize = 0; @@ -636,7 +636,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const try eh.appendFile(try std.fmt.allocPrintSentinel(arena, "{s}/pardes/init", .{config_home}, 0), setting); } else if (std.mem.eql(u8, cmd, "file")) { const name = tok.next() orelse return error.BadScript; - try eh.writeFile(try arena.dupeZ(u8, name), try unescape(arena, tok.rest())); + try eh.writeFile(try arena.dupeSentinel(u8, name, 0), try unescape(arena, tok.rest())); } else if (std.mem.eql(u8, cmd, "lines")) { const name = tok.next() orelse return error.BadScript; const n = try std.fmt.parseInt(usize, tok.next() orelse return error.BadScript, 10); @@ -646,7 +646,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // scroll test needs and `file` can only give as one huge script line const tail = tok.rest(); const buf = try numberedLines(arena, n, tail); - try eh.writeFile(try arena.dupeZ(u8, name), buf); + try eh.writeFile(try arena.dupeSentinel(u8, name, 0), buf); } else if (std.mem.eql(u8, cmd, "ppmdiag")) { // The diagonal-split test PPM from the old e2e (white over blue), // grown to 512x512 with the white half filled by a fixed LCG @@ -658,7 +658,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // down to flat color and a block always wins). const name = tok.next() orelse return error.BadScript; const ppm = try ppmDiag(arena); - try eh.writeFile(try arena.dupeZ(u8, name), ppm); + try eh.writeFile(try arena.dupeSentinel(u8, name, 0), ppm); } else if (std.mem.eql(u8, cmd, "dirmk")) { try mkdir(arena, tok.next() orelse return error.BadScript, false); } else if (std.mem.eql(u8, cmd, "run")) { @@ -668,7 +668,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // different inotify event. This runs in the script's cwd, as a // child of the RUNNER, so nothing it does reaches the app's ptys: // whatever the app then shows, it woke up for by itself. - if (system(try arena.dupeZ(u8, tok.rest())) != 0) return error.RunFailed; + if (system(try arena.dupeSentinel(u8, tok.rest(), 0)) != 0) return error.RunFailed; } else if (std.mem.eql(u8, cmd, "start")) { const rows = try std.fmt.parseInt(u16, tok.next() orelse return error.BadScript, 10); const cols = try std.fmt.parseInt(u16, tok.next() orelse return error.BadScript, 10); @@ -676,7 +676,7 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const var nextra: usize = 0; while (tok.next()) |a| : (nextra += 1) { if (nextra >= extra.len) return error.BadScript; - extra[nextra] = (try arena.dupeZ(u8, a)).ptr; + extra[nextra] = (try arena.dupeSentinel(u8, a, 0)).ptr; } if (h) |*hp| hp.deinit(); // scripts may restart (e.g. dump then -l) // a new process is a new screen: capture it whole, or its first @@ -963,13 +963,13 @@ fn treeAsleep(root: libc.pid_t) bool { while (n > 0) { n -= 1; const pid = stack[n]; - const dir_path = std.fmt.bufPrintZ(&path_buf, "/proc/{d}/task", .{pid}) catch continue; + const dir_path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task", .{pid}, 0) catch continue; const dir = libc.opendir(dir_path) orelse continue; // exited between steps defer _ = libc.closedir(dir); while (libc.readdir(dir)) |d| { const tid = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&d.name)), 0); if (tid[0] == '.') continue; - const stat = readProc(&buf, std.fmt.bufPrintZ(&path_buf, "/proc/{d}/task/{s}/stat", .{ pid, tid }) catch continue) orelse continue; + const stat = readProc(&buf, std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task/{s}/stat", .{ pid, tid }, 0) catch continue) orelse continue; // "pid (comm) S ..." — comm can hold spaces and parens, so the // state is the char two past the LAST ')' const close = std.mem.lastIndexOfScalar(u8, stat, ')') orelse continue; @@ -983,7 +983,7 @@ fn treeAsleep(root: libc.pid_t) bool { 'R', 'D', 'Z' => return false, else => {}, } - const kids = readProc(&buf, std.fmt.bufPrintZ(&path_buf, "/proc/{d}/task/{s}/children", .{ pid, tid }) catch continue) orelse continue; + const kids = readProc(&buf, std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task/{s}/children", .{ pid, tid }, 0) catch continue) orelse continue; var it = std.mem.tokenizeAny(u8, kids, " \n"); while (it.next()) |k| { if (n >= stack.len) return false; // deeper than we can walk: assume busy @@ -1554,7 +1554,7 @@ fn absPath(arena: std.mem.Allocator, cwd: []const u8, p: []const u8) ![]const u8 } fn listSnaps(arena: std.mem.Allocator, dir_path: []const u8) ![][]const u8 { - const dir_z = try arena.dupeZ(u8, dir_path); + const dir_z = try arena.dupeSentinel(u8, dir_path, 0); const count = countSnapEntries(dir_z, dir_path); const scripts = try arena.alloc([]const u8, count); const dir = libc.opendir(dir_z) orelse fatal("no snapshots/ dir at {s}", .{dir_path}); @@ -1583,7 +1583,7 @@ fn countSnapEntries(dir_z: [:0]const u8, dir_path: []const u8) usize { } fn readFileAlloc(arena: std.mem.Allocator, path: []const u8) ![]u8 { - const path_z = try arena.dupeZ(u8, path); + const path_z = try arena.dupeSentinel(u8, path, 0); const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY }); if (fd < 0) return error.OpenFailed; defer _ = libc.close(fd); @@ -1611,7 +1611,7 @@ fn readFileAlloc(arena: std.mem.Allocator, path: []const u8) ![]u8 { } fn mkdir(arena: std.mem.Allocator, path: []const u8, exist_ok: bool) !void { - const path_z = try arena.dupeZ(u8, path); + const path_z = try arena.dupeSentinel(u8, path, 0); const rc = libc.mkdir(path_z, 0o755); if (rc != 0) { if (exist_ok and libc.errno(rc) == .EXIST) return; diff --git a/test/snapshots/exec.golden b/test/snapshots/exec.golden index df49336c..30473c9e 100644 --- a/test/snapshots/exec.golden +++ b/test/snapshots/exec.golden @@ -22,15 +22,17 @@ == snap kept grid=140x31 cursor=6,3 |3: ZZARG ls |4: ./c.sh e.txt +|8: |9: == snap chord grid=140x31 cursor=6,3 |3: ZZARG Exec ls -|9: CHORDARG:ZZARG +|5: ./c.sh ZZARG +|6: CHORDARG:ZZARG == snap deleted grid=140x31 cursor=4,5 |3: ls ls |4: e.txt e.txt -|8: -|9: +|5: +|6: |17: |18: |19: diff --git a/test/snapshots/tinywin.golden b/test/snapshots/tinywin.golden deleted file mode 100644 index 787a9d8f..00000000 --- a/test/snapshots/tinywin.golden +++ /dev/null @@ -1,83 +0,0 @@ -== snap stacked grid=100x31 cursor=14,3 -| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Collapse Del -| $ :^[n^[n^[n -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del -| 1 -== snap shrunk grid=60x4 cursor=59,3 -| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Col -| /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del -== snap columns grid=100x31 cursor=23,3 -| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Collapse Del -| $ :^[n^[n^[n cn cn cn -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del -| 1 -== snap narrow grid=4x31 cursor=2,20 -| Ne -| Ne -|$ /t -| mp -| /p -| ar -| de -| s- -| sn -| ap -| $ -| ^[ -| n^ -| [n -| ^[ -| n -| cn -| c -| n -| cn -| -| /t -| mp -| /p -| ar -| de -| s- -| sn -| ap diff --git a/test/snapshots/tinywin.snap b/test/snapshots/tinywin.snap deleted file mode 100644 index 3d22d583..00000000 --- a/test/snapshots/tinywin.snap +++ /dev/null @@ -1,31 +0,0 @@ -# Shrinking the window past "one row per pane" used to panic: computeGeom gave -# every pane in a column at least one row, so `y` walked off the bottom and -# renderPane got a rect outside the surface (assert). Panes that no longer fit -# now get h = 0 and simply do not render until the window grows back. -start 31 100 -wait 8000 $ -key a-n -stable 400 8000 -key a-n -stable 400 8000 -key a-n -stable 400 8000 -key a-n -stable 700 15000 -snap stacked -resize 4 60 -stable 700 10000 -snap shrunk -# ...and the same sideways: more columns than the window is wide -resize 31 100 -stable 700 10000 -key space c n -stable 600 8000 -key space c n -stable 600 8000 -key space c n -stable 700 15000 -snap columns -resize 31 4 -stable 700 10000 -snap narrow diff --git a/test/unit_profile_test.zig b/test/unit_profile_test.zig index 721f1212..a4cdd09e 100644 --- a/test/unit_profile_test.zig +++ b/test/unit_profile_test.zig @@ -149,11 +149,8 @@ fn fixture(init: std.process.Init) !void { var write_buffer: [1024]u8 = undefined; var reader = std.Io.File.stdin().readerStreaming(io, &read_buffer); var writer = std.Io.File.stdout().writerStreaming(io, &write_buffer); - var server = try std.zig.Server.init(.{ - .in = &reader.interface, - .out = &writer.interface, - .zig_version = if (std.mem.eql(u8, mode, "version")) "wrong-version" else builtin.zig_version_string, - }); + var server: std.zig.Server = .{ .in = &reader.interface, .out = &writer.interface }; + try server.serveStringMessage(.zig_version, if (std.mem.eql(u8, mode, "version")) "wrong-version" else builtin.zig_version_string); while (true) { const request = try server.receiveMessage(); switch (request.tag) { diff --git a/tools/gen_themes.zig b/tools/gen_themes.zig index 65e85d1c..be5fde2f 100644 --- a/tools/gen_themes.zig +++ b/tools/gen_themes.zig @@ -152,13 +152,14 @@ fn byName(_: void, a: Theme, b: Theme) bool { fn emit(w: *std.Io.Writer, t: Theme) !void { try w.writeAll("// Generated by tools/gen_themes.zig. Do not edit.\npub const theme = .{\n"); try w.print(" .name = \"{s}\",\n", .{t.name}); - inline for (@typeInfo(Theme).@"struct".fields) |f| { - if (comptime std.mem.eql(u8, f.name, "name")) continue; - if (comptime std.mem.eql(u8, f.name, "palette")) continue; - try w.print(" .{s} = ", .{f.name}); - if (comptime @typeInfo(f.type) == .optional) { - if (@field(t, f.name)) |c| try rgb(w, c) else try w.writeAll("null"); - } else try rgb(w, @field(t, f.name)); + const info = @typeInfo(Theme).@"struct"; + inline for (info.field_names, info.field_types) |name, T| { + if (comptime std.mem.eql(u8, name, "name")) continue; + if (comptime std.mem.eql(u8, name, "palette")) continue; + try w.print(" .{s} = ", .{name}); + if (comptime @typeInfo(T) == .optional) { + if (@field(t, name)) |c| try rgb(w, c) else try w.writeAll("null"); + } else try rgb(w, @field(t, name)); try w.writeAll(",\n"); } if (t.palette) |p| { -- cgit v1.3 From 0073d05329335dbb0eb85f5c3044e42805d144e5 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 23 Oct 2026 17:10:58 -0300 Subject: Callstack lists every caller and pages a tree too big for one query; memory bounds and resident-size fixes Callstack walks while the server answers, counts on the message row past a second, puts test callers last at each level, and ends a tree past one query's memory (memory.limits.arena.lsp_query, a 256 MiB region taken and given back per query) in a row whose Callstack shows the next page. Grep reads whole files. New hard limits: undo text per file, image decode pixels, the LSP snapshot of other open files, one paste. Safe builds no longer fill worst-case buffers with 0xAA (memory.unfilled), big regions are kept off transparent huge pages, and malloc_trim runs after big results. Also: Look's git show pages into a +Diff, and dropped marks in File. Co-Authored-By: Claude Opus 5.5 --- build.zig.zon | 4 +- docs/typ/guide.typ | 14 +- docs/typ/reference.typ | 9 +- src/9p.zig | 24 -- src/9p_io.zig | 121 +++--- src/File.zig | 141 +++++-- src/Registers.zig | 13 + src/ShaderBuild.zig | 23 +- src/builtins.zig | 3 + src/colors.zig | 2 +- src/config.zig | 66 +--- src/crash.zig | 6 + src/detached/server.zig | 29 +- src/dump.zig | 11 - src/edit.zig | 190 ++++++++-- src/exec.zig | 6 + src/fs.zig | 82 ++-- src/gui/gui.zig | 329 ++++++---------- src/gui/pet.zig | 29 +- src/host_io.zig | 103 ++++-- src/hunks.zig | 19 +- src/image.zig | 8 +- src/locations.zig | 135 +++++-- src/look.zig | 61 ++- src/lsp/lsp.zig | 17 +- src/lsp/lsp_client.zig | 761 ++++++++++++++++++++++++++------------ src/macos.zig | 17 +- src/main.zig | 12 +- src/memory.zig | 98 +++++ src/mini.zig | 16 +- src/modal.zig | 139 +++++-- src/mouse.zig | 11 +- src/ninep/addr.zig | 42 ++- src/ninep/ctl.zig | 4 + src/panes.zig | 3 + src/pardes.zig | 42 ++- src/regexp.zig | 11 +- src/sam_edit.zig | 15 + src/selection_pipe.zig | 11 +- src/surface.zig | 5 - src/terminal.zig | 86 +---- src/tty/tty.zig | 51 ++- test/lspbench.zig | 22 +- test/panes.zig | 3 - test/perf-baseline-gui-debug.json | 2 +- test/perf-baseline-tty-debug.json | 2 +- test/perf-baseline-tty-fast.json | 2 +- test/perf.zig | 21 +- 48 files changed, 1843 insertions(+), 978 deletions(-) (limited to 'src/fs.zig') diff --git a/build.zig.zon b/build.zig.zon index 292bd479..7885fd4e 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,8 +9,8 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#d5c37d9122240fe95d308fbe15874e14dd786c5a", - .hash = "cloud9-0.1.0-yt86qnAvHgB1dEWGakukcJ54GZ7J3mv_lm_kApzAuEOY", + .url = "git+https://git.sr.ht/~gbrls/cloud9#0702e33bcfadf0abd9ccbaa8b681a19a84c332fe", + .hash = "cloud9-0.1.0-yt86qkExHgCRI7_eJsztRECamioWguBj2mTFsJ5N-AOn", }, // Pinned to the exact libvaxis commit ghostty is built against, so it // is compatible with ghostty's uucode configuration (the one we share diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index a5327a44..e60b4231 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -240,11 +240,19 @@ wrapping. Cross-directory Look paths are shortened when possible. pane. #word("LookNext") / #word("LookPrev") (#keys("SPC j n", "SPC j p")) select locations without opening them. The view follows the language server's static call hierarchy; recursive paths are marked `↻`, and a -large hierarchy invites continuing from another function. +hierarchy deeper than the limit invites continuing from another function. +Every caller is listed: the walk runs as long as the server keeps answering, +says how many callers it has found on the message row once it takes more +than a second, and shows what it found if the server stops answering. +Asking anything else stops it. A tree too big for one page (about 100,000 +rows, the memory one query may use) ends in a row saying so: running +#word("Callstack") in `+Callstack` shows the next page, from where this +one stopped, with that caller's own callers above it again. +At each level, callers whose function or file name contains "test" come +after the rest. #word("CallstackDepth") reports the current caller depth; `CallstackDepth 16` changes it for subsequent queries. The default is 8 -levels, and the accepted range is 1–64. The view also caps collection at -64 callers. +levels, and the accepted range is 1–64. `CallstackLayout stacked` (the default) puts each signature and call snippet below its location, aligned with the location text; `CallstackLayout inline` puts it diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index bb13b011..c14ad659 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -264,7 +264,9 @@ A line written to #file("exec") is #word("Exec"): a declaration; from a use it reaches every file); #word("Callstack") (#key("g c") or #key("SPC l b")) opens and focuses `+Callstack`, with static caller ancestry, tree-sitter signatures and Look locations - for callers and call sites. #word("CallstackDepth") reports or sets the + for callers and call sites, test callers after the rest at each level; run + in `+Callstack` itself, it shows the next page of a tree too big for one. + #word("CallstackDepth") reports or sets the runtime depth (1–64, default 8) for subsequent queries. `CallstackLayout stacked` (the default) aligns snippets below their locations; `CallstackLayout inline` places the snippets beside them. @@ -971,12 +973,11 @@ one a #file("exec") open still holds is never reused. In a command pane, #key("n = Find and Grep #word("Find") matches file names, #word("Grep") the text of lines, both literally and -ignoring ASCII case. #word("Grep") reads at most 256 KiB of a file and stops at 512 +ignoring ASCII case. #word("Grep") reads whole files and stops at 512 hits, #word("Find") at 512 names. The walk stops at 20000 files or 100000 entries, 16 deep, and passes over `.git`, `.jj`, `target`, `node_modules`, `.venv`, `__pycache__`, `.zig-cache` and `zig-out`. A cap hit, or a -directory it could not open, is said at the end: `cut at 512 hits`, `N -files read only in part (first 256 KiB)`, `walk cut at N entries`, `N +directory it could not open, is said at the end: `cut at 512 hits`, `walk cut at N entries`, `N directories skipped: permission denied`. A search that finds nothing and skipped nothing fails, `Grep: text not found`, and leaves the `+Search` as it was. diff --git a/src/9p.zig b/src/9p.zig index 67b3b39a..0979b66a 100644 --- a/src/9p.zig +++ b/src/9p.zig @@ -5,16 +5,10 @@ const cloud9 = @import("cloud9"); pub const fs = cloud9.fs; pub const Server = cloud9.fs.Server; -pub const Error = cloud9.Error; -pub const Type = cloud9.Type; -pub const isT = cloud9.isT; pub const header_len = cloud9.header_len; -pub const qid_len = cloud9.qid_len; -pub const stat_fixed = cloud9.stat_fixed; pub const notag = cloud9.notag; pub const nofid = cloud9.nofid; pub const max_welem = cloud9.max_welem; -pub const iohdrsz = cloud9.iohdrsz; pub const Qid = cloud9.Qid; pub const Stat = cloud9.Stat; pub const Msg = cloud9.Msg; @@ -23,29 +17,11 @@ pub const frameLen = cloud9.frameLen; pub const encode = cloud9.encode; pub const decode = cloud9.decode; pub const qtdir = cloud9.qtdir; -pub const qtappend = cloud9.qtappend; -pub const qtexcl = cloud9.qtexcl; -pub const qtmount = cloud9.qtmount; -pub const qtauth = cloud9.qtauth; -pub const qttmp = cloud9.qttmp; -pub const qtfile = cloud9.qtfile; -pub const dmdir = cloud9.dmdir; -pub const dmappend = cloud9.dmappend; -pub const dmexcl = cloud9.dmexcl; -pub const dmmount = cloud9.dmmount; -pub const dmauth = cloud9.dmauth; -pub const dmtmp = cloud9.dmtmp; -pub const dmperm = cloud9.dmperm; pub const Client = cloud9.Client; -pub const ClientError = cloud9.ClientError; -pub const max_tags = cloud9.max_tags; pub const oread = cloud9.oread; pub const owrite = cloud9.owrite; pub const ordwr = cloud9.ordwr; -pub const oexec = cloud9.oexec; pub const otrunc = cloud9.otrunc; -pub const ocexec = cloud9.ocexec; -pub const orclose = cloud9.orclose; pub const errmax = cloud9.fs.errmax; pub const errString = cloud9.fs.errString; pub const msize_min = cloud9.fs.msize_min; diff --git a/src/9p_io.zig b/src/9p_io.zig index 446c24de..87972b43 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -174,8 +174,15 @@ pub const Listener = struct { io: std.Io, /// The core that answers; `reset` puts a replacement in. core: *pardes.Pardes, - runner: Runner = undefined, + /// cloud9's runner, sized for every connection's buffers and parks (some + /// 136 MiB): pages of its own (`allocRunner`), written only as clients + /// take slots, so an idle session does not hold them resident. + runner: *Runner = undefined, stopping: std.atomic.Value(bool) = .init(false), + /// The watchers of held Edit writes (watchEdit): canceled and awaited + /// by `deinit`, once the turn lets a waiting one through, so none wakes + /// into a freed Listener. + edit_watchers: std.Io.Group = .init, /// A connection wrote the Restore and has yet to answer it. restore_writer: std.atomic.Value(bool) = .init(false), /// Clients turned away with every slot taken, since the log last said so. @@ -354,8 +361,7 @@ pub const Listener = struct { const later: pardes.ctlfs.Reply = .{ .tag = req.tag, .status = .again }; const ticket = conn.hold(&later) orelse return; core.fs.edit_hold = .{ .asker = conn, .slot = ticket.slot, .seq = ticket.seq, .tag = req.tag, .node = req.node, .handle = req.handle, .written = reply.written }; - const watcher = std.Thread.spawn(.{}, watchEdit, .{ l, conn, ticket }) catch return; - watcher.detach(); + l.edit_watchers.concurrent(l.io, watchEdit, .{ l, conn, ticket }) catch {}; return; } const restoring = core.restore_req != null; @@ -457,13 +463,13 @@ pub const Listener = struct { /// flush, so it is looked for, every 100 ms; a park out for a retry is /// not waiting either, so only three looks in a row with no write being /// served count. - fn watchEdit(l: *Listener, conn: *Runner.Conn, ticket: cloud9.fs.Ticket) void { - const io = pardes.turn.io orelse return; + fn watchEdit(l: *Listener, conn: *Runner.Conn, ticket: cloud9.fs.Ticket) error{Canceled}!void { var misses: u8 = 0; while (!l.stopping.load(.acquire)) { - io.sleep(.fromMilliseconds(100), .awake) catch return; + try l.io.sleep(.fromMilliseconds(100), .awake); _ = pardes.turn.take(); defer pardes.turn.give(); + if (l.stopping.load(.acquire)) return; const core = l.core; const h = core.fs.edit_hold orelse return; if (h.slot != ticket.slot or h.seq != ticket.seq or h.asker != @as(*anyopaque, conn)) return; @@ -914,6 +920,7 @@ pub const Listener = struct { // A connection task may be waiting for the turn; it answers // nothing more once stopping, but the wait itself must end. pardes.turn.rest(); + l.edit_watchers.cancel(l.io); // An answer given as the editor quit (a Kill written to /ctl) // may still be on its way out: let it go before the cut. const deadline = nowMs() +| 200; @@ -942,10 +949,26 @@ pub const Listener = struct { z[l.path_len] = 0; _ = libc.unlink(z[0..l.path_len :0]); } + freeRunner(l.runner); gpa.destroy(l); } }; +/// The runner's memory, from the page allocator with no fill: an Allocator's +/// `create` writes `undefined` over all of it in a safe build, which would make +/// every page resident at startup. +fn allocRunner() ?*Runner { + if (comptime !supported) return @constCast(&@as(Runner, {})); + const bytes = std.heap.page_allocator.rawAlloc(@sizeOf(Runner), .of(Runner), @returnAddress()) orelse return null; + @import("memory.zig").sparse(bytes[0..@sizeOf(Runner)]); + return @ptrCast(@alignCast(bytes)); +} + +fn freeRunner(runner: *Runner) void { + if (comptime !supported) return; + std.heap.page_allocator.rawFree(@as([*]u8, @ptrCast(runner))[0..@sizeOf(Runner)], .of(Runner), @returnAddress()); +} + /// The socket this process listens on, kept where a fatal signal's handler /// can reach it without allocating (unlinkOwnSocket); empty when none. var own_socket: [sun_path_len:0]u8 = undefined; @@ -1065,6 +1088,10 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: [ } const l = gpa.create(Listener) catch return null; l.* = .{ .io = io, .core = core }; + l.runner = allocRunner() orelse { + gpa.destroy(l); + return null; + }; pardes.turn.start(io); pardes.turn.wake_parked = Listener.wakeParked; pardes.turn.answer_held = Listener.answerHeld; @@ -1551,7 +1578,7 @@ test "a socket path too long for sun_path is no listener, and leaves the editor' defer if (old_copy) |o| { _ = setenv("XDG_RUNTIME_DIR", o, 1); } else { - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); }; const long = &@as([120]u8, @splat('n')); try testing.expect(listen(testing.io, testing.allocator, p, long, "", null, null) == null); @@ -1572,7 +1599,7 @@ test "a listening editor posts itself into the 9P registry and unposts on stop" if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -1633,7 +1660,7 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); const replacement = try gpa.alloc(u8, 3 * msize + 27); @@ -1754,7 +1781,7 @@ test "a change waits while the editor is out mid-step, a read does not, and the if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -1829,7 +1856,7 @@ test "a held read is answered when the log has news, and a flushed one spends no if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -2001,28 +2028,22 @@ pub fn exportSessionEnv(serial: u32, adopts: bool) void { exportEnv(if (own_socket_len > 0) own_socket[0..own_socket_len] else null, serial, adopts); } +/// Told to children through host_io.ChildEnv, never set into this process's +/// own environment (see ChildEnv.exportVar for why). fn exportEnv(socket: ?[]const u8, serial: u32, adopts: bool) void { - var announced = false; - if (adopts) announcing: { - var buf: [16]u8 = undefined; - const text = std.fmt.bufPrintSentinel(&buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}, 0) catch - break :announcing; - announced = setenv("PARDES_PID", text, 1) == 0; - } - if (!announced) _ = unsetenv("PARDES_PID"); - - if (socket) |own| exporting: { - var sock: [sun_path_len]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&sock, "{s}", .{own}, 0) catch break :exporting; + 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 null else null); + if (socket) |own| { var buf: [16]u8 = undefined; - const id = std.fmt.bufPrintSentinel(&buf, "{d}", .{serial}, 0) catch break :exporting; - if (setenv("PARDES_9P", path, 1) != 0) break :exporting; + ChildEnv.exportVar("PARDES_9P", own); exportMount(own); - if (setenv("PARDES_PANE", id, 1) == 0) return; + ChildEnv.exportVar("PARDES_PANE", std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); + return; } - _ = unsetenv("PARDES_9P"); - _ = unsetenv("PARDES_PANE"); - _ = unsetenv("PARDES_MOUNT"); + ChildEnv.exportVar("PARDES_9P", null); + ChildEnv.exportVar("PARDES_PANE", null); + ChildEnv.exportVar("PARDES_MOUNT", null); } /// $PARDES_MOUNT, the session's own directory, when the environment says @@ -2040,11 +2061,11 @@ fn exportMount(sock_path: []const u8) void { 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.bufPrintSentinel(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] }, 0)) |mount| { - if (setenv("PARDES_MOUNT", mount, 1) == 0) return; + 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 |_| {} } - _ = unsetenv("PARDES_MOUNT"); + @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", null); } test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and unset when not known" { @@ -2057,16 +2078,16 @@ test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and u if (value) |old| { _ = setenv(name, old, 1); testing.allocator.free(old); - } else _ = unsetenv(name); + } 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", std.mem.span(libc.getenv("PARDES_MOUNT").?)); + 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. - _ = unsetenv("NINE_MNTGEN"); + _ = @import("host_io.zig").testUnsetenv("NINE_MNTGEN"); exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expect(libc.getenv("PARDES_MOUNT") == null); + 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" { @@ -2079,16 +2100,16 @@ test "9P shell environment states being inside pardes apart from how to reach it if (value) |old| { _ = setenv(name, old, 1); testing.allocator.free(old); - } else _ = unsetenv(name); + } 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).?); - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); _ = setenv("HOME", "/home/example", 1); try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?); - _ = unsetenv("HOME"); + _ = @import("host_io.zig").testUnsetenv("HOME"); try testing.expect(socketDir(&dir) == null); const listener = try testing.allocator.create(Listener); @@ -2104,25 +2125,25 @@ test "9P shell environment states being inside pardes apart from how to reach it // parent, so a pardes started in one of its shells runs a session of // its own instead of handing its argument over. exportPaneEnv(listener, 7, false); - try testing.expectEqualStrings(path, std.mem.span(libc.getenv("PARDES_9P").?)); - try testing.expectEqualStrings("7", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expect(libc.getenv("PARDES_PID") == null); + 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); exportPaneEnv(listener, 8, true); - try testing.expectEqualStrings("8", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + 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").?); // 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. exportPaneEnv(null, 0, true); - try testing.expect(libc.getenv("PARDES_9P") == null); - try testing.expect(libc.getenv("PARDES_PANE") == null); - try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + 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").?); exportPaneEnv(null, 0, false); - try testing.expect(libc.getenv("PARDES_9P") == null); - try testing.expect(libc.getenv("PARDES_PANE") == null); - try testing.expect(libc.getenv("PARDES_PID") == null); + 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); } pub const Client = struct { diff --git a/src/File.zig b/src/File.zig index 59b04e3f..7e05ac9f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -43,14 +43,14 @@ pub const Snapshot = struct { saved_len: ?usize = null, fn deinit(s: Snapshot, gpa: std.mem.Allocator) void { - gpa.free(s.content); + pardes.memory.freeUnfilled(gpa, s.content); } }; /// The pane's text, place and name now, for an undo or redo step. fn snapshotOf(gpa: std.mem.Allocator, pane: *const Pane, f: *const State) ?Snapshot { return .{ - .content = gpa.dupe(u8, f.content) catch return null, + .content = pardes.memory.dupeUnfilled(gpa, f.content) catch return null, .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel, @@ -105,6 +105,8 @@ pub const History = struct { undo_len: usize = 0, redo: [limits.undo_max]Snapshot = undefined, redo_len: usize = 0, + /// The text `undo` and `redo` hold, kept near limits.undo_bytes. + bytes: usize = 0, /// The names the file had, each with the rename generation it ended /// (Snapshot.gen), and the generation now. @@ -115,6 +117,7 @@ pub const History = struct { const history = try gpa.create(History); history.undo_len = 0; history.redo_len = 0; + history.bytes = 0; history.names = .empty; history.gen = 0; return history; @@ -165,6 +168,9 @@ pub const State = struct { /// edit drops them (setContentSpan); shifting them through the splice, /// as pane.zig's shiftOne moves dot, would keep them. pager_spans: []pardes.pager.Span = &.{}, + /// The rows and spans an edit dropped, with the text they were for: an + /// edit (an undo) back to that very text takes them again. + dropped_marks: ?DroppedMarks = null, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -457,10 +463,6 @@ test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width try std.testing.expectEqual(@as(usize, 4), fitEnd(text, 0, 10)); } -pub fn byteDisplayWidth(byte: u8) usize { - return if (byte == '\t') config.tab_now else 1; -} - pub fn displayWidth(text: []const u8) usize { var width: usize = 0; var at: usize = 0; @@ -787,18 +789,9 @@ pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { pub const Span = struct { head: usize, tail: usize }; fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8, known: ?Span) ![]usize { - const n = @min(old.len, new.len); - var head: usize = 0; - var tail: usize = 0; - if (known) |span| { - head = span.head; - tail = span.tail; - } else { - while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; - while (head < n and old[head] == new[head]) head += 1; - while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; - while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; - } + const span = known orelse spanOf(old, new); + const head = span.head; + const tail = span.tail; // A start s follows the newline at s-1: kept while that newline is in // the common head, shifted while it is in the common tail. const kept = std.sort.upperBound(usize, starts, head, struct { @@ -1123,6 +1116,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); p.gpa.free(file.pager_spans); locations.freeRows(p.gpa, file.location_rows); + if (file.dropped_marks) |m| m.deinit(p.gpa); if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); if (file.node_tree) |tree| syntax.freeTree(tree); for (file.node_history.items) |step| p.gpa.free(step.ranges); @@ -1140,6 +1134,18 @@ fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { pardes.ctlfs.events.noteReplace(p, id, false, f.content, new); } +pub const DroppedMarks = struct { + len: usize, + hash: u64, + rows: []locations.Row, + spans: []pardes.pager.Span, + + fn deinit(m: DroppedMarks, gpa: std.mem.Allocator) void { + locations.freeRows(gpa, m.rows); + gpa.free(m.spans); + } +}; + pub fn setContent(p: *Pardes, f: *State, new: []u8) void { setContentSpan(p, f, new, null); } @@ -1160,10 +1166,16 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { moved[i] = .{ .cursor = spliced(@min(at, f.content.len), f.content.len, new.len, span.?), .scroll = spliced(lineStart(p.gpa, tf, tf.scroll), f.content.len, new.len, span.?) }; } const old_starts = f.line_starts.ptr; - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = &.{}; - p.gpa.free(f.pager_spans); - f.pager_spans = &.{}; + if (f.location_rows.len > 0 or f.pager_spans.len > 0) { + if (f.dropped_marks) |m| m.deinit(p.gpa); + f.dropped_marks = .{ .len = f.content.len, .hash = std.hash.Wyhash.hash(0, f.content), .rows = f.location_rows, .spans = f.pager_spans }; + f.location_rows = &.{}; + f.pager_spans = &.{}; + } else if (f.dropped_marks) |m| if (m.len == new.len and m.hash == std.hash.Wyhash.hash(0, new)) { + f.location_rows = m.rows; + f.pager_spans = m.spans; + f.dropped_marks = null; + }; for (p.panes) |slot| if (slot) |pane| { if (pane.file) |*file| if (file == f) { for (0..pane.sel.len) |button| { @@ -1182,7 +1194,9 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { f.saved_hash = std.hash.Wyhash.hash(0, f.content); f.saved_len = f.content.len; } - p.gpa.free(f.content); + // Raw: `free` overwrites a safe build's freed memory, a whole file's + // worth per keystroke. + if (f.content.len > 0) p.gpa.rawFree(f.content, .of(u8), @returnAddress()); f.content = new; f.revision +%= 1; if (f.saved_hash) |h| if ((f.saved_len orelse new.len) == new.len and std.hash.Wyhash.hash(0, new) == h) { @@ -1241,14 +1255,43 @@ fn spliced(at: usize, old_len: usize, new_len: usize, span: Span) usize { } /// What `old` and `new` agree on at either end. -fn spanOf(old: []const u8, new: []const u8) Span { +/// What `new` kept of `old` at either end, compared 32 bytes at a time +/// (a byte at a time was most of a `d` in a 7 MB file). +pub fn spanOf(old: []const u8, new: []const u8) Span { + const block = 32; const n = @min(old.len, new.len); - const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n; + var head: usize = 0; + while (head + block <= n and std.mem.eql(u8, old[head..][0..block], new[head..][0..block])) head += block; + while (head < n and old[head] == new[head]) head += 1; var tail: usize = 0; + while (tail + block <= n - head and std.mem.eql(u8, old[old.len - tail - block ..][0..block], new[new.len - tail - block ..][0..block])) tail += block; while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; 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); @@ -1492,14 +1535,18 @@ pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { pane.ensureCursorVisible(); } -fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, snap: Snapshot) void { - if (len.* == slots.len) { +/// Bounded in steps and in bytes: the oldest go first, though the one +/// pushed always stays. +fn pushHistory(gpa: std.mem.Allocator, history: *History, slots: []Snapshot, len: *usize, snap: Snapshot) void { + while (len.* > 0 and (len.* == slots.len or history.bytes + snap.content.len > limits.undo_bytes)) { + history.bytes -= slots[0].content.len; slots[0].deinit(gpa); - std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); + std.mem.copyForwards(Snapshot, slots[0 .. len.* - 1], slots[1..len.*]); len.* -= 1; } slots[len.*] = snap; len.* += 1; + history.bytes += snap.content.len; } pub fn pushUndo(p: *Pardes, pane: *Pane) void { @@ -1510,9 +1557,12 @@ pub fn pushUndo(p: *Pardes, pane: *Pane) void { if (std.mem.eql(u8, last.content, f.content) and last.gen == history.gen) return; } const snap = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.undo, &history.undo_len, snap); - for (history.redo[0..history.redo_len]) |item| item.deinit(p.gpa); + for (history.redo[0..history.redo_len]) |item| { + history.bytes -= item.content.len; + item.deinit(p.gpa); + } history.redo_len = 0; + pushHistory(p.gpa, history, &history.undo, &history.undo_len, snap); } pub fn undo(p: *Pardes, pane: *Pane) void { @@ -1520,9 +1570,10 @@ pub fn undo(p: *Pardes, pane: *Pane) void { const history = f.history; if (history.undo_len == 0) return; const current = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.redo, &history.redo_len, current); + pushHistory(p.gpa, history, &history.redo, &history.redo_len, current); history.undo_len -= 1; const previous = history.undo[history.undo_len]; + history.bytes -= previous.content.len; // the file's text now setContent(p, f, previous.content); restoreName(p, pane, f, previous); restoreSnap(pane, f, previous); @@ -1533,9 +1584,10 @@ pub fn redo(p: *Pardes, pane: *Pane) void { const history = f.history; if (history.redo_len == 0) return; const current = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.undo, &history.undo_len, current); + pushHistory(p.gpa, history, &history.undo, &history.undo_len, current); history.redo_len -= 1; const next = history.redo[history.redo_len]; + history.bytes -= next.content.len; // the file's text now setContent(p, f, next.content); restoreName(p, pane, f, next); restoreSnap(pane, f, next); @@ -2266,3 +2318,28 @@ pub fn paintWordSelection( } } } + +test "undo keeps its steps within a byte bound, the newest always" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile(""); + const f = &pane.file.?; + const step = limits.undo_bytes / 4 + 1; + const text = try gpa.alloc(u8, step); + defer gpa.free(text); + for (0..8) |i| { + @memset(text, 'a' + @as(u8, @intCast(i))); + pushUndo(p, pane); + setContent(p, f, try gpa.dupe(u8, text)); + } + pushUndo(p, pane); + const history = f.history; + try std.testing.expect(history.undo_len > 0 and history.undo_len < 8); + try std.testing.expect(history.bytes <= limits.undo_bytes + step); + var sum: usize = 0; + for (history.undo[0..history.undo_len]) |snap| sum += snap.content.len; + try std.testing.expectEqual(sum, history.bytes); + undo(p, pane); + try std.testing.expectEqualStrings(text[0..1], f.content[0..1]); +} diff --git a/src/Registers.zig b/src/Registers.zig index 3f2486cd..5e23da5b 100644 --- a/src/Registers.zig +++ b/src/Registers.zig @@ -81,6 +81,7 @@ pub fn text(r: *Registers, gpa: std.mem.Allocator, name: u21) ?[]const u8 { const reg = r.get(name) orelse return null; if (reg.joined) |j| return j; var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); // what a failed append left; empty once owned for (reg.values, 0..) |v, i| { if (i > 0 and !std.mem.endsWith(u8, reg.values[i - 1], "\n")) out.append(gpa, '\n') catch return null; out.appendSlice(gpa, v) catch return null; @@ -105,3 +106,15 @@ test "a register holds a value per range and joins them for one-text readers" { try std.testing.expectEqualStrings("x", r.text(gpa, 'a').?); try std.testing.expectEqualStrings("one\ntwo", r.text(gpa, default).?); } + +test "joining a register that runs out of memory partway leaks nothing" { + var r: Registers = .{}; + defer r.deinit(std.testing.allocator); + r.put(std.testing.allocator, default, "one", 0, 2, true); + r.put(std.testing.allocator, default, "two", 1, 2, false); + r.put(std.testing.allocator, default, &(@as([4096]u8, @splat('x'))), 1, 2, false); + // The first append allocates; growing for the 4096 bytes fails. + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1, .resize_fail_index = 0 }); + try std.testing.expect(r.text(failing.allocator(), default) == null); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); +} diff --git a/src/ShaderBuild.zig b/src/ShaderBuild.zig index b50999a5..e5b6680b 100644 --- a/src/ShaderBuild.zig +++ b/src/ShaderBuild.zig @@ -76,7 +76,8 @@ const Result = union(enum) { spirv: struct { bytes: []u8, source: u64, animated: bool }, }; -/// One compile of the stale files, on its own thread. +/// One compile of the stale files, a task of its own: `deinit` cancels it +/// (glslc's wait is a cancelation point) rather than waiting out a glslc. const Job = struct { io: std.Io, gpa: std.mem.Allocator, @@ -86,7 +87,10 @@ const Job = struct { results: [max]Result = @splat(.none), len: usize = 0, done: std.atomic.Value(bool) = .init(false), - thread: std.Thread = undefined, + /// Set before the cancel: the files after the one it stopped are not + /// compiled either (a cancel is said once, to the wait it lands in). + stop: std.atomic.Value(bool) = .init(false), + future: std.Io.Future(void) = undefined, }; files: [max]File = @splat(.{}), @@ -105,7 +109,7 @@ pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, var collected = false; if (b.job) |job| { if (!job.done.load(.acquire)) return false; - job.thread.join(); + job.future.await(job.io); b.job = null; b.collect(gpa, core, job); collected = true; @@ -148,7 +152,7 @@ pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, job.len += 1; file.stale = false; } - job.thread = std.Thread.spawn(.{}, compile, .{job}) catch { + job.future = io.concurrent(compile, .{job}) catch { for (job.paths[0..job.len]) |path| gpa.free(path); gpa.destroy(job); return collected; @@ -174,7 +178,8 @@ pub fn view(b: *const Build, chain: *const Chain, out: *[max]Pass) []const Pass pub fn deinit(b: *Build, gpa: std.mem.Allocator, fd: c_int, watches: *file_watch.Table) void { if (b.job) |job| { - job.thread.join(); + job.stop.store(true, .release); + job.future.cancel(job.io); freeJob(gpa, job); } for (b.files[0..b.len]) |file| free(gpa, file); @@ -245,7 +250,10 @@ fn expand(buf: *[4096]u8, path: []const u8) []const u8 { /// build's own flags (build.zig compileGlsl), source on stdin, SPIR-V on /// stdout. fn compile(job: *Job) void { - for (job.paths[0..job.len], 0..) |path, i| job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); + for (job.paths[0..job.len], 0..) |path, i| { + if (job.stop.load(.acquire)) break; + job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); + } job.done.store(true, .release); if (job.wake.call) |call| call(job.wake.ctx); } @@ -378,7 +386,8 @@ test "a save that changes a file compiles it again, a failed one keeps the last fn run(build: *Build, c: *pardes.Pardes, f: c_int, w: *file_watch.Table) void { _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); while (build.job) |job| { - while (!job.done.load(.acquire)) std.Thread.yield() catch {}; + job.future.await(std.testing.io); + job.done.store(true, .release); _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); } } diff --git a/src/builtins.zig b/src/builtins.zig index cc7d1d4a..fdce534b 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1971,6 +1971,9 @@ pub const WsDiagnostics = struct { /// Show outermost callers first, with signatures and call sites (gc). pub const Callstack = struct { pub fn run(c: Ctx) void { + // In +Callstack itself: the next page of what it shows. + if (c.pane.file) |f| if (f.output) |o| if (std.meta.eql(o.from, panes.Output.Origin{ .query = .callstack })) + return c.p.callstackMore(c.id); c.p.lspRequest(c.id, .callstack, ""); } }; diff --git a/src/colors.zig b/src/colors.zig index dd0d8938..28136975 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -840,7 +840,7 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo @memcpy(settled[0..request.path.len], request.path); _ = p.theme_file_loaded.set(settled[0..request.path.len]); invalidateThemeDependentRasters(p); - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = pardes.memory.limits.scratch_kept }); p.sync(); return true; } diff --git a/src/config.zig b/src/config.zig index a92aabb6..5251b1e5 100644 --- a/src/config.zig +++ b/src/config.zig @@ -1230,27 +1230,12 @@ pub const Runtime = struct { if (!state.shell.requested.set(value)) return false; state.shell.pending = true; }, - .tagline_size => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const percent = std.fmt.parseInt(u16, text, 10) catch return false; - if (percent < tagline_percent_min or percent > tagline_percent_max) return false; - state.font.tagline_percent = @intCast(percent); - }, + .tagline_size => state.font.tagline_percent = @intCast(number(u16, argument, " \t\r\n", tagline_percent_min, tagline_percent_max) orelse return false), .window_opacity => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.window_opacity = percent; + state.window_opacity = number(u8, argument, " \t\r\n", 0, 100) orelse return false; state.window_opacity_pending = true; }, - .window_blur => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.window_blur = percent; - }, + .window_blur => state.window_blur = number(u8, argument, " \t\r\n", 0, 100) orelse return false, // Bare, it returns to the default directory. Else an absolute or // `~` path, to a directory there or to be made, that may be // written: a Dump there could never be, refused now. @@ -1264,10 +1249,7 @@ pub const Runtime = struct { if (!state.dump_dir.set(text)) return false; }, .message_ms => |which| { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const ms = std.fmt.parseInt(u16, text, 10) catch return false; - if (ms > message_ms_max) return false; + const ms = number(u16, argument, " \t\r\n", 0, message_ms_max) orelse return false; switch (which) { inline else => |w| @field(state, "message_" ++ @tagName(w) ++ "_ms") = ms, } @@ -1330,30 +1312,10 @@ pub const Runtime = struct { std.meta.stringToEnum(LiftStyle, text) orelse return false; }, .motion => state.motion = stepped(animation.Motion.Flavour, state.motion, argument) orelse return false, - .inactive_dim => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n%"); - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.inactive_dim = percent; - }, - .grip_width => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n%"); - const percent = std.fmt.parseInt(u16, text, 10) catch return false; - if (percent < 50 or percent > 300) return false; - state.grip_width = percent; - }, - .callstack_depth => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const depth = std.fmt.parseInt(u8, text, 10) catch return false; - if (depth < 1 or depth > @import("lsp/lsp.zig").callstack_max_depth) return false; - state.callstack_depth = depth; - }, - .tab => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const width = std.fmt.parseInt(u16, text, 10) catch return false; - if (width < 1 or width > 16) return false; - state.tab = width; - }, + .inactive_dim => state.inactive_dim = number(u8, argument, " \t\r\n%", 0, 100) orelse return false, + .grip_width => state.grip_width = number(u16, argument, " \t\r\n%", 50, 300) orelse return false, + .callstack_depth => state.callstack_depth = number(u8, argument, " \t\r\n", 1, @import("lsp/lsp.zig").callstack_max_depth) orelse return false, + .tab => state.tab = number(u16, argument, " \t\r\n", 1, 16) orelse return false, .theme, .font => return false, } return true; @@ -1411,6 +1373,16 @@ pub const Runtime = struct { return all[(at + 1) % all.len]; } + /// A setting's number: digits only (parseInt alone takes a sign and `_`), + /// trimmed of `trim`, within lo..hi. + fn number(comptime T: type, argument: ?[]const u8, trim: []const u8, lo: T, hi: T) ?T { + const text = std.mem.trim(u8, argument orelse return null, trim); + if (text.len == 0) return null; + for (text) |byte| if (!std.ascii.isDigit(byte)) return null; + const n = std.fmt.parseInt(T, text, 10) catch return null; + return if (n < lo or n > hi) null else n; + } + /// What `on`, `off` or nothing after a switch word asks for: null flips /// it, as a bare tagline word does. fn switchedTo(argument: ?[]const u8) error{NotOnOrOff}!?bool { @@ -2523,7 +2495,7 @@ test "CallstackDepth is bounded and keeps the last valid runtime limit" { try std.testing.expect(Runtime.apply(&state, Runtime.find("CallstackDepth").?, value)); try std.testing.expectEqual(try std.fmt.parseInt(u8, value, 10), state.callstack_depth); } - for ([_][]const u8{ "0", "65", "256", "-1", "eight", "" }) |value| { + for ([_][]const u8{ "0", "65", "256", "-1", "+8", "1_6", "eight", "" }) |value| { try std.testing.expect(!Runtime.apply(&state, Runtime.find("CallstackDepth").?, value)); try std.testing.expectEqual(@as(u8, 64), state.callstack_depth); } diff --git a/src/crash.zig b/src/crash.zig index 34dc1b3d..a432fb87 100644 --- a/src/crash.zig +++ b/src/crash.zig @@ -34,6 +34,9 @@ pub const name = "crashes"; /// A panic handler is the one caller that cannot check whether its input is /// still alive, so it does not borrow. var dir_buf: [1024]u8 = undefined; + +/// The crash file's bound (see `record`). +const max_log_bytes = 256 * 1024; var dir_len: usize = 0; /// Called where the launcher sets `Options.config_dir`. Ignores a path too long @@ -109,6 +112,9 @@ pub fn record(msg: []const u8) void { }, @as(std.c.mode_t, 0o600)); if (fd < 0) return; defer _ = std.c.close(fd); + // Bounded: a file past `max_log_bytes` starts over, so it keeps the + // newest records rather than every crash since it was first made. + if (std.c.lseek(fd, 0, std.c.SEEK.END) > max_log_bytes) _ = std.c.ftruncate(fd, 0); var w: std.Io.Writer = .fixed(&scratch); diff --git a/src/detached/server.zig b/src/detached/server.zig index d6a1f553..6c8d4352 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -107,17 +107,19 @@ const Mailbox = struct { status: ?[]u8 = null, }; - mutex: std.atomic.Mutex = .unlocked, + /// Taken by the workers and the loop; `io` is the session's (initAsync). + mutex: std.Io.Mutex = .init, + io: std.Io = undefined, batch: Batch = .{}, wake: [2]c_int = .{ -1, -1 }, fn post(box: *Mailbox, completion: Completion) void { - while (!box.mutex.tryLock()) std.atomic.spinLoopHint(); + box.mutex.lockUncancelable(box.io); // Tasks retain their slot until the owner consumes their one completion. std.debug.assert(box.batch.len < capacity); box.batch.items[box.batch.len] = completion; box.batch.len += 1; - box.mutex.unlock(); + box.mutex.unlock(box.io); box.signal(); } @@ -130,8 +132,8 @@ const Mailbox = struct { fn take(box: *Mailbox) Batch { var bytes: [128]u8 = undefined; while (libc.recv(box.wake[0], &bytes, bytes.len, 0) > 0) {} - while (!box.mutex.tryLock()) std.atomic.spinLoopHint(); - defer box.mutex.unlock(); + box.mutex.lockUncancelable(box.io); + defer box.mutex.unlock(box.io); const batch = box.batch; box.batch.len = 0; box.batch.status = null; @@ -184,6 +186,7 @@ pub const Session = struct { accept_paused_ms: i64 = 0, pub fn initAsync(s: *Session) !void { + s.mailbox.io = s.io; var pair: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &pair) != 0) return error.SocketFailed; errdefer for (pair) |fd| { @@ -410,7 +413,7 @@ pub const Session = struct { s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } }); return s.core.reportError(request.pane, "lsp", err); }; - const future = s.io.concurrent(lspWorker, .{ s.worker_gpa, job, &s.mailbox }) catch |err| { + const future = s.io.concurrent(lspWorker, .{ s.io, s.worker_gpa, job, &s.mailbox }) catch |err| { job.free(s.worker_gpa); s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } }); return s.core.reportError(request.pane, "lsp", err); @@ -418,8 +421,8 @@ pub const Session = struct { s.lsp_task = .{ .id = request.id, .future = future }; } - fn lspWorker(gpa: std.mem.Allocator, job: *host_io.Lsp.Job, box: *Mailbox) anyerror!void { - host_io.Lsp.work(gpa, job, box, deliverLspRows); + fn lspWorker(io: std.Io, gpa: std.mem.Allocator, job: *host_io.Lsp.Job, box: *Mailbox) anyerror!void { + host_io.Lsp.work(io, gpa, job, box, deliverLspRows); } fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -430,10 +433,10 @@ pub const Session = struct { fn lspStatus(ctx: ?*anyopaque, text: []const u8) void { const s = of(ctx); const copy = s.worker_gpa.dupe(u8, text) catch return; - while (!s.mailbox.mutex.tryLock()) std.atomic.spinLoopHint(); + s.mailbox.mutex.lockUncancelable(s.io); if (s.mailbox.batch.status) |old| s.worker_gpa.free(old); s.mailbox.batch.status = copy; - s.mailbox.mutex.unlock(); + s.mailbox.mutex.unlock(s.io); s.mailbox.signal(); } @@ -529,7 +532,8 @@ pub const Session = struct { if (pane >= s.ptys.len) return; const pt = &s.ptys[pane]; if (pt.fd < 0) return; - if (pt.out.items.len > pty_backlog) { + // The bound holds with this write in: queued and new together. + if (pt.out.items.len + bytes.len > pty_backlog) { var mbuf: [256]u8 = undefined; const text = std.fmt.bufPrint( &mbuf, @@ -1145,6 +1149,9 @@ pub const Session = struct { s.queue(c, bytes); } + /// A client's queued output is at most `out_backlog + wire.max_payload`: + /// past the backlog it is closed, and one frame lands on top of it first + /// (a frame bigger than the backlog must still go out whole). fn queue(s: *Session, c: *Client, bytes: []const u8) void { if (c.out.items.len > out_backlog) return s.close(c, .backlog); s.account(); diff --git a/src/dump.zig b/src/dump.zig index 76a6de85..67934e0a 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -394,17 +394,6 @@ test "oversized recognized output argument is rejected before restore" { ); } -pub fn writeFile(io: std.Io, gpa: std.mem.Allocator, path: []const u8, state: State) !void { - try validate(state); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer); - - var file = try std.Io.Dir.createFileAbsolute(io, path, .{}); - defer file.close(io); - try file.writeStreamingAll(io, out.written()); -} - pub const Parsed = struct { value: State, arena: std.heap.ArenaAllocator, diff --git a/src/edit.zig b/src/edit.zig index 466b5cdb..55365692 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -119,7 +119,15 @@ pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) voi for (panes.terminal.encodePaste(pane, cp)) |part| if (part.len > 0) p.emitWrite(id, part); } -pub fn applyPaste(p: *Pardes, bytes: []const u8) void { +pub fn applyPaste(p: *Pardes, whole: []const u8) void { + // Every shell's paste comes through here, bounded: what is past the + // limit is left out, at a character's start, and said. + const limit = @import("memory.zig").limits.max_paste_bytes; + const bytes = if (whole.len > limit) whole[0..modal.graphemeStart(whole, limit)] else whole; + if (whole.len > limit) { + var said: [96]u8 = undefined; + p.setMessage(p.active, std.fmt.bufPrint(&said, "paste cut at its limit, {d} KiB: the rest left out", .{limit / 1024}) catch "paste cut at its limit"); + } // A prompt answering for a header takes the paste, as it takes keys. const asking = if (p.panes[p.active]) |active| active.prompt != .none else false; if (!asking) if (tagline.focusedHeader(p)) |t| { @@ -466,8 +474,10 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { const eb = editText(p, t, b.lo_row, b.hi_row, -1) orelse return null; const r: usize = @intCast(@max(0, b.hi_row - eb.row0)); - if (r + 1 < modal.lineCount(eb.text)) return eb; - if (b.hi_col < @as(i32, @intCast(modal.lineSlice(eb.text, r).len))) return eb; + // A file's own line count and line, from its index. + const lines = if (indexedLine(p, t, eb.text, 0) != null) panes.File.nlines(p.gpa, &t.pane().?.file.?) else modal.lineCount(eb.text); + if (r + 1 < lines) return eb; + if (b.hi_col < @as(i32, @intCast(lineAt(p, t, eb.text, r).line.len))) return eb; return editText(p, t, b.lo_row, b.hi_row + 1, -1); } @@ -476,6 +486,47 @@ pub fn setEditText(p: *Pardes, t: *Text, new: []u8) void { setEditTextEnd(p, t, new, null); } +const LineAt = struct { start: usize, line: []const u8 }; + +/// `text`'s line count: the file's index when `text` is the pane's file. +fn lineCountOf(p: *Pardes, t: *Text, text: []const u8) usize { + if (indexedLine(p, t, text, 0) != null) return panes.File.nlines(p.gpa, &t.pane().?.file.?); + return modal.cursorLineCount(text); +} + +/// The row offset `off` is on: a search of the file's index when `text` is +/// the pane's file, else the newlines before it counted (modal.lineAtOffset). +fn rowOf(p: *Pardes, t: *Text, text: []const u8, off: usize) usize { + if (indexedLine(p, t, text, 0) != null) { + const index = panes.File.lineIndex(p.gpa, &t.pane().?.file.?) catch return modal.lineAtOffset(text, off); + return std.sort.upperBound(usize, index, @min(off, text.len), struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order) -| 1; + } + return modal.lineAtOffset(text, off); +} + +/// Line `row` of `text` and where it starts: through the file's line index +/// when `text` is the pane's file (a lookup), else counted from the top. +/// Finding line 94000 by counting was most of a keystroke in a 7 MB file. +fn lineAt(p: *Pardes, t: *Text, text: []const u8, row: usize) LineAt { + return indexedLine(p, t, text, row) orelse .{ .start = modal.lineStartOffset(text, row), .line = modal.lineSlice(text, row) }; +} + +/// lineAt's lookup, null when `text` is not the pane's file or `row` is past its last line. +fn indexedLine(p: *Pardes, t: *Text, text: []const u8, row: usize) ?LineAt { + if (t.what != .body) return null; + const pane = t.pane() orelse return null; + const f = if (pane.file) |*f| f else return null; + if (f.content.ptr != text.ptr or f.content.len != text.len) return null; + if (row >= panes.File.nlines(p.gpa, f)) return null; + const start = @min(panes.File.lineStart(p.gpa, f, row), text.len); + const end = std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len; + return .{ .start = start, .line = text[start..end] }; +} + /// Where text `s` put in at `c` ends: `g.`'s place after typing it. fn insertedEnd(c: modal.Cursor, s: []const u8) modal.Cursor { const nl = std.mem.lastIndexOfScalar(u8, s, '\n') orelse return .{ .row = c.row, .col = c.col + s.len }; @@ -486,6 +537,13 @@ fn insertedEnd(c: modal.Cursor, s: []const u8) modal.Cursor { /// rows) when the caller knows it, as typing does: then nothing scans the /// whole text to find it. Null, it is found by comparing the texts. pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) void { + setEditTextSpan(p, t, new, known_end, null); +} + +/// `setEditTextEnd` with what a file's splice left alone at either end, when +/// the caller knows it (typing): the line index is then not found again by +/// comparing the whole old and new texts, which a keystroke in a 7 MB file did. +fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, span: ?panes.File.Span) void { if (t.what == .tag) { // A tag is edited as it is shown, but only what follows its // prefix is its own: an edit that changed the prefix is refused. @@ -511,16 +569,13 @@ pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) const pane = t.pane() orelse return retireEditText(p, new); // what changed ended where the texts agree again from their ends const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 }; - const end = known_end orelse found: { - // ponytail: O(file), for the edits that do not say where they ended - // (paste, a pipe, s): typing passes its end and never comes here. - const front = std.mem.indexOfDiff(u8, old, new) orelse @min(old.len, new.len); - var back: usize = 0; - while (back < @min(old.len, new.len) - front and old[old.len - 1 - back] == new[new.len - 1 - back]) back += 1; - break :found modal.positionAt(new, new.len - back); - }; + // ponytail: O(file), for the edits that do not say what they changed + // (paste, a pipe, d, s): compared once, block by block, here; the same + // span then spares the line index a second comparison. + const found = span orelse if (known_end == null or pane.file != null) panes.File.spanOf(old, new) else null; + const end = known_end orelse modal.positionAt(new, new.len - found.?.tail); t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; - if (pane.file) |*f| return panes.File.setContent(p, f, new); + if (pane.file) |*f| return panes.File.setContentSpan(p, f, new, found); panes.terminal.setEditText(p, pane, new); } @@ -815,8 +870,10 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { const text = eb.text; const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }; if (key.text.len > 0 and !key.ctrl and !key.alt) { - const new = modal.insertAt(p.gpa, text, c, key.text) catch return; - setEditTextEnd(p, t, new, insertedEnd(c, key.text)); + // insertAt's offset (col clamped to the line), the line found once. + const at = if (indexedLine(p, t, text, c.row)) |l| l.start + @min(c.col, l.line.len) else modal.insertOffset(text, c); + const new = modal.spliceAlloc(p.gpa, text, at, at, key.text) catch return; + setEditTextSpan(p, t, new, insertedEnd(c, key.text), .{ .head = at, .tail = text.len - at }); for (key.text) |ch| { if (ch == '\n') { t.cur_row += 1; @@ -918,7 +975,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { }, Key.backspace => { if (t.cur_col > 0) { - const line = modal.lineSlice(text, c.row); + const found = lineAt(p, t, text, c.row); + const line = found.line; var prev = modal.prevGrapheme(line, c.col); // in leading blanks, back to the previous indent stop (helix // dedent): a whole unit when on one, else the part past it @@ -931,8 +989,12 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { prev = c.col; while (drop > 0 and prev > 0 and line[prev - 1] == ' ') : (drop -= 1) prev -= 1; } - const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = prev }, c) catch return; - setEditTextEnd(p, t, new, .{ .row = c.row, .col = prev }); + // deleteSpan's splice, the line found once. + const s = found.start + @min(prev, line.len); + const e = found.start + @min(c.col, line.len); + const new = if (e > s) modal.spliceAlloc(p.gpa, text, s, e, "") catch return else p.gpa.dupe(u8, text) catch return; + const span: panes.File.Span = if (e > s) .{ .head = s, .tail = text.len - e } else .{ .head = text.len, .tail = 0 }; + setEditTextSpan(p, t, new, .{ .row = c.row, .col = prev }, span); t.cur_col = @intCast(prev); t.cur_pinned = true; t.show(); @@ -1479,26 +1541,33 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) void { const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); - const nlines = modal.cursorLineCount(text); + // Lines, their count and rows from the file's index when it has one: + // counted from the top, a J in a 7 MB file was 8 ms. + const nlines = lineCountOf(p, t, text); const arena = p.scratch.allocator(); - const chs = arena.alloc(TextChange, nlines) catch return; - var chs_len: usize = 0; + var changes: std.ArrayList(TextChange) = .empty; var next: usize = 0; // lines below this one are joined already for (rs[0..got.n]) |r| { - const span = Text.rangeLineSpan(text, r); + // Text.rangeLineSpan, through rowOf + const lo = @min(r.anchor, r.head); + const hi = @max(r.anchor, r.head); + const span = .{ .start = rowOf(p, t, text, lo), .end = rowOf(p, t, text, if (lo == hi) hi else @max(modal.prevGrapheme(text, hi), lo)) }; var end = span.end; if (span.start == end) end = @min(end + 1, nlines - 1); var l = @max(span.start, next); while (l < end) : (l += 1) { - const from = modal.lineEndOffset(text, l); - var to = if (l + 1 >= nlines) text.len else modal.lineStartOffset(text, l + 1); + const here = lineAt(p, t, text, l); + const from = here.start + here.line.len; + var to = if (l + 1 >= nlines) text.len else lineAt(p, t, text, l + 1).start; while (to < text.len and (text[to] == ' ' or text[to] == '\t')) to += 1; - const sep: []const u8 = if (to == modal.lineEndOffset(text, @min(l + 1, nlines - 1))) "" else " "; - chs[chs_len] = .{ .from = from, .to = to, .ins = sep }; - chs_len += 1; + const last = lineAt(p, t, text, @min(l + 1, nlines - 1)); + const sep: []const u8 = if (to == last.start + last.line.len) "" else " "; + changes.append(arena, .{ .from = from, .to = to, .ins = sep }) catch return; } next = @max(next, end); } + const chs = changes.items; + const chs_len = chs.len; if (chs_len == 0) return; pushUndo(p, t); const new = applyChanges(p, text, chs[0..chs_len]) catch return; @@ -2459,3 +2528,72 @@ test "a paste into a terminal is xterm's: bracketed when the program asked, cont p.update(.{ .paste = "x\x1b[201~y\n" }); try std.testing.expectEqualStrings("\x1b[200~x [201~y\n\x1b[201~", try take(p, &out)); } + +test "a paste past the limit is cut at it, and says so" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile(""); + pane.body.mode = .insert; + const limit = @import("memory.zig").limits.max_paste_bytes; + const big = try gpa.alloc(u8, limit + 100); + defer gpa.free(big); + @memset(big, 'x'); + applyPaste(p, big); + try std.testing.expect(pane.file.?.content.len <= limit); + try std.testing.expect(pane.file.?.content.len > 0); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "paste cut") != null); +} + +test "typing and backspace through the line index keep the text and the index as a rebuild has them" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("one\n two\n\nthree four\n"); + pane.body.mode = .insert; + var prng: std.Random.DefaultPrng = .init(11); + const random = prng.random(); + for (0..300) |_| { + _ = panes.File.lineIndex(gpa, &pane.file.?) catch unreachable; + const f = &pane.file.?; + const row = random.uintLessThan(usize, panes.File.nlines(gpa, f)); + const line = modal.lineSlice(f.content, row); + pane.body.cur_row = @intCast(row); + pane.body.cur_col = @intCast(random.uintLessThan(usize, line.len + 1)); + pane.body.cur_pinned = true; + if (random.boolean()) { + insertKey(p, &pane.body, .{ .cp = 'x', .text = "x" }); + } else { + insertKey(p, &pane.body, .{ .cp = Key.backspace }); + } + // the index the edits kept, against one built from the text + const kept = try gpa.dupe(usize, try panes.File.lineIndex(gpa, &pane.file.?)); + defer gpa.free(kept); + gpa.free(pane.file.?.line_starts); + pane.file.?.line_starts = &.{}; + try std.testing.expectEqualSlices(usize, try panes.File.lineIndex(gpa, &pane.file.?), kept); + } +} + +test "J joins a line with the next, its indent dropped, a space between unless the next is empty" { + const gpa = std.testing.allocator; + const cases = [_]struct { text: []const u8, row: i32, rows: i32 = 0, want: []const u8 }{ + .{ .text = "a\n b\nc\n", .row = 0, .want = "a b\nc\n" }, + .{ .text = "a\n\nc\n", .row = 0, .want = "a\nc\n" }, + .{ .text = "a\nb", .row = 1, .want = "a\nb" }, + .{ .text = "one\n\ttwo\nthree\nfour\n", .row = 0, .rows = 2, .want = "one two three\nfour\n" }, + }; + for (cases) |case| { + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile(case.text); + pane.body.mode = .normal; + pane.body.cur_row = case.row; + pane.body.cur_col = 0; + if (case.rows > 0) pane.body.vsel = .{ .active = true, .row = case.row + case.rows, .col = 0, .explicit = true }; + normalJoin(p, &pane.body, false); + try std.testing.expectEqualStrings(case.want, pane.file.?.content); + } +} diff --git a/src/exec.zig b/src/exec.zig index d03a4a48..c9f304b0 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -913,6 +913,12 @@ pub fn commandDone(p: *Pardes, id: usize, status: ?u8) void { pane.repl = null; pane.command_status = status; pane.body.mode = .normal; + // Look's `git show`: its output went to a +Pager, the +Diff now; only a + // failure is worth the pane. + if (pane.command_pages) { + pane.command_pages = false; + if (status == 0) return p.removePane(id, null) catch {}; + } var buf: [16]u8 = undefined; const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch "?" else "?"; var said: [32]u8 = undefined; diff --git a/src/fs.zig b/src/fs.zig index 061d4225..032ab9c0 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1087,17 +1087,17 @@ pub const platform_has_fs = !pardes.isolated and switch (pardes.platform) { const find_max_hits = 512; /// What a Find or Grep walk passed over, said under its hits: directories -/// it might not open, files read only in part, and caps it stopped at. +/// it might not open, and caps it stopped at. pub const WalkNotes = struct { skipped: usize = 0, - /// Files longer than grep_max_bytes, searched in their first part only. - partial: usize = 0, hits_cut: bool = false, + /// A pane search's matching lines it stopped at, its rows filling + /// look.search_text_output_bytes; 0 if none. + rows_cut: usize = 0, /// The cap on entries walked it stopped at, 0 if none. walk_cut: usize = 0, pub const max_hits = find_max_hits; - pub const max_file_bytes = grep_max_bytes; pub const max_files = grep_max_files; pub const max_depth = find_max_depth; @@ -1105,7 +1105,7 @@ pub const WalkNotes = struct { pub fn write(n: WalkNotes, out: []u8) usize { var w = std.Io.Writer.fixed(out); if (n.hits_cut) w.print("cut at {d} hits\n", .{max_hits}) catch {}; - if (n.partial > 0) w.print("{d} file{s} read only in part (first {d} KiB)\n", .{ n.partial, if (n.partial == 1) "" else "s", max_file_bytes / 1024 }) catch {}; + if (n.rows_cut > 0) w.print("cut at {d} lines\n", .{n.rows_cut}) catch {}; if (n.walk_cut > 0) w.print("walk cut at {d} entries\n", .{n.walk_cut}) catch {}; if (n.skipped > 0) w.print("{d} director{s} skipped: permission denied\n", .{ n.skipped, if (n.skipped == 1) "y" else "ies" }) catch {}; return w.buffered().len; @@ -1124,7 +1124,8 @@ pub const WalkNotes = struct { }; const find_max_depth = 16; const find_max_steps = 100_000; -pub const search_max_output_bytes = pardes.MAX_PANES * find_max_hits * (4096 + 320); +/// One root's Find or Grep rows at most: its hits, each a path and a line. +pub const search_root_output_bytes = find_max_hits * (4096 + 320); const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", @@ -1194,9 +1195,10 @@ const grep_max_files = 20_000; const GrepResult = struct { bytes: usize, hits: usize }; -fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize) GrepResult { +/// `text` starts at line `first_line` + 1 of its file. +fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize, first_line: usize) GrepResult { var result: GrepResult = .{ .bytes = 0, .hits = 0 }; - var line: usize = 0; + var line: usize = first_line; var it = std.mem.splitScalar(u8, text, '\n'); while (it.next()) |raw| { line += 1; @@ -1220,7 +1222,7 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b if (!platform_has_fs) { for (sources) |s| { if (hits >= find_max_hits or written == out.len) break; - const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits); + const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits, 0); hits += result.hits; written += result.bytes; } @@ -1276,30 +1278,39 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{path}, 0) catch return error.PathTooLong; const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NONBLOCK = true }); if (fd < 0) continue; + defer _ = libc.close(fd); + // The whole file, a buffer at a time: each searched through its last + // whole line, the rest carried into the next. + const shown = lsp.rel(home, path); var len: usize = 0; - var readable = true; - while (len < buf.len) { - const n = libc.read(fd, buf[len..].ptr, buf.len - len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - readable = false; - break; + var lines_before: usize = 0; + var first = true; + file: while (true) { + var eof = false; + while (len < buf.len) { + const n = libc.read(fd, buf[len..].ptr, buf.len - len); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + break :file; + } + if (n == 0) { + eof = true; + break; + } + len += @intCast(n); } - if (n == 0) break; - len += @intCast(n); + if (first and std.mem.indexOfScalar(u8, buf[0..@min(len, 1024)], 0) != null) break; + first = false; + // A line longer than the buffer is searched in buffer-sized parts. + const end = if (eof) len else if (std.mem.lastIndexOfScalar(u8, buf[0..len], '\n')) |nl| nl + 1 else len; + const result = grepText(shown, buf[0..end], pat, out[written..], find_max_hits - hits, lines_before); + hits += result.hits; + written += result.bytes; + if (eof or hits >= find_max_hits or written == out.len) break; + lines_before += std.mem.count(u8, buf[0..end], "\n"); + std.mem.copyForwards(u8, buf[0 .. len - end], buf[end..len]); + len -= end; } - // Read to its cap with more behind it: searched in part, and said. - var more: [1]u8 = undefined; - const longer = readable and len == buf.len and libc.read(fd, &more, 1) > 0; - _ = libc.close(fd); - if (!readable) continue; - const text = buf[0..len]; - if (std.mem.indexOfScalar(u8, text[0..@min(len, 1024)], 0) != null) continue; - if (longer) notes.partial += 1; - const shown = lsp.rel(home, path); - const result = grepText(shown, text, pat, out[written..], find_max_hits - hits); - hits += result.hits; - written += result.bytes; if (hits >= find_max_hits) notes.hits_cut = true; } return written; @@ -1366,14 +1377,14 @@ test "a directory the walk may not open is skipped and counted: Grep and Find ke try std.testing.expectEqual(@as(usize, 1), notes.skipped); } -test "Grep says when a cap hid what it might have found: a file read in part, the hits cut" { +test "Grep reads a long file to its end, and says when its hits were cut" { if (!platform_has_fs) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var base_buf: [std.fs.max_path_bytes]u8 = undefined; const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - // The match past the first 256 KiB of a long file. + // A match past the first buffer of a long file, on its own line number. const long = try gpa.alloc(u8, grep_max_bytes + 64); defer gpa.free(long); @memset(long, 'x'); @@ -1386,8 +1397,9 @@ test "Grep says when a cap hid what it might have found: a file read in part, th defer gpa.free(out); var notes: WalkNotes = .{}; var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expectEqual(@as(usize, 0), n); - try std.testing.expectEqual(@as(usize, 1), notes.partial); + var want_buf: [64]u8 = undefined; + const want = try std.fmt.bufPrint(&want_buf, "long.txt:{d}:", .{std.mem.count(u8, long, "\n")}); + try std.testing.expect(std.mem.startsWith(u8, out[0..n], want)); // More hits than the cap. var many: std.ArrayList(u8) = .empty; defer many.deinit(gpa); @@ -1398,7 +1410,7 @@ test "Grep says when a cap hid what it might have found: a file read in part, th try std.testing.expect(notes.hits_cut); var said: [256]u8 = undefined; const lines = said[0..notes.write(&said)]; - try std.testing.expectEqualStrings("cut at 512 hits\n1 file read only in part (first 256 KiB)\n", lines); + try std.testing.expectEqualStrings("cut at 512 hits\n", lines); try std.testing.expect(WalkNotes.isNote("cut at 512 hits") and WalkNotes.isNote("2 directories skipped: permission denied") and !WalkNotes.isNote("src/2 directories.txt")); } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index f9921111..9cd37b6b 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -828,18 +828,13 @@ fn emitTouchClick(t: *Touch, in: *Input, point: TouchNormPoint, button: pardes.M in.post(.{ .mouse = .{ .button = button, .kind = .release, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); } -fn normCell(norm: f32, win: f32, cell: f32) u16 { - const px = std.math.clamp(norm, 0.0, 1.0) * win; - return @intFromFloat(@max(0, @floor(px / cell))); -} - const Pty = struct { fd: c_int, pid: libc.pid_t, serial: u32, kill_at: i64 = 0, - reader: ?std.Thread = null, - stop: [2]c_int = .{ -1, -1 }, + /// Its reader, blocked in an Io read: `closePty` cancels it. + reader: ?std.Io.Future(void) = null, /// A command pane's child, watched to its exit (host_io.watchExit); /// the pty stays open until both its end of file and its exit. cmd: host_io.CommandWatch = .{}, @@ -876,31 +871,6 @@ const Msg = union(enum) { } }; -const LspWorkers = struct { - const capacity = 16; - active: std.atomic.Value(usize) = .init(0), - - fn start(workers: *LspWorkers) bool { - var count = workers.active.load(.monotonic); - while (count < capacity) - count = workers.active.cmpxchgWeak(count, count + 1, .monotonic, .monotonic) orelse return true; - return false; - } - - fn finish(workers: *LspWorkers) void { - const previous = workers.active.fetchSub(1, .release); - std.debug.assert(previous > 0); - } - - fn wait(workers: *LspWorkers) void { - var spins: u8 = 0; - while (workers.active.load(.acquire) != 0) { - spins +%= 1; - if (spins == 0) std.Thread.yield() catch {} else std.atomic.spinLoopHint(); - } - } -}; - const PipeTasks = selection_pipe.Tasks; const queue_capacity = 512; @@ -918,10 +888,13 @@ const MessageBatch = struct { const Queue = struct { gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator, - lsp_workers: *LspWorkers, + /// The query in flight; the UI thread's alone (spawnLsp, teardown). + lsp_task: ?host_io.Lsp.Task = null, sdl_wake: bool, // wake a blocking SDL_WaitEventTimeout on cross-thread push - mutex: libc.pthread_mutex_t = .{}, - space: libc.pthread_cond_t = .{}, + /// The process's Io: its terminal readers wait for space on `space`. + io: std.Io, + mutex: std.Io.Mutex = .init, + space: std.Io.Condition = .init, items: [queue_capacity]Msg = undefined, head: usize = 0, len: usize = 0, @@ -934,13 +907,11 @@ const Queue = struct { completion_len: usize = 0, fn lock(q: *Queue) void { - // unreachable failures: pthread calls on this queue's own initialised, non-recursive - // mutex and condition fail only on misuse (EINVAL, EDEADLK), never on input. - std.debug.assert(libc.pthread_mutex_lock(&q.mutex) == .SUCCESS); + q.mutex.lockUncancelable(q.io); } fn unlock(q: *Queue) void { - std.debug.assert(libc.pthread_mutex_unlock(&q.mutex) == .SUCCESS); + q.mutex.unlock(q.io); } fn wake(q: *Queue) void { @@ -973,14 +944,14 @@ const Queue = struct { }; if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1; } - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); } fn pushOutput(q: *Queue, pane: u8, gen: u32, bytes: []u8) bool { q.lock(); while (!q.closed and q.readers[pane] == gen and q.len >= output_capacity) { q.waiting += 1; - std.debug.assert(libc.pthread_cond_wait(&q.space, &q.mutex) == .SUCCESS); + q.space.waitUncancelable(q.io, &q.mutex); q.waiting -= 1; } if (q.closed or q.readers[pane] != gen) { @@ -1088,7 +1059,7 @@ const Queue = struct { @memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]); batch.len += q.completion_len; q.completion_len = 0; - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); } fn discardCompletions(q: *Queue) void { @@ -1104,7 +1075,7 @@ const Queue = struct { q.closed = true; q.files_changed = false; q.readers = @splat(null); - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); q.unlock(); q.discardCompletions(); q.lock(); @@ -1121,15 +1092,12 @@ const Queue = struct { fn deinit(q: *Queue) void { q.close(); std.debug.assert(q.waiting == 0); - std.debug.assert(libc.pthread_cond_destroy(&q.space) == .SUCCESS); - std.debug.assert(libc.pthread_mutex_destroy(&q.mutex) == .SUCCESS); } }; test "GUI completion survives a full output queue" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 7 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 7 }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ @@ -1185,8 +1153,7 @@ const PtyTests = struct { test "GUI PTY backpressure retains byte order and tail before EOF" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1220,8 +1187,7 @@ test "GUI PTY backpressure retains byte order and tail before EOF" { test "GUI PTY backpressure cancellation and close release owned producers" { const gpa = std.testing.allocator; for ([_]bool{ false, true }) |close| { - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1252,8 +1218,7 @@ test "GUI PTY backpressure cancellation and close release owned producers" { test "GUI PTY EOF reserve cannot evict terminal output" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); for (0..pardes.MAX_PANES) |pane| queue.acceptReader(@intCast(pane), 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1269,8 +1234,7 @@ 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 workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(1); @@ -1320,8 +1284,7 @@ test "GUI PTY Restore joins a real reader waiting for queue space" { var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); try dump.dumpState(core); - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; 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") } }); @@ -1365,8 +1328,7 @@ test "GUI PTY deletion joins an idle reader and retains only its owned child for const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(1); @@ -1397,8 +1359,7 @@ test "GUI PTY deletion joins an idle reader and retains only its owned child for 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 workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); const fd = file_watch.init(true); if (fd < 0) return error.WatchInitFailed; @@ -1422,8 +1383,7 @@ test "GUI completion failure survives backlog and leaves the document unchanged" pane.body.cur_col = 1; core.lspRequest(core.active, .completion, ""); const id = core.lsp_wait.?.id; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = id }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = id }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ @@ -1452,8 +1412,7 @@ test "GUI completion failure survives backlog and leaves the document unchanged" test "GUI completions retain their arrival order across LSP and pipes" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 2 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 2 }; defer queue.deinit(); queue.push(.{ .pipe = .{ .id = 1, .success = true, .outputs = &.{} } }); queue.push(.{ .lsp = .{ .id = 2, .rows = try gpa.dupe(u8, "second") } }); @@ -1469,8 +1428,7 @@ test "GUI completions retain their arrival order across LSP and pipes" { test "GUI completion reset frees queued payloads and rejects late LSP workers" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 9 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 9 }; defer queue.deinit(); queue.acceptReader(0, 1); queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "retained") } }); @@ -1523,29 +1481,22 @@ fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { q.push(.{ .lsp_status = copy }); } -fn readPtyThread(gpa: std.mem.Allocator, fd: c_int, stop: c_int, pane: u8, gen: u32, q: *Queue) void { +fn readPty(io: std.Io, gpa: std.mem.Allocator, fd: c_int, pane: u8, gen: u32, q: *Queue) void { + const pty: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; var buf: [0x10000]u8 = undefined; var failure: ?anyerror = null; while (true) { - var fds = [_]libc.pollfd{ - .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, - .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, + const n = pty.readStreaming(io, &.{&buf}) catch |err| switch (err) { + // A pty whose child has gone answers EIO: its end of file. + error.EndOfStream, error.InputOutput => break, + error.Canceled => return, + else => { + failure = err; + break; + }, }; - if (libc.poll(&fds, fds.len, -1) < 0) { - if (libc.errno(-1) == .INTR) continue; - failure = error.PollFailed; - break; - } - if (fds[0].revents != 0) return; - if (fds[1].revents == 0) continue; - const n = libc.read(fd, &buf, buf.len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - if (libc.errno(n) != .IO) failure = error.ReadFailed; - break; - } - if (n == 0) break; - const bytes = gpa.dupe(u8, buf[0..@intCast(n)]) catch |err| { + if (n == 0) continue; + const bytes = gpa.dupe(u8, buf[0..n]) catch |err| { failure = err; break; }; @@ -1566,14 +1517,9 @@ fn stopPipe() ![2]c_int { fn spawnReader(gpa: std.mem.Allocator, pt: *Pty, pane: u8, gen: u32, q: *Queue) !void { std.debug.assert(pt.reader == null and pt.fd >= 0); - const stop = try stopPipe(); - errdefer for (stop) |fd| { - _ = libc.close(fd); - }; q.acceptReader(pane, gen); errdefer q.cancelReader(pane, gen); - pt.reader = try std.Thread.spawn(.{}, readPtyThread, .{ gpa, pt.fd, stop[0], pane, gen, q }); - pt.stop = stop; + pt.reader = try q.io.concurrent(readPty, .{ q.io, gpa, pt.fd, pane, gen, q }); } fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { @@ -1592,9 +1538,8 @@ fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { } } -fn lspThread(lsp_allocator: std.mem.Allocator, workers: *LspWorkers, job: *host_io.Lsp.Job, q: *Queue) void { - defer workers.finish(); - host_io.Lsp.work(lsp_allocator, job, q, pushLspRows); +fn lspThread(io: std.Io, lsp_allocator: std.mem.Allocator, job: *host_io.Lsp.Job, q: *Queue) anyerror!void { + host_io.Lsp.work(io, lsp_allocator, job, q, pushLspRows); } fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -1602,107 +1547,52 @@ fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { q.push(.{ .lsp = .{ .id = id, .rows = rows } }); } -fn spawnLsp(core: *pardes.Pardes, q: *Queue, e: host_io.Lsp.Request) void { +fn spawnLsp(core: *pardes.Pardes, io: std.Io, q: *Queue, e: host_io.Lsp.Request) void { const lsp_allocator = q.lsp_allocator; q.lock(); q.lsp_id = e.id; q.discardLsp(); q.unlock(); - if (!q.lsp_workers.start()) { - core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); - return core.reportError(e.pane, "lsp", error.WorkersBusy); + // Its waits are cancelation points: this join is short, and what it + // still delivers carries an id the queue now rejects. + if (q.lsp_task) |*old| { + old.future.cancel(io) catch {}; + q.lsp_task = null; } const job = host_io.Lsp.snapshot(lsp_allocator, core, e) catch |err| { - q.lsp_workers.finish(); core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); return core.reportError(e.pane, "lsp", err); }; - const th = std.Thread.spawn(.{}, lspThread, .{ lsp_allocator, q.lsp_workers, job, q }) catch |err| { - q.lsp_workers.finish(); + const future = io.concurrent(lspThread, .{ io, lsp_allocator, job, q }) catch |err| { job.free(lsp_allocator); core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); return core.reportError(e.pane, "lsp", err); }; - th.detach(); + q.lsp_task = .{ .id = e.id, .future = future }; } -test "GUI LSP worker limit rejects before allocation and recovers after owned workers exit" { +test "GUI LSP query answers, and a newer one cancels it" { const gpa = std.testing.allocator; + const io = std.testing.io; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - const pane = try core.setTestFile("abc"); - pane.body.cur_col = 1; - var workers: LspWorkers = .{}; - var gate: std.Io.Event = .unset; - var threads: [LspWorkers.capacity]?std.Thread = @splat(null); - defer { - gate.set(std.testing.io); - for (threads) |thread| if (thread) |owned| owned.join(); - workers.wait(); - } - for (&threads) |*thread| { - try std.testing.expect(workers.start()); - thread.* = std.Thread.spawn(.{}, struct { - fn run(active: *LspWorkers, ready: *std.Io.Event) void { - defer active.finish(); - ready.waitUncancelable(std.testing.io); - } - }.run, .{ &workers, &gate }) catch |err| { - workers.finish(); - return err; - }; - } - try std.testing.expectEqual(@as(usize, LspWorkers.capacity), workers.active.load(.monotonic)); - try std.testing.expect(!workers.start()); - var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = failing.allocator(), .lsp_workers = &workers, .sdl_wake = false }; + _ = try core.setTestFile("abc"); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); - core.lspRequest(core.active, .completion, ""); - const rejected = core.lsp_wait.?.id; - queue.lsp_id = rejected -% 1; - queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "obsolete queued result") } }); - spawnLsp(core, &queue, .{ - .id = rejected, - .kind = .completion, - .pane = @intCast(core.active), - .offset = 1, - .arg = "", - }); - try std.testing.expect(core.lsp_wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "workers busy") != null); - try std.testing.expectEqual(@as(usize, 0), failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(rejected, queue.lsp_id.?); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - queue.push(.{ .lsp = .{ .id = rejected -% 1, .rows = try gpa.dupe(u8, "obsolete late result") } }); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - try std.testing.expectEqual(@as(usize, LspWorkers.capacity), workers.active.load(.monotonic)); - - gate.set(std.testing.io); - workers.wait(); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); - queue.lsp_allocator = gpa; - core.lspRequest(core.active, .status, ""); - const accepted = core.lsp_wait.?.id; - spawnLsp(core, &queue, .{ - .id = accepted, - .kind = .status, - .pane = @intCast(core.active), - .offset = 0, - .arg = "", - }); - workers.wait(); + for (0..2) |_| { + core.lspRequest(core.active, .status, ""); + spawnLsp(core, io, &queue, .{ .id = core.lsp_wait.?.id, .kind = .status, .pane = @intCast(core.active), .offset = 0, .arg = "" }); + } + const last = core.lsp_wait.?.id; + try queue.lsp_task.?.future.await(io); + queue.lsp_task = null; 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.expectEqual(accepted, batch.items[0].lsp.id); + try std.testing.expectEqual(last, batch.items[0].lsp.id); try std.testing.expect(batch.items[0].lsp.rows != null); - core.update(.{ .lsp_resp = .{ .id = accepted, .rows = batch.items[0].lsp.rows } }); + core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } }); try std.testing.expect(core.lsp_wait == null); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); - try std.testing.expectEqualStrings("abc", pane.file.?.content); } fn pipeThread(io: std.Io, gpa: std.mem.Allocator, job: *selection_pipe.Job, q: *Queue) anyerror!void { @@ -1748,11 +1638,10 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), }); - var workers: LspWorkers = .{}; var queue: Queue = .{ + .io = std.testing.io, .gpa = gpa, .lsp_allocator = failing.allocator(), - .lsp_workers = &workers, .sdl_wake = false, }; defer queue.deinit(); @@ -1768,7 +1657,7 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { if (failure == 0) { queue.lsp_id = req.id -% 1; queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "old queued result") } }); - spawnLsp(core, &queue, req); + spawnLsp(core, std.testing.io, &queue, 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") } }); @@ -1791,7 +1680,7 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { spawnPipe(core, failing_io, failing.allocator(), &queue, &tasks, pipe_id); try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); + 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); } @@ -2071,22 +1960,6 @@ fn fixedCellLayout(g: *const Gui) CellLayout { return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 }; } -fn compactTaglineLayout(g: *const Gui, origin_col: f32) CellLayout { - const body_w: f32 = @floatFromInt(g.cell_w); - const tag_w: f32 = @floatFromInt(g.tagline_width); - return .{ - .w = tag_w, - .h = @floatFromInt(g.cell_h), - .x_off = origin_col * (body_w - tag_w), - .y_off = 0, - }; -} - -fn taglineLayoutForCell(g: *const Gui, col: u16) CellLayout { - // Canonical tag cells are physical grips; text is drawn by TagLayer. - return compactTaglineLayout(g, @floatFromInt(col)); -} - const boxContains = pardes.animation.Box.contains; /// What one tier draws, or one track in tiers 2 and 3 (docs/render-pipeline.md @@ -2663,15 +2536,14 @@ fn localSession( var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, - .lsp_workers = &lsp_workers, .sdl_wake = true, }; defer { - lsp_workers.wait(); + if (queue.lsp_task) |*task| task.future.cancel(io) catch {}; queue.deinit(); } var pipe_tasks: PipeTasks = .{}; @@ -3035,15 +2907,14 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, - .lsp_workers = &lsp_workers, .sdl_wake = false, }; defer { - lsp_workers.wait(); + if (queue.lsp_task) |*task| task.future.cancel(io) catch {}; queue.deinit(); } var pipe_tasks: PipeTasks = .{}; @@ -4195,13 +4066,12 @@ const Shell = struct { fn closePty(s: *Shell, pane: u8) void { const pt = if (s.ptys[pane]) |*pt| pt else return; if (pt.fd < 0) return; + // Out of the queue first, which lets go a reader waiting for room + // in it; then its read is canceled (or, at its end, it is joined). s.queue.cancelReader(pane, s.gens[pane]); - if (pt.reader) |thread| { - _ = host_io.writeFd(pt.stop[1], "x"); - thread.join(); + if (pt.reader) |*reader| { + reader.cancel(s.queue.io); // the Io it was started on (spawnReader) pt.reader = null; - for (pt.stop) |fd| _ = libc.close(fd); - pt.stop = .{ -1, -1 }; } _ = libc.close(pt.fd); pt.fd = -1; @@ -4848,11 +4718,10 @@ test "the headless grid host round-trips a yank back as a paste" { var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, - .lsp_workers = &lsp_workers, .sdl_wake = false, }; defer queue.deinit(); @@ -4933,7 +4802,7 @@ fn openLink(ctx: ?*anyopaque, url: []const u8) void { fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { const s = shellOf(ctx); - if (s.threads_ok) return spawnLsp(s.core, s.queue, req); + if (s.threads_ok) return spawnLsp(s.core, s.io, s.queue, req); s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); } @@ -5198,6 +5067,12 @@ const Glide = struct { below: []pardes.Cell = &.{}, nabove: u16 = 0, nbelow: u16 = 0, + /// The core's lines a scroll moved, not yet measured; and what the + /// glide in flight has moved, in lines and in the picture's rows. A + /// wrapped line is several rows, and the thumb counts lines. + pending_lines: f32 = 0, + lines_moved: f32 = 0, + rows_moved: f32 = 0, /// The Motion flavour the last loop step read. motion: pardes.animation.Motion = .{}, @@ -5211,6 +5086,16 @@ const Glide = struct { glide.pending = false; glide.nabove = 0; glide.nbelow = 0; + glide.pending_lines = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; + } + + /// The glide's lag in the core's lines: its rows, scaled by the lines + /// they carried. + fn lagLines(glide: *const Glide) f32 { + if (glide.rows_moved == 0) return glide.offset; + return glide.offset * glide.lines_moved / glide.rows_moved; } fn deinit(glide: *Glide, gpa: std.mem.Allocator) void { @@ -5270,6 +5155,9 @@ const Glide = struct { break :found kk; } else 0; if (shift == 0) return glide.stop(); + glide.rows_moved += @floatFromInt(shift); + glide.lines_moved += glide.pending_lines; + glide.pending_lines = 0; // The rows that left: past the top going down, the bottom going up. if (!glide.ensure(gpa)) return glide.stop(); const keep = if (glide.dir > 0) &glide.above else &glide.below; @@ -5326,6 +5214,8 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { glide.offset = 0; glide.nabove = 0; glide.nbelow = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; } } const notch = g.scroll_notch; @@ -5357,6 +5247,8 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { } var left = notch; var moved = false; + const first = pane.scroll(); + defer glide.pending_lines += @floatFromInt(@abs(pane.scroll() - first)); while (left != 0) { const down = left > 0; left += if (down) -1 else 1; @@ -9347,7 +9239,7 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, gr // 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.offset != 0 and g.glide.pane == rail.owner) - g.glide.offset + 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)); @@ -9983,6 +9875,12 @@ test "the scrollbar thumb moves by the pixel and follows a glide" { g.glide.pane = core.active; g.glide.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.offset = -2; + try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); } test "the rule between stacked panes stays in the tag band's slack, at any tagline size" { @@ -10581,12 +10479,11 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard return; } // Read only the rendered global row. No pane/column tags, status text or - // mouse targets are changed, and editing the workspace parks the pet. + // mouse targets are changed; editing the workspace tag leaves it be. var occupied: usize = 0; for (surface.cells[0..surface.cols], 0..) |*cell, i| { if (cellCodepoint(cell) != ' ') occupied = i + 1; } - const editing = p.header_focus and p.header_column == null; 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, @@ -10594,7 +10491,6 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard builder.win_w, band_top, @floatFromInt(g.tagline_height), - editing, ); // SDL's regular pump already wakes at least every 16 ms. Quantization in // sample keeps this independent of input, render rate and scene effects, @@ -10602,16 +10498,24 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard const pose = g.pet_state.sample(kind, c.SDL_GetTicks(), region) orelse return; const ink = overlayRgb(p.chromeTheme().tag_fg); const eye = overlayRgb(p.chromeTheme().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 "pet overlay stays beyond workspace text and vanishes while its tag is edited" { +test "pet overlay stays beyond workspace text and keeps going while its tag is edited" { std.testing.refAllDecls(pet); const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer core.deinit(); @@ -10638,10 +10542,13 @@ test "pet overlay stays beyond workspace text and vanishes while its tag is edit try std.testing.expect(x >= 20 * 8 - 0.01); try std.testing.expect(y >= 0 and y < 20); } + const before = g.pet_state; pardes.tagline.enterHeader(core, null); builder.len = 0; appendWorkspacePet(&g, core, &surface, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); + try std.testing.expect(builder.len > 0); + try std.testing.expectEqual(before.tick, g.pet_state.tick); + try std.testing.expectEqual(before.x, g.pet_state.x); } fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: pardes.FontRole) [3]u8 { diff --git a/src/gui/pet.zig b/src/gui/pet.zig index a249d70f..7a13ca91 100644 --- a/src/gui/pet.zig +++ b/src/gui/pet.zig @@ -13,8 +13,8 @@ const hop_ticks = 8; /// Only the trailing blank part of the global tag is eligible. The caller /// supplies its last occupied cell, including any wide-grapheme continuation. -pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32, editing: bool) ?Lane { - if (editing or cell_w <= 0 or band_h < height + 2) return null; +pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32) ?Lane { + if (cell_w <= 0 or band_h < height + 2) return null; const scale = @min(3, @floor((band_h - 2) / height)); const left = @as(f32, @floatFromInt(occupied + 2)) * cell_w; const right = screen_w - 2 * cell_w - width * scale; @@ -32,11 +32,10 @@ pub const State = struct { frame: u8 = 0, rng: std.Random.DefaultPrng = undefined, + /// No lane (the tag's text has filled it) hides the pet but keeps + /// where it was and what it was doing. pub fn sample(s: *State, kind: Kind, now_ms: u64, area: ?Lane) ?Pose { - const region = area orelse { - s.* = .{}; - return null; - }; + const region = area orelse return null; if (kind == .off) { s.* = .{}; return null; @@ -142,11 +141,10 @@ pub fn pixel(kind: Kind, pose: Pose, x_in: usize, y: usize) u2 { }; } -test "pet stays in trailing workspace blanks and disappears during editing" { - try std.testing.expect(lane(20, 8, 200, 0, 16, false) == null); - try std.testing.expect(lane(3, 8, 200, 0, 16, true) == null); - try std.testing.expect(lane(3, 8, 200, 0, 10, false) == null); - const region = lane(3, 8, 200, 2, 20, false).?; +test "pet stays in trailing workspace blanks, and a lost lane hides it without a reset" { + try std.testing.expect(lane(20, 8, 200, 0, 16) == null); + try std.testing.expect(lane(3, 8, 200, 0, 10) == null); + const region = lane(3, 8, 200, 2, 20).?; try std.testing.expect(region.left >= 5 * 8); var state: State = .{}; var moved = false; @@ -159,12 +157,15 @@ test "pet stays in trailing workspace blanks and disappears during editing" { reversed = reversed or pose.left; } try std.testing.expect(moved and reversed); + const kept = state; try std.testing.expect(state.sample(.cat, 300000, null) == null); + try std.testing.expectEqual(kept.x, state.x); + try std.testing.expectEqual(kept.tick, state.tick); try std.testing.expect(state.sample(.off, 300100, region) == null); } test "pet clock is fixed rate and sprites bounded in both directions" { - const region = lane(1, 8, 400, 0, 16, false).?; + const region = lane(1, 8, 400, 0, 16).?; var state: State = .{}; const start = state.sample(.frog, 1000, region).?; try std.testing.expectEqualDeep(start, state.sample(.frog, 1099, region).?); @@ -180,7 +181,7 @@ test "pet clock is fixed rate and sprites bounded in both directions" { } test "pet rests at random spots and the frog travels only in the air" { - const region = lane(1, 8, 800, 0, 16, false).?; + const region = lane(1, 8, 800, 0, 16).?; var state: State = .{}; var last = state.sample(.frog, 0, region).?; var rested_midway = false; @@ -195,7 +196,7 @@ test "pet rests at random spots and the frog travels only in the air" { } test "pet initial idle visibly animates without walking or leaving its tile" { - const region = lane(1, 8, 400, 0, 16, false).?; + const region = lane(1, 8, 400, 0, 16).?; for ([_]Kind{ .cat, .frog }) |kind| { var state: State = .{}; const initial = state.sample(kind, 0, region).?; diff --git a/src/host_io.zig b/src/host_io.zig index c593551b..2c736e20 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -203,11 +203,14 @@ pub const Lsp = struct { } others.deinit(gpa); } + var copied: usize = 0; for (core.panes, 0..) |slot, i| { const other = slot orelse continue; if (i == req.pane) continue; const f = other.file orelse continue; if (f.output != null) continue; + if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue; + copied += f.content.len; const local = filesystem.localPath(f.path) orelse continue; const other_path = try gpa.dupe(u8, local); const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { @@ -224,13 +227,19 @@ pub const Lsp = struct { // Null is failure; the receiver frees non-null rows with the job's allocator. pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void; - pub fn work(gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { + pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { defer job.free(gpa); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); + // The query's memory is the fixed region memory.zig reserved at + // startup: a hard bound, reused by each query in turn. + const region = pardes.memory.takeLspQuery() orelse { + deliver(ctx, job.id, null); + return; + }; + var arena: std.heap.FixedBufferAllocator = .init(region); + defer pardes.memory.giveLspQuery(arena.end_index); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); - pardes.lsp.query(gpa, arena.allocator(), .{ + pardes.lsp.query(io, gpa, arena.allocator(), .{ .kind = job.kind, .path = job.path, .source = job.source, @@ -240,6 +249,7 @@ pub const Lsp = struct { .others = job.others, .callstack_depth = job.callstack_depth, .callstack_corners = job.callstack_corners, + .budget = &arena, }, &out.writer) catch { deliver(ctx, job.id, null); return; @@ -367,7 +377,7 @@ pub const Lsp = struct { .offset = 0, .arg = "", }); - work(gpa, job, null, Sink.take); + work(std.testing.io, gpa, job, null, Sink.take); // `status` is the one kind that answers with no file and no cursor, which // is what makes it assertable here without a language server on the box. @@ -416,7 +426,7 @@ pub const Lsp = struct { .arg = "renamed", }); if (fail) failing.fail_index = failing.alloc_index; - work(failing.allocator(), job, &sink, Sink.take); + work(std.testing.io, failing.allocator(), job, &sink, Sink.take); try std.testing.expectEqual(fail, sink.failed); try std.testing.expect(core.lsp_wait == null); if (fail) { @@ -482,7 +492,7 @@ pub const Lsp = struct { defer core.deinit(); const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = @intCast(core.active), .offset = 0, .arg = "" }); var sink: Sink = .{}; - work(gpa, job, &sink, Sink.take); + work(std.testing.io, gpa, job, &sink, Sink.take); if (sink.rows) |rows| gpa.free(rows); try std.testing.expect(allocator.failed); try std.testing.expectEqual(@as(usize, 1), sink.calls); @@ -1179,7 +1189,7 @@ pub const Shell = struct { if (builtin.os.tag == .windows) return; var saved_buf: [std.fs.max_path_bytes:0]u8 = @splat(0); const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null; - defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else unsetenv("XDG_RUNTIME_DIR"); + defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR"); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -1213,7 +1223,7 @@ pub const Shell = struct { try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed); // No runtime dir: private files, one per owner, gone at teardown. - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = testUnsetenv("XDG_RUNTIME_DIR"); var d = PromptFiles.init(); var e = PromptFiles.init(); defer e.deinit(); @@ -1294,6 +1304,44 @@ pub const ChildEnv = struct { "TERM_PROGRAM=" ++ pardes.config.child_term_program, }; + /// What this editor tells its children of itself (exportPaneEnv, `$winid`), + /// kept here rather than set into this process's environment: std's Io read + /// that block at startup, and setenv/unsetenv rewrite it in place under it + /// (a spawn then scans a null inside it). `build` puts each exported one in + /// place of an inherited variable of its name; a cleared one hides it; one + /// never exported is inherited as it is. + pub const exported_names = [_][]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE", "PARDES_MOUNT", "winid" }; + var exported_state: [exported_names.len]enum { inherited, cleared, set } = @splat(.inherited); + var exported_line: [exported_names.len][pardes.memory.limits.host_path_cap + 64:0]u8 = undefined; + + /// Set (or, null, clear) what children are told for `var_name`. + pub fn exportVar(var_name: []const u8, value: ?[]const u8) void { + const i = exportedIndex(var_name).?; + const v = value orelse { + exported_state[i] = .cleared; + return; + }; + const line = std.fmt.bufPrintSentinel(&exported_line[i], "{s}={s}", .{ var_name, v }, 0) catch { + exported_state[i] = .cleared; + return; + }; + exported_state[i] = .set; + _ = line; + } + + /// What children are told for `var_name`, as `exportVar` left it; null + /// when cleared or never exported. + pub fn exported(var_name: []const u8) ?[]const u8 { + const i = exportedIndex(var_name) orelse return null; + if (exported_state[i] != .set) return null; + return std.mem.span(@as([*:0]const u8, &exported_line[i]))[var_name.len + 1 ..]; + } + + fn exportedIndex(var_name: []const u8) ?usize { + for (exported_names, 0..) |n, i| if (std.mem.eql(u8, n, var_name)) return i; + return null; + } + /// Wide enough for any real environment; `build` answers null rather than /// truncate, because a child missing half its variables is a worse bug /// than one missing TERM, and the caller then execs with `environ` intact. @@ -1318,7 +1366,8 @@ pub const ChildEnv = struct { if (std.mem.eql(u8, inherited, name(mine))) break true; } else false; if (shadowed) continue; - if (n + own.len + 1 > slots.len) return null; + if (exportedIndex(inherited)) |e| if (exported_state[e] != .inherited) continue; + if (n + own.len + exported_names.len + 1 > slots.len) return null; slots[n] = entry; n += 1; } @@ -1336,10 +1385,14 @@ pub const ChildEnv = struct { if (std.mem.eql(u8, name(entry.?), name(default))) break true; } else false; if (set) continue; - if (n + own.len + 4 > slots.len) return null; + if (n + own.len + exported_names.len + 4 > slots.len) return null; slots[n] = default; n += 1; } + for (&exported_line, exported_state) |*line, state| if (state == .set) { + slots[n] = line; + n += 1; + }; for (own) |mine| { slots[n] = mine; n += 1; @@ -1411,14 +1464,14 @@ test "the child environment replaces the launcher's terminal identity exactly on defer if (restore) |t| { _ = Shell.setenv("TERM", t.ptr, 1); } else { - _ = unsetenv("TERM"); + _ = 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 _ = unsetenv("PARDES_CHILD_ENV_PROBE"); + defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); var slots: ChildEnv.Slots = undefined; // Where the user named no pager: a terminal's shell pages into a @@ -1481,6 +1534,16 @@ test "the child environment replaces the launcher's terminal identity exactly on extern "c" fn unsetenv(name: [*:0]const u8) c_int; +/// For tests: unset `name` without compacting the environment block std +/// captured at startup (std.testing.environ and Io's spawns read it later). A +/// new variable first moves glibc's `environ` to a heap copy, which unsetenv +/// then compacts instead. Runtime code never changes this process's +/// environment (ChildEnv.exportVar). +pub fn testUnsetenv(name: [*:0]const u8) c_int { + _ = Shell.setenv("PARDES_TEST_ENVIRON_COPIED", "1", 1); + return unsetenv(name); +} + /// The environment a pane's command is given (exportPaneEnv, `$winid`, /// ChildEnv), as `NAME=value` lines in `arena`, for a command that is not a /// pane's: an Edit's filters, run from pane `serial`. @@ -1497,10 +1560,7 @@ pub fn commandEnv(arena: std.mem.Allocator, serial: u32, adopts: bool) ![]const fn exportWinid(serial: u32) void { var buf: [16]u8 = undefined; - if (serial != 0) if (std.fmt.bufPrintSentinel(&buf, "{d}", .{serial}, 0)) |text| { - if (Shell.setenv("winid", text, 1) == 0) return; - } else |_| {}; - _ = unsetenv("winid"); + ChildEnv.exportVar("winid", if (serial == 0) null else std.fmt.bufPrint(&buf, "{d}", .{serial}) catch null); } /// The longest line a command pane runs (exec.zig refuses a longer one). @@ -1587,17 +1647,18 @@ pub fn forkShell( if (helper) |path| { const c = core.?; const pn = c.panes[pane].?; - const socket = libc.getenv("PARDES_9P") orelse return error.SessionSocketRequired; + const socket = ChildEnv.exported("PARDES_9P") orelse return error.SessionSocketRequired; var command: std.Io.Writer.Allocating = .init(c.gpa); defer command.deinit(); - try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, std.mem.span(socket), &spawn.argv); + try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, socket, &spawn.argv); if (!try pardes.panes.terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; } // Built here and not after the fork: between fork and exec the child may // not call setenv, whose malloc can deadlock against a pty reader thread // that held the heap when the fork took its snapshot. var env_slots: ChildEnv.Slots = undefined; - const paging: ChildEnv.Paging = if (one_line != null) + const pages = if (core) |c| if (c.panes[pane]) |pn| pn.command_pages else false else false; + const paging: ChildEnv.Paging = if (one_line != null and !pages) .command else if (core) |c| (if (c.settings.pager == .off) .terminal_off else .terminal) else .terminal; const envp = ChildEnv.build(&env_slots, paging); @@ -1695,7 +1756,7 @@ test "a forked shell is told which terminal it is talking to" { defer if (restore) |t| { _ = Shell.setenv("TERM", t.ptr, 1); } else { - _ = unsetenv("TERM"); + _ = testUnsetenv("TERM"); }; _ = Shell.setenv("TERM", "dumb", 1); diff --git a/src/hunks.zig b/src/hunks.zig index 73c0654a..24aaf63d 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -368,21 +368,34 @@ const max_line_distance = 0.6; /// rather than aligned at a quadratic cost (delta aligns them all). const max_run = 256; const max_cells = 1 << 16; +/// Pairs one hunk compares (each a table of up to `max_cells`): past it, the +/// rest of its lines are shown unemphasised. And the scratch each pair is +/// aligned in, reused by the next: its table and the ranges it marks. +const max_pairs = 4096; +const pair_scratch_bytes = 8 << 20; /// Pair each removed line with the first added line after the last one /// paired that is near enough to it, in order, and emphasise in both the /// tokens one has and the other has not. fn inferEdits(arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !void { if (minus.len == 0 or plus.len == 0 or minus.len > max_run or plus.len > max_run) return; + const plus_tokens = try arena.alloc([]const []const u8, plus.len); + for (plus, plus_tokens) |line, *tokens| tokens.* = try tokenize(arena, line.code); + var scratch: std.heap.FixedBufferAllocator = .init(try @import("memory.zig").unfilled(arena, pair_scratch_bytes)); + var pairs: usize = 0; var plus_index: usize = 0; for (minus) |*m| { const m_tokens = try tokenize(arena, m.code); var j = plus_index; while (j < plus.len) : (j += 1) { - const p_tokens = try tokenize(arena, plus[j].code); + const p_tokens = plus_tokens[j]; if ((m_tokens.len + 1) * (p_tokens.len + 1) > max_cells) continue; - var alignment = try Alignment.init(arena, m_tokens, p_tokens); - const marks = try annotate(arena, &alignment, m.code, plus[j].code); + if (pairs == max_pairs) return; + pairs += 1; + scratch.reset(); + const pair = scratch.allocator(); + var alignment = Alignment.init(pair, m_tokens, p_tokens) catch continue; + const marks = annotate(pair, &alignment, m.code, plus[j].code) catch continue; if (marks.distance > max_line_distance) continue; for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { b.* |= syntax.diff_emph; diff --git a/src/image.zig b/src/image.zig index 8bf9de08..5797ce9e 100644 --- a/src/image.zig +++ b/src/image.zig @@ -768,7 +768,13 @@ pub fn readable(bytes: []const u8) bool { /// decode + downscale to RGBA, gpa-owned. Returns null on any failure — the /// pane then simply shows a blank body. pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?struct { rgba: []u8, w: usize, h: usize } { - if (bytes.len == 0) return null; + if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return null; + // Bounded before decoding: a few KB of PNG can name gigapixels. + var iw: c_int = 0; + var ih: c_int = 0; + var ic: c_int = 0; + if (stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), &iw, &ih, &ic) != 1) return null; + if (@as(usize, @intCast(@max(0, iw))) * @as(usize, @intCast(@max(0, ih))) > @import("memory.zig").limits.image_decode_pixels) return null; var img = zstbi.Image.loadFromMemory(bytes, 4) catch return null; // 4 = RGBA defer img.deinit(); var scaled: ?zstbi.Image = null; diff --git a/src/locations.zig b/src/locations.zig index 2828566d..1e4a20cf 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -217,6 +217,98 @@ pub fn treeContinuation(line: []const u8, buffer: []u8, max_cells: usize) []cons return out.buffered()[0..end]; } +const Resolved = struct { code: []const u8 = "", colors: []const u8 = &.{}, source_row: usize = 0 }; + +/// Each Callstack row's code (its call site's line, or a caller's header) and +/// colors, by input line. A page spans thousands of files, so they are taken +/// a file at a time: grouped by path, each file read, line-indexed and +/// analyzed once, its rows' code and colors copied out, and the file let go +/// before the next. Row by row, the cache compared the whole source each +/// time and past its 64 entries parsed it again, every lookup walked the +/// file from its top, and every source stayed in the arena to the end. +fn resolveCallstack(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, input: []const u8) ![]Resolved { + const mark = @import("lsp/lsp.zig").callstack_match; + var all: std.ArrayList([]const u8) = .empty; + var by_path: std.StringArrayHashMapUnmanaged(std.ArrayList(u32)) = .empty; + var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); + while (lines.next()) |raw| { + const line = if (std.mem.startsWith(u8, raw, mark)) raw[mark.len..] else raw; + const index: u32 = @intCast(all.items.len); + try all.append(arena, line); + const target = parseRaw(line[treePrefix(line).end..]); + if (target.at.line == 0) continue; + const entry = try by_path.getOrPut(arena, target.path); + if (!entry.found_existing) entry.value_ptr.* = .empty; + try entry.value_ptr.append(arena, index); + } + const resolved = try arena.alloc(Resolved, all.items.len); + @memset(resolved, .{}); + var file_arena: std.heap.ArenaAllocator = .init(p.gpa); + defer file_arena.deinit(); + for (by_path.keys(), by_path.values()) |path, indexes| { + _ = file_arena.reset(.retain_capacity); + const fa = file_arena.allocator(); + const source = sourceText(p, fa, dir, path); + var cached: Cache.Hit = .{ .analysis = .{} }; + defer cached.deinit(p.tree_sitter_gpa); + // Where each line starts, the file's length closing the last. + var starts: std.ArrayList(usize) = .empty; + if (source) |text| { + cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, true) catch .{ .analysis = .{} }; + try starts.append(fa, 0); + var at: usize = 0; + while (std.mem.indexOfScalarPos(u8, text.bytes, at, '\n')) |nl| : (at = nl + 1) try starts.append(fa, nl + 1); + } + for (indexes.items) |index| { + const line = all.items[index]; + const prefix = treePrefix(line); + const target = parseRaw(line[prefix.end..]); + var code = line[prefix.end + target.code_start ..]; + var colors: []const u8 = &.{}; + var source_row = target.at.line - 1; + if (source) |text| { + const row = target.at.line - 1; + if (prefix.branch) { + // Choose the innermost header containing the server's name range. + var chosen: ?syntax.ContextDeclaration = null; + for (cached.analysis.declarations) |declaration| { + if (declaration.start_line <= row and row <= declaration.header_end_line) { + if (chosen == null or declaration.end_byte - declaration.start_byte < chosen.?.end_byte - chosen.?.start_byte) + chosen = declaration; + } + } + if (chosen) |header| { + code = text.bytes[header.start_byte..header.header_end_byte]; + source_row = header.start_line; + } else { + const fallback = indexedLine(text.bytes, starts.items, row); + if (fallback.len > 0) code = fallback; + } + } else if (code.len == 0) { + // A call site the language worker sent bare (it reads no + // sources for Callstack): its line, from the source here. + code = indexedLine(text.bytes, starts.items, row); + } + const offset = if (source_row < starts.items.len) starts.items[source_row] else text.bytes.len; + if (offset + code.len <= cached.analysis.colors.len and + std.mem.eql(u8, code, text.bytes[offset..][0..code.len])) + colors = cached.analysis.colors[offset..][0..code.len]; + code = try arena.dupe(u8, code); + colors = try arena.dupe(u8, colors); + } + resolved[index] = .{ .code = code, .colors = colors, .source_row = source_row }; + } + } + return resolved; +} + +/// modal.lineSlice through a line index (`starts`, as resolveCallstack builds it). +fn indexedLine(text: []const u8, starts: []const usize, row: usize) []const u8 { + if (row >= starts.len or starts[row] >= text.len) return ""; + const end = if (row + 1 < starts.len) starts[row + 1] - 1 else text.len; + return text[starts[row]..end]; +} + /// Enrich caller nodes on the UI thread, using the same source/declaration cache /// as LocationsContext. The LSP worker only supplies relationships and addresses. pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !Result { @@ -232,9 +324,10 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R rows.deinit(p.gpa); } const stacked = p.settings.callstack_layout == .stacked; - var sources: std.StringHashMap(?Source) = .init(arena); + const resolved = try resolveCallstack(p, arena, dir, input); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); - while (lines.next()) |raw| { + var index: usize = 0; + while (lines.next()) |raw| : (index += 1) { const mark = @import("lsp/lsp.zig").callstack_match; const focus = std.mem.startsWith(u8, raw, mark); const line = if (focus) raw[mark.len..] else raw; @@ -245,41 +338,9 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R try appendMetadata(p.gpa, &rows, .{ .path = "", .at = .{}, .label = "", .code = "", .original = null }, .context, 0, line.len, false); continue; } - const entry = try sources.getOrPut(target.path); - if (!entry.found_existing) entry.value_ptr.* = sourceText(p, arena, dir, target.path); - const source = entry.value_ptr.*; - var cached: Cache.Hit = .{ .analysis = .{} }; - defer cached.deinit(p.tree_sitter_gpa); - if (source) |text| cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, true) catch .{ .analysis = .{} }; - var code = line[prefix.end + target.code_start ..]; - var colors: []const u8 = &.{}; - var source_row = target.at.line - 1; - if (source) |text| { - const row = target.at.line - 1; - if (prefix.branch) { - // Choose the innermost header containing the server's name range. - var chosen: ?syntax.ContextDeclaration = null; - for (cached.analysis.declarations) |declaration| { - if (declaration.start_line <= row and row <= declaration.header_end_line) { - if (chosen == null or declaration.end_byte - declaration.start_byte < chosen.?.end_byte - chosen.?.start_byte) - chosen = declaration; - } - } - if (chosen) |header| { - code = text.bytes[header.start_byte..header.header_end_byte]; - source_row = header.start_line; - } else { - const fallback = @import("modal.zig").lineSlice(text.bytes, row); - if (fallback.len > 0) code = fallback; - } - } - { - const offset = @import("modal.zig").lineStartOffset(text.bytes, source_row); - if (offset + code.len <= cached.analysis.colors.len and - std.mem.eql(u8, code, text.bytes[offset..][0..code.len])) - colors = cached.analysis.colors[offset..][0..code.len]; - } - } + const code = resolved[index].code; + const colors = resolved[index].colors; + var source_row = resolved[index].source_row; const recursion = prefix.branch and std.mem.endsWith(u8, line, " ↻ recursion"); const first_line = code[0 .. std.mem.indexOfScalar(u8, code, '\n') orelse code.len]; const source_indent = if (stacked) first_line.len - std.mem.trimStart(u8, first_line, " \t").len else 0; diff --git a/src/look.zig b/src/look.zig index f4fbe52e..02754fff 100644 --- a/src/look.zig +++ b/src/look.zig @@ -587,6 +587,10 @@ fn lookFirstHit(p: *Pardes, id: usize) void { /// Fills the results buffer, and answers how many rows a text or PDF /// search found (0 for Find and Grep, which do not count). With /// `open_empty` false a text search that found nothing opens no buffer. +/// A search of one pane's text (or its PDF) writes at most this many bytes +/// of rows: past it, the rows stop and say where. +pub const search_text_output_bytes = 16 << 20; + pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart, open_empty: bool) !usize { const pane = p.panes[id] orelse return 0; // Blanks at either end are the pattern's (a look of an indented line); @@ -598,7 +602,9 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start // root, and the directory the results buffer is named in. From a // column's or the workspace's tag, the session's. const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(pane); - const out = try arena.alloc(u8, filesystem.search_max_output_bytes); + // As much as the search can write and no more: a root's hits for each + // root Grep walks, one for Find, `search_text_output_bytes` in a pane. + var out: []u8 = &.{}; var out_len: usize = 0; var nrows: usize = 0; var anchor: ?usize = null; @@ -631,6 +637,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start roots[nroots] = d; nroots += 1; } + out = try @import("memory.zig").unfilled(arena, @max(1, nroots) * filesystem.search_root_output_bytes); // A pane's directory that is not there (a scratch named into one // not made yet, a peer's) has nothing to grep: passed over, not the // search's failure. @@ -641,9 +648,11 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start }; nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (kind == .find) { + out = try @import("memory.zig").unfilled(arena, filesystem.search_root_output_bytes); out_len = try filesystem.find(arena, dir, pat, out, ¬es); nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (pane.hasPdf()) { + out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); if (comptime pdf_enabled) { const found = try panes.Pdf.searchRows( &pane.pdf.?, @@ -658,6 +667,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start anchor = found.anchor; } } else { + out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); const lines = try edit.paneCursorLines(p, &pane.body); // a real file names itself; a terminal or an output buffer has no path const has_path = if (pane.file) |f| f.output == null else false; @@ -675,7 +685,10 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start const row = try std.fmt.allocPrint(arena, "{s}:{d}:{d}{c}{d} {s}\n", .{ loc, i + 1, at + 1, config.range_sep, at + pat.len, std.mem.trimEnd(u8, ln, " \t"), }); - if (row.len > out.len - out_len) break; + if (row.len > out.len - out_len) { + notes.rows_cut = nrows; + break; + } if (start == .cursor and (i < cl or (i == cl and at <= cc))) anchor = nrows; @memcpy(out[out_len..][0..row.len], row); out_len += row.len; @@ -1451,6 +1464,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: // 9P is no keyboard input, and searches whatever the key mode. if (pane.image != null or (pane.body.mode == .tty and !p.fs.serving)) return; if (text.len == 0) return; + if (lookCommit(p, id, pane, trimmed)) return; if (p.settings.look_word == .search and pane.file != null) return lookWord(p, id, pane, text); p.word_look = true; defer p.word_look = false; @@ -1471,6 +1485,49 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: } } +/// A commit hash (7 to 40 hex digits, a letter and a digit among them) +/// looked at inside a git repository: `git show` it, paged into a +Pager, +/// which stacks its hunks in a +Diff (ctl.fillPager); the command pane +/// goes when it succeeds (exec.commandDone). +// ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. +fn lookCommit(p: *Pardes, id: usize, pane: *Pane, word: []const u8) bool { + if (comptime !pardes.hosted) return false; + if (!isCommitHash(word)) return false; + var dir = filesystem.localPath(Pardes.paneDir(pane)) orelse return false; + while (true) { + var buf: [4096]u8 = undefined; + const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return false; + if (exec.kindOf(dot_git) != null) break; + dir = std.fs.path.dirname(dir) orelse return false; + } + var line: [64]u8 = undefined; + const dst = exec.execute(p, id, std.fmt.bufPrint(&line, "git show {s}", .{word}) catch return false) orelse return true; + if (p.panes[dst]) |c| c.command_pages = true; + return true; +} + +fn isCommitHash(word: []const u8) bool { + if (word.len < 7 or word.len > 40) return false; + var digit = false; + var letter = false; + for (word) |c| switch (c) { + '0'...'9' => digit = true, + 'a'...'f' => letter = true, + else => return false, + }; + 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). diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 4a70efe5..1c1b57a2 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -26,6 +26,10 @@ pub const Kind = enum { }; pub const callstack_match = "@callstack-match "; +/// The last row of a Callstack page that stopped full: ` `, +/// the entry indices from the top the next page starts at (`3.0.17`), and +/// how many callers this page holds. +pub const callstack_more = "@callstack-more "; pub const CallstackCorners = enum { rounded, square }; pub const callstack_default_depth: u8 = 8; pub const callstack_max_depth: u8 = 64; @@ -46,6 +50,9 @@ pub const Req = struct { /// For `explain`: the query it narrates, read from `arg` (` /// `) by `explaining`; a definition when none was asked before. explains: Kind = .definition, + /// The fixed region `arena` allocates from, when it is one: a walk that + /// can grow (Callstack) reads how much is left and stops in time. + budget: ?*const std.heap.FixedBufferAllocator = null, }; pub const Doc = struct { path: []const u8, source: [:0]const u8 }; @@ -102,18 +109,18 @@ pub fn speaks(path: []const u8) bool { return false; } -pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { +pub fn query(io: std.Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { if (req.kind == .status) { try out.print("backend: {s}\n", .{backend_name}); - inline for (backends) |b| try b.query(gpa, arena, req, out); + inline for (backends) |b| try b.query(io, gpa, arena, req, out); return; } inline for (backends) |b| { if (b.speaks(req.path) and b.supports.contains(req.kind)) - return b.query(gpa, arena, req, out); + return b.query(io, gpa, arena, req, out); } if (req.kind == .explain and backends.len > 0) - return backends[0].query(gpa, arena, req, out); + return backends[0].query(io, gpa, arena, req, out); // Nothing asked: said why, where an empty answer would read as nothing // found. inline for (backends) |b| if (b.speaks(req.path)) @@ -217,6 +224,6 @@ test "a question no backend answers for a file says why rather than find nothing var buf: [256]u8 = undefined; var out: std.Io.Writer = .fixed(&buf); // A file no server speaks for is answered, not left empty. - try query(std.testing.allocator, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/notes.txt", .source = "", .offset = 0 }, &out); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/notes.txt", .source = "", .offset = 0 }, &out); try std.testing.expectStringStartsWith(out.buffered(), "@none "); } diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index b396879b..e356c979 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -8,9 +8,10 @@ //! worker thread, and a language server costs tens of milliseconds to start //! and MINUTES to index a large workspace. So a server is spawned lazily on //! the first query that needs it, kept for the life of the editor, and each -//! spec gets at most one — `conns[i]` guards itself with a pthread mutex -//! because the gui shell detaches its workers and a superseded query can still -//! be inside `run` when the next arrives. +//! spec gets at most one — `conns[i]` guards itself with an `Io.Mutex` +//! because a canceled query can still be inside `run` when the next arrives. +//! Every wait is an `Io` cancelation point: a shell cancels the worker of a +//! query it no longer wants, and the worker stops there. //! //! ONE READER THREAD PER SERVER, and it is not optional. The first design //! pumped the socket only while a query waited, which works for a server that @@ -28,7 +29,8 @@ //! under a thread still polling it. //! //! Nothing here may wedge the editor: -//! - every write and every mailbox wait is bounded by a deadline, +//! - every write is bounded by a deadline, and every mailbox wait by a +//! deadline or, while the server narrates progress, by cancelation, //! - a query the server does not answer in time returns no rows and sends //! `$/cancelRequest`; the server is NOT killed for being busy (an indexing //! server is busy for minutes and the status row says so) — but three @@ -58,20 +60,10 @@ extern "c" fn access(path: [*:0]const u8, mode: c_int) c_int; extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8; extern "c" fn usleep(usec: c_uint) c_int; extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; -extern "c" fn realpath(path: [*:0]const u8, resolved: [*]u8) ?[*:0]u8; // test-only libc (the seam's own tests build a real directory tree) extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; extern "c" fn mkdir(path: [*:0]const u8, mode: libc.mode_t) c_int; extern "c" fn system(cmd: [*:0]const u8) c_int; -// pthread condattr surface, absent from std.c: what makes the mailbox waits -// tick on CLOCK_MONOTONIC (linux) or a relative timeout (darwin). -const pthread_condattr_t = extern struct { data: [8]u8 align(@alignOf(usize)) = @splat(0) }; -extern "c" fn pthread_condattr_init(attr: *pthread_condattr_t) c_int; -extern "c" fn pthread_condattr_setclock(attr: *pthread_condattr_t, clock: c_int) c_int; -extern "c" fn pthread_condattr_destroy(attr: *pthread_condattr_t) c_int; -extern "c" fn pthread_cond_init(cond: *libc.pthread_cond_t, attr: ?*const pthread_condattr_t) c_int; -extern "c" fn pthread_cond_timedwait_relative_np(cond: *libc.pthread_cond_t, mutex: *libc.pthread_mutex_t, reltime: *const libc.timespec) c_int; -const CLOCK_MONOTONIC: c_int = 1; // linux ABI; the setclock call is linux-only const X_OK: c_int = 1; const POLLIN: i16 = 0x001; @@ -182,21 +174,35 @@ fn specFor(path: []const u8) ?usize { return null; } -// Deadlines. Requests are bounded because tty.zig cancels-and-joins the -// previous worker on a new keypress, so the worst UI stall a wedged wait can -// cause is one req_ms. Timeouts do NOT kill the server — an indexing -// rust-analyzer legitimately sits on a `gd` for longer than anyone will wait, -// and the message row is already narrating why. +// Deadlines. A shell cancels-and-joins the previous worker on a new query, +// and its waits are cancelation points: so a request needs no deadline to +// keep the editor responsive, and waits for its answer. Past req_ms the +// message row says the server is still at it; only a server silent and idle +// (no $/progress) for wedge_ms has failed to answer. Timeouts do NOT kill the +// server — an indexing rust-analyzer legitimately sits on a `gd` for minutes. +// The handshake runs protected from cancelation, so it keeps its deadline. const init_ms = 8_000; // spawn + initialize handshake -const req_ms = 4_000; // one request/response round trip +const req_ms = 4_000; // a request past this is said to be still working +const wedge_ms = 300_000; // silent and idle this long: not answering (rust-analyzer takes ~1 min on `default`'s callers in agave) const diag_ms = 1_200; // wait for a publishDiagnostics push after didChange const reply_ms = 2_000; // our answers to server-to-client requests +const reply_queue_bytes = 64 << 10; // replies waiting for the socket (Conn.replies) +const parse_kept = 1 << 20; // what the reader's parse arena keeps between messages +const max_diag_files = 256; // files a server's pushed diagnostics are kept for +const max_diag_bytes = 32 << 20; // and their bytes const wedged_strikes = 3; // consecutive timeouts before a restart -const max_rows = 2000; +/// Rows one answer may hold, and its writer's bytes: carved from the query's +/// fixed region (memory.limits.arena.lsp_query) with the rest of its memory. +const max_rows = 100_000; +/// What a Callstack walk leaves of its query's region for rendering the +/// tree it found: past this it stops and says so. +const callstack_reserve = 32 << 20; +/// What rendering leaves of the answer's writer for its closing line. +const row_room = 4096; const max_doc_bytes = 8 << 20; -const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed }; +const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed, Canceled }; /// Long-lived state outlives every query arena and cannot borrow the caller's /// gpa (a different one shows up in the harness than in the shell), so @@ -251,8 +257,22 @@ const State = enum(u8) { }; const Conn = struct { - mu: libc.pthread_mutex_t = .{}, - cond: libc.pthread_cond_t = .{}, + mu: std.Io.Mutex = .init, + cond: std.Io.Condition = .init, + /// Frames go out whole: a query's requests and the reader's replies + /// share the socket, and interleaved halves are a parse error that ends + /// the server. + write_mu: std.Io.Mutex = .init, + /// Replies the reader made while a query's write held the socket, sent + /// by that writer once its own message is out (releaseWrite): the reader + /// never waits to write, since a server blocked on its output reads + /// nothing more of ours. + /// Two halves: the reader appends to `replies[filling]`, and the writer + /// flips them and sends the other, with no copy and no wait. + replies: [2][reply_queue_bytes]u8 = undefined, + replies_len: [2]usize = .{ 0, 0 }, + filling: u1 = 0, + replies_mu: std.Io.Mutex = .init, state: State = .off, /// bumped per spawn. A reader thread that sees a different gen than its /// own is reading a corpse and exits; a waiter that sees one stops waiting. @@ -264,9 +284,6 @@ const Conn = struct { /// monotonic ms when the last handshake completed — a crash shortly /// after "ready" counts as a handshake failure for backoff purposes ready_at_ms: i64 = 0, - /// linux: the zeroed condvar defaults to REALTIME; re-initialized with a - /// monotonic condattr before its first wait (under the mutex) - cond_monotonic: bool = false, timeouts: u8 = 0, pid: libc.pid_t = -1, sock: c_int = -1, @@ -278,6 +295,8 @@ const Conn = struct { extra_roots: std.ArrayList([]u8) = .empty, docs: std.ArrayList(Doc) = .empty, diags: std.ArrayList(DiagSet) = .empty, + /// The bytes `diags` holds, kept under max_diag_bytes. + diag_bytes: usize = 0, /// the response mailbox: one request outstanding per connection want_id: u32 = 0, resp: ?[]u8 = null, @@ -285,13 +304,12 @@ const Conn = struct { progress: i32 = 0, title: [48]u8 = @splat(0), title_len: u8 = 0, + /// The server says it is still loading its workspace (rust-analyzer's + /// serverStatus, not quiescent): an empty answer now is not one. + loading: bool = false, + /// its index in `conns`, for what it posts + si: usize = 0, - fn lock(c: *Conn) void { - _ = libc.pthread_mutex_lock(&c.mu); - } - fn unlock(c: *Conn) void { - _ = libc.pthread_mutex_unlock(&c.mu); - } fn alive(c: *const Conn) bool { return c.state == .starting or c.state == .ready; } @@ -406,10 +424,10 @@ const Trace = struct { // ------------------------------------------------------------------- query -pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) !void { +pub fn query(io: std.Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) !void { _ = gpa; const req = lsp.explaining(asked); - if (req.kind == .status) return status(req, out); + if (req.kind == .status) return status(io, req, out); var tr: Trace = .{ .on = req.kind == .explain }; const si = specFor(req.path) orelse { @@ -421,13 +439,14 @@ pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, o }; tr.note("file {s} -> {s} (languageId {s})", .{ std.fs.path.basename(req.path), specs[si].name, specs[si].lang }); - const scratch_buf = try arena.alloc(u8, max_rows * 512); + // Raw: `alloc` fills a safe build's new memory, all 51 MB of it, per query. + const scratch_buf = (arena.rawAlloc(max_rows * 512, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0 .. max_rows * 512]; var scratch: std.Io.Writer = .fixed(scratch_buf); const t0 = nowUs(); var err_name: []const u8 = ""; var failure: ?anyerror = null; - answer(arena, si, req, &scratch, &tr) catch |e| { + answer(io, arena, si, req, &scratch, &tr) catch |e| { failure = e; err_name = @errorName(e); tr.note("ERROR: {s}", .{err_name}); @@ -443,9 +462,9 @@ pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, o // again, not that it is not there. if (failure) |err| if (err == error.Backoff) { const c = &conns[si]; - c.lock(); + c.mu.lockUncancelable(io); const left_ms = c.retry_after_ms -| nowMs(); - c.unlock(); + c.mu.unlock(io); return lsp.none(out, "{s} failed recently; retry in {d}s", .{ specs[si].name, @divFloor(left_ms + 999, 1000) }); }; if (failure) |err| return err; @@ -464,17 +483,34 @@ fn traceOut(tr: *const Trace, req: lsp.Req, out: *std.Io.Writer, rows: usize, us try out.print("\n{d} row(s) in {d}us\n", .{ rows, us }); } -fn answer(arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { +fn answer(io: std.Io, arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { const c = &conns[si]; - c.lock(); - defer c.unlock(); - const g = try ensure(c, si, arena, req, tr); - run(c, si, arena, req, out, tr) catch |e| { + try c.mu.lock(io); + defer c.mu.unlock(io); + const g = try ensure(c, io, si, arena, req, tr); + const before = out.end; + try attempt(c, io, si, arena, req, out, tr, g); + // A server still loading its workspace answers at once, with nothing + // (rust-analyzer before its index): that is no answer. Wait until it says + // it is loaded, the message row saying so, and ask again. + const answered = out.buffered()[before..]; + if (c.loading and c.gen == g and (answered.len == 0 or std.mem.startsWith(u8, answered, "@none "))) { + tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name}); + post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name}); + while (c.loading and c.gen == g and c.alive()) _ = try timedWait(c, io, nowMs() + 500); + out.end = before; + try attempt(c, io, si, arena, req, out, tr, g); + } +} + +/// One run of a query, and what its failure says of the server. +fn attempt(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace, g: u32) Err!void { + run(c, io, si, arena, req, out, tr) catch |e| { switch (e) { // transport-level: this server is gone; forget it, and the next // query respawns. Gen-checked so a respawn that happened while we // waited is not the one we kill. - error.Dead, error.Protocol => shutdownIf(c, g), + error.Dead, error.Protocol => shutdownIf(c, io, g), error.Timeout => { // Slow is only wedged when the server is IDLE. One with // active `$/progress` work (rust-analyzer running cargo @@ -487,18 +523,19 @@ fn answer(arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer c.timeouts +|= 1; if (c.timeouts >= wedged_strikes and c.gen == g) { post(si, .always, "{s} not answering — restarting", .{specs[si].name}); - shutdownIf(c, g); + shutdownIf(c, io, g); } } }, - error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed => {}, + // Canceled: the shell asked something newer, not a wedged server. + error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed, error.Canceled => {}, } return e; }; c.timeouts = 0; } -fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { +fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { // `explain` narrates the last query asked (a definition, `gd`, when // none was) — dispatch below on the effective kind so the trace // follows the code that query really runs. @@ -510,18 +547,18 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io var uri: std.ArrayList(u8) = .empty; try uriOf(&uri, arena, req.path); - try syncDoc(c, si, arena, uri.items, req.source); + try syncDoc(c, io, si, arena, uri.items, req.source); // Every other open file this server answers for, before a query whose // answer reaches them: zls renames only in the documents it has. if (lsp.reachesOtherFiles(kind)) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path)) { var other: std.ArrayList(u8) = .empty; try uriOf(&other, arena, doc.path); - try syncDoc(c, si, arena, other.items, doc.source); + try syncDoc(c, io, si, arena, other.items, doc.source); tr.note("synced {s} first", .{std.fs.path.basename(doc.path)}); }; const pos = posOf(req.source, req.offset, c.caps.enc); - var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .relative_parents = req.kind == .callstack, .callstack_corners = req.callstack_corners }; + var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = req.kind == .callstack, .callstack_corners = req.callstack_corners }; for (req.others) |doc| try cx.files.append(arena, .{ .path = doc.path, .text = doc.source }); tr.note("server {s} (pid {d}), root {s}, {s} columns", .{ @tagName(c.state), c.pid, c.root, @tagName(c.caps.enc), @@ -540,7 +577,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io var b = try atPos(arena, uri.items, pos); if (kind == .references) try app(&b, arena, ",\"context\":{\"includeDeclaration\":true}"); tr.note("-> {s} @ {d}:{d}", .{ method, pos.line + 1, pos.ch + 1 }); - const result = (try call(c, arena, method, b.items, deadline)) orelse { + const result = (try call(c, io, arena, method, b.items, deadline)) orelse { tr.note("<- empty (no result, an error response, or null)", .{}); return; }; @@ -549,12 +586,12 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io }, .select_refs => { const b = try atPos(arena, uri.items, pos); - const result = (try call(c, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return; for (items(result)) |h| try emitRange(&cx, c.caps.enc, uri.items, get(h, "range"), ""); }, .hover => { const b = try atPos(arena, uri.items, pos); - const result = (try call(c, arena, "textDocument/hover", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/hover", b.items, deadline)) orelse return; const contents = get(result, "contents") orelse return; const text = str(contents) orelse str(get(contents, "value")) orelse blk: { for (items(contents)) |m| if (str(m) orelse str(get(m, "value"))) |t| break :blk t; @@ -569,26 +606,26 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try app(&b, arena, "}"); - const result = (try call(c, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; try walkSymbols(&cx, c.caps.enc, uri.items, result, 0); }, .workspace_symbols => { var b: std.ArrayList(u8) = .empty; try app(&b, arena, "\"query\":"); try jstr(&b, arena, req.arg); - const result = (try call(c, arena, "workspace/symbol", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "workspace/symbol", b.items, deadline)) orelse return; for (items(result)) |sym| { const loc = get(sym, "location") orelse continue; try emitRange(&cx, c.caps.enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), str(get(sym, "name")) orelse ""); } }, - .diagnostics => try diagnostics(c, arena, &cx, uri.items, deadline), - .workspace_diagnostics => try workspaceDiagnostics(c, arena, &cx, deadline), + .diagnostics => try diagnostics(c, io, arena, &cx, uri.items, deadline), + .workspace_diagnostics => try workspaceDiagnostics(c, io, arena, &cx, deadline), .rename => { var b = try atPos(arena, uri.items, pos); try app(&b, arena, ",\"newName\":"); try jstr(&b, arena, req.arg); - const result = (try call(c, arena, "textDocument/rename", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/rename", b.items, deadline)) orelse return; // Other open files that say the old name, should the server // answer for this file alone (zls renaming at a declaration does, // whatever it was told): applied here, they would no longer build. @@ -603,7 +640,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try app(&b, arena, "},\"options\":{\"tabSize\":4,\"insertSpaces\":true}"); - const result = (try call(c, arena, "textDocument/formatting", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/formatting", b.items, deadline)) orelse return; try formatEdits(&cx, c.caps.enc, result, req.source); }, .code_action => { @@ -611,7 +648,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try b.print(arena, "}},\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch }); - const result = (try call(c, arena, "textDocument/codeAction", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/codeAction", b.items, deadline)) orelse return; for (items(result)) |ca| { const title = str(get(ca, "title")) orelse continue; try lsp.row(cx.out, lsp.rel(cx.base, cx.cur_path), pos.line, 0, flat(arena, title)); @@ -621,7 +658,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io .completion => { var b = try atPos(arena, uri.items, pos); try app(&b, arena, ",\"context\":{\"triggerKind\":1}"); - const result = (try call(c, arena, "textDocument/completion", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/completion", b.items, deadline)) orelse return; const list = if (get(result, "items")) |it| items(it) else items(result); const here = lsp.rel(cx.base, cx.cur_path); var n: usize = 0; @@ -643,11 +680,11 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io n += 1; } }, - .callstack => try callstack(c, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth), - .incoming_calls => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), - .outgoing_calls => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), - .supertypes => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .supers, tr), - .subtypes => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .subs, tr), + .callstack => try callstack(c, io, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth, req.budget, req.arg), + .incoming_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), + .outgoing_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), + .supertypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .supers, tr), + .subtypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .subs, tr), .status, .explain => unreachable, } } @@ -687,13 +724,13 @@ fn walkSymbols(cx: *Cx, enc: Enc, uri: []const u8, node: std.json.Value, depth: /// Pull when the server does (LSP 3.17), the push store otherwise. The store /// path waits briefly for a publish that postdates the didChange we just /// sent, so `]d` right after an edit sees the new truth, not the old one. -fn diagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void { +fn diagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void { if (c.caps.pull) { var b: std.ArrayList(u8) = .empty; try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri); try app(&b, arena, "}"); - const result = (try call(c, arena, "textDocument/diagnostic", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/diagnostic", b.items, deadline)) orelse return; for (items(get(result, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); return; } @@ -702,13 +739,13 @@ fn diagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, dea stale = d.stale; break; }; - if (stale) waitFresh(c, uri, nowMs() + diag_ms); + if (stale) try waitFresh(c, io, uri, nowMs() + diag_ms); try renderStore(c, arena, cx, uri); } -fn workspaceDiagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void { +fn workspaceDiagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void { if (c.caps.pull_workspace) { - const result = (try call(c, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return; + const result = (try call(c, io, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return; for (items(get(result, "items"))) |per| { const uri = str(get(per, "uri")) orelse continue; for (items(get(per, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); @@ -741,7 +778,7 @@ fn renderStore(c: *Conn, arena: std.mem.Allocator, cx: *Cx, only_uri: ?[]const u /// Block (mutex released) until the reader marks `uri` fresh or the deadline /// passes. The reader broadcasts on every publishDiagnostics. -fn waitFresh(c: *Conn, uri: []const u8, deadline: i64) void { +fn waitFresh(c: *Conn, io: std.Io, uri: []const u8, deadline: i64) error{Canceled}!void { const g = c.gen; while (c.gen == g and c.alive()) { var fresh = false; @@ -750,7 +787,7 @@ fn waitFresh(c: *Conn, uri: []const u8, deadline: i64) void { break; }; if (fresh) return; - if (!timedWait(c, deadline)) return; + if (!try timedWait(c, io, deadline)) return; } } @@ -873,18 +910,21 @@ fn sortEdits(edits: []PutEdit) void { /// A bounded static hierarchy. Reuse the prepared item verbatim (including /// server data), and retain every call-site range rather than just a declaration. -fn hierarchyResult(c: *Conn, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { +fn hierarchyResult(c: *Conn, io: std.Io, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { if (jsonDepth(item, 0) > 96) return null; var body: std.ArrayList(u8) = .empty; try app(&body, arena, "\"item\":"); try app(&body, arena, std.json.Stringify.valueAlloc(arena, item, .{}) catch return error.OutOfMemory); - return call(c, arena, method, body.items, deadline); + return call(c, io, arena, method, body.items, deadline); } const CallTree = struct { - const Site = struct { range: std.json.Value, focus: bool }; + /// What a node keeps of the server's item: its own copies, so the + /// response it came in is freed once its subtree is walked. + const Call = struct { uri: []const u8, name: []const u8, at: Range }; + const Site = struct { range: Range, focus: bool }; const Node = struct { - item: std.json.Value, + call: Call, ranges: std.ArrayList(Site) = .empty, children: std.ArrayList(usize) = .empty, cycle: bool = false, @@ -893,10 +933,39 @@ const CallTree = struct { roots: std.ArrayList(usize) = .empty, path: [lsp.callstack_max_depth]std.json.Value = undefined, depth_limit: usize = lsp.callstack_default_depth, - visited: usize = 0, limited: bool = false, + out_of_time: bool = false, + out_of_memory: bool = false, + budget: ?*const std.heap.FixedBufferAllocator = null, + si: usize = 0, + collected: usize = 0, + started_ms: i64 = 0, + narrated: bool = false, siblings: [lsp.callstack_max_depth]bool = @splat(false), rendered: usize = 0, + /// Paging. A page starts at `start`, a path of entry indices from the + /// top (empty: the start), skipping what is before it at each level; + /// `rows` and `bytes` count what rendering takes, and the walk stops + /// before their caps at `cut`, which the next page starts at (`more`). + /// The ancestors on the path are shown again on it, as context. + start: [lsp.callstack_max_depth]u32 = undefined, + start_len: usize = 0, + at: [lsp.callstack_max_depth]u32 = undefined, + cut: [lsp.callstack_max_depth]u32 = undefined, + cut_len: usize = 0, + more: bool = false, + rows: usize = 0, + row_cap: usize = max_rows - 16, + /// The bytes those rows take, over-estimated (the uri for the path it + /// becomes), kept under the answer writer's room. + bytes: usize = 0, + byte_cap: usize = std.math.maxInt(usize), + + /// A row of a caller at `depth`: its tree columns, the uri the path is + /// made from, the name, and room for the address. + fn rowBytes(depth: usize, caller: Call) usize { + return 5 * (depth + 2) + caller.uri.len + caller.name.len + 40; + } /// Incoming paths arrive nearest-first. Insert them outermost-first, /// sharing common caller prefixes and retaining all their call sites. @@ -909,11 +978,14 @@ const CallTree = struct { const item = get(entry, "from").?; const children = if (parent) |id| tree.nodes.items[id].children.items else tree.roots.items; const found = for (children) |id| { - if (sameCall(tree.nodes.items[id].item, item)) break id; + if (sameCall(tree.nodes.items[id].call, item)) break id; } else null; + const depth = path.len - 1 - at; const id = found orelse blk: { const id = tree.nodes.items.len; - try tree.nodes.append(arena, .{ .item = item }); + try tree.nodes.append(arena, .{ .call = try callOf(arena, item) }); + tree.rows += 1; + tree.bytes += rowBytes(depth, tree.nodes.items[id].call); if (parent) |pid| { try tree.nodes.items[pid].children.append(arena, id); } else try tree.roots.append(arena, id); @@ -924,23 +996,39 @@ const CallTree = struct { for (items(get(entry, "fromRanges"))) |range| { const parsed = rangeOf(range) orelse continue; for (node.ranges.items) |*other| { - if (std.meta.eql(parsed, rangeOf(other.range).?)) { + if (std.meta.eql(parsed, other.range)) { other.focus = other.focus or at == 0; break; } - } else try node.ranges.append(arena, .{ .range = range, .focus = at == 0 }); + } else { + try node.ranges.append(arena, .{ .range = parsed, .focus = at == 0 }); + tree.rows += 1; + tree.bytes += rowBytes(depth + 1, .{ .uri = node.call.uri, .name = "", .at = parsed }); + } } parent = id; } } }; -fn sameCall(a: std.json.Value, b: std.json.Value) bool { - const au = str(get(a, "uri")) orelse return false; +fn callOf(arena: std.mem.Allocator, item: std.json.Value) Err!CallTree.Call { + return .{ + .uri = try arena.dupe(u8, str(get(item, "uri")).?), + .name = try arena.dupe(u8, str(get(item, "name")) orelse "(unnamed)"), + .at = rangeOf(get(item, "selectionRange") orelse get(item, "range")).?, + }; +} + +fn sameCall(a: CallTree.Call, b: std.json.Value) bool { const bu = str(get(b, "uri")) orelse return false; - const ar = rangeOf(get(a, "selectionRange") orelse get(a, "range")) orelse return false; const br = rangeOf(get(b, "selectionRange") orelse get(b, "range")) orelse return false; - return std.mem.eql(u8, au, bu) and std.meta.eql(ar, br); + return std.mem.eql(u8, a.uri, bu) and std.meta.eql(a.at, br); +} + +fn sameItem(a: std.json.Value, b: std.json.Value) bool { + const au = str(get(a, "uri")) orelse return false; + const ar = rangeOf(get(a, "selectionRange") orelse get(a, "range")) orelse return false; + return sameCall(.{ .uri = au, .name = "", .at = ar }, b); } fn callPrefix(out: *std.Io.Writer, tree: *const CallTree, depth: usize) Err!void { @@ -954,44 +1042,115 @@ fn validCaller(entry: std.json.Value) bool { rangeOf(get(from, "selectionRange") orelse get(from, "range")) != null; } -fn callstack(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8) Err!void { +fn callstack(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator, arg: []const u8) Err!void { if (!c.caps.call_hier) return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); const b = try atPos(arena, uri, pos); - const prepared = (try call(c, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; + const prepared = (try call(c, io, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; if (items(prepared).len == 0) return lsp.none(cx.out, "no function at this position", .{}); + // The rows come from the tree alone: the core reads the sources. + cx.no_text = true; + // Each response is parsed into its own part of the region, freed once + // its subtree is walked; only the path being walked is live JSON. + // Raw, as query()'s scratch: `alloc` would fill all ~100 MB of it. + const parse_len = if (budget) |fixed| (fixed.buffer.len - fixed.end_index) / 2 else 0; + var parse_fba: std.heap.FixedBufferAllocator = .init(if (budget != null) + (arena.rawAlloc(parse_len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..parse_len] + else + &.{}); + const parse = if (budget != null) parse_fba.allocator() else arena; for (items(prepared)) |item| { - var tree: CallTree = .{ .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth) }; - const incoming = try hierarchyResult(c, arena, item, "callHierarchy/incomingCalls", deadline); - const count = try collectCallers(c, arena, item, incoming, deadline, &tree, 0); - if (count == 0) try cx.out.writeAll("No callers reported\n"); + var tree: CallTree = .{ + .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth), + .si = si, + .started_ms = nowMs(), + .budget = budget, + // The page ends while the answer's writer has room for the rest. + .byte_cap = if (cx.fixed_out) (cx.out.buffer.len - cx.out.end) -| (1 << 20) else std.math.maxInt(usize), + }; + var steps = std.mem.tokenizeScalar(u8, std.mem.trim(u8, arg, " \n"), '.'); + while (steps.next()) |step| { + if (tree.start_len == tree.start.len) break; + tree.start[tree.start_len] = std.fmt.parseInt(u32, step, 10) catch break; + tree.start_len += 1; + } + const incoming = try hierarchyResult(c, io, parse, item, "callHierarchy/incomingCalls", deadline); + const count = try collectCallers(c, io, arena, if (budget != null) &parse_fba else null, item, incoming, &tree, 0, tree.start_len > 0); + if (tree.narrated) post(si, .always, "Callstack: {d} callers", .{tree.collected}); + if (count == 0 and tree.start_len == 0) try cx.out.writeAll("No callers reported\n"); try renderCallers(cx, c.caps.enc, &tree, tree.roots.items, 0); - if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); + if (tree.more) { + try cx.out.writeAll(lsp.callstack_more); + for (tree.cut[0..tree.cut_len], 0..) |index, level| try cx.out.print("{s}{d}", .{ if (level == 0) "" else ".", index }); + try cx.out.print(" {d}\n", .{tree.collected}); + } else if (tree.out_of_time) { + try cx.out.writeAll("… the language server ran out of time; continue from a function above with Callstack\n"); + } else if (tree.out_of_memory) { + try cx.out.writeAll("… stopped at the query's memory limit; continue from a function above with Callstack\n"); + } else if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); tr.note("callstack: {d} callers", .{tree.rendered}); } } -fn collectCallers(c: *Conn, arena: std.mem.Allocator, focus: std.json.Value, incoming: ?std.json.Value, deadline: i64, tree: *CallTree, depth: usize) Err!usize { +/// No caller count and no overall deadline: the walk narrates itself on the +/// message row after a second, and it stops when a request goes unanswered +/// (what was collected is shown), when the page is full (the rest is the +/// next page), or when the shell cancels it for a newer query. +fn collectCallers(c: *Conn, io: std.Io, arena: std.mem.Allocator, parse: ?*std.heap.FixedBufferAllocator, focus: std.json.Value, incoming: ?std.json.Value, tree: *CallTree, depth: usize, on_path: bool) Err!usize { var count: usize = 0; - for (items(incoming)) |entry| { - if (tree.visited >= 64) { - tree.limited = true; - break; + for (items(incoming), 0..) |entry, index| { + // A later page skips what the pages before it walked. + const resuming = on_path and depth < tree.start_len; + if (resuming and index < tree.start[depth]) continue; + tree.at[depth] = @intCast(index); + if (tree.budget) |b| if (b.buffer.len - b.end_index < callstack_reserve) { + tree.out_of_memory = true; + }; + if (!tree.more and (tree.rows >= tree.row_cap or tree.bytes >= tree.byte_cap or tree.out_of_memory)) { + // The page is full: the next goes on here. Never where this + // one began, which would page in place: past that entry. + tree.more = true; + tree.cut_len = depth + 1; + @memcpy(tree.cut[0..tree.cut_len], tree.at[0..tree.cut_len]); + if (tree.cut_len == tree.start_len and std.mem.eql(u32, tree.cut[0..tree.cut_len], tree.start[0..tree.start_len])) + tree.cut[depth] += 1; } + if (tree.out_of_time or tree.more) break; if (!validCaller(entry)) continue; const from = get(entry, "from").?; - const cycle = sameCall(focus, from) or for (tree.path[0..depth]) |ancestor| { - if (sameCall(get(ancestor, "from").?, from)) break true; + const cycle = sameItem(focus, from) or for (tree.path[0..depth]) |ancestor| { + if (sameItem(get(ancestor, "from").?, from)) break true; } else false; tree.path[depth] = entry; - tree.visited += 1; count += 1; + tree.collected += 1; + if (nowMs() - tree.started_ms >= 1000) { + tree.narrated = true; + post(tree.si, .chatty, "Callstack: {d} callers\u{2026}", .{tree.collected}); + } var children: usize = 0; if (!cycle) { - if (depth + 1 == tree.depth_limit or tree.visited >= 64) { + if (depth + 1 == tree.depth_limit) { tree.limited = true; } else { - const ancestors = try hierarchyResult(c, arena, from, "callHierarchy/incomingCalls", deadline); - children = try collectCallers(c, arena, focus, ancestors, deadline, tree, depth + 1); + const mark = if (parse) |fixed| fixed.end_index else 0; + defer if (parse) |fixed| { + fixed.end_index = mark; + }; + const ancestors = hierarchyResult(c, io, if (parse) |fixed| fixed.allocator() else arena, from, "callHierarchy/incomingCalls", nowMs() + req_ms) catch |e| switch (e) { + error.Timeout => blk: { + tree.out_of_time = true; + break :blk null; + }, + // A response bigger than the parse region: this caller + // stops here, the page with it. + error.OutOfMemory => blk: { + tree.out_of_memory = true; + break :blk null; + }, + else => return e, + }; + const deeper = resuming and index == tree.start[depth] and depth + 1 < tree.start_len; + if (!tree.out_of_time and !tree.out_of_memory) children = try collectCallers(c, io, arena, parse, focus, ancestors, tree, depth + 1, deeper); } } if (children == 0) try tree.addPath(arena, tree.path[0 .. depth + 1], cycle); @@ -999,51 +1158,61 @@ fn collectCallers(c: *Conn, arena: std.mem.Allocator, focus: std.json.Value, inc return count; } +/// Test callers sink below the rest; each group keeps the usual order. +// ponytail: substring heuristic, "latest.zig" or "contest" count as tests too +fn testCaller(caller: CallTree.Call) bool { + return std.ascii.findIgnoreCase(caller.name, "test") != null or + std.ascii.findIgnoreCase(std.fs.path.basenamePosix(caller.uri), "test") != null; +} + fn callerLess(tree: *const CallTree, a: usize, b: usize) bool { - const left = tree.nodes.items[a].item; - const right = tree.nodes.items[b].item; - const uri_order = std.mem.order(u8, str(get(left, "uri")).?, str(get(right, "uri")).?); + const left = tree.nodes.items[a].call; + const right = tree.nodes.items[b].call; + if (testCaller(left) != testCaller(right)) return testCaller(right); + const uri_order = std.mem.order(u8, left.uri, right.uri); if (uri_order != .eq) return uri_order == .lt; - return callRangeLess({}, get(left, "selectionRange") orelse get(left, "range").?, get(right, "selectionRange") orelse get(right, "range").?); + return rangeLess(left.at, right.at); } -fn callRangeLess(_: void, a: std.json.Value, b: std.json.Value) bool { - const left = rangeOf(a).?; - const right = rangeOf(b).?; +fn rangeLess(left: Range, right: Range) bool { return left.sl < right.sl or (left.sl == right.sl and left.sc < right.sc); } fn renderCallers(cx: *Cx, enc: Enc, tree: *CallTree, children: []usize, depth: usize) Err!void { std.mem.sort(usize, children, @as(*const CallTree, tree), callerLess); for (children, 0..) |id, index| { - if (tree.rendered >= 64) { + // emitRange's row ceiling and the writer's room, met here before a + // prefix is half written + if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { tree.limited = true; return; } const node = &tree.nodes.items[id]; - const item = node.item; - const uri = str(get(item, "uri")).?; const more = index + 1 < children.len; try callPrefix(cx.out, tree, depth); const has_children = node.children.items.len > 0 or node.ranges.items.len > 0; const rounded = cx.callstack_corners == .rounded; try cx.out.writeAll(if (more) "├" else if (rounded) "╰" else "└"); try cx.out.writeAll(if (has_children) "──┬ " else "─── "); - const name = flat(cx.arena, str(get(item, "name")) orelse "(unnamed)"); + const name = flat(cx.arena, node.call.name); const label = if (node.cycle) try std.fmt.allocPrint(cx.arena, "{s} ↻ recursion", .{name}) else name; - try emitRange(cx, enc, uri, get(item, "selectionRange") orelse get(item, "range"), label); + try emitAt(cx, enc, node.call.uri, node.call.at, label); tree.rendered += 1; tree.siblings[depth] = more; std.mem.sort(CallTree.Site, node.ranges.items, {}, struct { fn less(_: void, a: CallTree.Site, b: CallTree.Site) bool { - return callRangeLess({}, a.range, b.range); + return rangeLess(a.range, b.range); } }.less); for (node.ranges.items, 0..) |site, site_index| { + if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { + tree.limited = true; + return; + } if (site.focus) try cx.out.writeAll(lsp.callstack_match); try callPrefix(cx.out, tree, depth + 1); try cx.out.writeAll(if (node.children.items.len > 0 or site_index + 1 < node.ranges.items.len) "├─ " else if (rounded) "╰─ " else "└─ "); - try emitRange(cx, enc, uri, site.range, ""); + try emitAt(cx, enc, node.call.uri, site.range, ""); } try renderCallers(cx, enc, tree, node.children.items, depth + 1); } @@ -1054,7 +1223,7 @@ const Hier = enum { incoming, outgoing, supers, subs }; /// The two-step hierarchy kinds: prepare at the cursor, then follow every /// item the server returned (usually one). Gated on the server capability so /// an old server costs zero round trips. -fn hierarchy(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { +fn hierarchy(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { const call_side = h == .incoming or h == .outgoing; if (call_side and !c.caps.call_hier) { tr.note("STOP: {s} does not advertise callHierarchyProvider", .{specs[si].name}); @@ -1072,9 +1241,9 @@ fn hierarchy(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []cons .subs => "typeHierarchy/subtypes", }; const b = try atPos(arena, uri, pos); - const prepared = (try call(c, arena, prepare, b.items, deadline)) orelse return; + const prepared = (try call(c, io, arena, prepare, b.items, deadline)) orelse return; for (items(prepared)) |item| { - const result = (try hierarchyResult(c, arena, item, follow, deadline)) orelse return; + const result = (try hierarchyResult(c, io, arena, item, follow, deadline)) orelse return; for (items(result)) |entry| switch (h) { .incoming => { // one row per CALL SITE, under the caller's name — that is @@ -1134,6 +1303,10 @@ const Cx = struct { cur_path: []const u8, cur_src: []const u8, out: *std.Io.Writer, + /// `out` is the query's fixed answer buffer, whose room is checked. + fixed_out: bool = false, + /// Rows without their source text (Callstack: the core reads it). + no_text: bool = false, rows: usize = 0, relative_parents: bool = false, callstack_corners: lsp.CallstackCorners = .rounded, @@ -1169,11 +1342,16 @@ const Cx = struct { /// columns, and a single-line range becomes the `path:LINE:COL-ENDCOL` form a /// look SELECTS. `note` overrides the source line as the row's text. fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: []const u8) Err!void { + return emitAt(cx, enc, uri, rangeOf(range) orelse return, note); +} + +fn emitAt(cx: *Cx, enc: Enc, uri: []const u8, r: Range, note: []const u8) Err!void { if (cx.rows >= max_rows) return; const path = pathOf(cx.arena, uri) orelse return; if (path.len == 0 or path[0] != '/') return; // rows promise absolute-or-rel-from-base - const r = rangeOf(range) orelse return; - const src = cx.text(path); + // Without sources (Callstack) the asking file is still known: its rows' + // columns convert from utf-16 as ever. + const src = if (cx.no_text and !std.mem.eql(u8, path, cx.cur_path)) null else cx.text(path); var bol: usize = 0; var eol: usize = 0; @@ -1323,7 +1501,8 @@ fn transportPair(sv: *[2]libc.fd_t) bool { /// Spawn-or-return, and tell an existing server about a new project root. /// Returns the generation the caller's whole query is bound to. -fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { +fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { + c.si = si; if (c.state == .disabled) { tr.note("STOP: {s} is disabled for this session (no binary; set {s})", .{ specs[si].name, specs[si].env }); return error.NoServer; @@ -1341,7 +1520,7 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac try app(&b, arena, "{\"jsonrpc\":\"2.0\",\"method\":\"workspace/didChangeWorkspaceFolders\",\"params\":{\"event\":{\"added\":[{\"name\":\"root\",\"uri\":\""); try uriOf(&b, arena, root); try app(&b, arena, "\"}],\"removed\":[]}}}"); - try frame(c.sock, b.items, nowMs() + reply_ms); + try send(c, io, b.items, nowMs() + wedge_ms); const owned = sa.dupe(u8, root) catch return error.OutOfMemory; c.extra_roots.append(sa, owned) catch sa.free(owned); } @@ -1430,12 +1609,13 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac if (c.resp) |r| sa.free(r); c.resp = null; c.progress = 0; + c.loading = false; c.timeouts = 0; forgetDocs(c); if (c.root.len > 0) sa.free(c.root); c.root = owned_root; - const th = std.Thread.spawn(.{}, reader, .{ si, g, sv[0] }) catch { + const th = std.Thread.spawn(.{}, reader, .{ io, si, g, sv[0] }) catch { // no reader means nobody would ever close the fd our way; do it here, // before anything else can see the conn _ = libc.close(sv[0]); @@ -1450,8 +1630,14 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac post(si, .always, "{s} starting — {s}", .{ specs[si].name, root }); tr.note("spawned {s} (pid {d}) at {s}", .{ specs[si].name, pid, root }); - handshake(c, arena, root) catch |e| { - shutdownIf(c, g); + // A start runs to the end however soon the query that began it is + // canceled: killing a half-started server would only make the next + // query start it again. The cancel lands at the next wait instead. + const protection = io.swapCancelProtection(.blocked); + const started = handshake(c, io, arena, root); + _ = io.swapCancelProtection(protection); + started catch |e| { + shutdownIf(c, io, g); // NOT a session disable. A handshake that misses the deadline is // routinely environmental — a rustup shim deciding to download the // project's pinned toolchain before launching the real server was @@ -1477,7 +1663,7 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac return g; } -fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { +fn handshake(c: *Conn, io: std.Io, arena: std.mem.Allocator, root: []const u8) Err!void { var b: std.ArrayList(u8) = .empty; try b.print(arena, "\"processId\":{d},\"clientInfo\":{{\"name\":\"pardes\"}},\"rootUri\":\"", .{@as(u32, @bitCast(libc.getpid()))}); try uriOf(&b, arena, root); @@ -1509,7 +1695,7 @@ fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { for (b.items) |ch| if (ch != '\n') try body.append(arena, ch); const deadline = nowMs() + init_ms; - const reply = (try call(c, arena, "initialize", body.items, deadline)) orelse return error.Protocol; + const reply = (try call(c, io, arena, "initialize", body.items, deadline)) orelse return error.Protocol; const caps = get(reply, "capabilities"); c.caps.enc = if (std.mem.eql(u8, str(get(caps, "positionEncoding")) orelse "utf-16", "utf-8")) .utf8 else .utf16; @@ -1521,7 +1707,7 @@ fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { c.caps.type_hier = provider(get(caps, "typeHierarchyProvider")); c.caps.folders = if (get(get(get(caps, "workspace"), "workspaceFolders"), "supported")) |s| s == .bool and s.bool else false; - try frame(c.sock, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline); + try send(c, io, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline); } /// A server capability that may be `true`, an options object, or absent. @@ -1536,7 +1722,7 @@ fn provider(v: ?std.json.Value) bool { /// didOpen the first time a file is seen, didChange when its bytes moved, /// nothing when they did not — the common case between two presses of gd. -fn syncDoc(c: *Conn, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { +fn syncDoc(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { const hash = std.hash.Wyhash.hash(0, src); var doc: ?*Doc = null; for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { @@ -1568,13 +1754,16 @@ fn syncDoc(c: *Conn, si: usize, arena: std.mem.Allocator, uri: []const u8, src: try jstr(&b, arena, src); try app(&b, arena, "}}}"); } - try frame(c.sock, b.items, nowMs() + req_ms); + // A server busy with what it was sent last reads no more meanwhile + // (clangd parses its compile database at a first open): this waits as + // an answer does, for a cancel or a server that has stopped. + try send(c, io, b.items, nowMs() + wedge_ms); } /// Send a request and wait on the mailbox. Returns the parsed `result`, or /// null for an error response / null result — both are legal "no answer". /// Runs with the conn mutex held; the mutex is released inside the wait. -fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value { +fn call(c: *Conn, io: std.Io, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value { const g = c.gen; const id = c.next_id; c.next_id +%= 1; @@ -1589,17 +1778,36 @@ fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const c.want_id = id; defer c.want_id = 0; - try frame(c.sock, b.items, deadline); + try send(c, io, b.items, if (c.state == .ready) nowMs() + wedge_ms else deadline); + // The handshake (still `.starting`) has its deadline. A ready server is + // waited for until it answers or the shell cancels this query for a + // newer one, so the first query after a start is answered, not lost: + // past `deadline` the message row says it is still working, and only + // silent and idle for wedge_ms is it not answering. + var said = false; + var busy_at = nowMs(); while (c.resp == null and c.gen == g and c.alive()) { - if (!timedWait(c, deadline)) break; + const ready = c.state == .ready; + const waiting = timedWait(c, io, if (ready) nowMs() + 500 else deadline) catch |e| { + cancelRequest(c, io, arena, id); + return e; + }; + if (!ready) { + if (waiting) continue; + break; + } + if (c.progress > 0) busy_at = nowMs(); + if (!said and nowMs() >= deadline) { + said = true; + post(c.si, .always, "{s} is still working on it\u{2026}", .{specs[c.si].name}); + } + if (nowMs() - busy_at >= wedge_ms) break; } + if (said and c.resp != null) post(c.si, .always, "{s} answered", .{specs[c.si].name}); if (c.gen != g or !c.alive()) return error.Dead; const raw = c.resp orelse { - // give the server leave to abandon the work we stopped waiting for - var cb: std.ArrayList(u8) = .empty; - cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return error.Timeout; - frame(c.sock, cb.items, nowMs() + reply_ms) catch {}; + cancelRequest(c, io, arena, id); return error.Timeout; }; c.resp = null; @@ -1609,49 +1817,23 @@ fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const if (result == .null) return null; return result; } -/// One bounded cond wait. False when the deadline has passed. -/// -/// The deadline arithmetic everywhere here is CLOCK_MONOTONIC, so the wait -/// must be too: a REALTIME abstime plus an NTP step backwards would park a -/// worker far past `req_ms`, violating the seam's bounded-wait promise. On -/// linux the condvar is lazily initialized with a monotonic condattr; darwin -/// has no setclock but has a RELATIVE wait, which never consults the wall -/// clock at all. -fn timedWait(c: *Conn, deadline: i64) bool { +/// Give the server leave to abandon the work we stopped waiting for. +fn cancelRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, id: u32) void { + var cb: std.ArrayList(u8) = .empty; + cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return; + send(c, io, cb.items, nowMs() + reply_ms) catch {}; +} + +/// One bounded cond wait, and a cancelation point: a worker the shell +/// cancels for a newer query stops here. False when the deadline has passed. +fn timedWait(c: *Conn, io: std.Io, deadline: i64) error{Canceled}!bool { const left = deadline - nowMs(); if (left <= 0) return false; const wait_ms = @min(left, 500); // tick so gen/state changes are noticed - if (comptime builtin.os.tag.isDarwin()) { - const rel: libc.timespec = .{ - .sec = @divTrunc(wait_ms, 1000), - .nsec = @rem(wait_ms, 1000) * 1_000_000, - }; - _ = pthread_cond_timedwait_relative_np(&c.cond, &c.mu, &rel); - return true; - } - if (!c.cond_monotonic) { - // lazily re-initialize the zeroed (REALTIME) condvar with a - // monotonic clock; under the mutex, and only before the first wait, - // so no thread can be parked on the old one - var attr: pthread_condattr_t = undefined; - if (pthread_condattr_init(&attr) == 0) { - _ = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); - _ = pthread_cond_init(&c.cond, &attr); - _ = pthread_condattr_destroy(&attr); - } - c.cond_monotonic = true; - } - var now: libc.timespec = undefined; - _ = libc.clock_gettime(.MONOTONIC, &now); - var abs: libc.timespec = .{ - .sec = now.sec + @divTrunc(wait_ms, 1000), - .nsec = now.nsec + @rem(wait_ms, 1000) * 1_000_000, + c.cond.waitTimeout(io, &c.mu, .{ .duration = .{ .raw = .fromMilliseconds(wait_ms), .clock = .awake } }) catch |e| switch (e) { + error.Timeout => {}, + error.Canceled => return error.Canceled, }; - if (abs.nsec >= 1_000_000_000) { - abs.sec += 1; - abs.nsec -= 1_000_000_000; - } - _ = libc.pthread_cond_timedwait(&c.cond, &c.mu, &abs); return true; } @@ -1659,7 +1841,7 @@ fn timedWait(c: *Conn, deadline: i64) bool { /// respawn that happened during the caller's wait must not be killed for its /// predecessor's crimes. Mutex held. The reader closes the fd; this only /// shuts the transport down and reaps the child. -fn shutdownIf(c: *Conn, g: u32) void { +fn shutdownIf(c: *Conn, io: std.Io, g: u32) void { if (c.gen != g or c.sock < 0) return; _ = libc.shutdown(c.sock, 2); // SHUT_RDWR: the reader sees EOF and closes reap(c.pid); @@ -1669,7 +1851,7 @@ fn shutdownIf(c: *Conn, g: u32) void { forgetDocs(c); if (c.resp) |r| sa.free(r); c.resp = null; - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } /// TERM, a bounded grace, then KILL, to the server's whole process group @@ -1715,6 +1897,7 @@ fn forgetDocs(c: *Conn) void { sa.free(d.body); } c.diags.clearRetainingCapacity(); + c.diag_bytes = 0; } // ------------------------------------------------------------ reader thread @@ -1722,20 +1905,22 @@ fn forgetDocs(c: *Conn) void { /// Owns the read side of one socket for one generation, and is the only /// closer of that fd. Routes responses to the mailbox, answers server /// requests, feeds the diagnostics store, narrates progress. -fn reader(si: usize, g: u32, sock: c_int) void { +fn reader(io: std.Io, si: usize, g: u32, sock: c_int) void { const c = &conns[si]; var buf = sa.alloc(u8, 256 * 1024) catch { - readerExit(c, si, g, sock); + readerExit(c, io, si, g, sock); return; }; defer sa.free(buf); var len: usize = 0; + var parse_arena: std.heap.ArenaAllocator = .init(sa); + defer parse_arena.deinit(); outer: while (true) { // drain every complete frame already buffered drain: while (true) switch (frameNext(buf[0..len])) { .frame => |m| { - dispatch(c, si, g, sock, buf[m.body_start..m.body_end]); + dispatch(c, io, si, g, sock, buf[m.body_start..m.body_end], &parse_arena); std.mem.copyForwards(u8, buf[0 .. len - m.consumed], buf[m.consumed..len]); len -= m.consumed; }, @@ -1761,9 +1946,9 @@ fn reader(si: usize, g: u32, sock: c_int) void { if (pr == 0) { // tick: a respawn while the server was silent leaves this thread // reading a corpse; notice and go - c.lock(); + c.mu.lockUncancelable(io); const stale = c.gen != g; - c.unlock(); + c.mu.unlock(io); if (stale) break :outer; continue; } @@ -1776,11 +1961,11 @@ fn reader(si: usize, g: u32, sock: c_int) void { if (got == 0) break :outer; // the server exited or shutdownIf spoke len += @intCast(got); } - readerExit(c, si, g, sock); + readerExit(c, io, si, g, sock); } -fn readerExit(c: *Conn, si: usize, g: u32, sock: c_int) void { - c.lock(); +fn readerExit(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int) void { + c.mu.lockUncancelable(io); if (c.gen == g and c.alive()) { // the server died on its own — shutdownIf never saw it, so the corpse // is ours to reap and the conn's transport fields are ours to clear @@ -1800,10 +1985,14 @@ fn readerExit(c: *Conn, si: usize, g: u32, sock: c_int) void { } else { post(si, .always, "{s} exited — restarts on the next query", .{specs[si].name}); } - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } - c.unlock(); + c.mu.unlock(io); + // A query writes with the mutex let go (send): the fd stays its until + // that write is done, and shutdown(2) has already made it fail fast. + c.write_mu.lockUncancelable(io); _ = libc.close(sock); + c.write_mu.unlock(io); } /// 10s doubling to 2min: the fork-per-keystroke guard's schedule. @@ -1845,32 +2034,33 @@ fn frameNext(data: []const u8) FrameStep { /// One message from the server. Parses into a throwaway arena; touches conn /// state only under the mutex; replies never hold it (bounded writes must not /// stall the mailbox). -fn dispatch(c: *Conn, si: usize, g: u32, sock: c_int, raw: []const u8) void { - var arena_state: std.heap.ArenaAllocator = .init(sa); - defer arena_state.deinit(); +fn dispatch(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int, raw: []const u8, arena_state: *std.heap.ArenaAllocator) void { + // The reader's one parse arena, reset per message: no mapping per + // `$/progress` report, and no more than parse_kept kept between them. + defer _ = arena_state.reset(.{ .retain_with_limit = parse_kept }); const arena = arena_state.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return; if (v != .object) return; if (str(get(v, "method"))) |method| { - if (get(v, "id")) |id| return serverRequest(arena, sock, method, id, get(v, "params")); - return notification(c, si, g, raw, method, get(v, "params")); + if (get(v, "id")) |id| return serverRequest(c, io, arena, sock, method, id, get(v, "params")); + return notification(c, io, si, g, raw, method, get(v, "params")); } // a response: deliver to the one waiting query, if it is still waiting const id = num(get(v, "id")) orelse return; - c.lock(); - defer c.unlock(); + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); if (c.gen == g and c.want_id != 0 and id == c.want_id and c.resp == null) { c.resp = sa.dupe(u8, raw) catch null; - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } } /// The server asked US something. Everything optional was declined in the /// handshake, so a null-ish answer is always legal — but it must ARRIVE, or /// the server blocks forever on its own question. -fn serverRequest(arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void { +fn serverRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void { var b: std.ArrayList(u8) = .empty; app(&b, arena, "{\"jsonrpc\":\"2.0\",\"id\":") catch return; switch (id) { @@ -1890,17 +2080,17 @@ fn serverRequest(arena: std.mem.Allocator, sock: c_int, method: []const u8, id: } else { app(&b, arena, ",\"result\":null}") catch return; } - frame(sock, b.items, nowMs() + reply_ms) catch {}; + answerServer(c, io, sock, b.items); } -fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { +fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { if (std.mem.eql(u8, method, "textDocument/publishDiagnostics")) { const uri = str(get(params, "uri")) orelse return; // keep the raw MESSAGE (params included); re-parsing it per query // beats owning a parsed tree past this arena's life const body = sa.dupe(u8, raw) catch return; - c.lock(); - defer c.unlock(); + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); if (c.gen != g) { sa.free(body); return; @@ -1914,10 +2104,25 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 slot = d; break; }; + // Bounded in files and bytes: a new set that does not fit pushes + // out the oldest files' (the server sends a file's again when it + // changes); one bigger than the whole store is not kept. + if (body.len > max_diag_bytes) { + sa.free(body); + return; + } if (slot) |d| { + c.diag_bytes -= d.body.len; sa.free(d.body); d.body = body; - } else if (c.diags.items.len < 256) { + c.diag_bytes += body.len; + } else { + while (c.diags.items.len > 0 and (c.diags.items.len >= max_diag_files or c.diag_bytes + body.len > max_diag_bytes)) { + const old = c.diags.orderedRemove(0); + c.diag_bytes -= old.body.len; + sa.free(old.uri); + sa.free(old.body); + } const owned = sa.dupe(u8, uri) catch { sa.free(body); return; @@ -1927,17 +2132,18 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 sa.free(body); return; }; - } else sa.free(body); - _ = libc.pthread_cond_broadcast(&c.cond); // waitFresh watches this + c.diag_bytes += body.len; + } + c.cond.broadcast(io); // waitFresh watches this return; } if (std.mem.eql(u8, method, "$/progress")) { const value = get(params, "value") orelse return; const pkind = str(get(value, "kind")) orelse return; const msg = str(get(value, "message")) orelse ""; - c.lock(); + c.mu.lockUncancelable(io); if (c.gen != g) { - c.unlock(); + c.mu.unlock(io); return; } if (std.mem.eql(u8, pkind, "begin")) { @@ -1948,7 +2154,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 var tbuf: [48]u8 = undefined; const t = tbuf[0..c.title_len]; @memcpy(t, c.title[0..c.title_len]); - c.unlock(); + c.mu.unlock(io); post(si, .chatty, "{s}: {s}\u{2026} {s}", .{ specs[si].name, t, msg }); return; } @@ -1957,7 +2163,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 const t = tbuf[0..c.title_len]; @memcpy(t, c.title[0..c.title_len]); const pct = num(get(value, "percentage")); - c.unlock(); + c.mu.unlock(io); if (pct) |p| post(si, .chatty, "{s}: {s} {d}% {s}", .{ specs[si].name, t, p, msg }) else @@ -1968,7 +2174,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 c.progress -= 1; const idle = c.progress <= 0; if (idle) c.progress = 0; - c.unlock(); + c.mu.unlock(io); // the setpoint every burst of progress ends on; `.always` + the // dedupe above means it lands exactly once however the reports raced if (idle) post(si, .always, "{s}: ready", .{specs[si].name}); @@ -1985,6 +2191,12 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 if (std.mem.eql(u8, method, "experimental/serverStatus")) { const health = str(get(params, "health")) orelse "ok"; const quiescent = if (get(params, "quiescent")) |q| q == .bool and q.bool else false; + c.mu.lockUncancelable(io); + if (c.gen == g) { + c.loading = !quiescent; + c.cond.broadcast(io); + } + c.mu.unlock(io); if (!std.mem.eql(u8, health, "ok")) post(si, .always, "{s}: {s} — {s}", .{ specs[si].name, health, str(get(params, "message")) orelse "" }) else if (quiescent) @@ -1995,12 +2207,12 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 // ------------------------------------------------------------- introspection -fn status(req: lsp.Req, out: *std.Io.Writer) !void { +fn status(io: std.Io, req: lsp.Req, out: *std.Io.Writer) !void { _ = req; try out.print("\nprotocol servers (lsp-client):\n", .{}); for (&specs, 0..) |*s, i| { const c = &conns[i]; - c.lock(); + c.mu.lockUncancelable(io); const state = c.state; var rootbuf: [256]u8 = undefined; const rootlen = @min(c.root.len, rootbuf.len); @@ -2012,7 +2224,7 @@ fn status(req: lsp.Req, out: *std.Io.Writer) !void { const pull = c.caps.pull; const chier = c.caps.call_hier; const thier = c.caps.type_hier; - c.unlock(); + c.mu.unlock(io); const env_v = if (getenv(s.env)) |v| std.mem.span(v) else null; // Never spawned is not off: the first query of its files starts it. try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (its first query starts it)" else @tagName(state) }); @@ -2069,21 +2281,80 @@ fn atPos(arena: std.mem.Allocator, uri: []const u8, pos: Pos) Err!std.ArrayList( return b; } -fn frame(sock: c_int, body: []const u8, deadline: i64) Err!void { +/// A message to the server from a query, the conn's mutex let go while it is +/// written: the reader goes on taking the server's output meanwhile, which a +/// server may be waiting to write before it reads more of ours. +fn send(c: *Conn, io: std.Io, body: []const u8, deadline: i64) Err!void { + const sock = c.sock; + c.mu.unlock(io); + defer c.mu.lockUncancelable(io); + return frame(c, io, sock, body, deadline); +} + +fn frame(c: *Conn, io: std.Io, sock: c_int, body: []const u8, deadline: i64) Err!void { if (sock < 0) return error.Dead; + c.write_mu.lockUncancelable(io); + defer releaseWrite(c, io, sock); var hdr: [64]u8 = undefined; const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return error.Protocol; - try sockWrite(sock, h, deadline); - try sockWrite(sock, body, deadline); + var started = false; + try sockWrite(io, sock, h, deadline, &started); + try sockWrite(io, sock, body, deadline, &started); +} + +/// The reader's answer to a server request: written now if the socket is +/// free, else queued for the query writing (bounded; one that does not fit is +/// dropped, and the server's request goes unanswered). +fn answerServer(c: *Conn, io: std.Io, sock: c_int, body: []const u8) void { + var hdr: [64]u8 = undefined; + const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return; + c.replies_mu.lockUncancelable(io); + const half = &c.replies[c.filling]; + const len = &c.replies_len[c.filling]; + if (len.* + h.len + body.len <= half.len) { + @memcpy(half[len.*..][0..h.len], h); + @memcpy(half[len.* + h.len ..][0..body.len], body); + len.* += h.len + body.len; + } + c.replies_mu.unlock(io); + if (c.write_mu.tryLock()) releaseWrite(c, io, sock); +} + +/// Lets the socket go, first sending what the reader queued meanwhile, and +/// again for what it queues while that goes out. +fn releaseWrite(c: *Conn, io: std.Io, sock: c_int) void { + while (true) { + c.replies_mu.lockUncancelable(io); + const sent = c.filling; + const n = c.replies_len[sent]; + if (n > 0) c.filling ^= 1; + c.replies_mu.unlock(io); + if (n > 0) { + var started = false; + sockWrite(null, sock, c.replies[sent][0..n], nowMs() + reply_ms, &started) catch {}; + c.replies_len[sent] = 0; + } + c.write_mu.unlock(io); + c.replies_mu.lockUncancelable(io); + const more = c.replies_len[c.filling] > 0; + c.replies_mu.unlock(io); + if (!more or !c.write_mu.tryLock()) return; + } } -fn sockWrite(sock: c_int, bytes: []const u8, deadline: i64) Err!void { +/// Writes `bytes`, `started` once any byte of their message is out. Before +/// then, the deadline and a cancel stop it; after, the message is finished +/// however long the server takes to read it (bounded by wedge_ms), since +/// half of one ends the server's reading of every message after it. +fn sockWrite(io: ?std.Io, sock: c_int, bytes: []const u8, deadline: i64, started: *bool) Err!void { var off: usize = 0; while (off < bytes.len) { - const left = deadline - nowMs(); - if (left <= 0) return error.Timeout; + if (!started.*) { + if (deadline - nowMs() <= 0) return error.Timeout; + if (io) |cancel_io| cancel_io.checkCancel() catch return error.Canceled; + } else if (nowMs() - deadline > wedge_ms) return error.Dead; var pfd = [_]libc.pollfd{.{ .fd = sock, .events = POLLOUT, .revents = 0 }}; - const pr = libc.poll(&pfd, 1, @intCast(@min(left, 1000))); + const pr = libc.poll(&pfd, 1, 500); if (pr < 0) { if (libc.errno(pr) == .INTR) continue; return error.Dead; @@ -2096,6 +2367,7 @@ fn sockWrite(sock: c_int, bytes: []const u8, deadline: i64) Err!void { return error.Dead; } if (n == 0) return error.Dead; + started.* = true; off += @intCast(n); } } @@ -2318,7 +2590,7 @@ test "caller trees reverse incoming paths and merge shared callers and sites" { try std.testing.expectEqual(@as(usize, 1), tree.roots.items.len); try std.testing.expectEqual(@as(usize, 4), tree.nodes.items.len); const root = tree.nodes.items[tree.roots.items[0]]; - try std.testing.expectEqualStrings("main", str(get(root.item, "name")).?); + try std.testing.expectEqualStrings("main", root.call.name); try std.testing.expectEqual(@as(usize, 1), root.ranges.items.len); const page = tree.nodes.items[root.children.items[0]]; try std.testing.expectEqual(@as(usize, 2), page.children.items.len); @@ -2355,6 +2627,32 @@ test "caller trees reverse incoming paths and merge shared callers and sites" { try std.testing.expect(recursive.nodes.items[1].cycle); } +test "test callers sort after the rest, each group by place" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"name\":\"test b\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"z\",\"uri\":\"file:///b.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"x\",\"uri\":\"file:///a_test.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"y\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":5,\"character\":0},\"end\":{\"line\":5,\"character\":1}}}]", .{}); + var tree: CallTree = .{}; + for (items(fixture)) |item| try tree.nodes.append(arena, .{ .call = try callOf(arena, item) }); + var order = [_]usize{ 0, 1, 2, 3 }; + std.mem.sort(usize, &order, @as(*const CallTree, &tree), callerLess); + try std.testing.expectEqualSlices(usize, &.{ 3, 1, 0, 2 }, &order); +} + +test "a mailbox wait is a cancelation point: a canceled worker stops waiting" { + const io = std.testing.io; + var c: Conn = .{}; + const Waiter = struct { + fn run(conn: *Conn, wio: std.Io) error{Canceled}!void { + conn.mu.lockUncancelable(wio); + defer conn.mu.unlock(wio); + while (true) _ = try timedWait(conn, wio, nowMs() + 60_000); + } + }; + var future = try io.concurrent(Waiter.run, .{ &c, io }); + try std.testing.expectError(error.Canceled, future.cancel(io)); +} + test "callstack cross-crate paths remain resolvable without absolute path clutter" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); @@ -2584,37 +2882,38 @@ test "a language with no server to start says so, not that it did not answer" { defer arena.deinit(); var buf: [256]u8 = undefined; var out: std.Io.Writer = .fixed(&buf); - try query(std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); try std.testing.expectEqualStrings("@none language server for .py not found\n", out.buffered()); } test "Lspinfo before any query says a server is not started yet, not off" { var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); - try status(.{ .kind = .status, .path = "", .source = "", .offset = 0 }, &out.writer); + try status(std.testing.io, .{ .kind = .status, .path = "", .source = "", .offset = 0 }, &out.writer); try std.testing.expect(std.mem.indexOf(u8, out.written(), "not started yet (its first query starts it)") != null); } test "a server that failed a moment ago is said to have failed, and when it is tried again, not to be missing" { if (getenv("PARDES_LSP_ZIG") != null) return error.SkipZigTest; + const io = std.testing.io; const si = specFor("/x/a.zig").?; const c = &conns[si]; - c.lock(); + c.mu.lockUncancelable(io); const was = .{ c.state, c.retry_after_ms }; c.state = .dead; c.retry_after_ms = nowMs() + 4500; - c.unlock(); + c.mu.unlock(io); defer { - c.lock(); + c.mu.lockUncancelable(io); c.state = was[0]; c.retry_after_ms = was[1]; - c.unlock(); + c.mu.unlock(io); } var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); - try query(std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer); try std.testing.expect(std.mem.indexOf(u8, out.written(), "zls failed recently; retry in 5s") != null); } diff --git a/src/macos.zig b/src/macos.zig index 50fa04fa..5d3dfec4 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -44,7 +44,11 @@ fn hostWatchFile(pane: u8, generation: u32, path: ?[*]const u8, path_len: usize) const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); -pub const std_options: std.Options = .{ .logFn = logFn }; +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 }; fn logFn( comptime level: std.log.Level, @@ -2419,7 +2423,7 @@ fn pipeWorker(st: *State, job: *selection_pipe.Job) anyerror!void { } fn lspWorker(st: *State, job: *host_io.Lsp.Job) anyerror!void { - host_io.Lsp.work(st.gpa, job, st, deliverLspRows); + host_io.Lsp.work(st.io, st.gpa, job, st, deliverLspRows); } fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -2582,12 +2586,11 @@ fn reap(st: *State, pane: u8) void { } fn readPty(st: *State, io: std.Io, pty: std.Io.File, id: u8, gen: u32) anyerror!void { - var read_buf: [0x10000]u8 = undefined; - var reader = pty.readerStreaming(io, &read_buf); + // 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; while (true) { - var buf: [0x10000]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = pty.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; const bytes = st.gpa.dupe(u8, buf[0..n]) catch break; st.inbox.pushOutput(st.gpa, io, .{ .pane = id, .gen = gen, .bytes = bytes }) catch break; diff --git a/src/main.zig b/src/main.zig index 64614daa..ea2db917 100644 --- a/src/main.zig +++ b/src/main.zig @@ -16,7 +16,11 @@ pub const std_options_debug_io: std.Io = if (is_emscripten) else std_options_debug_threaded_io.?.io(); -pub const std_options: std.Options = .{ .logFn = logFn }; +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 }; fn logFn( comptime level: std.log.Level, @@ -328,7 +332,11 @@ fn webMain() !void { // malloc otherwise. Kept on purpose: glibc's malloc was measured at least as // fast as std.heap.smp_allocator on every scenario and faster on MuPDF's // page-sized rasters. macos.zig makes the same choice for itself. -fn nativeMain(init: std.process.Init) !void { +fn nativeMain(std_init: std.process.Init) !void { + var init = std_init; + // Zig 0.17's std.start gives a safe build a SafeAllocator over the page + // allocator, not libc's malloc: hand the shells malloc, as above. + if (builtin.mode != .debug) init.gpa = std.heap.c_allocator; var stderr_probe: [64]u8 = undefined; _ = std.debug.lockStderr(&stderr_probe); std.debug.unlockStderr(); diff --git a/src/memory.zig b/src/memory.zig index 48403c55..853d641a 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -16,6 +16,10 @@ pub const limits = struct { pub const pending_write_cap: usize = if (board) 0 else 4 * MiB; pub const wrap_rows = if (board) 128 else 256; pub const undo_max = if (board) 16 else 256; + /// The text a file's undo and redo steps hold together, kept by dropping + /// the oldest; the newest step always stays, so the bound per file is + /// this plus one snapshot (at most max_file_bytes). + pub const undo_bytes: usize = if (board) 64 * KiB else 64 * MiB; pub const message_log = if (board) 16 else 128; /// ranges one selection holds; helix has no limit, and a `%s` over a /// file's words wants hundreds @@ -23,6 +27,19 @@ pub const limits = struct { /// /log's ring, which records whether or not anyone reads it. pub const log_bytes: usize = if (board) 4 * KiB else 64 * KiB; pub const max_tag_tail: usize = if (board) 512 else 4096; + /// Pixels one image may decode to (RGBA, 4 bytes each): checked from its + /// header before stb_image allocates them. + pub const image_decode_pixels: usize = if (board) 0 else 64 * 1024 * 1024; + /// What the core's per-step scratch arena and the frame arena keep + /// between steps: a step that needed more (a huge Callstack's sources) + /// gives the rest back instead of holding its high-water mark. + pub const scratch_kept: usize = if (board) 4 * KiB else 16 * MiB; + pub const frame_kept: usize = if (board) 4 * KiB else 16 * MiB; + /// The other open files one language query copies for its server, in + /// bytes: past it the rest are left out (the asked file always goes). + pub const lsp_snapshot_bytes: usize = if (board) 0 else 64 * MiB; + /// One paste, from any shell: past it, the rest is left out and said. + pub const max_paste_bytes: usize = if (board) 16 * KiB else 4 * MiB; pub const host_path_cap: usize = if (board) 0 else 4095; /// -Dembed-sources: the editor serves its own sources under /src. pub const embedded_sources = config.embed_sources; @@ -34,6 +51,10 @@ pub const limits = struct { pub const tree_sitter = if (board) 0 else if (reduced_target) 4 * MiB else 16 * MiB; pub const image = if (board) 0 else if (reduced_target) 64 * KiB else 32 * MiB; pub const pdf = if (board) 0 else if (reduced_target or !config.mupdf) 64 * KiB else 64 * MiB; + /// One language query's working memory (its parsed answers, the rows + /// it writes): a hard bound, nothing spills. Callstack walks until it + /// would leave less than its rendering reserve. + pub const lsp_query = if (board or reduced_target) 0 else 256 * MiB; }; }; @@ -96,6 +117,82 @@ var frame_buffer: [limits.arena.frame]u8 = @splat(0); var tree_sitter_buffer: [limits.arena.tree_sitter]u8 = @splat(0); var image_buffer: [limits.arena.image]u8 = @splat(0); var pdf_buffer: [limits.arena.pdf]u8 = @splat(0); +var lsp_query_buffer: [limits.arena.lsp_query]u8 align(std.heap.page_size_max) = @splat(0); +var lsp_query_busy: std.atomic.Value(bool) = .init(false); +/// What a query may leave resident of the region (giveLspQuery). +const lsp_query_kept = 8 * MiB; + +/// The language query region, for the one query running; null while another +/// holds it (the shells cancel and join a query before starting the next). +pub fn takeLspQuery() ?[]u8 { + if (lsp_query_busy.swap(true, .acquire)) return null; + return &lsp_query_buffer; +} + +/// Gives the region back after a query. A big one's touched pages go back to +/// the system (zeroed again on their next touch, as .bss is), so one huge +/// answer does not stay resident; a small one's stay, for the next query to +/// reuse without faulting them in again. +pub fn giveLspQuery(used: usize) void { + if (comptime builtin.os.tag == .linux) if (used > lsp_query_kept) { + const page = std.heap.pageSize(); + const len = std.mem.alignForward(usize, @min(used, lsp_query_buffer.len), page); + std.posix.madvise(@as([*]align(std.heap.page_size_min) u8, @ptrCast(&lsp_query_buffer)), len, std.posix.MADV.DONTNEED) catch {}; + }; + lsp_query_busy.store(false, .release); +} + +/// `n` bytes as they come: `Allocator.alloc` fills a safe build's new memory +/// as `undefined` (0xAA), which writes, and makes resident, all of a buffer +/// sized for the worst case: every language query wrote its 51 MB answer +/// room, every search its 16 MiB. For buffers written before they are read. +pub fn unfilled(allocator: Allocator, n: usize) Allocator.Error![]u8 { + if (n == 0) return allocator.alloc(u8, 0); + const ptr = allocator.rawAlloc(n, .of(u8), @returnAddress()) orelse return error.OutOfMemory; + return ptr[0..n]; +} + +/// `bytes` copied into memory `unfilled` takes: a text-sized copy (an undo +/// snapshot) is written once, not filled first. +pub fn dupeUnfilled(allocator: Allocator, bytes: []const u8) Allocator.Error![]u8 { + const out = try unfilled(allocator, bytes.len); + @memcpy(out, bytes); + return out; +} + +/// Frees without the safe-build overwrite `free` does, for text-sized buffers +/// freed on every edit. +pub fn freeUnfilled(allocator: Allocator, bytes: []const u8) void { + if (bytes.len > 0) allocator.rawFree(@constCast(bytes), .of(u8), @returnAddress()); +} + +/// Gives libc's free memory back to the system, inside its heap too: after a +/// big result is formatted or a big pane torn down, glibc keeps what was freed +/// (a V8 Callstack page left 21 MiB free in the heap; this returned 20). +/// Walks the heap, so for rare, large events only. +pub fn trim() void { + if (comptime builtin.os.tag != .linux or builtin.abi.isMusl() or !builtin.link_libc) return; + const glibc = struct { + extern "c" fn malloc_trim(pad: usize) c_int; + }; + _ = glibc.malloc_trim(0); +} + +/// Marks a big region that is touched sparsely as not for huge pages. With +/// transparent huge pages on `always` (a common default), touching one byte +/// of a 2 MiB-aligned stretch makes all 2 MiB resident: the 9P runner's +/// slots and these arenas' first pages held 45 MiB of an idle session's +/// 71 MiB that way. Only the region given, never the whole process (a prctl +/// would reach every shell and server pardes starts). +pub fn sparse(region: []u8) void { + if (comptime builtin.os.tag != .linux) return; + const page = std.heap.pageSize(); + const start = std.mem.alignForward(usize, @intFromPtr(region.ptr), page); + const end = std.mem.alignBackward(usize, @intFromPtr(region.ptr) + region.len, page); + if (end <= start) return; + std.posix.madvise(@ptrFromInt(start), end - start, std.posix.MADV.NOHUGEPAGE) catch {}; +} + var pardes_fallback: SharedStackFallback = .{ .buffer = &pardes_buffer }; var frame_fallback: SharedStackFallback = .{ .buffer = &frame_buffer }; var tree_sitter_fallback: SharedStackFallback = .{ .buffer = &tree_sitter_buffer }; @@ -118,6 +215,7 @@ pub fn init(fallback: Allocator) Allocators { // a Debug build `fallback` is std.process.Init's gpa, a DebugAllocator // already, and a second one checked every block twice. const backing = if (debug_enabled) std.heap.page_allocator else fallback; + inline for (.{ &pardes_buffer, &frame_buffer, &tree_sitter_buffer, &image_buffer, &pdf_buffer, &lsp_query_buffer }) |buffer| sparse(buffer); pardes_fallback.fallback_allocator = backing; frame_fallback.fallback_allocator = backing; tree_sitter_fallback.fallback_allocator = backing; diff --git a/src/mini.zig b/src/mini.zig index ce291c99..8d8ea0b2 100644 --- a/src/mini.zig +++ b/src/mini.zig @@ -313,7 +313,21 @@ test "Mini publishes only complete snapshots and content replacement drops metad const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; var path_buf: [4096]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); + // Growth that never resizes in place: whether a resize fits where it is + // depends on the heap's layout, and with it how many allocations a run + // makes, which checkAllAllocationFailures needs to be the same each run. + const NoResize = struct { + fn resize(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) bool { + return false; + } + fn remap(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) ?[*]u8 { + return null; + } + }; + const testing_vtable = std.testing.allocator.vtable; + const no_resize_vtable: std.mem.Allocator.VTable = .{ .alloc = testing_vtable.alloc, .resize = NoResize.resize, .remap = NoResize.remap, .free = testing_vtable.free }; + const backing: std.mem.Allocator = .{ .ptr = std.testing.allocator.ptr, .vtable = &no_resize_vtable }; + try std.testing.checkAllAllocationFailures(backing, Case.run, .{path}); } test "Mini refuses a file that is no UTF-8, before its decoding could panic" { diff --git a/src/modal.zig b/src/modal.zig index 82f1a3a0..ad06833f 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -989,13 +989,77 @@ pub fn lineCount(content: []const u8) usize { // byte offset of the start of line `row` (0-based). row may == lineCount() // (== content.len, the end). pub fn lineStartOffset(content: []const u8, row: usize) usize { + // Newlines counted 32 bytes at a time, the last block byte by byte: one + // indexOfScalarPos per line was a call per line, 7000 of them to find + // line 7000 of a source, for every cursor move, selection and language + // request there. + const block = 32; + const Block = @Vector(block, u8); var off: usize = 0; - var r: usize = 0; - while (r < row) : (r += 1) { - const nl = std.mem.indexOfScalarPos(u8, content, off, '\n') orelse return content.len; - off = nl + 1; + var left = row; + if (left == 0) return 0; + while (off + block <= content.len) : (off += block) { + const chunk: Block = content[off..][0..block].*; + const found: usize = @popCount(@as(u32, @bitCast(chunk == @as(Block, @splat('\n'))))); + if (found >= left) break; + left -= found; + } + while (off < content.len) : (off += 1) if (content[off] == '\n') { + left -= 1; + if (left == 0) return off + 1; + }; + 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)); + // rangeBytes, as it was: each line looked for from the top, twice. + const other: Cursor = .{ .row = random.uintLessThan(usize, len + 3), .col = random.uintLessThan(usize, 6) }; + var lo = cursor; + var hi = other; + if (hi.row < lo.row or (hi.row == lo.row and hi.col < lo.col)) std.mem.swap(Cursor, &lo, &hi); + const lo_line = lineSlice(text, lo.row); + const hi_line = lineSlice(text, hi.row); + const s0 = lineStartOffset(text, lo.row) + graphemeStart(lo_line, @min(lo.col, lo_line.len)); + var e0 = lineStartOffset(text, hi.row) + graphemeStart(hi_line, @min(hi.col, hi_line.len)); + if (e0 < text.len) e0 = nextGrapheme(text, e0); + const got = rangeBytes(text, cursor, other); + try std.testing.expectEqual(s0, got.s); + try std.testing.expectEqual(@max(s0, e0), got.e); + } } - return off; +} + +/// The line that starts at `start` (lineSlice's, once its start is known). +fn lineFrom(content: []const u8, start: usize) []const u8 { + if (start >= content.len) return ""; + return content[start .. std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len]; } // the text of line `row` (no terminator), a slice into `content`. @@ -1011,23 +1075,29 @@ pub fn lineSlice(content: []const u8, row: usize) []const u8 { /// A bounded scan of one line; null if the row does not exist. pub const LineSpan = struct { start: usize, end: usize }; +/// Just past the `row`-th newline; null if the text has fewer. +pub fn lineStartExact(content: []const u8, row: usize) ?usize { + const at = lineStartOffset(content, row); + // At the end: either the row-th newline was the last byte, or there were fewer. + if (at == content.len and std.mem.count(u8, content, "\n") < row) return null; + return at; +} + pub fn lineSpan(content: []const u8, row: usize) ?LineSpan { // Match lineCount: empty content has no lines; a trailing newline adds one. if (content.len == 0) return null; - var start: usize = 0; - var r: usize = 0; - while (r < row) : (r += 1) { - const nl = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse return null; - start = nl + 1; - } - if (start > content.len) return null; + const start = lineStartExact(content, row) orelse return null; if (start == content.len and !(row == 0 or content.len == 0 or content[content.len - 1] == '\n')) return null; const end = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len; return .{ .start = start, .end = end }; } -fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: usize, replacement: []const u8) ![]u8 { - const out = try alloc.alloc(u8, content.len - (end - start) + replacement.len); +pub fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: usize, replacement: []const u8) ![]u8 { + // Raw: every byte is written below, where `alloc` fills a safe build's + // new memory first, a whole file's worth per keystroke. + const len = content.len - (end - start) + replacement.len; + if (len == 0) return alloc.alloc(u8, 0); + const out = (alloc.rawAlloc(len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..len]; @memcpy(out[0..start], content[0..start]); @memcpy(out[start..][0..replacement.len], replacement); @memcpy(out[start + replacement.len ..], content[end..]); @@ -1036,13 +1106,18 @@ fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: /// insert `text` at (row, col). col is clamped to the line length. pub fn insertAt(alloc: std.mem.Allocator, content: []const u8, c: Cursor, text: []const u8) ![]u8 { + const off = insertOffset(content, c); + return spliceAlloc(alloc, content, off, off, text); +} + +/// Where insertAt puts its text: col clamped to the line, no further. +pub fn insertOffset(content: []const u8, c: Cursor) usize { // Only an out-of-range row requires counting the whole document. const span = lineSpan(content, c.row) orelse blk: { const last = lineCount(content) -| 1; break :blk lineSpan(content, last) orelse LineSpan{ .start = content.len, .end = content.len }; }; - const off = span.start + @min(c.col, span.end - span.start); - return spliceAlloc(alloc, content, off, off, text); + return span.start + @min(c.col, span.end - span.start); } // delete the character at (row, col). no-op if col is past the line end. @@ -1105,12 +1180,15 @@ fn rangeBytes(content: []const u8, a: Cursor, b: Cursor) struct { s: usize, e: u lo = b; hi = a; } - const lo_line = lineSlice(content, lo.row); - const hi_line = lineSlice(content, hi.row); + // Each line found once, the second from the first. + const lo_start = lineStartOffset(content, lo.row); + const hi_start = if (hi.row == lo.row) lo_start else lo_start + lineStartOffset(content[lo_start..], hi.row - lo.row); + const lo_line = lineFrom(content, lo_start); + const hi_line = lineFrom(content, hi_start); const lo_col = graphemeStart(lo_line, @min(lo.col, lo_line.len)); const hi_col = graphemeStart(hi_line, @min(hi.col, hi_line.len)); - const s = lineStartOffset(content, lo.row) + lo_col; - var e = lineStartOffset(content, hi.row) + hi_col; + const s = lo_start + lo_col; + var e = hi_start + hi_col; if (e < content.len) e = nextGrapheme(content, e); // include the grapheme under the head return .{ .s = s, .e = @max(s, e) }; } @@ -1138,12 +1216,12 @@ pub fn clearLine(alloc: std.mem.Allocator, content: []const u8, row: usize) ![]u // paste `text` as a new line BELOW `row`. Multiline `text` becomes several lines. pub fn pasteLineBelow(alloc: std.mem.Allocator, content: []const u8, row: usize, text: []const u8) ![]u8 { - const n = lineCount(content); - const off = if (row + 1 < n) lineStartOffset(content, row + 1) else content.len; + // The next line's start, or the end: no whole-text line count to know which. + const off = lineStartExact(content, row + 1) orelse content.len; const suffix_newline = off < content.len or (content.len > 0 and content[content.len - 1] == '\n'); const prefix_newline = !suffix_newline and off > 0; const extra: usize = @intFromBool(suffix_newline or prefix_newline); - const out = try alloc.alloc(u8, content.len + text.len + extra); + const out = try @import("memory.zig").unfilled(alloc, content.len + text.len + extra); var write: usize = 0; @memcpy(out[write..][0..off], content[0..off]); write += off; @@ -1393,8 +1471,10 @@ pub fn positionAt(text: []const u8, off: usize) Cursor { /// (row, col) -> clamped gap offset; col == line length lands ON the '\n' pub fn offsetAt(text: []const u8, c: Cursor) usize { - const row = @min(c.row, cursorLineCount(text) - 1); - const s = lineStartOffset(text, row); + // A row past the last is the last: found back from the end, where + // counting every line of the text to clamp it cost a pass over all of it. + var s = lineStartOffset(text, c.row); + if (s == text.len) s = if (std.mem.lastIndexOfScalar(u8, text, '\n')) |nl| nl + 1 else 0; // lineEndOffset(text, row) inlined: it starts by walking to `row` again, // and we are already standing there const e = std.mem.indexOfScalarPos(u8, text, s, '\n') orelse text.len; @@ -1783,15 +1863,6 @@ test "selection textobjects distinguish words and paragraph boundaries" { try std.testing.expectEqual(@as(usize, 7), r.head); } -/// leading-whitespace visual width (tab -> next multiple of INDENT_W) -pub fn indentWidth(line: []const u8) usize { - var w: usize = 0; - for (line) |ch| { - if (ch == ' ') w += 1 else if (ch == '\t') w = (w / INDENT_W + 1) * INDENT_W else break; - } - return w; -} - /// 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 { diff --git a/src/mouse.zig b/src/mouse.zig index 76c65a16..eeb987b2 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1114,7 +1114,9 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { /// second selects what edit.doubleClickRange says, from the caret the click /// left. A plain click still puts the caret on its cell. fn doubleClick(p: *Pardes, id: usize, t: *panes.Text, on_tag: bool, row: i32, col: i32) void { - const now = clockMs(); + // The host's clock, which every host keeps (a libc clock is no clock on + // the web or the board) and a test's virtual one replaces. + const now: i64 = @intCast(p.now_ns / std.time.ns_per_ms); const prev = p.last_click; p.last_click = .{ .id = id, .on_tag = on_tag, .row = row, .col = col, .ms = now }; const c = prev orelse return; @@ -1160,13 +1162,6 @@ fn sweepPoint(p: *Pardes, pane: *panes.Pane, r: i32, c: i32) ?modal.Cursor { return .{ .row = @intCast(w.line), .col = @intCast(@max(0, col)) }; } -fn clockMs() i64 { - if (comptime !pardes.hosted) return 0; - var ts: std.c.timespec = undefined; - if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; - return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000); -} - fn dragRelease(p: *Pardes, button: Mouse.Button) void { // A different button's release belongs to a chord or another host // stream; only the button which began this gesture may end it. diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index 86d2d49e..7753c94d 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -239,21 +239,15 @@ pub const Addr = struct { k = @intFromBool(a.text[p] == '\n'); p += 1; } - while (k < n) { - if (p >= nc) { + if (k < n) { + p = nthLineAfter(a.text, p, n - k) orelse { a.err = e_range; return null; - } - if (a.text[p] == '\n') k += 1; - p += 1; + }; } p1 = p; } - while (p < nc) { - const ch = a.text[p]; - p += 1; - if (ch == '\n') break; - } + p = if (std.mem.indexOfScalarPos(u8, a.text, p, '\n')) |nl| nl + 1 else nc; return .{ .q0 = clip(p1), .q1 = clip(p) }; } @@ -678,3 +672,31 @@ test "a line just past the last newline is an empty one there, as sam's lineaddr try testing.expectEqual(Status.ok, th.wr(p, Node.of(th.serialOf(p), .ctl), "Edit 1i/header/\n").reply.status); try testing.expectEqualStrings("header", p.panes[0].?.file.?.content); } + +/// Just past the `count`-th newline at or after `from`; null if the text has +/// fewer. Counted a block at a time (modal.lineStartOffset), where a byte at +/// a time made `echo 7000 > addr` walk every byte above line 7000. +fn nthLineAfter(text: []const u8, from: usize, count: usize) ?usize { + return from + (modal.lineStartExact(text[from..], count) orelse return null); +} + +test "nthLineAfter finds what a byte at a time finds" { + var prng: std.Random.DefaultPrng = .init(0x51ab); + const random = prng.random(); + var buf: [200]u8 = undefined; + for (0..3000) |_| { + const len = random.uintLessThan(usize, buf.len); + for (buf[0..len]) |*b| b.* = if (random.uintLessThan(u8, 3) == 0) '\n' else 'x'; + const text = buf[0..len]; + const from = random.uintLessThan(usize, len + 1); + const count = 1 + random.uintLessThan(usize, 40); + var p = from; + var k: usize = 0; + const want: ?usize = while (k < count) { + if (p >= text.len) break null; + if (text[p] == '\n') k += 1; + p += 1; + } else p; + try std.testing.expectEqual(want, nthLineAfter(text, from, count)); + } +} diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 733d9c8e..480c1dc7 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4684,6 +4684,10 @@ test "what a /pager open writes after its directory is the text: plain in the bo // An edit drops the colours (pager.zig's ponytail). try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = Node.of(pn.serial, .body), .data = "more\n" }).reply.status); try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + // Undone back to the paged text: its colours come back with it. + panes.File.undo(p, pn); + try testing.expectEqualStrings("red /a\nNext\n", f.content); + try testing.expectEqual(@as(usize, 2), f.pager_spans.len); // PagerColor off, and an open closed with no read: the same text, plain, // in at the editor's next step (a close through a mount never waits). diff --git a/src/panes.zig b/src/panes.zig index 7ce85419..b535993e 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -133,6 +133,9 @@ pub const Pane = struct { /// Its pty is still open: a job the command left in the background may /// be printing to it, and a reuse would hang it up. command_pty: bool = false, + /// Its child pages as a terminal's does (`pardes -`, a +Pager), not + /// through cat: Look's `git show` of a commit (look.lookCommit). + command_pages: bool = false, /// The shell a terminal runs when it is not the configured one (`Tty /// fish`), owned. shell: ?[]u8 = null, diff --git a/src/pardes.zig b/src/pardes.zig index aaa9d177..c2a3ba21 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -478,6 +478,7 @@ pub const Loc = struct { }; test { + _ = @import("modal.zig"); _ = @import("tagline.zig"); _ = @import("hunks.zig"); _ = @import("builtins_json.zig"); @@ -4645,6 +4646,10 @@ pub const Pardes = struct { /// The last query asked (Lspwhy explains it): its kind, argument, and /// the pane and place it was asked at. lsp_last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } = null, + /// The Callstack page `+Callstack` shows stopped short: its file's pane, + /// the place it was asked at, and the direct caller the next page starts + /// at. Callstack run in `+Callstack` asks for it. + callstack_more: ?struct { serial: u32, offset: u32, next: Effect.Buf(128) } = null, lsp_wait: ?struct { id: u32, kind: lsp.Kind, @@ -5168,10 +5173,13 @@ pub const Pardes = struct { } fn reapPanes(p: *Pardes) void { + var reaped = false; for (&p.retired_panes.previous) |*slot| if (slot.*) |pane| { p.teardownPane(pane); slot.* = null; + reaped = true; }; + if (reaped) memory.trim(); p.retired_panes.previous = p.retired_panes.current; p.retired_panes.current = @splat(null); } @@ -5544,7 +5552,7 @@ pub const Pardes = struct { p.invalidate(); look.invalidateLookHover(p, id); const applied = p.applyWatchedFileChanged(id, bytes); - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); return applied; } @@ -6000,7 +6008,7 @@ pub const Pardes = struct { // A pty streaming into an unwatched session spent most of its time // drawing what nobody looked at. if (v.watched) |f| if (!f(h.ctx)) return; - _ = p.frame_arena.reset(.retain_capacity); + _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); const surface = try p.render(p.frame_arena.allocator()); if (v.present) |f| f(h.ctx, surface); // Settled before post_present: a shell ticks there, and what that @@ -6202,7 +6210,7 @@ pub const Pardes = struct { look.advanceLookHover(p); }, } - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); ctlfs.events.announce(p); @@ -6777,6 +6785,19 @@ pub const Pardes = struct { pub const SavePath = Effect.Buf(effect_path_cap); pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void { + p.lspRequestAt(asked, kind, arg_in, null); + } + + /// The next page of the Callstack `+Callstack` shows, asked where the + /// first was. + pub fn callstackMore(p: *Pardes, from: usize) void { + const more = p.callstack_more orelse return p.reportFailure(from, "Callstack: this is the last page; run it in a file to start again"); + const id = p.paneBySerial(more.serial) orelse return p.reportFailure(from, "Callstack: the file it was asked in is closed"); + p.lspRequestAt(id, .callstack, more.next.slice(), more.offset); + } + + /// `lspRequest` at byte `at` of the pane's file rather than its cursor. + fn lspRequestAt(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8, at_byte: ?u32) void { var arg = arg_in; if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary // Lspwhy narrates the last query where it was asked -- that pane's @@ -6800,7 +6821,7 @@ pub const Pardes = struct { (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null)) return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name"); } - var off = if (pane.file) |f| modal.offsetAt(f.content, .{ + var off = if (at_byte) |at| @min(at, if (pane.file) |f| f.content.len else 0) else if (pane.file) |f| modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)), }) else 0; @@ -7089,13 +7110,24 @@ pub const Pardes = struct { } const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); - const content = p.gpa.dupe(u8, rows) catch return; + // A Callstack page that stops short ends in its marker: said as a + // row naming the word that shows the next page, and kept. + if (w.kind == .callstack) p.callstack_more = null; + const marker = if (w.kind == .callstack) std.mem.lastIndexOf(u8, rows, lsp.callstack_more) else null; + const content = if (marker) |at| more: { + var fields = std.mem.tokenizeAny(u8, rows[at + lsp.callstack_more.len ..], " \n"); + const next = fields.next() orelse ""; + const shown = fields.next() orelse "?"; + if (p.lsp_last) |last| p.callstack_more = .{ .serial = w.serial, .offset = last.offset, .next = .from(next) }; + break :more std.fmt.allocPrint(p.gpa, "{s}… {s} callers on this page, more after them: Callstack here shows the next page\n", .{ rows[0..at], shown }) catch return; + } else p.gpa.dupe(u8, rows) catch return; const serial_before = p.next_serial; p.fs.refilled = null; panes.Output.fillResults(p, w.pane, dir, from, w.arg.slice(), content, null) catch |err| { p.reportError(w.pane, "language response", err); return; }; + if (rows.len >= 1 << 20) memory.trim(); // What a 9P write that asked it answers: the pane the rows are in // (a multi-file Rename's preview, Lspinfo's +Lsp), made or filled // again, not the pane it was asked from. diff --git a/src/regexp.zig b/src/regexp.zig index 4cbca57e..6d281859 100644 --- a/src/regexp.zig +++ b/src/regexp.zig @@ -283,7 +283,10 @@ pub const Regex = struct { /// its top level and every branch starts with `^`; null when it is not /// one, or no branch does. fn anchoredAlternation(pat: []const u8, out: *[5 * max_ops + 2]u8) error{ Bad, Mixed }!?[]const u8 { - var bars: [16]usize = undefined; + // No rewrite is longer than `out`, so neither is any pattern it + // takes, nor its count of bars. + if (pat.len > out.len) return error.Bad; + var bars: [5 * max_ops + 2]u16 = undefined; var n: usize = 0; var depth: usize = 0; var in_class = false; @@ -301,8 +304,7 @@ pub const Regex = struct { } else if (c == ')') { depth -|= 1; } else if (c == '|' and depth == 0) { - if (n == bars.len) return error.Bad; - bars[n] = i; + bars[n] = @intCast(i); n += 1; } } @@ -518,6 +520,9 @@ test "a ^ after | anchors that branch: ^def|^ finds a line that starts either w try std.testing.expectError(error.Mixed, Regex.compile("^def|x")); var plain = try Regex.compile("a|b"); try std.testing.expectEqual(@as(usize, 7), (try plain.find(text, 0, text.len, text.len)).?.start); + // Seventeen branches and more are a pattern like any other. + var many = try Regex.compile("q|r|s|t|u|v|w|x|y|z|k|l|m|n|o|p|j|b"); + try std.testing.expectEqual(@as(usize, 0), (try many.find(text, 0, text.len, text.len)).?.start); } test "a quoted backslash before n is no newline, and a class ends where mvzr ends it" { diff --git a/src/sam_edit.zig b/src/sam_edit.zig index f6253c89..94b76816 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -259,6 +259,10 @@ fn fail(why: *Why, comptime fmt: []const u8, args: anytype) Failure { // ---- parsing: edit.c ---- +/// Commands one Edit may nest, loops (`x`, `y`, `g`, `v`, `X`, `Y`) and +/// braces together: each level is a stack frame holding a compiled regex. +pub const max_nest = 32; + const Parser = struct { arena: std.mem.Allocator, src: []const u8, @@ -271,6 +275,9 @@ const Parser = struct { open_text: bool = false, /// The address being read had a `,` after a `"re"`. file_comma: bool = false, + /// Commands open around the one being read, braces and loops alike: + /// each is a frame of `parse` and later of `execIn`, so it is bounded. + depth: u8 = 0, why: *Why, fn getch(ps: *Parser) ?u8 { @@ -460,6 +467,9 @@ const Parser = struct { /// edit.c:467, parsecmd. fn parse(ps: *Parser, nest: u32) Failure!?*Cmd { + if (ps.depth >= max_nest) return fail(ps.why, "commands nested more than {d} deep", .{max_nest}); + ps.depth += 1; + defer ps.depth -= 1; var file_re: ?[]const u8 = null; ps.file_comma = false; const a = try ps.address(&file_re); @@ -1163,6 +1173,11 @@ test "an Edit that fails halfway changes nothing, and says why in acme's words" .{ "e /tmp/x", "can't open /tmp/x: no files here" }, .{ "\"zz\" p", "no file matches \"zz\"" }, .{ ",s/(a)/\\1/", "no \\1: mvzr keeps no submatches" }, + .{ comptime deep: { + var loops: []const u8 = ""; + for (0..40) |_| loops = loops ++ ",x/a/"; + break :deep loops ++ "d"; + }, "commands nested more than 32 deep" }, .{ "1 m 1,2", "move overlaps itself" }, .{ ",x/(^|\\n)foo/d", "bad regular expression: in a pattern with \\n, ^ can only come first and $ only just before a \\n" }, }) |c| { diff --git a/src/selection_pipe.zig b/src/selection_pipe.zig index c3e5e3a6..229b3d67 100644 --- a/src/selection_pipe.zig +++ b/src/selection_pipe.zig @@ -401,7 +401,7 @@ pub fn runIn( }, }; child.stdin = null; // writer_context owns and closes this endpoint - var writer: ?std.Thread = std.Thread.spawn(.{}, writeInput, .{writer_context}) catch { + var writer: ?std.Io.Future(void) = io.concurrent(writeInput, .{writer_context}) catch { writer_context.file.close(io); gpa.free(writer_context.input); gpa.destroy(writer_context); @@ -410,8 +410,9 @@ pub fn runIn( }; // On every early return (a timeout, a ceiling) the answer goes at once: // the group is killed and the shell left to be reaped elsewhere - // (abandon), and the writer, which owns its input, let go. - defer if (writer) |thread| thread.detach(); + // (abandon), and the writer's write canceled (it closes and frees what + // it owns as it ends). + defer if (writer) |*w| w.cancel(io); defer if (child.id != null) abandonNow(io, &child, pid); defer if (token != 0) Running.remove(pid); if (token != 0 and !Running.add(token, pid)) return fail.k(.signal); @@ -443,7 +444,9 @@ pub fn runIn( multi_reader.checkAnyError() catch return fail.k(.io); if (token != 0) Running.remove(pid); const term = child.wait(io) catch return fail.k(.io); - writer.?.join(); + // A cancel of this job reaches the write too: a grandchild that keeps + // stdin open and never reads holds no worker. + writer.?.await(io); writer = null; const stdout = multi_reader.toOwnedSlice(0) catch return fail.k(.io); diff --git a/src/surface.zig b/src/surface.zig index e67cf21c..d6ec016d 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -533,11 +533,6 @@ pub const Surface = struct { return s.cell_diffs[@as(usize, y) * s.cols + x].changed(); } - pub fn panelCellDiff(s: *const Surface, x: u16, y: u16) PanelCellDiff { - if (!s.hasPanelDiff() or x >= s.cols or y >= s.rows) return .unchanged; - return s.cell_diffs[@as(usize, y) * s.cols + x]; - } - pub fn at(s: *Surface, x: u16, y: u16) *Cell { std.debug.assert(x < s.cols and y < s.rows); return &s.cells[@as(usize, y) * s.cols + x]; diff --git a/src/terminal.zig b/src/terminal.zig index 33ad22e6..05054521 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1,4 +1,4 @@ -//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay +//! A terminal pane: its VT emulator, prompt rows, the edit overlay //! typed over shell rows, and the Filter that recolours output to the theme. const panes = @import("panes.zig"); const std = @import("std"); @@ -141,16 +141,9 @@ pub const MarkedHandler = if (enabled) struct { } } else void; -pub const Replay = struct { - bytes: [1024 * 1024]u8 = undefined, - head: usize = 0, - len: usize = 0, -}; - pub const State = struct { vt: VtSlot, stream: StreamSlot, - replay: Replay, reply: [256]u8 = undefined, reply_len: u16 = 0, /// The grid cell the program last heard the mouse at, so motion is @@ -613,8 +606,6 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, }); state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa }); - state.replay.head = 0; - state.replay.len = 0; state.reply_len = 0; state.mouse_cell = null; state.images = if (images_enabled) .{} else {}; @@ -678,43 +669,12 @@ pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { return pane; } -/// Feed the emulator and retain the bounded suffix a dump can replay. Live -/// output and restoration share this byte path, then apply different views. +/// Feed the emulator. Live output and restoration share this byte path, +/// then apply different views. fn ingest(pane: *Pane, bytes: []const u8) void { - const state = pane.terminal.?; - const replay = &state.replay; - if (bytes.len >= replay.bytes.len) { - const kept = bytes[bytes.len - replay.bytes.len ..]; - @memcpy(&replay.bytes, kept); - replay.head = 0; - replay.len = replay.bytes.len; - } else { - const overflow = bytes.len -| (replay.bytes.len - replay.len); - replay.head = (replay.head + overflow) % replay.bytes.len; - replay.len -= overflow; - const tail = (replay.head + replay.len) % replay.bytes.len; - const first = @min(bytes.len, replay.bytes.len - tail); - @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); - @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); - replay.len += bytes.len; - } - state.stream.nextSlice(bytes); + pane.terminal.?.stream.nextSlice(bytes); } -/// Return the replay ring in chronological order. Wrapped records are copied -/// into `allocator`; contiguous records remain a borrowed slice of the pane. -fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { - const state = pane.terminal orelse return &.{}; - const replay = &state.replay; - if (replay.len == 0) return &.{}; - if (replay.head + replay.len <= replay.bytes.len) - return replay.bytes[replay.head..][0..replay.len]; - const out = try allocator.alloc(u8, replay.len); - const first = replay.bytes.len - replay.head; - @memcpy(out[0..first], replay.bytes[replay.head..]); - @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); - return out; -} test "replay ownership is terminal-only and construction rolls back on allocation failure" { const Case = struct { @@ -753,7 +713,6 @@ test "document construction allocates only the pane and has inert terminal defau 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.expectEqualStrings("", try replayBytes(pane, allocator)); try std.testing.expect(!failing.has_induced_failure); } @@ -779,46 +738,18 @@ test "terminal state keeps parser fragments and sends emulator replies through i } try std.testing.expectEqual(@as(usize, 1), replies); try std.testing.expectEqual(@as(u16, 0), state.reply_len); - try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); } -test "replay keeps a bounded chronological suffix across large writes and wrapping" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); - ingest(pane, "hello"); - const small = try replayBytes(pane, gpa); - try std.testing.expectEqualStrings("hello", small); - try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); - - const capacity = pane.terminal.?.replay.bytes.len; - const input = try gpa.alloc(u8, capacity + 7); - defer gpa.free(input); - @memset(input, 0); - const ending = "\x1b[31mred\x1b[0m\r\n"; - @memcpy(input[input.len - ending.len ..], ending); - ingest(pane, input); - try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); - ingest(pane, "next\r\n"); - const wrapped = try replayBytes(pane, gpa); - defer gpa.free(wrapped); - try std.testing.expectEqual(capacity, wrapped.len); - try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); - try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); -} - -test "replay restores terminal cells from the retained stream" { +test "a terminal stream restores the cells it drew" { if (comptime !enabled) 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, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); + const drawn = "\x1b[31mred\x1b[0m\r\ncafé\r\n"; + feedOutput(p, pane, drawn); + const encoded = try dump.encodeBytes(gpa, drawn); defer gpa.free(encoded); const restored = try restore(p, .{ .kind = .terminal, @@ -835,7 +766,6 @@ test "replay restores terminal cells from the retained stream" { const after = try screenTextAlloc(restored, gpa); defer gpa.free(after); try std.testing.expectEqualStrings(before, after); - try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); } test "a restored command pane comes back finished, its command not run again" { diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 4cd1bc9a..afc0dbf0 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -34,6 +34,8 @@ var kitty_shm = std.atomic.Value(bool).init(false); var kitty_shm_probing = std.atomic.Value(bool).init(false); const kitty_shm_probe_id = 0x7fff_fff1; var kitty_shm_serial: u32 = 0; +/// Transmissions an unread shm segment outlives before it is removed. +const kitty_shm_window = 64; fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); @@ -1787,6 +1789,13 @@ const Shell = struct { if (!s.kitty.contains(key) and vx.caps.kitty_graphics and kitty_shm.load(.acquire)) shm: { var buf: [64]u8 = undefined; kitty_shm_serial +%= 1; + // Bounded: a segment this many transmissions old was never + // read (a terminal reads one as its command arrives), and a + // tmpfs holds it in memory until it goes. + if (kitty_shm_serial > kitty_shm_window) { + var old_buf: [64]u8 = undefined; + if (kittyShmName(&old_buf, kitty_shm_serial - kitty_shm_window)) |old| _ = libc.shm_unlink(old) else |_| {} + } const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; if (!kittyShmWrite(name, place.rgba)) break :shm; if (vx.transmitLocalImagePath(s.gpa, s.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| @@ -2010,7 +2019,7 @@ const Shell = struct { old.future.cancel(s.io) catch {}; s.lsp_task = null; } - const future = s.io.concurrent(lspWorker, .{ s.lsp_gpa, job, s.loop }) catch |err| { + const future = s.io.concurrent(lspWorker, .{ s.io, s.lsp_gpa, job, s.loop }) catch |err| { job.free(s.lsp_gpa); s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); return s.core.reportError(req.pane, "lsp", err); @@ -2144,9 +2153,9 @@ fn requestClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { vx.requestSystemClipboard(tty.writer()) catch {}; } -fn lspWorker(allocator: std.mem.Allocator, job: *host_io.Lsp.Job, loop: *Loop) anyerror!void { +fn lspWorker(io: std.Io, allocator: std.mem.Allocator, job: *host_io.Lsp.Job, loop: *Loop) anyerror!void { var sink: LspRowSink = .{ .allocator = allocator, .loop = loop }; - host_io.Lsp.work(allocator, job, &sink, LspRowSink.take); + host_io.Lsp.work(io, allocator, job, &sink, LspRowSink.take); } const LspRowSink = struct { @@ -2185,23 +2194,30 @@ fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { return; } const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - var read_buf: [4096]u8 = undefined; - var reader = file.readerStreaming(io, &read_buf); + // 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) { - var buf: [4096]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = file.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; loop.postEvent(.files_changed) catch break; } } fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { + winchWatchUntil(loop, vx, tty, null); +} + +/// A SIGWINCH watcher that ends: `stop` set, then a SIGWINCH sent to its +/// thread, wakes its sigwait and it returns, so whoever owns `loop` can join +/// it before the loop goes (attachSession's loop is on its stack). +fn winchWatchUntil(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty, stop: ?*const std.atomic.Value(bool)) void { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); while (true) { var sig: c_int = 0; if (libc.sigwait(&set, &sig) != 0) continue; + if (stop) |flag| if (flag.load(.acquire)) return; if (vx.state.in_band_resize) continue; // terminal reports via CSI 48 const ws = tty.getWinsize() catch continue; loop.postEvent(.{ .winsize = ws }) catch {}; @@ -2285,12 +2301,11 @@ fn wakeFs(ctx: ?*anyopaque) void { } fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { - var read_buf: [0x10000]u8 = undefined; - var reader = pty.readerStreaming(io, &read_buf); + // 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; while (true) { - var buf: [0x10000]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = pty.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; const bytes = try gpa.dupe(u8, buf[0..n]); loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { @@ -2301,7 +2316,7 @@ fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; } -const max_paste_bytes: usize = 4 << 20; +const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; fn pasteBytes(key: vaxis.Key) []const u8 { const text = key.text orelse ""; @@ -3023,7 +3038,13 @@ fn attachSession(init: std.process.Init, name: []const u8, tty: *vaxis.Tty, vx: startInput(&loop, &input_cache) catch |err| return .{ .lost = err }; defer stopInput(&loop); - (std.Thread.spawn(.{}, winchWatch, .{ &loop, vx, tty }) catch |err| return .{ .lost = err }).detach(); + var winch_stop: std.atomic.Value(bool) = .init(false); + const winch = std.Thread.spawn(.{}, winchWatchUntil, .{ &loop, vx, tty, &winch_stop }) catch |err| return .{ .lost = err }; + defer { + winch_stop.store(true, .release); + _ = libc.pthread_kill(winch.getHandle(), posix.SIG.WINCH); + winch.join(); + } vx.queryTerminalSend(tty.writer()) catch {}; return attachLoop(&a); diff --git a/test/lspbench.zig b/test/lspbench.zig index d0e25aee..08df9f4c 100644 --- a/test/lspbench.zig +++ b/test/lspbench.zig @@ -110,8 +110,13 @@ test "lspbench options reject unknown flags and multiple roots before probing" { try std.testing.expectError(error.MultipleRoots, Options.parse(&.{ "first", "--check", "second" })); } +/// The process's Io, for the queries: their waits are woken by the client's +/// reader threads, which a single-threaded Io cannot be. +var query_io: std.Io = undefined; + pub fn main(init: std.process.Init) !void { const gpa = std.heap.page_allocator; + query_io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len > 1 and std.mem.eql(u8, args[1], "probe")) return probeCommand(init); @@ -171,13 +176,19 @@ fn checkResults(results: []const Result, required: usize) !void { for (results) |r| if (r.empty or !r.correct) return error.IncorrectProbe; } -fn runOnce(gpa: std.mem.Allocator, req: lsp.Req, expected: []const u8, r: *Result) !u64 { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); +fn runOnce(gpa: std.mem.Allocator, req_in: lsp.Req, expected: []const u8, r: *Result) !u64 { + // The editor's own path (host_io.Lsp.work): the query in the fixed + // region reserved at startup, not a heap arena that maps its memory anew. + const memory = @import("pardes").memory; + const region = memory.takeLspQuery() orelse return error.QueryRegionBusy; + var arena: std.heap.FixedBufferAllocator = .init(region); + defer memory.giveLspQuery(arena.end_index); + var req = req_in; + req.budget = &arena; var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); const t0 = nowNs(); - try lsp.query(gpa, arena.allocator(), req, &out.writer); + try lsp.query(query_io, gpa, arena.allocator(), req, &out.writer); const ns = nowNs() -| t0; r.accept(out.written(), expected); return ns / 1000; @@ -341,6 +352,7 @@ extern "c" fn usleep(usec: c_uint) c_int; /// [--reps N] [--warm S]`, rows on stdout, the timing on stderr. fn probeCommand(init: std.process.Init) !void { const gpa = std.heap.page_allocator; + query_io = init.io; const arena = init.arena.allocator(); const io = std.Io.Threaded.global_single_threaded.io(); @@ -431,7 +443,7 @@ fn probeCommand(init: std.process.Init) !void { var scratch: std.heap.ArenaAllocator = .init(gpa); defer scratch.deinit(); const t0 = nowUs(); - try lsp.query(gpa, scratch.allocator(), .{ + try lsp.query(query_io, gpa, scratch.allocator(), .{ .kind = kind, .path = path, .source = source, diff --git a/test/panes.zig b/test/panes.zig index e98e3a54..1460b355 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -1913,9 +1913,6 @@ test "terminal output keeps following new rows after scrollback eviction" { try std.testing.expectEqualStrings("f", effect.write.bytes.slice()); try std.testing.expect(p.nextEffect() == null); } - const replay = &pane.terminal.?.replay; - try std.testing.expectEqual(replay.bytes.len, replay.len); - try std.testing.expect(replay.head > 0); } test "terminal edit stays on its surviving row when old scrollback is evicted" { diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json index ffcd678f..a41c92b2 100644 --- a/test/perf-baseline-gui-debug.json +++ b/test/perf-baseline-gui-debug.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1744,"med_us":1832,"p90_us":2468,"max_us":2524},{"op":"render","fixture":"medium","min_us":88,"med_us":97,"p90_us":114,"max_us":115},{"op":"key-down","fixture":"medium","min_us":95,"med_us":98,"p90_us":104,"max_us":105},{"op":"key-right","fixture":"medium","min_us":92,"med_us":96,"p90_us":98,"max_us":105},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":97,"max_us":105},{"op":"wheel","fixture":"medium","min_us":87,"med_us":93,"p90_us":99,"max_us":100},{"op":"edit-char","fixture":"medium","min_us":1241,"med_us":1459,"p90_us":1691,"max_us":1724},{"op":"edit-twin","fixture":"medium","min_us":2592,"med_us":3003,"p90_us":3481,"max_us":3503},{"op":"body-2m","fixture":"medium","min_us":4576,"med_us":8262,"p90_us":15424,"max_us":17259},{"op":"body-appends","fixture":"medium","min_us":152003,"med_us":227268,"p90_us":272872,"max_us":326510},{"op":"deep-sel","fixture":"medium","min_us":82,"med_us":83,"p90_us":90,"max_us":93}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2253,"med_us":2626,"p90_us":3065,"max_us":3090},{"op":"render","fixture":"medium","min_us":100,"med_us":103,"p90_us":103,"max_us":110},{"op":"key-down","fixture":"medium","min_us":102,"med_us":103,"p90_us":105,"max_us":113},{"op":"key-right","fixture":"medium","min_us":98,"med_us":104,"p90_us":108,"max_us":113},{"op":"page-down","fixture":"medium","min_us":103,"med_us":104,"p90_us":111,"max_us":114},{"op":"wheel","fixture":"medium","min_us":98,"med_us":100,"p90_us":102,"max_us":108},{"op":"edit-char","fixture":"medium","min_us":1251,"med_us":1940,"p90_us":2652,"max_us":3041},{"op":"edit-twin","fixture":"medium","min_us":2779,"med_us":3177,"p90_us":3366,"max_us":3657},{"op":"body-2m","fixture":"medium","min_us":5812,"med_us":11423,"p90_us":13681,"max_us":13758},{"op":"body-appends","fixture":"medium","min_us":153898,"med_us":241075,"p90_us":284518,"max_us":305761},{"op":"deep-sel","fixture":"medium","min_us":86,"med_us":91,"p90_us":94,"max_us":122}]} diff --git a/test/perf-baseline-tty-debug.json b/test/perf-baseline-tty-debug.json index b8e534c4..dc37e033 100644 --- a/test/perf-baseline-tty-debug.json +++ b/test/perf-baseline-tty-debug.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1747,"med_us":1912,"p90_us":2150,"max_us":2247},{"op":"render","fixture":"medium","min_us":89,"med_us":95,"p90_us":102,"max_us":104},{"op":"key-down","fixture":"medium","min_us":97,"med_us":101,"p90_us":107,"max_us":133},{"op":"key-right","fixture":"medium","min_us":93,"med_us":104,"p90_us":109,"max_us":112},{"op":"page-down","fixture":"medium","min_us":92,"med_us":96,"p90_us":106,"max_us":108},{"op":"wheel","fixture":"medium","min_us":90,"med_us":92,"p90_us":96,"max_us":96},{"op":"edit-char","fixture":"medium","min_us":1167,"med_us":1345,"p90_us":1483,"max_us":1627},{"op":"edit-twin","fixture":"medium","min_us":2319,"med_us":2921,"p90_us":3425,"max_us":3539},{"op":"body-2m","fixture":"medium","min_us":4333,"med_us":7752,"p90_us":15941,"max_us":17192},{"op":"body-appends","fixture":"medium","min_us":149149,"med_us":234177,"p90_us":285302,"max_us":295516},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":88,"p90_us":99,"max_us":119}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2181,"med_us":2495,"p90_us":2621,"max_us":2660},{"op":"render","fixture":"medium","min_us":96,"med_us":98,"p90_us":102,"max_us":112},{"op":"key-down","fixture":"medium","min_us":101,"med_us":103,"p90_us":107,"max_us":108},{"op":"key-right","fixture":"medium","min_us":100,"med_us":112,"p90_us":118,"max_us":119},{"op":"page-down","fixture":"medium","min_us":97,"med_us":101,"p90_us":105,"max_us":107},{"op":"wheel","fixture":"medium","min_us":98,"med_us":100,"p90_us":108,"max_us":110},{"op":"edit-char","fixture":"medium","min_us":1377,"med_us":1842,"p90_us":2336,"max_us":2418},{"op":"edit-twin","fixture":"medium","min_us":2655,"med_us":3200,"p90_us":3321,"max_us":3660},{"op":"body-2m","fixture":"medium","min_us":5420,"med_us":10753,"p90_us":12826,"max_us":15385},{"op":"body-appends","fixture":"medium","min_us":153569,"med_us":232519,"p90_us":281625,"max_us":309036},{"op":"deep-sel","fixture":"medium","min_us":91,"med_us":98,"p90_us":111,"max_us":111}]} diff --git a/test/perf-baseline-tty-fast.json b/test/perf-baseline-tty-fast.json index 46125349..bd8f32dc 100644 --- a/test/perf-baseline-tty-fast.json +++ b/test/perf-baseline-tty-fast.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1904,"med_us":2040,"p90_us":2290,"max_us":2600},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":88,"max_us":93},{"op":"key-down","fixture":"medium","min_us":81,"med_us":87,"p90_us":93,"max_us":109},{"op":"key-right","fixture":"medium","min_us":79,"med_us":82,"p90_us":86,"max_us":96},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":89,"max_us":93},{"op":"wheel","fixture":"medium","min_us":77,"med_us":79,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1139,"med_us":1338,"p90_us":1453,"max_us":1578},{"op":"edit-twin","fixture":"medium","min_us":2515,"med_us":2776,"p90_us":2879,"max_us":2907},{"op":"body-2m","fixture":"medium","min_us":4832,"med_us":7650,"p90_us":15076,"max_us":15371},{"op":"body-appends","fixture":"medium","min_us":165796,"med_us":240881,"p90_us":284919,"max_us":292573},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":75,"p90_us":83,"max_us":93}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2283,"med_us":2611,"p90_us":2812,"max_us":2917},{"op":"render","fixture":"medium","min_us":89,"med_us":97,"p90_us":105,"max_us":119},{"op":"key-down","fixture":"medium","min_us":88,"med_us":95,"p90_us":100,"max_us":116},{"op":"key-right","fixture":"medium","min_us":90,"med_us":99,"p90_us":103,"max_us":106},{"op":"page-down","fixture":"medium","min_us":86,"med_us":90,"p90_us":96,"max_us":97},{"op":"wheel","fixture":"medium","min_us":85,"med_us":91,"p90_us":94,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1229,"med_us":1823,"p90_us":1874,"max_us":2101},{"op":"edit-twin","fixture":"medium","min_us":2196,"med_us":2745,"p90_us":2928,"max_us":2972},{"op":"body-2m","fixture":"medium","min_us":5606,"med_us":10369,"p90_us":14063,"max_us":14406},{"op":"body-appends","fixture":"medium","min_us":155867,"med_us":237195,"p90_us":289128,"max_us":306283},{"op":"deep-sel","fixture":"medium","min_us":82,"med_us":84,"p90_us":86,"max_us":91}]} diff --git a/test/perf.zig b/test/perf.zig index 7662d028..ab284739 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -665,8 +665,6 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { .row = pane.body.cur_row, .col = pane.body.cur_col, .edit_len = if (pane.ovl) |overlay| overlay.text.len else 0, - .replay_head = state.replay.head, - .replay_len = state.replay.len, .cols = pane.cols, .rows = pane.rows, }; @@ -689,22 +687,11 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { _ = try frame(core); const dt = nowNs() -| t0; switch (op) { - .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or - state.replay.head != before.replay_head or state.replay.len != before.replay_len) + .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col) return error.RenderChangedTerminal, - .output => { - const capacity = state.replay.bytes.len; - if (term_chunk.len == 0 or term_chunk.len >= capacity) return error.InvalidOutputFixture; - const overflow = term_chunk.len -| (capacity - before.replay_len); - if (state.replay.len != @min(capacity, before.replay_len + term_chunk.len) or - state.replay.head != (before.replay_head + overflow) % capacity) - return error.OutputWasNotRecorded; - const start = (state.replay.head + state.replay.len - term_chunk.len) % capacity; - const first = @min(term_chunk.len, capacity - start); - if (!std.mem.eql(u8, term_chunk[0..first], state.replay.bytes[start..][0..first]) or - !std.mem.eql(u8, term_chunk[first..], state.replay.bytes[0 .. term_chunk.len - first])) - return error.WrongTerminalOutput; - }, + // What the output did to the screen is the snapshot suite's to + // check; here it is timed. + .output => if (term_chunk.len == 0) return error.InvalidOutputFixture, .resize_rows => if (pane.rows == before.rows or pane.cols != before.cols or state.vt.screens.active.pages.rows != pane.rows) return error.TerminalDidNotResize, .resize_cols => if (pane.cols == before.cols or pane.rows != before.rows or -- cgit v1.3 From 80314064f6e81c8828340e010202b446f0e1f36d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 23 Oct 2026 11:00:44 -0300 Subject: Audit (misc): std mkdir -p and JSON escaping, a 9P late failure's errno from ctl.failureErrno, dead switches and dumpHex out Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 112 +++++++++++++++++++++----------------------------- src/File.zig | 5 +-- src/Output.zig | 52 ++++++----------------- src/builtins.zig | 86 ++++++++++++-------------------------- src/builtins_json.zig | 22 +++------- src/config.zig | 75 ++++++--------------------------- src/dump.zig | 11 +---- src/esp32p4/uart.zig | 16 -------- src/fs.zig | 12 +----- src/gui/gui.zig | 13 ++---- src/hunks.zig | 6 +-- src/locations.zig | 25 +++++------ src/look.zig | 8 ++-- src/main.zig | 40 +++++++----------- src/syntax.zig | 5 +-- src/tagline.zig | 7 +--- src/terminal.zig | 4 +- src/web.zig | 59 +++++--------------------- 18 files changed, 156 insertions(+), 402 deletions(-) (limited to 'src/fs.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index a825475f..a089a7cf 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -11,10 +11,7 @@ const quic = if (quic_enabled) @import("9p_quic.zig") else struct {}; const log = std.log.scoped(.ninep); -pub const darwin = switch (builtin.os.tag) { - .macos, .ios, .tvos, .watchos, .visionos => true, - else => false, -}; +pub const darwin = builtin.os.tag.isDarwin(); pub const supported = builtin.os.tag == .linux or darwin; pub const sun_path_len = @typeInfo(@FieldType(libc.sockaddr.un, "path")).array.len; @@ -47,15 +44,8 @@ pub fn statNoFollow(path: [:0]const u8) ?FileFacts { pub fn ensureSocketDir(dir: [:0]const u8) bool { if (dir.len == 0) return false; - var partial: [sun_path_len:0]u8 = undefined; - @memcpy(partial[0 .. dir.len + 1], dir[0 .. dir.len + 1]); - for (1..dir.len) |i| { - if (dir[i] != '/') continue; - partial[i] = 0; - _ = libc.mkdir(partial[0..i :0], 0o700); - partial[i] = '/'; - } - _ = libc.mkdir(dir, 0o700); + // A failure shows in the stat below. + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o700)) catch {}; const stat = statNoFollow(dir) orelse return false; return stat.mode & 0o170000 == 0o040000 and stat.uid == libc.getuid() and stat.mode & 0o077 == 0; } @@ -394,11 +384,11 @@ pub const Listener = struct { // settle in the same wait is told to this write too. if (l.core == core and core.fs.late_failure_len != 0) { const late = core.fs.late_failure[0..core.fs.late_failure_len]; - // What is not there (`no such directory`) is ENOENT, as a - // builtin's failure saying so is (ctl.failureErrno). - const errno = if (std.mem.indexOf(u8, late, "no such") != null or std.mem.indexOf(u8, late, "not found") != null) - pardes.ctlfs.E.NOENT - else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else if (std.mem.indexOf(u8, late, "permission denied") != null) pardes.ctlfs.E.PERM else if (std.mem.indexOf(u8, late, "invalid") != null) pardes.ctlfs.E.INVAL else pardes.ctlfs.E.IO; + // The errno a builtin's failure in the same words has; what + // that leaves EIO and says `no space` (a full disk under a + // Save) is ENOSPC. + const said = @import("ninep/ctl.zig").failureErrno(late); + const errno = if (said == pardes.ctlfs.E.IO and std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else said; const failed = pardes.ctlfs.failText(req.tag, errno, late); // Its err record says it (the path in it), the one record: it // was said with no msg while this waited (fs.write_waits). @@ -1017,21 +1007,11 @@ fn onFatalSignal(s: std.posix.SIG) callconv(.c) void { pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { if (comptime !supported) return; var names: [8192]u8 = undefined; - var staged: usize = 0; - { - const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return; - defer d.close(io); - var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; - var reader: std.Io.Dir.Reader = .init(d, &read_buf); - while (true) { - const listed = (reader.next(io) catch break) orelse break; - if (deadSocketPid(listed.name) == null) continue; - if (staged + 1 + listed.name.len > names.len) break; - names[staged] = @intCast(listed.name.len); - @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); - staged += 1 + listed.name.len; + const staged = stageNames(io, dir, &names, struct { + fn keep(name: []const u8) bool { + return deadSocketPid(name) != null; } - } + }.keep); var i: usize = 0; while (i < staged) { const name = names[i + 1 ..][0..names[i]]; @@ -1048,6 +1028,28 @@ pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { } } +/// The names in `dir` that `keep` takes (all with none), into `names` as a length byte and +/// the name each, until it is full; the bytes staged. They are staged +/// before anything is unlinked, so a sweep never asks a directory to keep +/// reading while it is being edited. +fn stageNames(io: std.Io, dir: [:0]const u8, names: []u8, comptime keep: ?fn ([]const u8) bool) usize { + const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return 0; + defer d.close(io); + var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; + var reader: std.Io.Dir.Reader = .init(d, &read_buf); + var staged: usize = 0; + while (true) { + const listed = (reader.next(io) catch break) orelse break; + if (listed.name.len == 0 or listed.name.len > 255) continue; + if (keep) |takes| if (!takes(listed.name)) continue; + if (staged + 1 + listed.name.len > names.len) break; + names[staged] = @intCast(listed.name.len); + @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); + staged += 1 + listed.name.len; + } + return staged; +} + /// The pid a `pardes-9p-.sock` name carries, or null for any other. fn deadSocketPid(name: []const u8) ?std.c.pid_t { if (!std.mem.startsWith(u8, name, prefix) or !std.mem.endsWith(u8, name, ".sock")) return null; @@ -1279,24 +1281,8 @@ fn ourSocket(target: []const u8, sockets: []const u8) bool { fn sweepRegistry(io: std.Io, svc: [:0]const u8, sockets: []const u8) void { if (comptime !supported) return; - // The names are staged before anything is unlinked, so the sweep - // never asks a directory to keep reading while it is being edited. var names: [4096]u8 = undefined; - var staged: usize = 0; - { - const dir = std.Io.Dir.openDirAbsolute(io, svc, .{ .iterate = true }) catch return; - defer dir.close(io); - var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; - var reader: std.Io.Dir.Reader = .init(dir, &read_buf); - while (true) { - const listed = (reader.next(io) catch break) orelse break; - if (listed.name.len == 0 or listed.name.len > 255) continue; - if (staged + 1 + listed.name.len > names.len) break; - names[staged] = @intCast(listed.name.len); - @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); - staged += 1 + listed.name.len; - } - } + const staged = stageNames(io, svc, &names, null); var reaped: usize = 0; var i: usize = 0; @@ -2179,10 +2165,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - return fetchBytes(gpa, sock, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { + return fetchBytes(gpa, dial, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -2209,10 +2193,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const result = fetchBytes(gpa, sock, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { + const result = fetchBytes(gpa, dial, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -2470,7 +2452,7 @@ pub const Client = struct { fn fetchBytes( gpa: std.mem.Allocator, - sock: Dial, + dial: []const u8, names: []const []const u8, remote: *RemoteError, write_bytes: ?[]const u8, @@ -2478,7 +2460,7 @@ pub const Client = struct { read_limit: usize, ) ![]u8 { if (comptime !supported) return Error.Dial; - const s = try startSession(gpa, sock, display_path); + const s = try startSession(gpa, dial, display_path); defer endSession(gpa, s); var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); @@ -2486,8 +2468,10 @@ pub const Client = struct { return out.toOwnedSlice(); } - /// A connected session whose requests have the usual deadline. - fn startSession(gpa: std.mem.Allocator, sock: Dial, display_path: []const u8) !*Session { + /// A connected session at `dial` whose requests have the usual deadline. + fn startSession(gpa: std.mem.Allocator, 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; const s = try gpa.create(Session); s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; @@ -2518,11 +2502,9 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; errdefer said = remote; - const s = try startSession(gpa, sock, path); + const s = try startSession(gpa, dial, path); defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); @@ -2562,10 +2544,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const s = try startSession(gpa, sock, path); + const s = try startSession(gpa, dial, path); defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); @@ -2642,7 +2622,7 @@ pub const Client = struct { const before = nowMs(); try testing.expectError( Error.Dial, - fetchBytes(testing.allocator, .{ .unix = "/tmp/pardes-9p-no-such-socket.sock" }, names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), + fetchBytes(testing.allocator, "/tmp/pardes-9p-no-such-socket.sock", names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), ); try testing.expect(nowMs() - before < budget_ms); } diff --git a/src/File.zig b/src/File.zig index e92efaba..b1a4271f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -2153,15 +2153,14 @@ pub const DiffOutput = struct { text[at] = '\n'; at += 1; } + // An empty slot, else the least recently used. var oldest: usize = 0; for (&o.slots, 0..) |*slot, i| { const e = slot.* orelse { oldest = i; break; }; - if (o.slots[oldest]) |old| if (e.used < old.used) { - oldest = i; - }; + if (e.used < o.slots[oldest].?.used) oldest = i; } if (o.slots[oldest]) |old| { p.gpa.free(old.text); diff --git a/src/Output.zig b/src/Output.zig index 3fc08d9a..9a11b2fc 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -949,51 +949,23 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { "C-left-click definition, by mouse\n" ++ "SPC l ... hover, rename, symbols,\n" ++ " calls, types: above\n"; - var len: usize = if (prefix.len == 0) - full_header.len + language_footer.len - else - group_header.len + prefix.len * 2 + 2; - if (show_calls_help) len += calls_help.len; + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + if (prefix.len == 0) try w.writeAll(full_header) else { + try w.writeAll(group_header); + for (prefix) |c| try w.print(" {c}", .{c}); + try w.writeAll("\n\n"); + } for (pardes.builtin_rows) |row| { // a path-less builtin filters as the empty path: in the full listing // (which starts with nothing) and out of every group if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - len += row.line.len + 1; - } - const content = try gpa.alloc(u8, len); - var at: usize = 0; - if (prefix.len == 0) { - @memcpy(content[0..full_header.len], full_header); - at = full_header.len; - } else { - @memcpy(content[0..group_header.len], group_header); - at = group_header.len; - for (prefix) |c| { - content[at] = ' '; - content[at + 1] = c; - at += 2; - } - content[at] = '\n'; - content[at + 1] = '\n'; - at += 2; - } - for (pardes.builtin_rows) |row| { - if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - @memcpy(content[at..][0..row.line.len], row.line); - at += row.line.len; - content[at] = '\n'; - at += 1; - } - if (show_calls_help) { - @memcpy(content[at..][0..calls_help.len], calls_help); - at += calls_help.len; - } - if (prefix.len == 0) { - @memcpy(content[at..][0..language_footer.len], language_footer); - at += language_footer.len; + try w.print("{s}\n", .{row.line}); } - std.debug.assert(at == content.len); - return content; + if (show_calls_help) try w.writeAll(calls_help); + if (prefix.len == 0) try w.writeAll(language_footer); + return out.toOwnedSlice(); } pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { diff --git a/src/builtins.zig b/src/builtins.zig index 7b1541ac..64710554 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -109,54 +109,27 @@ pub fn absentWhy(name: []const u8) ?[]const u8 { return null; } -fn manualBuiltinCount() comptime_int { +fn manualBuiltinList() []const type { comptime { - var count = 0; + @setEvalBranchQuota(4000); + var list: []const type = &.{}; for (@typeInfo(@This()).@"struct".decl_names) |d| { if (@TypeOf(@field(@This(), d)) != type) continue; const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; if (@TypeOf(T.run) != fn (Ctx) void) @compileError(d ++ ".run must have signature fn (Ctx) void"); - count += 1; - } - return count; - } -} - -fn manualBuiltinList() [manualBuiltinCount()]type { - comptime { - @setEvalBranchQuota(4000); - var list: [manualBuiltinCount()]type = undefined; - var count = 0; - for (@typeInfo(@This()).@"struct".decl_names) |d| { - if (@TypeOf(@field(@This(), d)) != type) continue; - const T = @field(@This(), d); - if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; - list[count] = T; - count += 1; + list = list ++ .{T}; } return list; } } -fn settingCount() comptime_int { +fn settingList() []const config.Runtime.Setting { comptime { - var count = 0; + var list: []const config.Runtime.Setting = &.{}; for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - count += 1; - }; - return count; - } -} - -fn settingList() [settingCount()]config.Runtime.Setting { - comptime { - var list: [settingCount()]config.Runtime.Setting = undefined; - var count = 0; - for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - list[count] = setting; - count += 1; + list = list ++ .{setting}; }; return list; } @@ -197,11 +170,17 @@ pub const registry = struct { return @Enum(Tag, .exhaustive, &names, &std.simd.iota(Tag, count)); } + /// What a hand-written builtin says as `name` (`pub const takes_arg = + /// true;`), `default` when it says nothing, and `setting` for a setting. + fn declOr(b: Builtin(), comptime name: []const u8, default: anytype, setting: @TypeOf(default)) @TypeOf(default) { + inline for (comptime manualBuiltinList(), 0..) |T, i| + if (@backingInt(b) == i) return if (@hasDecl(T, name)) @field(T, name) else default; + return setting; + } + pub fn takesArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; // Every setting takes its value, and a switch flips when bare. - return true; + return declOr(b, "takes_arg", false, true); } /// Whether the word takes its argument joined by a `+` as one word a @@ -209,9 +188,7 @@ pub const registry = struct { /// that says `pub const plus_arg = true;`: others have arguments a `+` /// may be in (`Dump+2024.zon` is a name, not Dump's argument). pub fn plusArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; - return false; + return declOr(b, "plus_arg", false, false); } /// Whether the word means nothing without its argument (`Mount`, @@ -222,15 +199,11 @@ pub const registry = struct { /// it says `pub const needs: PaneKind = .terminal;`, and on any other /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are. pub fn needs(b: Builtin()) ?PaneKind { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; - return null; + return declOr(b, "needs", @as(?PaneKind, null), null); } pub fn requiresArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return switch (setting.action) { // a switch flips bare, a choice steps, and DumpDir and Shell bare // are the default @@ -239,35 +212,28 @@ pub const registry = struct { // bare, it says the current value (exec.applySettingBuiltin) .tab, .callstack_depth => false, }; - unreachable; + return declOr(b, "requires_arg", false, false); } pub fn scope(b: Builtin()) Scope { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; - return .session; // a setting + return declOr(b, "scope", Scope.pane, .session); } pub fn outputTraits(b: Builtin()) ?OutputTraits { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "output")) T.output else null; - inline for (comptime settingList(), manualBuiltinCount()..) |_, i| - if (@backingInt(b) == i) return null; - unreachable; + return declOr(b, "output", @as(?OutputTraits, null), null); } /// Does this builtin say its own name on the message row before it runs? /// The ones that own that row themselves declare `quiet` and do not. pub fn announces(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); - return true; // a setting builtin changes something invisible; say so + // a setting builtin changes something invisible; say so + return !declOr(b, "quiet", false, false); } pub fn dispatch(b: Builtin(), c: Ctx) void { - inline for (manualBuiltinList(), 0..) |T, i| + inline for (comptime manualBuiltinList(), 0..) |T, i| if (@backingInt(b) == i) return T.run(c); - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } diff --git a/src/builtins_json.zig b/src/builtins_json.zig index 7f998388..4440130d 100644 --- a/src/builtins_json.zig +++ b/src/builtins_json.zig @@ -11,17 +11,7 @@ const builtins = @import("builtins.zig"); const config = @import("config.zig"); const ctl = @import("ninep/ctl.zig"); -fn str(w: *std.Io.Writer, s: []const u8) !void { - try w.writeByte('"'); - for (s) |c| switch (c) { - '"' => try w.writeAll("\\\""), - '\\' => try w.writeAll("\\\\"), - '\n' => try w.writeAll("\\n"), - 0...9, 11...0x1f => try w.print("\\u{x:0>4}", .{c}), - else => try w.writeByte(c), - }; - try w.writeByte('"'); -} +const str = std.json.Stringify.encodeJsonString; const Entry = struct { name: []const u8, row: usize }; @@ -39,7 +29,7 @@ pub fn write(w: *std.Io.Writer) !void { const b = row.cmd; const name = @tagName(b); try w.writeAll(" {\"name\": "); - try str(w, name); + try str(name, .{}, w); try w.writeAll(", \"leader\": "); if (row.path) |p| { try w.writeAll("\"SPC"); @@ -55,21 +45,21 @@ pub fn write(w: *std.Io.Writer) !void { while (parts.next()) |part| if (part.len > 0) { if (!first) try w.writeAll(", "); first = false; - try str(w, part); + try str(part, .{}, w); }; try w.writeAll("], \"arg\": "); try w.writeAll(if (builtins.registry.takesArg(b)) "true" else "false"); try w.writeAll(", \"scope\": "); - try str(w, if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane"); + try str(if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane", .{}, w); const setting = config.Runtime.find(name); try w.writeAll(", \"setting\": "); try w.writeAll(if (setting != null) "true" else "false"); try w.writeAll(", \"choices\": "); - if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(w, v) else try w.writeAll("null") else try w.writeAll("null"); + if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(v, .{}, w) else try w.writeAll("null") else try w.writeAll("null"); var buf: [2048]u8 = undefined; const doc = if (setting) |s| s.doc else ctl.summaryOf(name, &buf); try w.writeAll(", \"doc\": "); - try str(w, doc); + try str(doc, .{}, w); try w.writeAll(if (n + 1 < order.len) "},\n" else "}\n"); } try w.writeAll("]\n"); diff --git a/src/config.zig b/src/config.zig index 5251b1e5..1fbf0d1b 100644 --- a/src/config.zig +++ b/src/config.zig @@ -293,9 +293,6 @@ pub const back_out: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; -// OSC 133 prompt cells are hidden in normal mode; input columns stay intact. -pub const tty_blank: enum { prompt, prompt_and_input } = .prompt; - // Projected colors below this contrast use the theme's more legible anchor. pub const tty_filter_min_contrast: f64 = 1.5; @@ -386,9 +383,6 @@ pub const gui_topbar_pane_border_px: u8 = 1; // null follows the theme's scrollbar track. pub const gui_topbar_pane_border_rgb: ?[3]u8 = null; -// Transparency requires the SDL readback/blit path, even with an opaque theme. -pub const gui_transparent: bool = false; - // A vertical wheel tick suppresses this many subsequent horizontal ticks. pub const wheel_guard_ticks: u8 = 3; @@ -1428,12 +1422,12 @@ pub const Runtime = struct { /// effect but set by no word follows, after a blank line. pub fn writeReport(out: *std.Io.Writer, context: ReportContext) !void { const state = context.state; - for (settings) |setting| switch (setting.action) { + // TaglineSize is said wherever the shell sizes its tag, by its word + // or only at build time. + for (settings) |setting| if (!(if (setting.action == .tagline_size) context.capabilities.tagline_font_size else setting.enabled(context.capabilities))) + try out.print("# {s} unsupported\n", .{setting.word}) + else switch (setting.action) { .toggle => |field| { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } const value = switch (field) { inline else => |f| @field(state, @tagName(f)), }; @@ -1443,18 +1437,8 @@ pub const Runtime = struct { try out.print("ThemeFile {s}\n", .{path}) else try out.print("{s} {s}\n", .{ setting.word, context.theme_name }), - .window_opacity => { - if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.window_opacity }) - else - try out.print("# {s} unsupported\n", .{setting.word}); - }, - .window_blur => { - if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.window_blur }) - else - try out.print("# {s} unsupported\n", .{setting.word}); - }, + .window_opacity => try out.print("{s} {d}\n", .{ setting.word, state.window_opacity }), + .window_blur => try out.print("{s} {d}\n", .{ setting.word, state.window_blur }), .dump_dir => { const dir = if (state.dump_dir.len > 0) state.dump_dir.get() else context.default_dump_dir; if (dir.len > 0) try out.print("{s} {s}\n", .{ setting.word, dir }) else try out.print("# {s} (none)\n", .{setting.word}); @@ -1466,9 +1450,7 @@ pub const Runtime = struct { const chosen = state.shell.requested.get(); try out.print("{s} {s}\n", .{ setting.word, if (chosen.len == 0) context.compiled_default_shell else chosen }); }, - .font => if (!setting.enabled(context.capabilities)) - try out.print("# {s} unsupported\n", .{setting.word}) - else { + .font => { // As `Font` takes it, `name:size`: the one asked for, else // the one in use. const f = &state.font; @@ -1483,28 +1465,14 @@ pub const Runtime = struct { if (f.requested_size_hundredths != 0) try out.print(":{d}.{d:0>2}", .{ f.requested_size_hundredths / 100, f.requested_size_hundredths % 100 }); try out.writeByte('\n'); }, - .tagline_size => if (!context.capabilities.tagline_font_size) - try out.print("# {s} unsupported\n", .{setting.word}) - else - try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), + .tagline_size => try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), // Each a switch of its own, the one in use on. - .transition => |transition| if (!setting.enabled(context.capabilities)) - try out.print("# {s} unsupported\n", .{setting.word}) - else - try out.print("{s} {s}\n", .{ setting.word, onOff(state.panel_transition == transition) }), + .transition => |transition| try out.print("{s} {s}\n", .{ setting.word, onOff(state.panel_transition == transition) }), .scene => |effect| { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } const level = state.post.level(effect); if (level == 0) try out.print("{s} off\n", .{setting.word}) else try out.print("{s} {d}\n", .{ setting.word, level }); }, .shader => { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } var files: usize = 0; for (state.post.list()) |entry| if (entry.scene == null) { try out.print("{s} {s}\n", .{ setting.word, entry.path.get() }); @@ -1512,25 +1480,16 @@ pub const Runtime = struct { }; if (files == 0) try out.print("{s} off\n", .{setting.word}); }, - .shader_animation => if (setting.enabled(context.capabilities)) - try out.print("{s} {s}\n", .{ setting.word, @tagName(state.shader_animation) }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .shader_animation => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.shader_animation) }), .choice => |which| switch (which) { inline else => |field| try out.print("{s} {s}\n", .{ setting.word, @tagName(@field(state, @tagName(field))) }), }, - .lift => if (setting.enabled(context.capabilities)) - try out.print("{s} {s}\n", .{ setting.word, @tagName(state.lift) }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .lift => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.lift) }), .motion => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.motion) }), .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), - .grip_width => if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.grip_width }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .grip_width => try out.print("{s} {d}\n", .{ setting.word, state.grip_width }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); @@ -1566,14 +1525,6 @@ pub const Runtime = struct { try out.print("# Pet: {s}\n", .{@tagName(state.pet)}); } - test "setting names are unique" { - for (settings, 0..) |setting, i| { - try std.testing.expect(setting.word.len > 0); - for (settings[i + 1 ..]) |later| - try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); - } - } - test "panel and scene effects flip bare and are set by on and off" { var state: Runtime = .{}; const slide = findAction(.{ .transition = .slide }).?; diff --git a/src/dump.zig b/src/dump.zig index 67934e0a..c8c302ab 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -38,16 +38,7 @@ pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null; var dir_buf: [900]u8 = undefined; const dir = directory(&dir_buf, dir_setting) orelse return null; - var dz: [901:0]u8 = undefined; - @memcpy(dz[0..dir.len], dir); - dz[dir.len] = 0; - // Each missing directory on the way, as `mkdir -p`: EEXIST is fine. - for (dz[1..dir.len], 1..) |c, i| if (c == '/') { - dz[i] = 0; - _ = std.c.mkdir(dz[0..i :0], 0o755); - dz[i] = '/'; - }; - _ = std.c.mkdir(dz[0..dir.len :0], 0o755); + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; var ts: std.c.timespec = undefined; _ = std.c.clock_gettime(.REALTIME, &ts); const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, ts.sec)) }; diff --git a/src/esp32p4/uart.zig b/src/esp32p4/uart.zig index 5690520c..a185737d 100644 --- a/src/esp32p4/uart.zig +++ b/src/esp32p4/uart.zig @@ -126,22 +126,6 @@ pub fn writeByte(b: u8) void { uart0.pushByte(b); } -/// Emit `n` bytes read from `addr` as two hex digits each, computing the digits arithmetically so -/// nothing here reads a lookup table. Used to answer "does a load from this address return what the -/// linker put there", which is not a question a string literal can be trusted to ask. -pub fn dumpHex(addr: u32, n: u32) void { - const p: [*]const volatile u8 = @ptrFromInt(addr); - var i: u32 = 0; - while (i < n) : (i += 1) { - const byte = p[i]; - for ([2]u8{ byte >> 4, byte & 0xf }) |nib| { - writeByte(if (nib < 10) '0' + nib else 'a' + (nib - 10)); - } - } - writeByte('\r'); - writeByte('\n'); -} - /// A u32 as eight hex digits, reading no memory at all. pub fn dumpWord(v: u32) void { var shift: u5 = 28; diff --git a/src/fs.zig b/src/fs.zig index 032ab9c0..e809eda5 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -686,18 +686,10 @@ test "a path with a part over 255 bytes is NameTooLong, never a panic" { /// that follows. pub fn makeDirs(dir: []const u8) void { if (comptime !platform_has_fs) return; - var z: [4096:0]u8 = undefined; - if (dir.len == 0 or dir.len >= z.len) return; - @memcpy(z[0..dir.len], dir); - z[dir.len] = 0; + if (dir.len == 0) return; pardes.turn.yield(); defer pardes.turn.back(); - for (z[1..dir.len], 1..) |c, i| if (c == '/') { - z[i] = 0; - _ = libc.mkdir(z[0..i :0], 0o755); - z[i] = '/'; - }; - _ = libc.mkdir(z[0..dir.len :0], 0o755); + _ = 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 diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 2d01db33..795ea743 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -54,11 +54,6 @@ const Ground = struct { } }; -fn ground(theme_bg: ?[3]u8, transparent: bool) Ground { - if (theme_bg) |rgb| return .opaqueRgb(rgb); - return .{ .rgb = bg_default, .clear = transparent }; -} - const p9_arrow_clr = [32]u8{ 0xFF, 0xFF, 0x80, 0x01, 0x80, 0x02, 0x80, 0x0C, 0x80, 0x10, 0x80, 0x10, 0x80, 0x08, 0x80, 0x04, @@ -1769,7 +1764,6 @@ const Gui = struct { capture_xfer_size: u32 = 0, soft_present: bool = false, - transparent: bool = false, surface_opacity: bool = false, applied_window_opacity: u8 = 100, soft_renderer: ?*c.SDL_Renderer = null, @@ -2187,7 +2181,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); // Background-only opacity needs per-pixel alpha; whole-window compositor // opacity would dim the text as well. SDL requires this flag at creation. - const surface_opacity = config.gui_transparent or native_wayland; + const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; const window = c.SDL_CreateWindow("pardes", 1120, 720, win_flags) orelse { log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); @@ -2391,7 +2385,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, .capture_dir = capture_dir orelse "", .soft_present = soft_present, - .transparent = config.gui_transparent, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, }; @@ -6092,7 +6085,7 @@ fn renderFrame( coverFrame(previous_covered, surface.cols, surface.rows, surface.previous_body_layers, surface.previous_tag_layers, surface.previous_regions); try buildDecor(g, gpa, surface, &groups, layout, win_w, win_h, cursors_shown); - const page = ground(chrome.page, g.transparent); + const page: Ground = .opaqueRgb(chrome.page orelse bg_default); const background_opacity = backgroundOpacity(g.applied_window_opacity); var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo); color_target.texture = scene; @@ -8449,7 +8442,7 @@ fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTex // 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.transparent or g.surface_opacity) 0 else 255); + _ = 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); _ = c.SDL_RenderPresent(renderer); diff --git a/src/hunks.zig b/src/hunks.zig index 24aaf63d..8cd5c43a 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -111,11 +111,7 @@ const Out = struct { fn deinit(out: *Out) void { out.text.deinit(); - for (out.rows.items) |r| { - out.p.gpa.free(r.path); - out.p.gpa.free(r.colors); - } - out.rows.deinit(out.p.gpa); + locations.freeRowList(out.p.gpa, &out.rows); } const Meta = struct { diff --git a/src/locations.zig b/src/locations.zig index 1e4a20cf..6f086214 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -33,6 +33,15 @@ pub fn freeRows(gpa: std.mem.Allocator, rows: []Row) void { gpa.free(rows); } +/// A list of rows being built, given up: each row's own bytes, then the list. +pub fn freeRowList(gpa: std.mem.Allocator, rows: *std.ArrayList(Row)) void { + for (rows.items) |row| { + gpa.free(row.path); + gpa.free(row.colors); + } + rows.deinit(gpa); +} + pub fn equalRows(a: []const Row, b: []const Row) bool { if (a.len != b.len) return false; for (a, b) |left, right| { @@ -316,13 +325,7 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var rows: std.ArrayList(Row) = .empty; - errdefer { - for (rows.items) |row| { - p.gpa.free(row.path); - p.gpa.free(row.colors); - } - rows.deinit(p.gpa); - } + errdefer freeRowList(p.gpa, &rows); const stacked = p.settings.callstack_layout == .stacked; const resolved = try resolveCallstack(p, arena, dir, input); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); @@ -496,13 +499,7 @@ pub fn format(p: *pardes.Pardes, dir: []const u8, input: []const u8, anchor: ?us var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var rows: std.ArrayList(Row) = .empty; - errdefer { - for (rows.items) |row| { - p.gpa.free(row.path); - p.gpa.free(row.colors); - } - rows.deinit(p.gpa); - } + errdefer freeRowList(p.gpa, &rows); var mapped = anchor; if (p.locations_config.layout == .stacked) { for (pending.items, 0..) |row, index| { diff --git a/src/look.zig b/src/look.zig index 588574ed..2d97cb9f 100644 --- a/src/look.zig +++ b/src/look.zig @@ -32,9 +32,7 @@ const Key = pardes.Key; const Event = pardes.Event; const Pardes = pardes.Pardes; -extern "c" fn fork() c_int; extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; -extern "c" fn _exit(status: c_int) noreturn; const opener_path: ?[*:0]const u8 = switch (builtin.os.tag) { .linux => "/usr/bin/xdg-open", @@ -46,15 +44,15 @@ pub fn openLink(url: []const u8) void { const opener = opener_path orelse return; var buf: [1024]u8 = undefined; const url_z = std.fmt.bufPrintSentinel(&buf, "{s}", .{url}, 0) catch return; - const pid = fork(); + const pid = libc.fork(); if (pid < 0) return; if (pid == 0) { - if (fork() == 0) { + if (libc.fork() == 0) { @import("host_io.zig").resetChildSignals(); const argv: [3:null]?[*:0]const u8 = .{ opener, url_z.ptr, null }; _ = execv(opener, &argv); } - _exit(0); + libc._exit(0); } _ = libc.waitpid(pid, null, 0); } diff --git a/src/main.zig b/src/main.zig index ea2db917..52093b9a 100644 --- a/src/main.zig +++ b/src/main.zig @@ -144,32 +144,22 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const /// Stdin to its end, as it came (its escapes are the session's to parse, /// pager.zig), at most a file's limit, a longer one cut there and said so /// at its end. -fn readStdinText(gpa: std.mem.Allocator) ![]u8 { +fn readStdinText(io: std.Io, gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; var raw: std.ArrayList(u8) = .empty; var chunk: [64 * 1024]u8 = undefined; - var cut = false; - while (true) { - const n = std.c.read(0, &chunk, chunk.len); - if (n < 0) { - if (std.posix.errno(n) == .INTR) continue; - return error.ReadFailed; - } - if (n == 0) break; - const got: usize = @intCast(n); - if (raw.items.len + got > limit) { - try raw.appendSlice(gpa, chunk[0 .. limit - raw.items.len]); - cut = true; - break; - } - try raw.appendSlice(gpa, chunk[0..got]); - } - if (cut) { - // CAN ends an escape the cut left half sent, and SGR 0 its colour, - // so the note is never swallowed or tinted. - const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; - try raw.appendSlice(gpa, said); - } + var stdin = std.Io.File.stdin().readerStreaming(io, &chunk); + // One byte past the limit says there is more. + stdin.interface.appendRemaining(gpa, &raw, .limited(limit + 1)) catch |err| switch (err) { + error.StreamTooLong => { + raw.shrinkRetainingCapacity(limit); + // CAN ends an escape the cut left half sent, and SGR 0 its colour, + // so the note is never swallowed or tinted. + const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + try raw.appendSlice(gpa, said); + }, + else => |e| return e, + }; return raw.toOwnedSlice(gpa); } @@ -561,7 +551,7 @@ fn nativeMain(std_init: std.process.Init) !void { // made of it (as acme's `B` has no stdin, through pane/new, a name // and the body), and back at once: the PAGER a pane's shell gets. if (positional) |word| if (std.mem.eql(u8, word, "-")) { - const text = readStdinText(arena) catch |err| Refuse.with(init.io, "stdin", err); + const text = readStdinText(init.io, arena) catch |err| Refuse.with(init.io, "stdin", err); // Nothing paged: no pane, and done. if (text.len == 0) return; pageInto(init.io, arena, parent.dial, text); @@ -676,7 +666,7 @@ fn nativeMain(std_init: std.process.Init) !void { // `pardes -` outside a session: an editor whose first pane holds stdin, // as `vim -` does; the terminal is /dev/tty, never stdin. if (positional) |a| if (std.mem.eql(u8, a, "-")) { - opts.stdin_text = readStdinText(arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); + opts.stdin_text = readStdinText(init.io, arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); // Nothing paged: nothing to show. if (opts.stdin_text.?.len == 0) return; positional = null; diff --git a/src/syntax.zig b/src/syntax.zig index 1c09c9f3..803d815a 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -1172,15 +1172,14 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: anytype, bytes: []const u8, at errdefer syntax_allocator.free(colored); try paintHunk(gpa, colored, bytes, kinds, sel); window.put(at, colored); + // An empty slot, else the least recently used. var oldest: usize = 0; for (&diff_pieces, 0..) |*slot, i| { const piece = slot.* orelse { oldest = i; break; }; - if (diff_pieces[oldest]) |o| if (piece.used < o.used) { - oldest = i; - }; + if (piece.used < diff_pieces[oldest].?.used) oldest = i; } if (diff_pieces[oldest]) |old| syntax_allocator.free(old.styles); diff_pieces[oldest] = .{ .hash = hash, .styles = colored, .used = diff_clock }; diff --git a/src/tagline.zig b/src/tagline.zig index b6601d61..e668419d 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -192,12 +192,7 @@ pub fn defaultTail(pane: *const Pane) []const u8 { /// The tag as it is shown, read and pointed at: its computed prefix and /// its own text after it. pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { - const prefix = try tagPrefix(p, pane); - const tail = curTail(pane); - const out = try arena.alloc(u8, prefix.len + tail.len); - @memcpy(out[0..prefix.len], prefix); - @memcpy(out[prefix.len..], tail); - return out; + return std.mem.concat(arena, u8, &.{ try tagPrefix(p, pane), curTail(pane) }); } /// Give the keyboard to the tag in normal mode (`:`), its cursor where diff --git a/src/terminal.zig b/src/terminal.zig index 05054521..755fde6c 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1363,7 +1363,8 @@ const Rows = struct { const empty_grid = [1][]const u8{""}; /// What LEAVING raw tty mode does to one prompt row, decided from its cells -/// alone. See config.tty_blank for why any of this happens. +/// alone: OSC 133 prompt cells are hidden in normal mode, what was typed at +/// them stays. const PromptCut = union(enum) { /// show the row exactly as ghostty dumped it keep, @@ -1375,7 +1376,6 @@ const PromptCut = union(enum) { }; fn promptCut(pin: ghostty_vt.Pin) PromptCut { - if (config.tty_blank == .prompt_and_input) return .blank; const cells = pin.cells(.all); var cols: usize = 0; while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; diff --git a/src/web.zig b/src/web.zig index f89aa7e9..fd6371c0 100644 --- a/src/web.zig +++ b/src/web.zig @@ -15,58 +15,19 @@ const mouse = @import("mouse.zig"); const gpa = std.heap.wasm_allocator; const embedded_dump = @embedFile("embedded.dump.zon"); const input_capacity = 64 * 1024; -const c_alloc_header_size = 16; const attr_tagline: u16 = 1 << 7; +/// Tree-sitter's C runtime is linked into this module: its malloc, calloc, +/// realloc and free are the wasm allocator's, as the Zig core's are. A var, +/// as c_heap compares the allocator it is at run time (wasm_allocator's +/// `ptr` is undefined, which comptime refuses to compare). +var c_allocator: std.mem.Allocator = gpa; +const c_heap = @import("c_heap").Heap(&c_allocator); comptime { - if (c_alloc_header_size < @sizeOf(usize)) @compileError("C allocation header is too small"); -} - -/// Tree-sitter's C runtime is linked into this module. Its conventional -/// allocation symbols share the same wasm allocator as the Zig core and keep -/// the original allocation size in a 16-byte, max-aligned prefix. -export fn malloc(size_arg: usize) callconv(.c) ?*anyopaque { - const size = @max(size_arg, 1); - const total = std.math.add(usize, c_alloc_header_size, size) catch return null; - const bytes = gpa.alignedAlloc(u8, .@"16", total) catch return null; - const header: *align(16) usize = @ptrCast(bytes.ptr); - header.* = total; - return @ptrCast(bytes.ptr + c_alloc_header_size); -} - -export fn calloc(count: usize, size: usize) callconv(.c) ?*anyopaque { - const len = std.math.mul(usize, count, size) catch return null; - const ptr = malloc(len) orelse return null; - if (len != 0) { - const bytes: [*]u8 = @ptrCast(ptr); - @memset(bytes[0..len], 0); - } - return ptr; -} - -export fn free(ptr: ?*anyopaque) callconv(.c) void { - const data = ptr orelse return; - const data_bytes: [*]u8 = @ptrCast(data); - const base: [*]align(16) u8 = @ptrCast(@alignCast(data_bytes - c_alloc_header_size)); - const header: *align(16) usize = @ptrCast(base); - gpa.free(base[0..header.*]); -} - -export fn realloc(ptr: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { - if (ptr == null) return malloc(size); - if (size == 0) { - free(ptr); - return null; - } - const data_bytes: [*]u8 = @ptrCast(ptr.?); - const base: [*]align(16) u8 = @ptrCast(@alignCast(data_bytes - c_alloc_header_size)); - const header: *align(16) usize = @ptrCast(base); - const old_size = header.* - c_alloc_header_size; - const replacement = malloc(size) orelse return null; - const replacement_bytes: [*]u8 = @ptrCast(replacement); - @memcpy(replacement_bytes[0..@min(old_size, size)], data_bytes[0..@min(old_size, size)]); - free(ptr); - return replacement; + @export(&c_heap.malloc, .{ .name = "malloc" }); + @export(&c_heap.calloc, .{ .name = "calloc" }); + @export(&c_heap.realloc, .{ .name = "realloc" }); + @export(&c_heap.free, .{ .name = "free" }); } pub const std_options: std.Options = .{ .logFn = logFn }; -- cgit v1.3 From 51903dd947f90381d1a908c488a019289a1c8413 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 11:57:26 -0300 Subject: Search converge 3/6: the query pane, line 1 the query and its first word the source, rows made live like Callstack's, the owner's places showing the set, a +Preview promoted in place, Enter freezes, Esc restores --- docs/typ/builtins-gui.json | 7 +- docs/typ/builtins-tty.json | 7 +- src/File.zig | 2 + src/Names.zig | 446 +++++++++ src/Output.zig | 8 +- src/Places.zig | 39 +- src/Query.zig | 2155 ++++++++++++++++++++++++++++++++++++++++++++ src/Text.zig | 5 +- src/body_layer.zig | 1 + src/builtins.zig | 35 +- src/config.zig | 54 +- src/edit.zig | 20 + src/exec.zig | 20 + src/fs.zig | 2 +- src/layout.zig | 18 +- src/look.zig | 2 + src/mouse.zig | 9 + src/ninep/ctl.zig | 16 +- src/normal.zig | 16 +- src/panes.zig | 7 + src/pardes.zig | 54 +- src/tagline.zig | 8 + test/output.zig | 59 +- 23 files changed, 2921 insertions(+), 69 deletions(-) create mode 100644 src/Names.zig create mode 100644 src/Query.zig (limited to 'src/fs.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index de8fde9c..a502836e 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -102,6 +102,7 @@ {"name": "PanelVertical", "leader": "SPC a v", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close with a vertical wipe, on or off."}, {"name": "PanelWave", "leader": "SPC a w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close in a wave, on or off."}, {"name": "PanelZoom", "leader": "SPC a z", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes zoom in and out as they open and close, on or off."}, + {"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."}, {"name": "Parallax", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A theme's page pattern moves with the text at a quarter of its speed, on or off."}, {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."}, {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."}, @@ -111,7 +112,7 @@ {"name": "Placement", "leader": "SPC c p", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "acme, pardes", "doc": "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules."}, {"name": "ProgramEsc", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them."}, {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, - {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, + {"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, @@ -119,6 +120,10 @@ {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right."}, {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names."}, + {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, line 1 the argument (`Panes`, `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`."}, + {"name": "SearchPane", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "reuse, new", "doc": "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is."}, + {"name": "SearchPlace", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "attached, column", "doc": "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column."}, + {"name": "SearchRows", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself."}, {"name": "SelectRefs", "leader": "SPC l h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select every reference to the symbol under the cursor."}, {"name": "SelectionGlow", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A soft halo of the selection's colour round it in the body, on or off."}, {"name": "Shader", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A Shadertoy file into the post chain, or out of it, compiled again when saved; off empties the chain."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 4db29e6e..7e9ba678 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -91,6 +91,7 @@ {"name": "PanelVertical", "leader": "SPC a v", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close with a vertical wipe, on or off."}, {"name": "PanelWave", "leader": "SPC a w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close in a wave, on or off."}, {"name": "PanelZoom", "leader": "SPC a z", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes zoom in and out as they open and close, on or off."}, + {"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."}, {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."}, {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."}, {"name": "PdfTint", "leader": "SPC t i", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Tint the PDF page to the theme, or show it as printed, stepping through them (or to the one named, `disabled|filtered|full`)."}, @@ -98,7 +99,7 @@ {"name": "Placement", "leader": "SPC c p", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "acme, pardes", "doc": "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules."}, {"name": "ProgramEsc", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them."}, {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, - {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, + {"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, @@ -106,6 +107,10 @@ {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right."}, {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names."}, + {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, line 1 the argument (`Panes`, `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`."}, + {"name": "SearchPane", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "reuse, new", "doc": "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is."}, + {"name": "SearchPlace", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "attached, column", "doc": "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column."}, + {"name": "SearchRows", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself."}, {"name": "SelectRefs", "leader": "SPC l h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select every reference to the symbol under the cursor."}, {"name": "Shell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The shell new terminals run; bare, $SHELL if it is executable, else /bin/sh."}, {"name": "Subtypes", "leader": "SPC l T", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the subtypes of the type under the cursor."}, diff --git a/src/File.zig b/src/File.zig index 3db22f95..f633cad0 100644 --- a/src/File.zig +++ b/src/File.zig @@ -598,6 +598,8 @@ pub fn gutterWidth(pane: *const Pane) u16 { // pager and delta show none. if (file.pager) return 0; if (file.output) |o| if (std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return 0; + // A query pane's rows carry their own line numbers (Query.zig). + if (pane.query != null) return 0; var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); var digits: u16 = 1; while (lines >= 10) : (lines /= 10) digits += 1; diff --git a/src/Names.zig b/src/Names.zig new file mode 100644 index 00000000..48447f56 --- /dev/null +++ b/src/Names.zig @@ -0,0 +1,446 @@ +//! Names a query pane picks from by a fuzzy query: the files under a +//! directory (walked a slice a frame), the recent files, the open panes, +//! a file's declarations. Each keystroke scores them again with a small +//! fzf-style scorer (subsequence, Smith-Waterman with affine gaps, bonuses +//! at the starts of words and path segments), a frame's budget at a time, +//! the best kept first. Lifted from the pick prototype (Pick.zig), whose +//! scorer took ~1 ms for 20k paths in a release build. Embedded in a +//! Query; the rows it shows are the Query's to make. +const Names = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const filesystem = @import("fs.zig"); +const Pardes = pardes.Pardes; + +/// The candidates' rows, back to back, no newlines. +bytes: std.ArrayList(u8) = .empty, +/// `bytes` in lowercase, for a lowercase query to match without folding. +lower: std.ArrayList(u8) = .empty, +cands: std.ArrayList(Cand) = .empty, +/// The candidates `query` matches, best first. +hits: std.ArrayList(Hit) = .empty, +/// `cands[0..scored]` were scored against `query` (in `hits` or not): the +/// ones a walk adds past it are scored as they come. +scored: u32 = 0, +/// Candidates to score before `cands[scored..]`: what the last query +/// matched, when this one only grew from it. +pending: std.ArrayList(u32) = .empty, +pending_at: usize = 0, +query_buf: [max_query]u8 = undefined, +query_len: u8 = 0, +/// The files walk, while it lasts (Find in a query pane until the disk +/// engine has it). +walk: ?Walk = null, +/// Bumped whenever `hits` change: the rows are made again only then. +gen: u32 = 0, + +pub const Cand = struct { + /// The row: `bytes[start..][0..len]`. + start: u32, + len: u16, + /// What is scored: the row's `[key..][0..key_len]` (a path, a + /// declaration's text, a name), its basename from `base` within it. + key: u16, + key_len: u16, + base: u16, + /// What the row is of: a line of the owner (Symbols, 1-based), a + /// pane's serial (Panes); 0 for a path. + ref: u32 = 0, +}; + +pub const Hit = struct { cand: u32, score: i32 }; + +/// The most rows shown: the rest are counted. +pub const max_rows = 200; +pub const max_query = 64; +/// A candidate is scored over its first this many bytes. +const max_text = 512; +const max_cands = 200_000; +/// Entries a walk reads a frame: ~1-3 ms warm. +const walk_slice = 2000; +const walk_max_depth = 16; +/// A keystroke's scoring, and a frame's: what is left waits a frame. +const score_budget_ns = 4 * std.time.ns_per_ms; + +const Walk = struct { + root: std.Io.Dir, + walker: std.Io.Dir.SelectiveWalker, + done: bool = false, + skipped: u32 = 0, + + fn deinit(w: *Walk) void { + const io = std.Io.Threaded.global_single_threaded.io(); + // The walker closes a directory only as it leaves it: the ones it + // is still in (all but the root, which is ours) are closed here. + if (w.walker.stack.items.len > 1) for (w.walker.stack.items[1..]) |*item| item.iter.reader.dir.close(io); + w.walker.deinit(); + w.root.close(io); + } +}; + +pub fn deinit(n: *Names, gpa: std.mem.Allocator) void { + if (n.walk) |*w| w.deinit(); + n.bytes.deinit(gpa); + n.lower.deinit(gpa); + n.cands.deinit(gpa); + n.hits.deinit(gpa); + n.pending.deinit(gpa); + n.* = .{}; +} + +/// No candidates, no walk: for a source filled again. +pub fn reset(n: *Names) void { + if (n.walk) |*w| w.deinit(); + n.walk = null; + n.bytes.clearRetainingCapacity(); + n.lower.clearRetainingCapacity(); + n.cands.clearRetainingCapacity(); + n.hits.clearRetainingCapacity(); + n.pending.clearRetainingCapacity(); + n.pending_at = 0; + n.scored = 0; + n.gen +%= 1; +} + +pub fn queryText(n: *const Names) []const u8 { + return n.query_buf[0..n.query_len]; +} + +pub fn add(n: *Names, gpa: std.mem.Allocator, row_in: []const u8, key: usize, key_len: usize, base: u16, ref: u32) !void { + if (n.cands.items.len >= max_cands) return; + const text = row_in[0..@min(row_in.len, std.math.maxInt(u16))]; + try n.cands.append(gpa, .{ + .start = @intCast(n.bytes.items.len), + .len = @intCast(text.len), + .key = @intCast(@min(key, text.len)), + .key_len = @intCast(@min(key_len, text.len - @min(key, text.len))), + .base = base, + .ref = ref, + }); + try n.bytes.appendSlice(gpa, text); + try n.lower.ensureUnusedCapacity(gpa, text.len); + for (text) |c| n.lower.appendAssumeCapacity(std.ascii.toLower(c)); +} + +pub fn relative(path: []const u8, dir: []const u8) []const u8 { + const d = std.mem.trimEnd(u8, dir, "/"); + if (d.len > 0 and path.len > d.len + 1 and std.mem.startsWith(u8, path, d) and path[d.len] == '/') return path[d.len + 1 ..]; + return path; +} + +pub fn baseOf(path: []const u8) u16 { + const slash = std.mem.lastIndexOfScalar(u8, std.mem.trimEnd(u8, path, "/"), '/') orelse return 0; + return @intCast(@min(slash + 1, max_text)); +} + +/// The files under `dir`, walked from now on a slice a frame (`walkSlice`): +/// the first slice now, so a small tree is whole before the first frame. +pub fn startWalk(n: *Names, gpa: std.mem.Allocator, dir: []const u8) !void { + if (comptime !filesystem.platform_has_fs) return error.NoFilesystem; + const io = std.Io.Threaded.global_single_threaded.io(); + pardes.turn.yield(); + defer pardes.turn.back(); + var dir_handle = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); + errdefer dir_handle.close(io); + n.walk = .{ .root = dir_handle, .walker = try dir_handle.walkSelectively(gpa) }; + n.walkSlice(gpa); +} + +/// One frame's slice of a walk: up to `walk_slice` entries, files kept, +/// what a Find skips skipped and dot-directories too. +pub fn walkSlice(n: *Names, gpa: std.mem.Allocator) void { + const w = if (n.walk) |*w| w else return; + if (w.done) return; + const io = std.Io.Threaded.global_single_threaded.io(); + pardes.turn.yield(); + defer pardes.turn.back(); + var steps: usize = 0; + walk: while (steps < walk_slice) : (steps += 1) { + const e = (w.walker.next(io) catch { + w.skipped += 1; + continue; + }) orelse { + w.done = true; + break; + }; + if (e.kind != .directory) { + n.add(gpa, e.path, 0, e.path.len, baseOf(e.path), 0) catch { + w.done = true; + break; + }; + if (n.cands.items.len >= max_cands) { + w.done = true; + break; + } + continue; + } + if (e.depth() >= walk_max_depth or e.basename[0] == '.') continue; + for (filesystem.find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; + w.walker.enter(io, e) catch { + w.skipped += 1; + }; + } +} + +pub fn walking(n: *const Names) bool { + return if (n.walk) |w| !w.done else false; +} + +/// Still walking, or still scoring what it has: it wants the next frame. +pub fn busy(n: *const Names) bool { + return n.walking() or n.scored < n.cands.items.len or n.pending_at < n.pending.items.len; +} + +/// A new query: scored again, from what the last one matched when it only +/// grew from it. +pub fn typed(n: *Names, gpa: std.mem.Allocator, text: []const u8) void { + const q = text[0..@min(text.len, max_query)]; + if (std.mem.eql(u8, q, n.queryText()) and n.scored > 0) return; + // A query that only grew matches a subset of what the last one did: + // only those are scored again (and then the ones not yet scored). + const grew = n.query_len > 0 and std.mem.startsWith(u8, q, n.queryText()) and std.mem.indexOfScalar(u8, q[n.query_len..], ' ') == null; + n.query_len = @intCast(q.len); + @memcpy(n.query_buf[0..q.len], q); + if (grew) { + const pending = n.pending.items[n.pending_at..]; + std.mem.copyForwards(u32, n.pending.items[0..pending.len], pending); + n.pending.items.len = pending.len; + n.pending.ensureUnusedCapacity(gpa, n.hits.items.len) catch return; + for (n.hits.items) |h| n.pending.appendAssumeCapacity(h.cand); + } else { + n.scored = 0; + n.pending.clearRetainingCapacity(); + } + n.pending_at = 0; + n.hits.clearRetainingCapacity(); + n.rescore(gpa); +} + +/// Scores the pending candidates, then `cands[scored..]`, into `hits`, and +/// sorts them: at most `score_budget_ns` of it a call, the rest on the +/// next frames while the best so far is shown. +pub fn rescore(n: *Names, gpa: std.mem.Allocator) void { + const q = n.queryText(); + const empty = std.mem.trim(u8, q, " ").len == 0; + const io = std.Io.Threaded.global_single_threaded.io(); + const started = std.Io.Clock.awake.now(io); + const had = n.hits.items.len; + const was_scored = n.scored; + var count: usize = 0; + while (true) : (count += 1) { + const i: u32 = if (n.pending_at < n.pending.items.len) blk: { + n.pending_at += 1; + break :blk n.pending.items[n.pending_at - 1]; + } else if (n.scored < n.cands.items.len) blk: { + n.scored += 1; + break :blk n.scored - 1; + } else break; + const c = n.cands.items[i]; + const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; + const s = if (empty) 0 else match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, null, null, null); + if (s) |score| n.hits.append(gpa, .{ .cand = i, .score = score }) catch break; + // The clock every 256 candidates: reading it is not free either. + if (!empty and count % 256 == 255 and + started.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds() > score_budget_ns) break; + } + // An empty query keeps the source's order (the walk's, recency): no + // row moves as the walk goes on, it only grows at the foot. + if (!empty) std.sort.pdq(Hit, n.hits.items, n.cands.items, struct { + fn lt(cands: []const Cand, a: Hit, b: Hit) bool { + if (a.score != b.score) return a.score > b.score; + const la = cands[a.cand].key_len; + const lb = cands[b.cand].key_len; + if (la != lb) return la < lb; + return a.cand < b.cand; + } + }.lt); + if (n.hits.items.len != had or n.scored != was_scored or count > 0) n.gen +%= 1; +} + +/// The row of hit `i` and, in `marks`, the bytes of it the query matched. +pub fn row(n: *const Names, i: usize, marks: []u16, nmarks: *usize) []const u8 { + const c = n.cands.items[n.hits.items[i].cand]; + nmarks.* = 0; + const q = n.queryText(); + if (std.mem.trim(u8, q, " ").len > 0) { + const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; + _ = match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, marks, nmarks, &dp_trace); + for (marks[0..nmarks.*]) |*m| m.* += c.key; + } + return n.bytes.items[c.start..][0..c.len]; +} + +// ---- the scorer (pick's) ---- + +const neg: i32 = -(1 << 24); +const score_match = 16; +const gap_start = 3; +const gap_ext = 1; +const bonus_consecutive = 7; +/// At the start of the text or of a path segment. +const bonus_start = 12; +/// After `_ - . : space`. +const bonus_delim = 9; +/// A camelCase hump, or a word after other punctuation. +const bonus_camel = 8; +/// Each matched character in the basename. +const bonus_base = 2; + +/// The scorer's two rows, and the whole table the marks are backtracked +/// through: the main loop's, one score at a time. Not locals: a safe build +/// fills an undefined local, 4 KB a candidate, which was most of a +/// keystroke's time. +var dp_rows: [2][max_text]i32 = undefined; +var dp_trace: [max_query * max_text]i32 = undefined; + +fn bonusAt(text: []const u8, j: usize) i32 { + if (j == 0) return bonus_start; + const prev = text[j - 1]; + const c = text[j]; + if (prev == '/') return bonus_start; + switch (prev) { + '_', '-', '.', ':', ' ', '\t' => return bonus_delim, + else => {}, + } + if (std.ascii.isLower(prev) and std.ascii.isUpper(c)) return bonus_camel; + if (!std.ascii.isAlphanumeric(prev) and std.ascii.isAlphanumeric(c)) return bonus_camel; + return 0; +} + +/// `query`'s score against `text` (`lower` its lowercase copy, its +/// basename from `base`), null if some term of it is not a subsequence of +/// `text`. Terms split on spaces are ANDed; smart case per term. With +/// `marks`, the bytes matched are written there, ascending. +pub fn match(query: []const u8, text_in: []const u8, lower_in: []const u8, base: usize, marks: ?[]u16, marks_len: ?*usize, trace: ?[]i32) ?i32 { + const text = text_in[0..@min(text_in.len, max_text)]; + const lower = lower_in[0..text.len]; + var total: i32 = 0; + var nmarks: usize = 0; + var terms = std.mem.tokenizeScalar(u8, query, ' '); + while (terms.next()) |term_in| { + const term = term_in[0..@min(term_in.len, max_query)]; + const m = term.len; + const sensitive = for (term) |c| { + if (std.ascii.isUpper(c)) break true; + } else false; + // A lowercase term is matched against the lowercase copy. + var low_buf: [max_query]u8 = undefined; + const want = if (sensitive) term else std.ascii.lowerString(&low_buf, term); + const hay = if (sensitive) text else lower; + // The window a match can be in: from the first character's first + // place to the last one's last place, else no match at all. + const lo = std.mem.indexOfScalar(u8, hay, want[0]) orelse return null; + var pos = lo + 1; + for (want[1..]) |c| pos = (std.mem.indexOfScalarPos(u8, hay, pos, c) orelse return null) + 1; + const end = std.mem.lastIndexOfScalar(u8, hay, want[m - 1]).? + 1; + // D[i][j]: the best score with term[i] matched at text[j]. + var prev = &dp_rows[0]; + var cur = &dp_rows[1]; + const width = text.len; + const keep = if (trace) |t| t.len >= m * width else false; + for (0..m) |i| { + var gapped: i32 = neg; // max over k <= j-2 of D[i-1][k], less the gap to j + for (lo..end) |col| { + var best: i32 = neg; + if (i > 0 and col >= lo + 2) gapped = @max(gapped - gap_ext, prev[col - 2] - gap_start); + if (hay[col] == want[i]) { + const own: i32 = score_match + bonusAt(text, col) + @as(i32, if (col >= base) bonus_base else 0); + if (i == 0) { + best = own; + } else if (col > lo) { + const from = @max(if (prev[col - 1] > neg) prev[col - 1] + bonus_consecutive else neg, gapped); + if (from > neg) best = from + own; + } + } + cur[col] = best; + if (keep) trace.?[i * width + col] = best; + } + const t = prev; + prev = cur; + cur = t; + } + var best: i32 = neg; + var at: usize = lo; + for (lo..end) |col| if (prev[col] > best) { + best = prev[col]; + at = col; + }; + if (best <= neg) return null; + total += best; + // Back from the best end, the place each character was matched at. + if (keep and marks != null) { + const out = marks.?; + const t = trace.?; + var i = m; + var col = at; + while (i > 0) { + i -= 1; + if (nmarks < out.len) { + out[nmarks] = @intCast(col); + nmarks += 1; + } + if (i == 0) break; + const here = t[i * width + col]; + const own: i32 = score_match + bonusAt(text, col) + @as(i32, if (col >= base) bonus_base else 0); + if (col > lo and t[(i - 1) * width + col - 1] > neg and t[(i - 1) * width + col - 1] + bonus_consecutive + own == here) { + col -= 1; + continue; + } + var found = col - 1; + if (col >= lo + 2) { + var k = col - 2; + while (true) { + const d = t[(i - 1) * width + k]; + if (d > neg and d - gap_start - @as(i32, @intCast(col - 2 - k)) * gap_ext + own == here) { + found = k; + break; + } + if (k == lo) break; + k -= 1; + } + } + col = found; + } + } + } + if (marks_len) |count| { + if (marks) |out| std.mem.sort(u16, out[0..nmarks], {}, std.sort.asc(u16)); + count.* = nmarks; + } + return total; +} + +const test_paths = [_][]const u8{ + "src/layout.zig", "src/locations.zig", "src/Output.zig", "src/hunks.zig", + "src/pardes.zig", "src/pdf.zig", "src/look.zig", "src/syntax.zig", + "src/body_layer.zig", "build.zig", "src/ninep/ctl.zig", "docs/helix-keys.md", + "notes/helix-keys.md", "src/gui/Post.zig", "cmd/tool/ui_review.py", +}; + +fn topFor(q: []const u8) []const u8 { + var best: ?[]const u8 = null; + var best_score: i32 = std.math.minInt(i32); + for (test_paths) |path| { + var low: [256]u8 = undefined; + const s = match(q, path, std.ascii.lowerString(&low, path), baseOf(path), null, null, null) orelse continue; + if (s > best_score or (s == best_score and path.len < best.?.len)) { + best = path; + best_score = s; + } + } + return best orelse ""; +} + +test "Names ranks real paths as the pick prototype did" { + try std.testing.expectEqualStrings("src/layout.zig", topFor("layout")); + try std.testing.expectEqualStrings("src/Output.zig", topFor("out")); + try std.testing.expectEqualStrings("src/pardes.zig", topFor("prz")); + try std.testing.expectEqualStrings("src/body_layer.zig", topFor("bl")); + try std.testing.expectEqualStrings("src/ninep/ctl.zig", topFor("ctl ninep")); + try std.testing.expectEqualStrings("docs/helix-keys.md", topFor("helkey")); + try std.testing.expectEqualStrings("src/gui/Post.zig", topFor("gui/po")); + try std.testing.expectEqualStrings("src/Output.zig", topFor("Out")); +} diff --git a/src/Output.zig b/src/Output.zig index 9a11b2fc..1e62b04a 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -35,6 +35,9 @@ pub const Origin = union(enum) { unsaved, /// A directory's entries (Dir.zig), the pane named for it. dir, + /// A query pane's +Preview (Query.zig): a file's text shown, not yet + /// its pane; Enter promotes it to one where it stands. + preview, }; pub const max_arg = dump.max_origin_arg; @@ -259,6 +262,7 @@ pub fn traits(o: Origin) Traits { .errors => .{ .name = config.errors_buffer, .doc = true }, .pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true }, .unsaved => .{ .name = config.unsaved_buffer, .doc = true }, + .preview => .{ .name = config.preview_buffer, .doc = true }, // Named for its directory, not a `+` name in it. .dir => .{ .name = "", .doc = true }, .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, @@ -324,6 +328,7 @@ pub fn word(o: Origin) []const u8 { .pdf_links => config.pdf_links_buffer, .unsaved => config.unsaved_buffer, .dir => dir_word, + .preview => config.preview_buffer, }; } @@ -337,6 +342,7 @@ pub fn fromWord(w: []const u8) ?Origin { if (std.mem.eql(u8, w, config.pdf_links_buffer)) return .pdf_links; if (std.mem.eql(u8, w, config.unsaved_buffer)) return .unsaved; if (std.mem.eql(u8, w, dir_word)) return .dir; + if (std.mem.eql(u8, w, config.preview_buffer)) return .preview; if (std.meta.stringToEnum(Builtin, w)) |b| if (builtins.registry.outputTraits(b) != null) return .{ .cmd = b }; if (std.meta.stringToEnum(lsp.Kind, w)) |k| return .{ .query = k }; @@ -399,7 +405,7 @@ fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?u => {}, else => return anchor, }, - .errors, .pdf_links, .unsaved, .dir => return anchor, + .errors, .pdf_links, .unsaved, .dir, .preview => return anchor, } if (content.len == 0) return anchor; const path_only = std.meta.eql(from, Origin{ .cmd = .Find }); diff --git a/src/Places.zig b/src/Places.zig index 435a138a..cff7c22e 100644 --- a/src/Places.zig +++ b/src/Places.zig @@ -207,7 +207,8 @@ pub fn search(set: *Places, p: *Pardes, pane: *Pane, provenance: Provenance, fro set.revision = f.revision +% 1; // `fill` starts it over for the text as it is set.seek = seek; set.seek_moves = moves; - set.fill(p, pane, frame_bytes, frame_steps); + // The keystroke's share: the view; the rest a frame's slice a tick. + set.fill(p, pane, 0, frame_steps); } /// A list's places in this text, as it gives them (sorted here), in place @@ -589,7 +590,7 @@ pub fn step(set: *Places, p: *Pardes, pane: *Pane, forward: bool, count: u32, ad /// Whether n and N in this pane are these places' to step: a list's or a /// query's always; a search's while it is what the register says (an `s`, /// a `/` elsewhere or `"a` since makes them helix's register search again). -pub fn answersN(set: *const Places, p: *Pardes, pane: *const Pane) bool { +pub fn answersN(set: *const Places, p: *Pardes, pane: *Pane) bool { if (!set.shows(pane) and !set.started) return false; if (set.provenance != .search) return p.register == 0; const name = if (p.register != 0) p.register else p.registers.last_search; @@ -634,10 +635,11 @@ pub fn forget(set: *Places, gpa: std.mem.Allocator) void { set.snap = &.{}; } -/// Where the query began: the primary selection's end when it was -/// remembered, else now. -pub fn origin(set: *const Places, pane: *const Pane) usize { - if (set.snap.len > 0) return @max(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); +/// Where the query began: the primary selection's start when it was +/// remembered, else now; a place there counts (helix's `/` from the +/// cursor). +pub fn origin(set: *const Places, pane: *Pane) usize { + if (set.snap.len > 0) return @min(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); const f = pane.file orelse return 0; const r = pane.body.primaryRange(f.content, 0); return @min(r.anchor, r.head); @@ -847,3 +849,28 @@ test "places: a big file costs a keystroke its view, the ticks find the rest, an if (std.c.getenv("PLACES_TIMES") != null) std.debug.print("places: first key {d} us, {d} ticks, an edit {d} us (the text's own splice {d} us)\n", .{ first_ns / 1000, ticks, edit_ns / 1000, text_ns / 1000 }); } + +test "zz stress analysis cost" { + const path = "/home/goblin/00-projects/0x4200.cafe/pardes-s-converge/.scratch/stress/src/layout.zig"; + if (std.c.getenv("PLACES_TIMES") == null) return error.SkipZigTest; + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(4 << 20)); + defer std.testing.allocator.free(bytes); + const syntax = @import("syntax.zig"); + syntax.start(std.testing.allocator); + defer syntax.stop(); + const tp = nowNs(); + const tree = syntax.parseTree(path, bytes); + const tq = nowNs(); + if (tree) |t| syntax.freeTree(t); + std.debug.print("parse alone {d} us\n", .{(tq - tp) / 1000}); + const t0 = nowNs(); + const d = try syntax.contextDeclarations(std.testing.allocator, path, bytes); + const t1 = nowNs(); + std.testing.allocator.free(d); + const a = try syntax.analyzeSource(std.testing.allocator, path, bytes, true, true); + const t2 = nowNs(); + std.testing.allocator.free(a.declarations); + std.testing.allocator.free(a.colors); + std.debug.print("decls {d} us ({d}), analysis with colours {d} us\n", .{ (t1 - t0) / 1000, d.len, (t2 - t1) / 1000 }); +} diff --git a/src/Query.zig b/src/Query.zig new file mode 100644 index 00000000..fbce95b2 --- /dev/null +++ b/src/Query.zig @@ -0,0 +1,2155 @@ +//! The query pane: the one pane search is. A +Search attached under the +//! pane that asked (its owner, layout.zig "Attached panes"), born at a +//! fixed height, whose body's line 1 is the query, editable text, and +//! whose rows below are made live from a source, read-only while live. +//! Line 1's first word names the source: `/pat` the owner's text (smart- +//! case regex), `Find pat` the files under its directory, `Grep pat` the +//! lines of those files, `Recent pat`, `Panes pat`, `Symbols pat` (the +//! owner's declarations), `All pat` (every open pane's text), and the +//! language server's `Refs`, `Def`, `Impl`, `Diagnostics`. Names are +//! matched fuzzy (Names.zig), text by regex. Editing the word changes +//! the source. +//! +//! The rows look like a Callstack's: the hit line with the match tinted +//! under a gutter line number, under the declaration it is in (when the +//! owner's parse exists: never made here on the loop), under its file +//! (Grep) or under `@pN name (count)` (All). They are addresses, all text: +//! B3 on one looks, B2 on line 1 runs it again. Wherever a row points into +//! an open pane's text, that pane's places (Places.zig) show the set: +//! tints, rail ticks, the current one selected. A row pointing at a file +//! no pane shows is shown in the +Preview attached under this pane; Enter +//! promotes the preview to the file's pane where it stands. +//! +//! Nothing moves while you type: the pane never closes, resizes or +//! rewrites line 1 on its own; zero hits is a state (`0` in the tag). +//! Enter lands on the current hit and freezes the rows into ordinary text; +//! Esc while typing puts every view back and closes the pane (or brings a +//! reused pane's frozen rows back); Del closes it. One per owner, reused +//! (SearchPane reuse|new). +const Query = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const edit = @import("edit.zig"); +const exec = @import("exec.zig"); +const layout = @import("layout.zig"); +const locations = @import("locations.zig"); +const look = @import("look.zig"); +const modal = @import("modal.zig"); +const normal = @import("normal.zig"); +const syntax = @import("syntax.zig"); +const tagline = @import("tagline.zig"); +const filesystem = @import("fs.zig"); +const colors = @import("colors.zig"); +const memory = @import("memory.zig"); +const Names = @import("Names.zig"); +const Places = @import("Places.zig"); +const Surface = @import("surface.zig").Surface; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const File = panes.File; +const Output = panes.Output; +const Key = pardes.Key; +const hit = pardes.hit; + +pub const Source = enum { text, find, grep, recent, panes, symbols, all, refs, defs, impls, diagnostics }; + +/// Line 1's words, each the source it names. `/` is vim's spelling, no +/// space after it; the others take one. +pub const words = [_]struct { word: []const u8, source: Source }{ + .{ .word = "Find", .source = .find }, + .{ .word = "Grep", .source = .grep }, + .{ .word = "Recent", .source = .recent }, + .{ .word = "Panes", .source = .panes }, + .{ .word = "Symbols", .source = .symbols }, + .{ .word = "All", .source = .all }, + .{ .word = "Refs", .source = .refs }, + .{ .word = "Def", .source = .defs }, + .{ .word = "Impl", .source = .impls }, + .{ .word = "Diagnostics", .source = .diagnostics }, +}; + +/// What a line 1 asks: its source and what follows its word. Null when it +/// starts with no word this knows (the user rewrote it): the rows say so. +pub fn parse(line: []const u8) ?struct { source: Source, pat: []const u8 } { + if (line.len > 0 and line[0] == '/') return .{ .source = .text, .pat = line[1..] }; + for (words) |w| { + if (std.mem.startsWith(u8, line, w.word) and (line.len == w.word.len or line[w.word.len] == ' ')) + return .{ .source = w.source, .pat = std.mem.trim(u8, line[w.word.len..], " \t") }; + } + return null; +} + +/// The word line 1 starts with for `source`, as typed after it. +pub fn wordOf(source: Source) []const u8 { + if (source == .text) return "/"; + for (words) |w| if (w.source == source) return w.word; + unreachable; +} + +/// A source whose rows can point at files no pane shows: its group is +/// made with a +Preview from the start, so nothing moves later. +fn previews(source: Source) bool { + return switch (source) { + .find, .grep, .recent, .refs, .defs, .impls, .diagnostics => true, + .text, .panes, .symbols, .all => false, + }; +} + +/// The most rows of hits a frozen list keeps: the rest are counted, and +/// said in a row. +pub const max_rows = 2000; +/// While typed, the rows are a window of this many around the current +/// place: the pane shows a few, and a row is two allocations a refill. +pub const live_rows = 100; + +/// One row's model, row `i + 1` of the pane (line 1 is the query): a hit, +/// a header (a declaration, a file, a pane) or a note. Where a row points +/// is in its locations.Row (path, at); a hit in an open pane's text also +/// knows its places there, `hit` and the `n` of them on its line. +pub const Item = struct { + kind: enum { hit, header, note }, + /// The pane whose text it is in (by serial), 0 when it is a file's. + serial: u32 = 0, + hit: usize = 0, + n: usize = 0, + /// A Panes row's pane, a Symbols row's line: Names.Cand.ref. + ref: u32 = 0, +}; + +/// A line a Grep found: its path and code in `found_bytes`. +pub const Found = struct { path: u32, path_len: u16, line: u32, col: u32, end: u32, code: u32, code_len: u32 }; + +/// The pane it answers for, by serial. +owner: u32, +/// Line 1 as the rows were last made for (gpa). +asked: []u8 = &.{}, +source: Source = .text, +/// Enter answered it: its rows are ordinary text from here, nothing remade. +frozen: bool = false, +items: std.ArrayList(Item) = .empty, +/// The current item, which Enter lands on and the places show. +current: ?usize = null, +/// The tag's `k/N`: how many places or names the rows are of, and where +/// the current one is among them (1-based; 0, none); `more` while counting. +total: usize = 0, +k: usize = 0, +more: bool = false, +/// What the rows were made of: the places' or names' generation and the +/// owner's text, so that a frame with nothing new makes nothing. +made_gen: u64 = std.math.maxInt(u64), +made_rev: u32 = 0, +/// The owner's revision seen last tick: rows follow an edit of the owner +/// once it has stood a frame (the rows refresh on idle frames). +seen_rev: u32 = 0, +/// The body cursor's row as last seen: B1, j or k on a row makes it current. +seen_row: i32 = 0, +/// The places a `/`'s rows are a window of: [lo, hi) of its owner's hits. +window: struct { lo: usize = 0, hi: usize = 0 } = .{}, +/// Ticks the rows waited while the places are still being found: they are +/// made every third, the frame's time going to the finding. +waited: u8 = 0, +names: Names = .{}, +/// A Grep's lines, found a slice a frame (Query.grepSlice). +found: std.ArrayList(Found) = .empty, +found_bytes: std.ArrayList(u8) = .empty, +grep_next: usize = 0, +grep_gen: u32 = 0, +/// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave +/// them (`path:line:col text`, gpa), filtered by what follows the word. +lsp_rows: []u8 = &.{}, +/// The +Preview under this pane, by serial; 0, none. +preview: u32 = 0, +/// A reused pane's frozen rows when a new query began in it: Esc brings +/// them back. +saved: ?Saved = null, + +pub const Saved = struct { + content: []u8, + rows: []locations.Row, + asked: []u8, + source: Source, + items: []Item, + current: ?usize, + total: usize, + k: usize, +}; + +pub fn deinit(q: *Query, gpa: std.mem.Allocator) void { + gpa.free(q.asked); + q.items.deinit(gpa); + q.names.deinit(gpa); + q.found.deinit(gpa); + q.found_bytes.deinit(gpa); + gpa.free(q.lsp_rows); + if (q.saved) |s| freeSaved(gpa, s); + q.* = undefined; +} + +fn freeSaved(gpa: std.mem.Allocator, s: Saved) void { + gpa.free(s.content); + locations.freeRows(gpa, s.rows); + gpa.free(s.asked); + gpa.free(s.items); +} + +/// The query pane `pane` is, if it is one. +pub fn of(pane: *Pane) ?*Query { + return pane.query; +} + +/// The owner's query pane (attached to it, or left where it was by +/// SearchPane new): the one a later search from it reuses. +pub fn ofOwner(p: *Pardes, owner_serial: u32) ?usize { + var found: ?usize = null; + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.owner != owner_serial) continue; + // the attached one first: an unattached one is a kept result + if (pane.attached_to == owner_serial) return i; + found = found orelse i; + } + return found; +} + +fn lineOne(content: []const u8) []const u8 { + return content[0 .. std.mem.indexOfScalar(u8, content, '\n') orelse content.len]; +} + +// ---- opening ---- + +/// A search from pane `from`: its owner's query pane, made under the owner +/// (with a +Preview when `source` can need one) or reused, line 1 the +/// source's word and `arg`. With `focus` the keyboard goes to line 1's end +/// in insert mode, as to a prompt; without (`*`), it stays where it is. +pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: bool) void { + const asker = p.panes[from] orelse return; + // Asked from a query pane (`/` in it, its own SPC f g): its own line 1; + // from a +Preview, its query pane's. + var owner_id = from; + if (asker.query) |q| owner_id = p.paneBySerial(q.owner) orelse from else if (isPreview(p, asker)) |qid| { + owner_id = p.paneBySerial(p.panes[qid].?.query.?.owner) orelse from; + } + const owner = p.panes[owner_id] orelse return; + if (asker.query != null and arg.len == 0 and asker.query.?.source == source and !asker.query.?.frozen) { + // Back to typing the query it has. + if (focus) toLineOne(p, from); + return; + } + const line = std.mem.concat(p.scratch.allocator(), u8, &.{ wordOf(source), if (source == .text) "" else " ", arg }) catch return; + var id: usize = undefined; + const existing = ofOwner(p, owner.serial); + if (existing != null and (p.settings.search_pane == .reuse or existing.? == from)) { + id = existing.?; + const rp = p.panes[id].?; + const q = rp.query.?; + // Its frozen rows, kept for an Esc to bring back. + if (q.frozen and q.saved == null) q.saved = save(p, rp, q) catch null; + q.frozen = false; + const f = &rp.file.?; + const new = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return; + File.setContent(p, f, new); + q.reset(p); + if (rp.collapsed) layout.toggleCollapse(p, id); + } else { + if (existing) |old| { + // SearchPane new: the last one stays where it is, a result of + // its own; its places are the new one's to feed. + p.panes[old].?.attached_to = null; + } + id = create(p, owner_id, line, source) orelse return; + } + // Every view as the search found it, for Esc to put back. + owner.places.remember(p, owner); + // Before the first key: a names source lists every candidate at once. + produce(p, id, false); + // What a 9P exec reads back: the pane it filled (ninep/ctl.zig). + p.fs.refilled = p.panes[id].?.serial; + if (focus) toLineOne(p, id) else p.active = from; +} + +/// A new query pane under pane `owner_id`, `rows` of the owner's rows (the +/// SearchRows setting), its +Preview under it when `source` can need one. +fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize { + const owner = p.panes[owner_id] orelse return null; + const free = p.freeSlot() orelse { + p.reportError(owner_id, "search", error.NoPaneSlots); + return null; + }; + const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(owner); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return null; + const np = Output.open(p, free, dir, .search, "", content) catch |err| { + p.gpa.free(content); + p.reportError(owner_id, "search", err); + return null; + }; + const q = p.gpa.create(Query) catch { + p.reportError(owner_id, "search", error.OutOfMemory); + return null; + }; + q.* = .{ .owner = owner.serial }; + np.query = q; + const body: u16 = 1 + p.settings.search_rows; + const tag = @max(pardes.BOX_H, np.tag_rows); + const with_preview = previews(source); + // The preview, made right after, takes its own rows from the owner. + const want = tag + body; + if (p.settings.search_place == .column) { + // The finder column (phase 6): until it exists, under the owner. + if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); + } else if (!layout.attach(p, owner_id, free, want)) { + // An owner too short to give a query pane its rows: placed as any + // new pane is, the one place a search moves another pane. + exec.placeNew(p, owner_id, owner_id, free, .doc); + } + if (with_preview) _ = makePreview(p, free); + return free; +} + +/// The keyboard to the end of line 1 of query pane `id`, in insert mode. +pub fn toLineOne(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + tagline.exitHeader(p); + p.active = id; + if (layout.findPane(p, id)) |at| p.setActiveColumn(at.col); + rp.focus = .body; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + t.cur_row = 0; + t.cur_col = @intCast(lineOne(rp.file.?.content).len); + t.vsel.active = false; + t.nsel = 0; + t.cur_pinned = true; + rp.query.?.seen_row = 0; + edit.enterInsert(p, t, .line_end, 1); + showCurrent(rp); +} + +/// The rows' state for a new question: nothing found yet. +fn reset(q: *Query, p: *Pardes) void { + q.items.clearRetainingCapacity(); + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + q.made_gen = std.math.maxInt(u64); + p.gpa.free(q.asked); + q.asked = &.{}; +} + +fn save(p: *Pardes, rp: *Pane, q: *Query) !Saved { + const f = &rp.file.?; + const content = try p.gpa.dupe(u8, f.content); + errdefer p.gpa.free(content); + const rows = try p.gpa.alloc(locations.Row, f.location_rows.len); + var made: usize = 0; + errdefer { + for (rows[0..made]) |r| { + p.gpa.free(r.path); + p.gpa.free(r.colors); + } + p.gpa.free(rows); + } + for (f.location_rows, 0..) |r, i| { + rows[i] = r; + rows[i].path = try p.gpa.dupe(u8, r.path); + rows[i].colors = p.gpa.dupe(u8, r.colors) catch |err| { + p.gpa.free(rows[i].path); + return err; + }; + made += 1; + } + const asked = try p.gpa.dupe(u8, q.asked); + errdefer p.gpa.free(asked); + return .{ .content = content, .rows = rows, .asked = asked, .source = q.source, .items = try p.gpa.dupe(Item, q.items.items), .current = q.current, .total = q.total, .k = q.k }; +} + +// ---- making the rows ---- + +/// After every step: each live query pane whose line 1 changed, or whose +/// source has something new, has its rows made again. A walk takes a slice +/// on a tick. Nothing here is synchronous with an edit of the owner: its +/// places shift (Places.shift) and the rows follow once it stands a frame. +pub fn produceAll(p: *Pardes, tick: bool) void { + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + if (pane.query == null) continue; + produce(p, id, tick); + } +} + +/// The frames a query pane still owes (a walk, scoring): nextWake's. +pub fn busy(p: *const Pardes) bool { + for (p.panes) |slot| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.frozen) continue; + if (q.names.busy() or (q.source == .grep and q.grep_next < q.names.cands.items.len) or q.made_rev != q.seen_rev) return true; + } + return false; +} + +fn produce(p: *Pardes, id: usize, tick: bool) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const f = if (rp.file) |*file| file else return; + const line = lineOne(f.content); + const changed = !std.mem.eql(u8, line, q.asked); + if (q.frozen and !changed) return; + if (q.frozen) { + // Line 1 of a frozen pane edited: it is a live query again. + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + q.frozen = false; + } + const owner_id = p.paneBySerial(q.owner); + const asked = parse(line); + if (changed) { + const was = q.source; + const new_asked = p.gpa.dupe(u8, line) catch return; + p.gpa.free(q.asked); + q.asked = new_asked; + q.made_gen = std.math.maxInt(u64); + if (asked) |a| { + if (a.source != was or q.names.cands.items.len == 0) startSource(p, id, q, a.source, owner_id); + q.source = a.source; + } + // The places this fed are another question's now. + if (asked == null or asked.?.source != .text) clearPlaces(p, q, rp.serial, owner_id, asked); + } + const a = asked orelse return noteRows(p, id, " line 1 asks: /text, Find, Grep, Recent, Panes, Symbols, All, Refs, Def, Impl or Diagnostics, then what to find\n"); + // A row clicked or stepped onto (B1, j, k): current, and shown. + if (rp.body.cur_row != q.seen_row) { + q.seen_row = rp.body.cur_row; + if (rp.body.cur_row > 0 and rp.body.cur_row <= q.items.items.len) { + const i: usize = @intCast(rp.body.cur_row - 1); + if (q.items.items[i].kind == .hit) setCurrent(p, id, i, true); + } + } + switch (a.source) { + .text => { + const oid = owner_id orelse return noteRows(p, id, " the pane this searched is gone: Del, or / in another\n"); + const owner = p.panes[oid].?; + const of_ = owner.file orelse return noteRows(p, id, " a terminal's text is not searched here yet: / in a file\n"); + const set = &owner.places; + if (changed) { + if (a.pat.len == 0) { + if (set.from == rp.serial) set.clear(p.gpa); + set.restore(p, owner); + } else set.search(p, owner, .typed, rp.serial, a.pat, false, set.origin(owner), p.active == id); + } + // The owner edited: its places shifted at once; the rows follow + // once its text has stood a frame. + if (!changed and of_.revision != q.made_rev) { + if (!tick or of_.revision != q.seen_rev) { + q.seen_rev = of_.revision; + return; + } + } + q.seen_rev = of_.revision; + const gen: u64 = (@as(u64, set.hits_gen) << 32) | of_.revision; + if (gen == q.made_gen and !changed) return showPlacesCurrent(p, id); + if (a.pat.len > 0 and set.from != rp.serial) return; + if (!changed and !set.complete() and q.made_gen != std.math.maxInt(u64) and q.waited < 2) { + q.waited += 1; + return showPlacesCurrent(p, id); + } + q.waited = 0; + q.made_gen = gen; + q.made_rev = of_.revision; + makeTextRows(p, id, oid, false) catch |err| p.reportError(id, "search", err); + }, + .all => { + if (changed) for (p.panes) |slot| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + if (a.pat.len == 0) { + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + continue; + } + tp.places.search(p, tp, .list, rp.serial, a.pat, false, null, false); + }; + var gen: u64 = 0; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial) { + gen +%= tp.places.hits_gen +% (@as(u64, tp.serial) << 20); + }; + if (gen == q.made_gen and !changed) return; + if (!changed and !tick) return; + q.made_gen = gen; + makeAllRows(p, id) catch |err| p.reportError(id, "search", err); + }, + .find, .recent, .panes, .symbols => { + if (tick) q.names.walkSlice(p.gpa); + if (changed) q.names.typed(p.gpa, a.pat) else if (q.names.busy()) q.names.rescore(p.gpa); + if (q.names.gen == q.made_gen and !changed) return; + q.made_gen = q.names.gen; + makeNameRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + .grep => { + if (changed) { + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + q.grep_gen +%= 1; + } + if (a.pat.len == 0) { + if (changed) makeGrepRows(p, id) catch {}; + return; + } + if (tick or changed) { + q.names.walkSlice(p.gpa); + grepSlice(p, q, rp, a.pat); + } + const gen: u64 = (@as(u64, q.grep_gen) << 32) | q.found.items.len; + if (gen == q.made_gen and !changed and !(q.grep_next >= q.names.cands.items.len and q.more)) return; + q.made_gen = gen; + makeGrepRows(p, id) catch |err| p.reportError(id, "search", err); + if (changed or q.current == null) feedGrepPlaces(p, q, rp.serial, a.pat); + }, + .refs, .defs, .impls, .diagnostics => { + if (changed and q.lsp_rows.len == 0) { + // Typed, not answered: asked of the language server at the + // owner's cursor; its answer fills these rows (fillList). + // An answer opening the pane is no typing. + if (p.active != id) return; + if (owner_id) |oid| p.lspRequest(oid, switch (a.source) { + .refs => .references, + .defs => .definition, + .impls => .implementation, + else => .diagnostics, + }, ""); + return noteRows(p, id, " asked of the language server...\n"); + } + if (!changed) return; + makeListRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + } +} + +/// Whether pane `tp`'s text is one All searches: a file's or a list's, +/// not a query pane's nor a preview's. +fn searchable(tp: *const Pane) bool { + const f = tp.file orelse return false; + if (tp.query != null) return false; + if (f.output) |o| if (o.from == .preview) return false; + return true; +} + +/// A source begun: its candidates gathered (names), its walk started. +fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usize) void { + const rp = p.panes[id].?; + q.names.reset(); + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const gpa = p.gpa; + switch (source) { + .find, .grep => q.names.startWalk(gpa, dir) catch |err| p.reportError(id, "search", err), + .recent => { + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + Output.recentText(p, &out.writer, true) catch {}; + var lines = std.mem.splitScalar(u8, out.written(), '\n'); + while (lines.next()) |ln| { + if (ln.len == 0) continue; + const rel = Names.relative(ln, dir); + const path_end = std.mem.indexOfAny(u8, rel, ": ") orelse rel.len; + q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; + } + }, + .panes => for (p.panes) |slot| { + const other = slot orelse continue; + if (other == rp or other.query != null) continue; + var buf: [4096 + 32]u8 = undefined; + const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; + q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + }, + .symbols => { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const f = if (owner.file) |*file| file else return; + const decls = ownerDecls(p, f, true) orelse return; + for (decls) |d| { + const header = f.content[d.start_byte..@min(d.header_end_byte, f.content.len)]; + const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r"); + var buf: [256 + 16]u8 = undefined; + const row = std.fmt.bufPrint(&buf, "{d: >6} {s}", .{ d.start_line + 1, first[0..@min(first.len, 240)] }) catch continue; + q.names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break; + } + }, + else => {}, + } +} + +/// The owner's declarations, from a parse that already exists: its sticky +/// headers' (TreeContext) at this revision, or the locations cache's. None +/// is made here, on the loop, unless `small` and the text is small: a +/// tree-sitter parse of a 1.2 MB file is seconds in a Debug build. +/// ponytail: no grouping for a big file until the disk engine's worker +/// parses it (phase 4). +fn ownerDecls(p: *Pardes, f: *File.State, small: bool) ?[]const syntax.ContextDeclaration { + if (f.context_revision) |rev| if (rev == f.revision and f.context_declarations.len > 0) return f.context_declarations; + const cache = &p.locations_cache; + for (cache.entries[0..cache.len]) |entry| { + if (entry.declarations_ready and std.mem.eql(u8, entry.path, f.path) and std.mem.eql(u8, entry.source, f.content)) return entry.analysis.declarations; + } + if (!small or f.content.len > small_parse_bytes or !syntax.supportsPath(f.path)) return null; + var got = p.locations_cache.get(p.tree_sitter_gpa, f.path, f.content, true, false) catch return null; + if (got.owned) { + got.deinit(p.tree_sitter_gpa); + return null; + } + return got.analysis.declarations; +} + +/// A text this small is parsed on the loop for its declarations when a +/// Symbols query asks (about 40 ms in a Debug build). +const small_parse_bytes = 64 << 10; + +/// The rows as `note` says, and nothing else: no hits. +fn noteRows(p: *Pardes, id: usize, note: []const u8) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.items.append(p.gpa, .{ .kind = .note }) catch return; + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + writeRow(p, &out, &rows, note[0 .. note.len - 1], .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }) catch return; + setRows(p, rp, &out, &rows); +} + +/// One row: its text and its metadata, the path copied. +fn writeRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8, meta: locations.Row) !void { + try out.appendSlice(p.gpa, text); + try out.append(p.gpa, '\n'); + var m = meta; + m.path = try p.gpa.dupe(u8, meta.path); + errdefer p.gpa.free(m.path); + // Coloured whole (zeros where nothing coloured it): the pane's syntax + // pass then parses no fragment of it, per refill. + const code = text[@min(meta.code_start, text.len)..]; + m.colors = if (meta.colors.len >= code.len) try p.gpa.dupe(u8, meta.colors[0..code.len]) else blk: { + const c = try p.gpa.alloc(u8, code.len); + @memset(c, 0); + @memcpy(c[0..meta.colors.len], meta.colors); + break :blk c; + }; + rows.append(p.gpa, m) catch |err| { + p.gpa.free(m.path); + p.gpa.free(m.colors); + return err; + }; +} + +/// The rows made into the pane: line 1 as it is (the user's), then `out`, +/// with `rows` their metadata. The keyboard's place is left where it was. +fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) void { + defer locations.freeRowList(p.gpa, rows); + const f = &rp.file.?; + const line = lineOne(f.content); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n", out.items }) catch return; + const meta = p.gpa.alloc(locations.Row, rows.items.len + 1) catch { + p.gpa.free(content); + return; + }; + meta[0] = .{ .kind = .context, .path = p.gpa.dupe(u8, "") catch &.{}, .at = .{}, .location_end = 0, .code_start = 0 }; + @memcpy(meta[1..], rows.items); + rows.clearRetainingCapacity(); + const kept_row = rp.body.cur_row; + const kept_col = rp.body.cur_col; + if (std.mem.eql(u8, content, f.content)) { + // Same text: the metadata alone, no undo step, no syntax pass. + p.gpa.free(content); + if (locations.equalRows(f.location_rows, meta)) { + locations.freeRows(p.gpa, meta); + } else { + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.syntax_dirty = true; + } + } else { + File.setContent(p, f, content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.saved_revision = f.revision; + } + gpa_free_pager(p, f); + // The cursor stays where it was typing; on a row that went, the last. + const last: i32 = @intCast(File.nlines(p.gpa, f) -| 1); + rp.body.cur_row = @min(kept_row, last); + rp.body.cur_col = if (rp.body.cur_row == kept_row) kept_col else 0; + if (rp.body.cur_row == 0 and rp.body.cur_col > line.len) rp.body.cur_col = @intCast(line.len); + rp.query.?.seen_row = rp.body.cur_row; +} + +fn gpa_free_pager(p: *Pardes, f: *File.State) void { + if (f.pager_spans.len == 0) return; + p.gpa.free(f.pager_spans); + f.pager_spans = &.{}; +} + +/// The gutter a file of `nlines` lines numbers its rows in: two spaces, +/// the number right-aligned, two spaces. +fn gutterWidth(nlines: usize) usize { + var digits: usize = 1; + var n = nlines; + while (n >= 10) : (n /= 10) digits += 1; + return 2 + @max(3, digits) + 2; +} + +fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), width: usize, path: []const u8, line_no: usize, whole: []const u8, col: usize, end: usize, shade: []const u8) !void { + var lead: usize = 0; + while (lead < whole.len and (whole[lead] == ' ' or whole[lead] == '\t')) lead += 1; + const code = std.mem.trimEnd(u8, whole[lead..], "\r"); + var buf: [4096 + 32]u8 = undefined; + var num: [24]u8 = undefined; + const number = std.fmt.bufPrint(&num, "{d}", .{line_no}) catch ""; + const pad = width -| 2 -| number.len; + if (pad + number.len + 2 + code.len > buf.len) return; + @memset(buf[0..pad], ' '); + @memcpy(buf[pad..][0..number.len], number); + @memcpy(buf[pad + number.len ..][0..2], " "); + @memcpy(buf[pad + number.len + 2 ..][0..code.len], code); + const text = buf[0 .. pad + number.len + 2 + code.len]; + const gutter = pad + number.len + 2; + try writeRow(p, out, rows, text, .{ + .kind = .match, + .source_column = lead, + .path = @constCast(path), + .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) }, + .location_end = gutter, + .code_start = gutter, + .colors = @constCast(if (shade.len >= lead) shade[lead..][0..@min(shade.len - lead, code.len)] else &.{}), + }); +} + +/// The path a row of pane `tp`'s text says: its file's, or `@pN` for a +/// text that is no file (a list, a scratch). +fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { + const f = tp.file orelse return ""; + if (f.output == null and !std.mem.startsWith(u8, std.fs.path.basename(f.path), "+")) return f.path; + return std.fmt.allocPrint(arena, config.pane_addr ++ "{d}", .{tp.serial}) catch ""; +} + +/// Rows from pane `tp`'s places: one a line with any (two on a line are +/// one row: everywhere's bug), the declaration they are in over them when +/// its parse exists, from place `from` on, `budget` rows at most. The +/// place it stopped before. +fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, from: usize, budget: *usize) !usize { + const f = &tp.file.?; + const set = &tp.places; + const hits = set.hits.items; + const index = try File.lineIndex(p.gpa, f); + const width = gutterWidth(index.len); + const path = addressOf(p.scratch.allocator(), tp); + const decls = ownerDecls(p, f, false) orelse &.{}; + var decl_now: ?usize = null; + var i: usize = @min(from, hits.len); + // the line of the first, found in the index + var line: usize = if (i < hits.len) blk: { + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= hits[i].start) lo = mid + 1 else hi = mid; + } + break :blk lo -| 1; + } else 0; + // a window begins at a line's first place + while (i > 0 and hits[i - 1].start >= index[line]) i -= 1; + while (i < hits.len) { + while (line + 1 < index.len and index[line + 1] <= hits[i].start) line += 1; + // the places on this line + var n: usize = 1; + const ls = index[line]; + const le = if (line + 1 < index.len) index[line + 1] - 1 else f.content.len; + while (i + n < hits.len and hits[i + n].start <= le) n += 1; + if (budget.* == 0) { + q.more = true; + break; + } + budget.* -= 1; + // the innermost declaration around it, its first line once + var inner: ?usize = null; + for (decls, 0..) |d, di| { + if (d.start_line > line) break; + if (d.end_line < line) continue; + inner = di; + } + if (inner != decl_now) { + decl_now = inner; + if (inner) |di| if (decls[di].start_line != line) { + const head_ls = index[decls[di].start_line]; + const head_le = if (decls[di].start_line + 1 < index.len) index[decls[di].start_line + 1] - 1 else f.content.len; + const head = std.mem.trim(u8, f.content[head_ls..head_le], " \t\r"); + var hb: [600]u8 = undefined; + const text = std.fmt.bufPrint(&hb, " {s}", .{head[0..@min(head.len, 560)]}) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, out, rows, text, .{ .kind = .context, .declaration = true, .path = @constCast(path), .at = .{ .line = decls[di].start_line + 1 }, .location_end = 0, .code_start = 0 }); + }; + } + const shade: []const u8 = if (f.highlights.len > 0 and ls >= f.highlight_start and le <= f.highlight_start + f.highlights.len) f.highlights[ls - f.highlight_start .. le - f.highlight_start] else &.{}; + try q.items.append(p.gpa, .{ .kind = .hit, .serial = tp.serial, .hit = i, .n = n }); + try writeHitRow(p, out, rows, width, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); + i += n; + } + return i; +} + +/// The rows of a `/`: while typed, a window of `live_rows` around the +/// current place; `full` (frozen), the whole list up to `max_rows`. +fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[oid].?; + const set = &owner.places; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var budget: usize = if (full) max_rows else live_rows; + const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); + const from = if (full) 0 else at -| live_rows / 2; + q.window = .{ .lo = from, .hi = from }; + if (set.started and set.from == rp.serial) { + if (from > 0) { + var hb: [64]u8 = undefined; + try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} places before these", .{from}) catch " ..."); + } + q.window.hi = try writePlacesRows(p, q, &out, &rows, owner, from, &budget); + q.window.lo = @min(from, q.window.hi); + } + if (q.more) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + showPlacesCurrent(p, id); +} + +fn noteRow(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8) !void { + try q.items.append(p.gpa, .{ .kind = .note }); + try writeRow(p, out, rows, text, .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }); +} + +/// The current row from the places of the pane its rows are in, the count +/// with them: for `/`, the owner's. +fn showPlacesCurrent(p: *Pardes, id: usize) void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[p.paneBySerial(q.owner) orelse return].?; + const set = &owner.places; + q.total = if (set.from == rp.serial) set.hits.items.len else 0; + q.more = q.more or (set.from == rp.serial and !set.complete()); + q.k = if (set.current) |c| c + 1 else 0; + if (set.from != rp.serial) q.k = 0; + q.current = null; + // By line, not by the rows' place indices: the rows may lag the places + // a tick while they are still being found. + if (set.current) |c| if (c < set.hits.items.len) { + const at = lineOfOffset(p, &owner.file.?, set.hits.items[c].start) + 1; + const rows = rp.file.?.location_rows; + for (q.items.items, 0..) |it, i| { + if (it.kind != .hit or it.serial != owner.serial or i + 1 >= rows.len) continue; + if (rows[i + 1].at.line == at) { + q.current = i; + break; + } + } + }; + // Stepped out of the window the live rows are: made again around it. + if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64); + showCurrent(rp); +} + +/// Every open pane's rows for All, grouped under `@pN name (count)` in +/// the order of the panes' serials (everywhere's other bug: it went by +/// column). +fn makeAllRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var order: [pardes.MAX_PANES]usize = undefined; + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == rp.serial and tp.places.started) { + order[n] = i; + n += 1; + }; + std.mem.sort(usize, order[0..n], p, struct { + fn lt(pp: *Pardes, a: usize, b: usize) bool { + return pp.panes[a].?.serial < pp.panes[b].?.serial; + } + }.lt); + var budget: usize = max_rows; + q.total = 0; + for (order[0..n]) |tid| { + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp) or set.hits.items.len == 0) { + q.more = q.more or !set.complete(); + continue; + } + q.total += set.hits.items.len; + q.more = q.more or !set.complete(); + var hb: [600]u8 = undefined; + const name = if (tp.file) |f| Names.relative(f.path, std.fs.path.dirname(rp.file.?.path) orelse "") else ""; + const head = std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 }); + _ = try writePlacesRows(p, q, &out, &rows, tp, 0, &budget); + } + if (budget == 0) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + // The current one: the first hit row, until a step moves it. + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +fn firstHit(q: *const Query) ?usize { + for (q.items.items, 0..) |it, i| if (it.kind == .hit) return i; + return null; +} + +/// `k` from the current row: the hits on the rows before it, and its own. +fn countCurrent(q: *Query) void { + q.k = 0; + const c = q.current orelse return; + for (q.items.items[0..c]) |it| q.k += if (it.kind == .hit) @max(1, it.n) else 0; + q.k += 1; +} + +/// The names the query matches, best first, `Names.max_rows` of them: each +/// a row as its source has it, the matched bytes tinted. +fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { + _ = pat; + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const was_current: ?u32 = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].ref else null) else null; + _ = was_current; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var spans: std.ArrayList(pardes.pager.Span) = .empty; + errdefer spans.deinit(p.gpa); + const chrome = p.bodyChrome(); + const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true }; + const shown = @min(q.names.hits.items.len, Names.max_rows); + var marks: [Names.max_query * 4]u16 = undefined; + const base = lineOne(rp.file.?.content).len + 1; + for (0..shown) |i| { + var nmarks: usize = 0; + const row = q.names.row(i, &marks, &nmarks); + const cand = q.names.cands.items[q.names.hits.items[i].cand]; + const at = base + out.items.len; + // Where it points: a path (Find, Recent), a pane (Panes), a line + // of the owner (Symbols). + var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; + var pathbuf: [4096 + 32]u8 = undefined; + switch (q.source) { + .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), + .recent => { + const t = look.parsePathLine(row); + meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); + meta.at = t.at; + }, + .panes => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, config.pane_addr ++ "{d}", .{cand.ref}) catch ""), + .symbols => { + const owner = p.panes[p.paneBySerial(q.owner) orelse 0]; + meta.path = @constCast(if (owner) |o| addressOf(p.scratch.allocator(), o) else ""); + meta.at = .{ .line = cand.ref }; + }, + else => {}, + } + try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); + try writeRow(p, &out, &rows, row, meta); + var k: usize = 0; + while (k < nmarks) { + var e = k + 1; + while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; + try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); + k = e; + } + } + if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + setRows(p, rp, &out, &rows); + const f = &rp.file.?; + f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; + q.total = q.names.hits.items.len; + q.more = q.names.busy(); + // The best is current until a step or a click moves it. + q.current = if (shown > 0) 0 else null; + countCurrent(q); + showCurrent(rp); + showTarget(p, id); +} + +/// A slice of a Grep: the files the walk has found so far read and +/// searched, about 4 ms of them a frame, each line holding the pattern +/// (a literal, smart case: a capital makes it exact) kept. +/// ponytail: on the loop, a file a step; the disk engine's worker (phase +/// 4) takes this over. +fn grepSlice(p: *Pardes, q: *Query, rp: *Pane, pat: []const u8) void { + const started = Places.nowNs(); + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const fold = for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true; + var low_buf: [256]u8 = undefined; + const needle = if (fold) std.ascii.lowerString(low_buf[0..@min(pat.len, low_buf.len)], pat[0..@min(pat.len, low_buf.len)]) else pat; + while (q.grep_next < q.names.cands.items.len) { + if (q.found.items.len >= grep_cap) break; + const c = q.names.cands.items[q.grep_next]; + q.grep_next += 1; + const rel = q.names.bytes.items[c.start..][0..c.len]; + var pathbuf: [4096 + 8]u8 = undefined; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch continue; + }; + defer p.gpa.free(bytes); + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) continue; + var line_no: u32 = 1; + var ls: usize = 0; + while (ls <= bytes.len) { + const le = std.mem.indexOfScalarPos(u8, bytes, ls, '\n') orelse bytes.len; + const ln = bytes[ls..le]; + const at = if (fold) std.ascii.findIgnoreCase(ln, needle) else std.mem.indexOf(u8, ln, needle); + if (at) |col| { + const path_at: u32 = @intCast(q.found_bytes.items.len); + q.found_bytes.appendSlice(p.gpa, rel) catch return; + const code_at: u32 = @intCast(q.found_bytes.items.len); + const code = ln[0..@min(ln.len, 400)]; + q.found_bytes.appendSlice(p.gpa, code) catch return; + q.found.append(p.gpa, .{ .path = path_at, .path_len = @intCast(rel.len), .line = line_no, .col = @intCast(col), .end = @intCast(col + needle.len), .code = code_at, .code_len = @intCast(code.len) }) catch return; + if (q.found.items.len >= grep_cap) break; + } + if (le == bytes.len) break; + ls = le + 1; + line_no += 1; + } + if (started != 0 and Places.nowNs() - started > Places.frame_ns) break; + } +} + +/// A Grep keeps this many lines: the rest wait (the disk engine's `More`). +pub const grep_cap = 2000; + +fn makeGrepRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + for (q.found.items, 0..) |fd, i| { + const rel = q.found_bytes.items[fd.path..][0..fd.path_len]; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + if (!std.mem.eql(u8, rel, last_path)) { + last_path = rel; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const code = q.found_bytes.items[fd.code..][0..fd.code_len]; + try q.items.append(p.gpa, .{ .kind = .hit, .hit = i, .n = 1 }); + try writeHitRow(p, &out, &rows, 9, path, fd.line, code, fd.col, fd.end, &.{}); + } + const walking = q.names.walking() or q.grep_next < q.names.cands.items.len; + if (q.found.items.len >= grep_cap) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: type more of it"); + setRows(p, rp, &out, &rows); + q.total = q.found.items.len; + q.more = walking and q.found.items.len < grep_cap; + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +/// A Grep's hits in each open file are that pane's places: its tints, +/// ticks and n/N. +fn feedGrepPlaces(p: *Pardes, q: *Query, serial: u32, pat: []const u8) void { + _ = q; + for (p.panes) |slot| { + const tp = slot orelse continue; + const f = tp.file orelse continue; + if (f.output != null or tp.query != null) continue; + tp.places.search(p, tp, .list, serial, pat, true, null, false); + } +} + +/// The language server's answer for an owner's Refs, Def, Impl or +/// Diagnostics, into its query pane (made or reused) with line 1 the word: +/// what follows the word filters the rows; the places in the owner's text +/// are its places. `rows` are `path:line:col text`, as the server's +/// answer is written (lsp_client). +pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) void { + const owner = p.panes[owner_id] orelse return; + var id = ofOwner(p, owner.serial); + if (id == null or p.panes[id.?].?.query.?.source != source) { + open(p, owner_id, source, "", false); + id = ofOwner(p, owner.serial); + } + const qid = id orelse return; + const rp = p.panes[qid].?; + const q = rp.query.?; + const copy = p.gpa.dupe(u8, rows) catch return; + p.gpa.free(q.lsp_rows); + q.lsp_rows = copy; + const line = lineOne(rp.file.?.content); + const a = parse(line) orelse return; + makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); + toLineOne(p, qid); +} + +fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + const owner_id = p.paneBySerial(q.owner); + const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else ""; + var feed: std.ArrayList(Places.Hit) = .empty; + defer feed.deinit(p.gpa); + // In order: by path, then place, as a list of places reads. + var sorted: std.ArrayList([]const u8) = .empty; + defer sorted.deinit(p.gpa); + var split = std.mem.splitScalar(u8, q.lsp_rows, '\n'); + while (split.next()) |ln| if (ln.len > 0) try sorted.append(p.gpa, ln); + std.mem.sort([]const u8, sorted.items, {}, struct { + fn lt(_: void, a: []const u8, b: []const u8) bool { + const ta = look.parsePathLine(a); + const tb = look.parsePathLine(b); + const order = std.mem.order(u8, ta.path, tb.path); + if (order != .eq) return order == .lt; + if (ta.at.line != tb.at.line) return ta.at.line < tb.at.line; + return ta.at.col < tb.at.col; + } + }.lt); + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + var n: usize = 0; + for (sorted.items) |ln| { + if (ln.len == 0) continue; + if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue; + const t = look.parsePathLine(ln); + if (t.at.line == 0) continue; + const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; + if (!std.mem.eql(u8, t.path, last_path)) { + last_path = t.path; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, Names.relative(t.path, dir), .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); + const col0 = t.at.col -| 1; + try q.items.append(p.gpa, .{ .kind = .hit, .n = 1 }); + // The row's text: the line in the owner when it is the owner's, + // else as the server said it. + var code: []const u8 = rest; + var col = col0; + var end = if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1; + if (owner_id) |oid| if (std.mem.eql(u8, path, owner_path)) { + const owner_f = &p.panes[oid].?.file.?; + if (t.at.line <= File.nlines(p.gpa, owner_f)) { + const ls = File.lineStart(p.gpa, owner_f, t.at.line - 1); + const nx = File.lineStart(p.gpa, owner_f, t.at.line); + const le = if (nx > ls and owner_f.content[nx - 1] == '\n') nx - 1 else nx; + code = owner_f.content[ls..le]; + col = @min(col0, code.len); + end = @min(@max(end, col + 1), code.len); + feed.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; + } + } else { + col = 0; + end = 0; + }; + try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); + n += 1; + } + if (n == 0) try noteRow(p, q, &out, &rows, " nothing"); + setRows(p, rp, &out, &rows); + q.total = n; + q.more = false; + q.current = firstHit(q); + if (owner_id) |oid| { + const owner = p.panes[oid].?; + // Current: the first place after where it was asked (the answer + // may come after the cursor moved), shown in the owner. + const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner); + owner.places.feed(p, owner, rp.serial, feed.items, null); + const hits = owner.places.hits.items; + var next: ?usize = null; + for (hits, 0..) |h, i| if (h.start > asked_at) { + next = i; + break; + }; + if (next == null and hits.len > 0) next = 0; + if (next) |hi| { + owner.places.goTo(owner, hi, false); + for (q.items.items, 0..) |it, i| if (it.kind == .hit and i + 1 < rp.file.?.location_rows.len) { + const meta = rp.file.?.location_rows[i + 1]; + if (!std.mem.eql(u8, meta.path, owner_path)) continue; + const ls = File.lineStart(p.gpa, &owner.file.?, meta.at.line -| 1); + if (ls + meta.at.col -| 1 == hits[hi].start) { + q.current = i; + break; + } + }; + } + } + countCurrent(q); + showCurrent(rp); +} + +/// The places query `serial` fed in panes other than the owner, cleared +/// (a new source or pattern makes its own); the owner's too when the new +/// line is no `/`. +fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anytype) void { + _ = q; + _ = asked; + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (tp.places.from != serial) continue; + if (owner_id != null and owner_id.? == i) tp.places.restore(p, tp); + tp.places.clear(p.gpa); + } +} + +// ---- the current row ---- + +/// The current row drawn as the visited row is (a line selection), while +/// the keyboard is on line 1 or elsewhere; on the rows, the cursor itself +/// is current. Scrolled into view, line 1 kept when it can be. +fn showCurrent(rp: *Pane) void { + const q = rp.query orelse return; + if (rp.body.cur_row != 0 and rp.focus == .body) return; + const c = q.current orelse { + rp.body.msel.active = false; + return; + }; + const r: i32 = @intCast(c + 1); + rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + const off = rp.scroll(); + const shown = off + @as(i32, rp.rows) - 1; + if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); +} + +/// The line (0-based) of byte `at` of `f`'s text. +fn lineOfOffset(p: *Pardes, f: *File.State, at: usize) usize { + const index = File.lineIndex(p.gpa, f) catch return 0; + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= at) lo = mid + 1 else hi = mid; + } + return lo -| 1; +} + +/// The first of pane `tp`'s places on line `line` (1-based), if any. +fn placeOnLine(p: *Pardes, tp: *Pane, line: usize) ?usize { + const f = &tp.file.?; + if (line == 0 or line > File.nlines(p.gpa, f)) return null; + const ls = File.lineStart(p.gpa, f, line - 1); + const next = File.lineStart(p.gpa, f, line); + const hits = tp.places.hits.items; + const i = Places.firstFrom(hits, ls); + if (i < hits.len and (hits[i].start < next or (next == ls))) return i; + return null; +} + +/// Item `i` current, and shown where it points (`show`). +fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.current = i; + const it = q.items.items[i]; + const rows = rp.file.?.location_rows; + if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| { + const tp = p.panes[tid].?; + if (placeOnLine(p, tp, rows[i + 1].at.line)) |hi| { + tp.places.current = hi; + tp.places.gen +%= 1; + if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q); + } else countCurrent(q); + } else countCurrent(q) else countCurrent(q); + showCurrent(rp); + if (show) showTarget(p, id); +} + +/// Step the current row `delta` hits on, round the end silently: Ctrl-n, +/// Ctrl-p, Down and Up on line 1, n and N in the pane. +pub fn step(p: *Pardes, id: usize, delta: i32) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + // A `/`: the owner's places step, the rows follow them. + if (q.source == .text) if (p.paneBySerial(q.owner)) |oid| { + const owner = p.panes[oid].?; + if (owner.places.from == rp.serial) { + const keyboard = p.active; + owner.places.step(p, owner, delta > 0, 1, false); + p.active = keyboard; + showPlacesCurrent(p, id); + return; + } + }; + const items = q.items.items; + if (items.len == 0) return; + var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0); + for (0..items.len) |_| { + if (delta > 0) i = if (i + 1 >= items.len) 0 else i + 1 else i = if (i == 0) items.len - 1 else i - 1; + if (items[i].kind == .hit) break; + } else return; + setCurrent(p, id, i, true); +} + +/// Where the current row points, shown with the keyboard left where it is: +/// a place in an open pane's text selected there (its places' current), +/// in view; a file an open pane shows, its line there; any other file in +/// the +Preview under this pane. Every pane it moves remembers its view +/// first, for Esc. +fn showTarget(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const c = q.current orelse return; + const f = &rp.file.?; + if (c + 1 >= f.location_rows.len) return; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + const keyboard = p.active; + defer p.active = keyboard; + if (it.serial != 0) { + const tid = p.paneBySerial(it.serial) orelse return; + const tp = p.panes[tid].?; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + if (placeOnLine(p, tp, meta.at.line)) |hi| tp.places.goTo(tp, hi, false); + return; + } + if (q.source == .symbols) { + const oid = p.paneBySerial(q.owner) orelse return; + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + } + if (q.source == .panes) return; + if (meta.path.len == 0) return; + // A file open in a pane: shown there. + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + const tf = tp.file orelse continue; + if (tf.output != null or !std.mem.eql(u8, tf.path, meta.path)) continue; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + const line0 = meta.at.line -| 1; + const visible = line0 >= tf.scroll and line0 < tf.scroll + tp.rows; + if (meta.at.line > 0) look.focusPaneLine(p, i, meta.at, if (visible) .keep else .center); + return; + } + displayPreview(p, id, meta.path, meta.at); +} + +// ---- the +Preview ---- + +/// The +Preview under query pane `qid`, if it has one: by serial. +fn previewOf(p: *Pardes, qid: usize) ?usize { + const q = p.panes[qid].?.query.?; + if (q.preview == 0) return null; + return p.paneBySerial(q.preview) orelse { + q.preview = 0; + return null; + }; +} + +/// Whether `pane` is a query pane's +Preview: that query pane's slot. +pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { + const f = pane.file orelse return null; + const o = f.output orelse return null; + if (o.from != .preview) return null; + for (p.panes, 0..) |slot, i| if (slot) |qp| if (qp.query) |q| if (q.preview == pane.serial) return i; + return null; +} + +/// A +Preview made under query pane `qid`, out of its rows alone. +fn makePreview(p: *Pardes, qid: usize) ?usize { + const rp = p.panes[qid].?; + const free = p.freeSlot() orelse return null; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const content = p.gpa.dupe(u8, "") catch return null; + const np = Output.open(p, free, dir, .preview, "", content) catch { + p.gpa.free(content); + return null; + }; + layout.compute(p); + const rows = @max(pardes.BOX_H, np.tag_rows) + p.settings.search_rows; + // Out of the group's root, the text that asked: the query pane keeps + // the rows it was typed into with (made later, for a reused pane). + if (!layout.attachFrom(p, qid, free, rows, layout.groupRoot(p, qid))) { + p.removePane(free, qid) catch {}; + return null; + } + rp.query.?.preview = np.serial; + return free; +} + +/// File `path` at `at` in the +Preview: its text read (once a file: a +/// file open in a pane would be shown there instead), the place centred +/// and selected. Made when the pane has none and its owner has the rows. +fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void { + const id = previewOf(p, qid) orelse makePreview(p, qid) orelse return; + const pane = p.panes[id].?; + const f = &pane.file.?; + if (!std.mem.eql(u8, f.path, path)) { + if (exec.kindOf(path)) |kind| if (kind != .file) return; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch return; + }; + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { + p.gpa.free(bytes); + return; + } + const owned_path = p.gpa.dupe(u8, path) catch { + p.gpa.free(bytes); + return; + }; + p.gpa.free(f.path); + f.path = owned_path; + File.setContent(p, f, bytes); + f.saved_revision = f.revision; + f.scroll = 0; + f.syntax_dirty = true; + pane.hscroll = 0; + p.sync(); + } + look.clearNavigationSelection(p, pane); + if (at.line == 0 or at.line > File.nlines(p.gpa, f)) { + f.scroll = 0; + f.syntax_dirty = true; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + pane.body.cur_pinned = true; + return; + } + look.focusPaneLine(p, id, at, .center); + if (at.end_line == 0 or at.end_col <= at.col) + pane.body.msel = .{ .active = true, .r0 = @intCast(at.line - 1), .r1 = @intCast(at.line - 1) }; +} + +/// The +Preview becomes the file's pane where it stands: same slot, same +/// serial, same rect, its scroll and selection as the preview left them. +/// It is a file pane from here: an empty undo history, the Recent entry, +/// the watch, a file's tag; and a pane of its own, no longer attached (it +/// stays when its query pane goes). +fn promote(p: *Pardes, qid: usize, id: usize) void { + const pane = p.panes[id] orelse return; + const f = &pane.file.?; + f.output = null; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; + f.saved_revision = f.revision; + f.saved_hash = null; + f.saved_len = null; + f.disk_gone = false; + f.syntax_dirty = true; + pane.attached_to = null; + if (Pardes.recentKeeps(f.path)) p.recent.opened(p.recentGpa(), f.path); + if (filesystem.localPath(f.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + pardes.ctlfs.events.noteLog(p, .rename, pane); + p.panes[qid].?.query.?.preview = 0; +} + +// ---- Enter, Esc ---- + +/// Enter on line 1 (or on a row, `row`): the keyboard to the current hit +/// in its pane (the +Preview promoted to the file's pane when it shows +/// it), a `/` into the register, and the rows frozen into ordinary text. +pub fn land(p: *Pardes, id: usize, row: ?usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + if (row) |r| if (r < q.items.items.len and q.items.items[r].kind == .hit) setCurrent(p, id, r, true); + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + freeze(p, id); + const owner_id = p.paneBySerial(q.owner); + if (q.source == .text) { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const set = &owner.places; + // The whole list now, once, every place found: a result from here. + if (set.started and set.from == rp.serial) { + set.fill(p, owner, std.math.maxInt(usize), @import("regexp.zig").Regex.budget); + makeTextRows(p, id, oid, true) catch {}; + } + if (set.started and set.from == rp.serial) { + if (set.literal) { + var escaped: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&escaped, p.scratch.allocator(), set.pattern) catch {}; + p.registers.put(p.gpa, '/', escaped.items, 0, 1, true); + } else p.registers.put(p.gpa, '/', set.pattern, 0, 1, true); + p.registers.last_search = '/'; + set.provenance = .search; + } + p.jump_force = true; + p.active = oid; + return; + } + const c = q.current orelse { + if (owner_id) |oid| p.active = oid; + return; + }; + const f = &rp.file.?; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + p.jump_force = true; + if (it.serial != 0) { + if (p.paneBySerial(it.serial)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + } + return; + } + switch (q.source) { + .symbols => if (owner_id) |oid| { + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + }, + .panes => if (p.paneBySerial(it.ref)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + return; + }, + else => {}, + } + // The preview shows it: promoted where it stands. + if (previewOf(p, id)) |pid| if (std.mem.eql(u8, p.panes[pid].?.file.?.path, meta.path)) { + promote(p, id, pid); + p.active = pid; + if (q.source == .grep) { + const a = parse(q.asked) orelse return; + const pp = p.panes[pid].?; + pp.places.search(p, pp, .list, rp.serial, a.pat, true, null, false); + } + return; + }; + var buf: [4096 + 64]u8 = undefined; + const address = if (meta.at.line > 0) + std.fmt.bufPrint(&buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch meta.path + else + meta.path; + look.lookAt(p, id, address); +} + +/// The rows frozen: ordinary text from here, Save works on them; the +/// places they fed stay, while the pane lives; every view stays where the +/// search left it; the preview, of no more use, goes. +fn freeze(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + q.frozen = true; + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial or tp.serial == q.owner) tp.places.forget(p.gpa); + if (previewOf(p, id)) |pid| { + const pv = p.panes[pid].?; + // A preview showing the current row is promoted by `land`: one + // showing another file goes. + _ = pv; + } +} + +/// Esc on line 1 while typing: every view as the search found it, the +/// places it fed gone, and the pane closed (nothing was answered); a +/// reused pane's frozen rows come back instead, and their places. +pub fn cancel(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + const owner_id = p.paneBySerial(q.owner); + for (p.panes) |slot| if (slot) |tp| { + if (tp.places.from != rp.serial and tp.serial != q.owner) continue; + tp.places.restore(p, tp); + tp.places.forget(p.gpa); + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + }; + if (q.saved) |s| { + q.saved = null; + // A preview made for the query Esc took back has no use: its rows + // go to the text whose rows they were. + if (previewOf(p, id)) |pid| { + p.panes[pid].?.attached_to = null; + p.removePane(pid, owner_id) catch {}; + q.preview = 0; + } + const f = &rp.file.?; + File.setContent(p, f, s.content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = s.rows; + p.gpa.free(q.asked); + q.asked = s.asked; + q.source = s.source; + q.items.clearRetainingCapacity(); + q.items.appendSlice(p.gpa, s.items) catch {}; + p.gpa.free(s.items); + q.current = s.current; + q.total = s.total; + q.k = s.k; + q.frozen = true; + rp.body.cur_row = 0; + rp.body.cur_col = 0; + showCurrent(rp); + // Its places again, as Enter left them. + if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| { + const owner = p.panes[oid].?; + owner.places.search(p, owner, .search, rp.serial, a.pat, false, null, false); + }; + if (owner_id) |oid| p.active = oid; + return; + } + if (owner_id) |oid| { + p.removePane(id, oid) catch {}; + p.active = oid; + if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col); + } else p.removePane(id, null) catch {}; +} + +/// The pane going (Del, its owner's Del): the places it fed go with it. +pub fn release(p: *Pardes, pane: *Pane) void { + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pane.serial) { + tp.places.forget(p.gpa); + tp.places.clear(p.gpa); + }; +} + +// ---- keys, the mouse, edits ---- + +/// The keys a query pane answers itself, before its text has them. On +/// line 1, typing: Enter lands, Esc cancels, Ctrl-n, Ctrl-p, Down and Up +/// step the current row. In normal mode: Enter on a hit row lands on it, +/// n and N step. Anything else is ordinary text editing (line 1) or is +/// refused (the rows, while live: clampEdit). Tab stays the exec chord. +pub fn key(p: *Pardes, id: usize, k: Key) bool { + const rp = p.panes[id] orelse return false; + const q = rp.query orelse return false; + if (rp.focus != .body) return false; + const t = &rp.body; + if (q.frozen) return false; + if (t.mode == .normal) { + if (t.normal.prefix != .none or k.ctrl or k.alt or t.normal.count != 0) return false; + if (k.cp == 'n' or k.cp == 'N') { + step(p, id, if (k.cp == 'n') 1 else -1); + return true; + } + if (hit(k, config.look_key) and t.cur_row > 0) { + land(p, id, @intCast(t.cur_row - 1)); + return true; + } + return false; + } + if (t.cur_row != 0 or t.mode != .insert or t.reg_wait) return false; + if (hit(k, config.escape)) { + cancel(p, id); + return true; + } + if (k.cp == Key.enter and !k.ctrl and !k.alt and !k.shift) { + land(p, id, null); + return true; + } + const down = (k.cp == Key.down and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'n'); + const up = (k.cp == Key.up and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'p'); + if (down or up) { + step(p, id, if (down) 1 else -1); + return true; + } + return false; +} + +/// An edit of a live query pane's text (edit.setEditTextSpan): inside line +/// 1, as typed; one from line 1 into the rows, cut at line 1's end (and a +/// newline put in it, a blank); one wholly in the rows refused, as a tag's +/// prefix refuses one. Null: refused. Lifted from queryline. +pub fn clampEdit(p: *Pardes, t: *panes.Text, old: []const u8, new: []u8) ?[]u8 { + const end = std.mem.indexOfScalar(u8, old, '\n') orelse old.len; + const span = File.spanOf(old, new); + const old_to = old.len - span.tail; + const put = new[span.head .. new.len - span.tail]; + const rows_same = old_to <= end and std.mem.indexOfScalar(u8, put, '\n') == null; + if (rows_same) return new; + if (span.head > end or (span.head == end and old_to > end and put.len == 0 and end < old.len)) { + t.refused = true; + if (t.pane()) |pane| if (p.paneIdOf(pane)) |id| + p.setMessage(id, "the rows are line 1's: edit the query (Enter keeps them as text)"); + return null; + } + // From inside line 1 into the rows: what it put in, flat, and what is + // left of line 1 after it; the rows as they were. + const kept = if (old_to < end) old[old_to..end] else ""; + const out = std.mem.concat(p.gpa, u8, &.{ old[0..span.head], put, kept, old[end..] }) catch return null; + for (out[0 .. span.head + put.len + kept.len]) |*c| if (c.* == '\n') { + c.* = ' '; + }; + return out; +} + +/// B3 on a row's gutter (its line number): the row's address, as a +Diff +/// line's prefix is its place (exec.operandAt). Null off a gutter. +pub fn rowAddress(pane: *const Pane, row: usize, col: usize, buf: []u8) ?[]const u8 { + if (pane.query == null) return null; + const f = pane.file orelse return null; + if (row == 0 or row >= f.location_rows.len) return null; + const meta = f.location_rows[row]; + if (meta.kind != .match or meta.path.len == 0 or meta.location_end == 0 or col >= meta.location_end) return null; + if (meta.at.line == 0) return std.fmt.bufPrint(buf, "{s}", .{meta.path}) catch null; + return std.fmt.bufPrint(buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch null; +} + +/// The tag's start for a query pane: its name and where it is, `+Search +/// 3/27`, `0` with nothing found, `+` while it still counts. +pub fn tagPrefix(q: *const Query, arena: std.mem.Allocator, path: []const u8) ![]const u8 { + const name = std.fs.path.basename(path); + const more = if (q.more and !q.frozen) "+" else ""; + if (q.total == 0) return std.fmt.allocPrint(arena, "{s} 0{s}", .{ name, more }); + if (q.k == 0) return std.fmt.allocPrint(arena, "{s} {d}{s}", .{ name, q.total, more }); + return std.fmt.allocPrint(arena, "{s} {d}/{d}{s}", .{ name, q.k, q.total, more }); +} + +/// The other places on a hit row's line tinted, from the pane its rows are +/// in (the first is the row's own mark, Output.decorateRow): the current +/// one strongest, as in that pane's text. +pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const q = pane.query orelse return; + const f = if (pane.file) |*file| file else return; + const th = p.theme(); + const strong = p.chromeTheme().search_bg; + const quiet = colors.mix(th.bg orelse th.tag_bg, strong); + var vr: i32 = 0; + var last: i32 = -1; + while (vr < body_h) : (vr += 1) { + const row = pane.wrapAt(vr).line; + if (row == last or row < 1) continue; + last = row; + const i: usize = @intCast(row - 1); + if (i >= q.items.items.len or @as(usize, @intCast(row)) >= f.location_rows.len) continue; + const it = q.items.items[i]; + if (it.kind != .hit or it.serial == 0) continue; + const tid = p.paneBySerial(it.serial) orelse continue; + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp)) continue; + const tf = &tp.file.?; + const meta = f.location_rows[@intCast(row)]; + // Its line's places as they are now, found by the line: the rows + // may be a tick behind the places. + if (meta.at.line == 0 or meta.at.line > File.nlines(p.gpa, tf)) continue; + const ls = File.lineStart(p.gpa, tf, meta.at.line - 1); + const next = File.lineStart(p.gpa, tf, meta.at.line); + const line = modal.lineSlice(f.content, @intCast(row)); + var hi = Places.firstFrom(set.hits.items, ls); + while (hi < set.hits.items.len and set.hits.items[hi].start < next) : (hi += 1) { + const h = set.hits.items[hi]; + if (h.start < ls + meta.source_column) continue; + const a = meta.code_start + (h.start - ls - meta.source_column); + const b = @min(line.len, meta.code_start + (@min(h.end, next) - ls - meta.source_column)); + if (b <= a or a >= line.len) continue; + const current = set.current != null and set.current.? == hi; + File.paintWordSelection(p, s, pane, r, row, @intCast(a), @intCast(b), if (current) strong else quiet); + } + } +} + +// ---- tests ---- + +fn typeKeys(p: *Pardes, text: []const u8) void { + for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +fn queryPane(p: *Pardes) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null) return i; + return null; +} + +test "parse: line 1's first word names the source" { + try std.testing.expectEqual(Source.text, parse("/alpha").?.source); + try std.testing.expectEqualStrings("alpha", parse("/alpha").?.pat); + try std.testing.expectEqual(Source.find, parse("Find lay").?.source); + try std.testing.expectEqualStrings("lay", parse("Find lay").?.pat); + try std.testing.expectEqual(Source.grep, parse("Grep").?.source); + try std.testing.expectEqual(Source.all, parse("All x y").?.source); + try std.testing.expectEqualStrings("x y", parse("All x y").?.pat); + try std.testing.expectEqual(Source.refs, parse("Refs").?.source); + try std.testing.expect(parse("Findx") == null); + try std.testing.expect(parse("grep x") == null); + try std.testing.expect(parse("") == null); +} + +test "a / query: keystroke by keystroke, the owner shows the set, rows from its own rows alone, zero hits a state, Esc puts all back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + p.newScratchBelow(0); + const below = p.col_panes[0][1]; + p.active = 0; + layout.compute(p); + const before = p.rects; + // cursor on line 3 (row 2) + pane.body.cur_row = 2; + pane.body.cur_col = 0; + typeKeys(p, "/"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, qid)); + try std.testing.expectEqual(qid, p.active); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + const born = p.rects[qid]; + try std.testing.expectEqualStrings("/", lineOne(qp.file.?.content)); + // keystroke 1 + typeKeys(p, "a"); + const q = qp.query.?; + try std.testing.expectEqual(Source.text, q.source); + try std.testing.expect(pane.places.started and pane.places.from == qp.serial); + try std.testing.expect(q.total > 0); + try std.testing.expectEqualDeep(born, p.rects[qid]); + // keystroke 2 .. `alph`: four places on four lines (rows), the + // current the first at or after the cursor (line 3's alphabet) + typeKeys(p, "lph"); + try std.testing.expectEqual(@as(usize, 4), q.total); + try std.testing.expectEqual(@as(usize, 2), q.k); + try std.testing.expectEqual(@as(?usize, 1), pane.places.current); + const sel = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(@as(usize, 15), @min(sel.anchor, sel.head)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expectEqual(qid, p.active); + // Ctrl-n steps, the owner follows + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expectEqual(@as(usize, 3), q.k); + // drawn: rows, tints, ticks + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + try std.testing.expect(p.surface.nrail_ticks > 0); + // zero hits: a state, the pane stays where it was, line 1 as typed + typeKeys(p, "zz"); + try std.testing.expectEqual(@as(usize, 0), q.total); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expectEqualStrings("/alphzz", lineOne(qp.file.?.content)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + const tag = try tagline.pathPrefix(p, p.scratch.allocator(), qp); + try std.testing.expectEqualStrings("+Search 0", tag); + // Esc: the pane gone, its rows back to the owner, the owner as it was + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expectEqual(@as(usize, 0), p.active); + layout.compute(p); + try std.testing.expectEqualDeep(before[0], p.rects[0]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expect(!pane.places.started); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); +} + +test "a / query: Enter lands and freezes, the register filled, n and N step silently, a later / reuses the pane and Esc brings the frozen rows back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + typeKeys(p, "/alpha"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const q = qp.query.?; + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(q.frozen); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("alpha", p.registers.value('/', 0).?); + try std.testing.expectEqual(Places.Provenance.search, pane.places.provenance); + const frozen = try std.testing.allocator.dupe(u8, qp.file.?.content); + defer std.testing.allocator.free(frozen); + // the rows: one a line (gamma alpha has one), a gutter number each + try std.testing.expect(std.mem.indexOf(u8, frozen, " 1 alpha one\n") != null); + // n and N in the owner step the same set, round the end silently + const logged = p.messages.len; + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + typeKeys(p, "nnn"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + try std.testing.expect(pane.places.wrapped); + try std.testing.expectEqual(logged, p.messages.len); + typeKeys(p, "N"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + // a later `/` reuses the pane: line 1 fresh, the rows the new query's + typeKeys(p, "/"); + try std.testing.expectEqual(qid, queryPane(p).?); + try std.testing.expectEqual(qid, p.active); + try std.testing.expect(!q.frozen); + typeKeys(p, "beta"); + try std.testing.expectEqual(@as(usize, 1), q.total); + // Esc: the frozen rows of `/alpha` again, the owner's places with them + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expect(q.frozen); + try std.testing.expectEqualStrings(frozen, qp.file.?.content); + try std.testing.expectEqualStrings("alpha", pane.places.pattern); + // Del closes it, its places with it + exec.runBuiltin(p, .Del, qid, "", null); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!pane.places.started); +} + +/// A test's file pane in `tmp`, named `name`, holding `text`. +fn testFileIn(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) !*Pane { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text }); + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + const pane = try p.setTestFile(text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, name }); + return pane; +} + +fn leader(p: *Pardes, keys: []const u8) void { + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + typeKeys(p, keys); +} + +fn settle(p: *Pardes) void { + var frames: usize = 0; + while (busy(p) and frames < 2000) : (frames += 1) p.update(.tick); + p.update(.tick); +} + +test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(std.testing.io, "src"); + for ([_][]const u8{ "src/layout.zig", "src/look.zig", "notes.md" }) |name| + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = "pub fn split() void {}\nconst x = 1;\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + _ = try testFileIn(p, &tmp, "x.txt", "x\n"); + p.newScratchBelow(0); + const other = p.col_panes[0][1]; + try std.testing.expect(layout.splitColumn(p, other, other, false)); + p.active = 0; + layout.compute(p); + const before = p.rects; + leader(p, "ff"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + try std.testing.expectEqual(Source.find, q.source); + try std.testing.expectEqualStrings("Find ", lineOne(p.panes[qid].?.file.?.content)); + // the group: owner, query pane, +Preview, out of the owner's rows alone + const pv = previewOf(p, qid).?; + try std.testing.expectEqual(@as(usize, 0), layout.groupRoot(p, pv)); + try std.testing.expectEqualDeep(before[other], p.rects[other]); + try std.testing.expectEqual(before[0].h, p.rects[0].h + p.rects[qid].h + p.rects[pv].h); + settle(p); + // an empty query lists every name + try std.testing.expectEqual(@as(usize, 4), q.total); + const born = p.rects; + typeKeys(p, "lay"); + settle(p); + try std.testing.expectEqual(@as(usize, 1), q.total); + try std.testing.expectEqualDeep(born[qid], p.rects[qid]); + try std.testing.expectEqualDeep(born[pv], p.rects[pv]); + // the current one in the preview, never by the pointer + try std.testing.expect(std.mem.endsWith(u8, p.panes[pv].?.file.?.path, "src/layout.zig")); + try std.testing.expectEqual(qid, p.active); + const serial = p.panes[pv].?.serial; + const rect = p.rects[pv]; + p.update(.{ .key = .{ .cp = Key.enter } }); + // promoted where it stands: same slot, serial, rect; a file pane now + try std.testing.expectEqual(pv, p.active); + try std.testing.expectEqual(serial, p.panes[pv].?.serial); + try std.testing.expect(p.panes[pv].?.file.?.output == null); + try std.testing.expect(p.panes[pv].?.attached_to == null); + layout.compute(p); + try std.testing.expectEqualDeep(rect, p.rects[pv]); + try std.testing.expect(q.frozen); + try std.testing.expectEqualDeep(before[other], p.rects[other]); +} + +test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const a = try testFileIn(p, &tmp, "a.txt", "one needle\ntwo\n"); + leader(p, "fg"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + typeKeys(p, "needle"); + settle(p); + // a.txt's one, b.zig's three lines + try std.testing.expectEqual(@as(usize, 3), q.total); + const body = p.panes[qid].?.file.?.content; + try std.testing.expect(std.mem.indexOf(u8, body, "\nb.zig\n") != null); + // the open file's hits are its places + try std.testing.expect(a.places.started and a.places.hits.items.len == 1); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!a.places.started); + + // All: a second pane, both searched, grouped by serial + p.newScratchBelow(0); + const s = p.active; + const sf = &p.panes[s].?.file.?; + File.setContent(p, sf, try p.gpa.dupe(u8, "needle needle twice\n")); + p.active = 0; + leader(p, "/"); + const aid = queryPane(p).?; + const aq = p.panes[aid].?.query.?; + try std.testing.expectEqual(Source.all, aq.source); + typeKeys(p, "needle"); + settle(p); + try std.testing.expectEqual(@as(usize, 3), aq.total); + const all = p.panes[aid].?.file.?.content; + var hb: [32]u8 = undefined; + const first = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{a.serial})).?; + const second = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{p.panes[s].?.serial})).?; + try std.testing.expect(a.serial < p.panes[s].?.serial and first < second); + try std.testing.expect(second < std.mem.indexOf(u8, all, "twice").?); + // two places on one line are one row + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, all, "twice")); +} + +test "zz query timings on the 1.2 MB stress file (QUERY_TIMES=)" { + const path_z = std.c.getenv("QUERY_TIMES") orelse return error.SkipZigTest; + const path = std.mem.span(path_z); + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(8 << 20)); + defer std.testing.allocator.free(bytes); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + const pane = try p.setTestFile(bytes); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, path); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + pane.body.cur_row = 15000; + pane.ensureCursorVisible(); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const Clock = struct { + fn step(pp: *Pardes, fr: *std.heap.ArenaAllocator, ev: pardes.Event) !u64 { + const t0 = Places.nowNs(); + pp.update(ev); + _ = fr.reset(.retain_capacity); + _ = try pp.render(fr.allocator()); + return Places.nowNs() - t0; + } + }; + var report: std.ArrayList(u8) = .empty; + defer report.deinit(std.testing.allocator); + var base: u64 = 0; + for (0..10) |_| base += try Clock.step(p, &frame, .{ .key = .{ .cp = 'j', .text = "j" } }); + try report.print(std.testing.allocator, "a cursor move and its frame, no search: {d} us\n", .{base / 10 / 1000}); + const t_open = try Clock.step(p, &frame, .{ .key = .{ .cp = '/', .text = "/" } }); + try report.print(std.testing.allocator, "open / {d} us\n", .{t_open / 1000}); + for ("pane.v") |c| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + var ticks: usize = 0; + var worst: u64 = 0; + while (busy(p) or pane.places.busy(pane)) : (ticks += 1) { + if (ticks > 500) break; + worst = @max(worst, try Clock.step(p, &frame, .tick)); + } + const qid = queryPane(p).?; + try report.print(std.testing.allocator, "key '{c}': {d} us, then {d} ticks (worst {d} us), {d} places\n", .{ c, t / 1000, ticks, worst / 1000, p.panes[qid].?.query.?.total }); + } + // Enter: frozen; then edits in the owner with the pane open. + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = Key.enter } }); + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = 'i', .text = "i" } }); + var worst_edit: u64 = 0; + var sum: u64 = 0; + for (0..20) |_| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + worst_edit = @max(worst_edit, t); + sum += t; + const t2 = try Clock.step(p, &frame, .tick); + worst_edit = @max(worst_edit, t2); + } + try report.print(std.testing.allocator, "edit in the owner (insert x, then a tick): mean {d} us, worst {d} us\n", .{ sum / 20 / 1000, worst_edit / 1000 }); + // The same edits with no query pane at all, for the editor's own cost. + p.update(.{ .key = .{ .cp = Key.escape } }); + exec.runBuiltin(p, .Del, queryPane(p).?, "", null); + p.update(.tick); + p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + sum = 0; + for (0..20) |_| sum += try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + try report.print(std.testing.allocator, "the same edit, no search: mean {d} us\n", .{sum / 20 / 1000}); + std.debug.print("{s}", .{report.items}); +} + +test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration; SearchPane new leaves the last where it is" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n _ = alpha;\n}\nfn gamma() void {}\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/x.zig"); + // `*` on `const`: line 1 `/\bconst\b`, the keyboard still in the text + typeKeys(p, "e*"); + const qid = queryPane(p).?; + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(std.mem.startsWith(u8, lineOne(p.panes[qid].?.file.?.content), "/")); + try std.testing.expect(pane.places.started); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + // SPC b b: the open panes by name; Enter goes to the marked one + p.newScratchBelow(0); + const other = p.active; + p.active = 0; + leader(p, "bb"); + const bid = queryPane(p).?; + try std.testing.expectEqual(bid, qid); + try std.testing.expectEqual(Source.panes, p.panes[bid].?.query.?.source); + try std.testing.expect(p.panes[bid].?.query.?.total >= 1); + // SPC s s: the declarations, fuzzy; Enter lands on the line + p.update(.{ .key = .{ .cp = Key.escape } }); + p.active = 0; + leader(p, "ss"); + const sid = queryPane(p).?; + try std.testing.expectEqual(Source.symbols, p.panes[sid].?.query.?.source); + // (context declarations span lines: a one-line fn is none of them) + typeKeys(p, "bet"); + try std.testing.expectEqual(@as(usize, 1), p.panes[sid].?.query.?.total); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + _ = other; + // SearchPane new: the frozen one stays, unattached; a new one under the owner + p.settings.search_pane = .new; + typeKeys(p, "/"); + const nid = queryPane2(p, sid).?; + try std.testing.expect(nid != sid); + try std.testing.expect(p.panes[sid].?.attached_to == null); + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, nid)); +} + +fn queryPane2(p: *Pardes, not: usize) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null and i != not) return i; + return null; +} diff --git a/src/Text.zig b/src/Text.zig index cef76b3b..88630f83 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -182,7 +182,10 @@ pub fn primaryRange(t: *Text, text: []const u8, row0: i32) modal.Selection { const e = if (r1 + 1 >= modal.cursorLineCount(text)) text.len else modal.lineStartOffset(text, r1 + 1); return .{ .anchor = s, .head = @max(e, modal.nextGrapheme(text, c)) }; } - if (t.vsel.active) return cellRange(text, t.vsel.row - row0, t.vsel.col, t.cur_row - row0, t.cur_col); + // Both ends through the line index, as the cursor's: cellRange counts + // lines from the top for each, a pass over a big file per call (the + // places' settle and every insert-mode key asked it). + if (t.vsel.active) return cellOffRange(text, File.textOffset(t, text, .{ .row = @intCast(@max(0, t.vsel.row - row0)), .col = @intCast(@max(0, t.vsel.col)) }), c); return .{ .anchor = c, .head = modal.nextGrapheme(text, c) }; } diff --git a/src/body_layer.zig b/src/body_layer.zig index d44045a6..e50b7e3e 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -275,6 +275,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); pane.places.paint(p, s, pane, r, body_h); + panes.Query.paint(p, s, pane, r, body_h); } else if (pane.isTerminal() and p.settings.colors) { panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); diff --git a/src/builtins.zig b/src/builtins.zig index 1ec33d88..7cdee9de 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -210,7 +210,7 @@ pub const registry = struct { .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .shader, .inactive_dim, .grip_width => true, // bare, it says the current value (exec.applySettingBuiltin) - .tab, .callstack_depth => false, + .tab, .callstack_depth, .search_rows => false, }; return declOr(b, "requires_arg", false, false); } @@ -1721,7 +1721,8 @@ pub const Find = struct { if (rows == 0) c.p.reportFailure(c.id, e_search_miss_find); return; } - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.find_marker }); + // Bare (SPC f f): the query pane, line 1 `Find `, typed into. + panes.Query.open(c.p, c.id, .find, "", true); } }; @@ -1738,7 +1739,29 @@ pub const Grep = struct { if (rows == 0) c.p.reportFailure(c.id, e_search_miss_grep); return; } - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.grep_marker }); + // Bare (SPC f g): the query pane, line 1 `Grep `, typed into. + panes.Query.open(c.p, c.id, .grep, "", true); + } +}; + +/// Search in a query pane under this pane, line 1 the argument (`Panes`, +/// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. +pub const Search = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + const line = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const asked = panes.Query.parse(line) orelse panes.Query.parse(std.mem.concat(c.p.scratch.allocator(), u8, &.{ "/", line }) catch return).?; + panes.Query.open(c.p, c.id, asked.source, asked.pat, true); + } +}; + +/// Pick an open pane by its name in a query pane under this one (SPC b b). +pub const Panes = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + panes.Query.open(c.p, c.id, .panes, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; @@ -1866,9 +1889,13 @@ pub const Last = struct { /// List the files opened lately, closed ones too, each a place to open again. pub const Recent = struct { pub const scope: Scope = .session; + pub const takes_arg = true; pub const output: OutputTraits = .{ .name = config.recent_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { - panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + // From a pane: the query pane under it, line 1 `Recent `, typed + // into; from a header, which no pane owns, the +Recent list. + if (c.p.exec_header or c.p.panes[c.id] == null) return panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; diff --git a/src/config.zig b/src/config.zig index 06eec2d9..2fa4a55d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -26,6 +26,26 @@ pub const leader_help: u8 = '?'; const undecided: []const u8 = ""; +/// Leader paths that run a builtin WITH an argument (the pick prototype's): +/// the query pane's sources that have no word of their own, `Search` and +/// line 1. `SPC s` is the session group (Dump, Restore, Attach), so the +/// declarations are `SPC s s`, a key from helix's. +pub const leader_args = [_]struct { path: []const u8, cmd: Builtin, arg: []const u8 }{ + .{ .path = "bb", .cmd = .Search, .arg = "Panes" }, + .{ .path = "ss", .cmd = .Search, .arg = "Symbols" }, + .{ .path = "/", .cmd = .Search, .arg = "All" }, +}; + +comptime { + @setEvalBranchQuota(20_000); + // A path here is a leaf: no builtin's path is it or runs past it, and + // none of it is a builtin's whole path. + for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { + if (std.mem.startsWith(u8, path, la.path) or std.mem.startsWith(u8, la.path, path)) + @compileError("leader_args path collides with " ++ @tagName(b) ++ ": " ++ la.path); + }; +} + // null means word/chord-only. Every enabled builtin must explicitly choose a path. pub const leader_path = paths: { @setEvalBranchQuota(10_000); // a check per builtin, and they grow @@ -94,6 +114,11 @@ pub const leader_path = paths: { .Delcol = "cd", .Joincol = "cj", .Placement = "cp", + .SearchPlace = null, + .SearchPane = null, + .SearchRows = null, + .Search = null, + .Panes = null, .BootShell = null, .LookWord = null, .DirLook = null, @@ -517,6 +542,7 @@ pub const dump_config_buffer = "+DumpConfig"; pub const effect_code_buffer = "+EffectCode"; pub const jumps_buffer = "+Jumps"; pub const recent_buffer = "+Recent"; +pub const preview_buffer = "+Preview"; pub const unsaved_buffer = "+Unsaved"; pub const themes_buffer = "+Themes"; pub const fonts_buffer = "+Fonts"; @@ -846,6 +872,15 @@ pub const Runtime = struct { callstack_layout: CallstackLayout = .stacked, callstack_corners: CallstackCorners = .rounded, callstack_depth: u8 = @import("lsp/lsp.zig").callstack_default_depth, + /// Where a query pane goes (Query.zig): `attached`, under the pane that + /// asked, out of its rows alone; `column`, in the finder column. + search_place: SearchPlace = .attached, + /// A search from a pane that has a query pane: `reuse` it (its frozen + /// rows back on Esc), or open a `new` one, the last left where it is. + search_pane: SearchPane = .reuse, + /// The body rows a query pane is born with under its line 1 (and its + /// +Preview with): it never resizes itself after. + search_rows: u16 = 8, pub const ShaderAnimation = enum { off, on, always }; pub const Placement = enum { acme, pardes }; @@ -858,8 +893,10 @@ pub const Runtime = struct { pub const JumpScope = enum { file, all }; pub const CallstackLayout = enum { @"inline", stacked }; pub const CallstackCorners = @import("lsp/lsp.zig").CallstackCorners; + pub const SearchPlace = enum { attached, column }; + pub const SearchPane = enum { reuse, new }; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners, search_place, search_pane }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1048,6 +1085,7 @@ pub const Runtime = struct { grip_width, tab, callstack_depth, + search_rows, transition: animation.Transition, scene: Scene, /// A Shadertoy file into the post chain or out of it; `off` empties @@ -1137,6 +1175,9 @@ pub const Runtime = struct { .{ .word = "CallstackCorners", .action = .{ .choice = .callstack_corners }, .doc = "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query." }, .{ .word = "CallstackDepth", .action = .callstack_depth, .doc = "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit." }, .{ .word = "Tab", .action = .tab, .doc = "A tab's width in cells, 1 through 16, in every pane; bare, it says the width." }, + .{ .word = "SearchPlace", .action = .{ .choice = .search_place }, .doc = "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column." }, + .{ .word = "SearchPane", .action = .{ .choice = .search_pane }, .doc = "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is." }, + .{ .word = "SearchRows", .action = .search_rows, .doc = "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself." }, }; pub fn find(name: []const u8) ?Setting { @@ -1311,6 +1352,7 @@ pub const Runtime = struct { .grip_width => state.grip_width = number(u16, argument, " \t\r\n%", 50, 300) orelse return false, .callstack_depth => state.callstack_depth = number(u8, argument, " \t\r\n", 1, @import("lsp/lsp.zig").callstack_max_depth) orelse return false, .tab => state.tab = number(u16, argument, " \t\r\n", 1, 16) orelse return false, + .search_rows => state.search_rows = number(u16, argument, " \t\r\n", 1, 100) orelse return false, .theme, .font => return false, } return true; @@ -1348,6 +1390,7 @@ pub const Runtime = struct { .grip_width => "50-300 (a percentage)", .tab => "1-16 (cells)", .callstack_depth => "1-64 (levels)", + .search_rows => "1-100 (rows)", .tagline_size => std.fmt.comptimePrint("{d}-{d} (a percentage)", .{ tagline_percent_min, tagline_percent_max }), .message_ms => std.fmt.comptimePrint("0-{d} (milliseconds)", .{message_ms_max}), .shell => "a path of at most 255 bytes; bare, $SHELL, else /bin/sh", @@ -1490,6 +1533,7 @@ pub const Runtime = struct { .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), + .search_rows => try out.print("{s} {d}\n", .{ setting.word, state.search_rows }), .grip_width => try out.print("{s} {d}\n", .{ setting.word, state.grip_width }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); @@ -1773,6 +1817,8 @@ pub const Runtime = struct { .jump_scope => "all", .callstack_layout => "inline", .callstack_corners => "square", + .search_place => "column", + .search_pane => "new", }, .lift => "rim", .motion => "playful", @@ -1780,6 +1826,7 @@ pub const Runtime = struct { .grip_width => "200", .callstack_depth => "16", .tab => "8", + .search_rows => "12", else => null, }; try std.testing.expect(apply(&state, setting, argument)); @@ -1853,6 +1900,8 @@ pub const Runtime = struct { .jump_scope => "JumpScope all\n", .callstack_layout => "CallstackLayout inline\n", .callstack_corners => "CallstackCorners square\n", + .search_place => "SearchPlace column\n", + .search_pane => "SearchPane new\n", }, .lift => "Lift rim\n", .motion => "Motion playful\n", @@ -1860,6 +1909,7 @@ pub const Runtime = struct { .grip_width => "GripWidth 200\n", .callstack_depth => "CallstackDepth 16\n", .tab => "Tab 8\n", + .search_rows => "SearchRows 12\n", .theme, .font => unreachable, }; try std.testing.expect(std.mem.indexOf(u8, report, expected) != null); @@ -2212,6 +2262,7 @@ const doc_typ = struct { if (n == 0) return leader.len == 1 and leader[0].cp == ' '; for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.eql(u8, p, path[0..n])) return true; + for (leader_args) |la| if (std.mem.eql(u8, la.path, path[0..n])) return true; return false; } toks.reset(); @@ -2308,6 +2359,7 @@ const doc_tutor = struct { fn path(keys: []const u8) bool { for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.startsWith(u8, p, keys)) return true; + for (leader_args) |la| if (std.mem.startsWith(u8, la.path, keys)) return true; return false; } diff --git a/src/edit.zig b/src/edit.zig index c9477c29..a06f5f2d 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -568,6 +568,26 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp return; } const pane = t.pane() orelse return retireEditText(p, new); + // A live query pane's rows are its line 1's (Query.zig): an edit there + // is refused, as a tag's prefix refuses one, and one from line 1 into + // them is cut at its end. The rows' metadata stays theirs across an + // edit of the line, which moves no row. + if (pane.file) |*f| if (pane.query) |q| if (!q.frozen) { + const kept = panes.Query.clampEdit(p, t, f.content, new) orelse return retireEditText(p, new); + if (kept.ptr != new.ptr) retireEditText(p, new); + const end = modal.positionAt(kept, kept.len - panes.File.spanOf(f.content, kept).tail); + t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; + const rows = f.location_rows; + const spans = f.pager_spans; + f.location_rows = &.{}; + f.pager_spans = &.{}; + panes.File.setContentSpan(p, f, kept, null); + if (f.location_rows.len > 0) @import("locations.zig").freeRows(p.gpa, f.location_rows); + p.gpa.free(f.pager_spans); + f.location_rows = rows; + f.pager_spans = spans; + return; + }; // what changed ended where the texts agree again from their ends const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 }; // ponytail: O(file), for the edits that do not say what they changed diff --git a/src/exec.zig b/src/exec.zig index a9c11049..2bc1a3e5 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -194,6 +194,20 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l // the look is of the address it names (look.diffAddress), a regular // look from there. A hunk line's code is words, looked at as ever: // the code's, the prefix never one of them. + // A query pane's row pointed at on its gutter (its line number): the + // look is of the row's address (Query.rowAddress), as a +Diff line's + // prefix is its place; the row's code is words, looked at as ever. + if (for_look and pane.query != null and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0 and col >= 0) gutter: { + var address_buf: [4096 + 32]u8 = undefined; + const address = panes.Query.rowAddress(pane, @intCast(row), @intCast(col), &address_buf) orelse break :gutter; + const meta = pane.file.?.location_rows[@intCast(row)]; + result.text = p.scratch.allocator().dupe(u8, address) catch break :gutter; + result.file_word = .{ .row = row, .lo = 0, .hi = @intCast(meta.location_end) }; + const expanded = fileWordCells(pane, clicked, row, 0, @intCast(meta.location_end)) orelse return result; + result.preview = expanded; + result.expanded = expanded; + return result; + } var word_from: usize = 0; if (for_look and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0) diff: { var address_buf: [4096 + 32]u8 = undefined; @@ -1118,6 +1132,12 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] } else if (!p.settings.apply(setting, arg)) { p.reportFailure(p.active, "CallstackDepth: takes " ++ comptime config.Runtime.takes(.callstack_depth).?); }, + .search_rows => if (arg == null) { + var said: [40]u8 = undefined; + return p.setMessage(p.active, std.fmt.bufPrint(&said, "SearchRows {d}", .{p.settings.search_rows}) catch "SearchRows"); + } else if (!p.settings.apply(setting, arg)) { + p.reportFailure(p.active, "SearchRows: takes " ++ comptime config.Runtime.takes(.search_rows).?); + }, // Bare, it says the width, as acme's Tab does. .tab => if (arg == null) { var said: [32]u8 = undefined; diff --git a/src/fs.zig b/src/fs.zig index e809eda5..cb813262 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1119,7 +1119,7 @@ const find_max_steps = 100_000; /// One root's Find or Grep rows at most: its hits, each a path and a line. pub const search_root_output_bytes = find_max_hits * (4096 + 320); -const find_skip = [_][]const u8{ +pub const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", ".venv", "__pycache__", ".zig-cache", "zig-out", }; diff --git a/src/layout.zig b/src/layout.zig index f0689b10..dac0aa7e 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1016,21 +1016,31 @@ pub fn keepGroups(p: *Pardes) void { /// False, `id` in no column, when the owner has not the rows for its tag /// and the attachment's minimum. pub fn attach(p: *Pardes, owner: usize, id: usize, rows: u16) bool { + return attachFrom(p, owner, id, rows, owner); +} + +/// attach, the rows given by `giver`: the owner itself or a pane of its +/// group (a +Preview added under a query pane later takes the text's rows, +/// so the query pane, typed into, keeps its own). +pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool { const o = p.panes[owner] orelse return false; + const g = p.panes[giver] orelse return false; const nw = p.panes[id] orelse return false; if (o.collapsed) toggleCollapse(p, owner); + if (g.collapsed) toggleCollapse(p, giver); compute(p); const f = findPane(p, owner) orelse return false; + if (giver != owner and groupRoot(p, owner) != groupRoot(p, giver)) return false; // Its tag wraps at the column's width: measured there. p.rects[id].w = p.col_w[f.col]; - const oh = p.rects[owner].h; + const oh = p.rects[giver].h; const least = minRows(p, id); if (oh < least + BOX_H) return false; - const owner_keeps = if (oh >= least + minRows(p, owner)) minRows(p, owner) else BOX_H; - const give = std.math.clamp(rows, least, oh - owner_keeps); + const giver_keeps = if (oh >= least + minRows(p, giver)) minRows(p, giver) else BOX_H; + const give = std.math.clamp(rows, least, oh - giver_keeps); snapColWeights(p, f.col); insert(p, f.col, groupEnd(p, f.col, f.idx), id); - o.vweight = @floatFromInt(oh - give); + g.vweight = @floatFromInt(oh - give); nw.vweight = @floatFromInt(give); nw.attached_to = o.serial; compute(p); diff --git a/src/look.zig b/src/look.zig index 2d97cb9f..eed3dbd9 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1719,6 +1719,8 @@ pub fn reopenAt(p: *Pardes, from: usize, path: []const u8, at: Spot) void { /// Whether `pane` is the +Recent or the Jumplist list, whose rows are /// remembered places: a look at one clamps to the file as it is now. fn isRecentList(pane: *const Pane) bool { + // A query pane over the recent files: its rows are remembered places. + if (pane.query) |q| if (q.source == .recent) return true; const f = pane.file orelse return false; const o = f.output orelse return false; return std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Recent }) or std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Jumplist }); diff --git a/src/mouse.zig b/src/mouse.zig index ec5560d0..3400afbe 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1083,6 +1083,15 @@ pub fn dispatchPointerBuiltin( // nothing, as acme's look3 and execute return on an empty expansion. const operand = text orelse return; if (gesture) |g| if (reportGesture(p, id, cmd, operand, g.on_tag, g.operand, arg)) return; + // B2 anywhere on a query pane's line 1 is the line: run again, whatever + // word of it was clicked (Query.zig). + if (gesture) |g| if (!g.on_tag and g.operand.row == 0 and cmd == config.exec_cmd) if (p.panes[id]) |pane| if (pane.query) |q| { + p.gpa.free(q.asked); + q.asked = &.{}; + q.frozen = false; + panes.Query.produceAll(p, false); + return; + }; // A middle click on a body is the exec a bound REPL may take. exec.runBuiltinFrom(p, cmd, id, "", exec.withArg(p, operand, arg), gesture != null and !gesture.?.on_tag); } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f9bec775..45336a1e 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -89,6 +89,8 @@ pub fn run(p: *Pardes, id: usize, exec: bool, text: []const u8, in_tag: bool) vo const after = Serials.snapshot(p); var created = false; for (after.list[0..after.len]) |serial| if (std.mem.indexOfScalar(u32, before.list[0..before.len], serial) == null) { + // A query pane's +Preview is its query pane's: that answers. + if (p.paneBySerial(serial)) |made| if (p.panes[made].?.file) |f| if (f.output) |o| if (o.from == .preview) continue; // A look that made a +Search pane (LookWord list, a terminal) // answers it: that is where the places it found are. noteResult(p, serial); @@ -555,6 +557,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? // Bare, it says the width, as from a pane's exec. .tab => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 16, .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth, + .search_rows => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 100, else => probe: { var probe = p.settings; break :probe probe.apply(setting, if (arg.len > 0) arg else null); @@ -664,6 +667,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) .inactive_dim => try w.print("{s} {d}\n", .{ word, s.inactive_dim }), .grip_width => try w.print("{s} {d}\n", .{ word, s.grip_width }), .callstack_depth => try w.print("{s} {d}\n", .{ word, s.callstack_depth }), + .search_rows => try w.print("{s} {d}\n", .{ word, s.search_rows }), .tab => try w.print("{s} {d}\n", .{ word, s.tab }), } } @@ -3890,8 +3894,10 @@ test "Recent's row for a file still open is where its dot is now, not where it l pane.body.cur_col = 2; try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}/a.txt:2:3 open\n", .{dir})) != null); + // A query pane under the file (line 1 `Recent `), its rows said from + // its directory. + try testing.expect(std.mem.startsWith(u8, rows.file.?.content, "Recent \n")); + try testing.expect(std.mem.indexOf(u8, rows.file.?.content, "\na.txt:2:3 open\n") != null); } test "a closed file is found again: Recent and /recent list it closed, a look at its row reopens it at its dot, and a jump back does too" { @@ -3924,7 +3930,8 @@ test "a closed file is found again: Recent and /recent list it closed, a look at // Recent lists it, closed, at its dot; a look at the row opens it there. try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - const at = std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}:3:", .{a})).?; + // Its query pane's rows are said from its directory, a.txt's. + const at = std.mem.indexOf(u8, rows.file.?.content, "\na.txt:3:").? + 1; const row = rows.file.?.content[at..std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; try testing.expect(std.mem.endsWith(u8, row, " (closed)")); try testing.expectEqual(Status.ok, wr(p, Node.of(rows.serial, .look), try std.fmt.bufPrint(&line, "{s}\n", .{row[0 .. row.len - " (closed)".len]})).reply.status); @@ -3939,6 +3946,9 @@ test "a closed file is found again: Recent and /recent list it closed, a look at var closed_entry = false; for (p.jumps[0..p.njumps]) |j| closed_entry = closed_entry or j.serial == 0; try testing.expect(closed_entry); + // Every entry in order (JumpScope all): which file has the focus after + // a Del is the layout's to choose, and Back keeps to it first. + p.settings.jump_scope = .all; var tries: usize = 0; while (tries < p.njumps) : (tries += 1) { p.jumpBy(-1); diff --git a/src/normal.zig b/src/normal.zig index 808ac886..ebace536 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -930,7 +930,12 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .body, .input => tagline.enterTag(p, pane), }, .pipe_selection => |how| return p.startPrompt(pane, t, .{ .pipe = how }), - .search => return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), + // `/` in a text is its query pane's line 1 (Query.zig); a + // terminal's still asks on the notice band. + .search => if (pane.file != null and t.what == .body) + panes.Query.open(p, p.active, .text, "", true) + else + return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), // In a file's text, n and N step its places while they answer for // the register (Places.answersN); else helix's search of the register. .search_step => |step| if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) @@ -939,12 +944,13 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void return searchStep(p, t, text, step.direction, step.count), .search_selection => |boundary| { searchSelection(p, t, text, boundary); - // The pattern's places: the selection is already on one of them. - if (t.what == .body and pane.file != null) { + // The pattern is line 1 of this text's query pane, made or + // reused, the keyboard staying here: n and N step its places. + if (t.what == .body and pane.file != null and !pane.hasPdf() and pane.query == null) { const name = if (p.register != 0) p.register else '/'; const pat = p.registers.value(name, 0) orelse return; - const r = pane.body.primaryRange(text, 0); - pane.places.search(p, pane, .search, 0, pat, false, @min(r.anchor, r.head), false); + panes.Query.open(p, p.active, .text, pat, false); + pane.places.provenance = .search; } }, .node => |walk| return nodeSelect(p, pane, t, walk), diff --git a/src/panes.zig b/src/panes.zig index 73794b91..e0eb3fec 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -108,6 +108,9 @@ pub const Pane = struct { /// gone, or a pane no longer right under its owner's group, leaves it /// an ordinary pane (layout.keepGroups). attached_to: ?u32 = null, + /// This pane is a query pane: its line 1 the query, its rows made live + /// from a source (Query.zig, gpa-owned). + query: ?*Query = null, cols: u16, rows: u16, greet: bool = false, @@ -463,6 +466,8 @@ pub const Pane = struct { if (f.mini != null) return .source; if (std.mem.endsWith(u8, f.path, ".diff") or std.mem.endsWith(u8, f.path, ".patch") or f.pager_diff) return .diff; if (f.output != null) { + // A +Preview is a file's text: coloured as the file. + if (f.output.?.from == .preview) return .source; const tr = Output.fileTraits(f.output); if (tr.locations) return .locations; if (!tr.saves) return .none; @@ -655,6 +660,8 @@ pub const Output = @import("Output.zig"); pub const Places = @import("Places.zig"); +pub const Query = @import("Query.zig"); + pub const Dir = @import("Dir.zig"); pub const mini = @import("mini.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index c4011f7d..1b4e9920 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -486,6 +486,8 @@ test { _ = @import("animation.zig"); _ = @import("pager.zig"); _ = @import("Places.zig"); + _ = @import("Query.zig"); + _ = @import("Names.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4402,6 +4404,9 @@ pub const Pardes = struct { jumps: [MAX_JUMPS]Loc = undefined, njumps: usize = 0, jcur: usize = 0, + /// The next place tracked is an entry of its own however near the last + /// (a query answered: Ctrl-o goes back to where it was asked). + jump_force: bool = false, look_src: [MAX_PANES]u32 = undefined, n_look_src: usize = 0, look_walk_owner: ?u32 = null, @@ -5049,6 +5054,8 @@ pub const Pardes = struct { // to it reopen it there. p.noteClosed(pane); panes.Output.dropUnsaved(p, pane); + // A query pane's places, in whatever panes it fed, go with it. + if (pane.query != null) panes.Query.release(p, pane); if (pane.file) |*file| panes.File.leaveTwins(p, file); const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf(); for (p.panes, 0..) |slot, id| if (slot == pane) { @@ -5084,6 +5091,11 @@ pub const Pardes = struct { pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); + if (pane.query) |q| { + q.deinit(p.gpa); + p.gpa.destroy(q); + pane.query = null; + } panes.terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); @@ -6121,6 +6133,8 @@ pub const Pardes = struct { // Each pane's places find a frame's more on a tick, and on any other // step the ones an edit or a scroll left unfound in the view. for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); + // Each live query pane's rows, made from what changed this step. + panes.Query.produceAll(p, ev == .tick); _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); @@ -6450,6 +6464,9 @@ pub const Pardes = struct { return; } if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key); + // A query pane's line 1 answers Enter, Esc and the stepping keys + // itself (Query.zig). + if (t == &pane.body and header == null and pane.query != null and panes.Query.key(p, p.active, key)) return; if (t.mode == .normal and p.macro.replaying == 0 and (hit(key, config.look_key) or hit(key, config.exec_key))) { // A header's words are the workspace's and column's commands, so // Enter runs them there, as the execute key does. @@ -6564,6 +6581,12 @@ pub const Pardes = struct { p.leader_keys[p.leader_n] = c; p.leader_n += 1; const pfx = p.leader_keys[0..p.leader_n]; + // A path that runs a builtin with its argument (the query pane's + // sources with no word of their own). + for (config.leader_args) |la| if (std.mem.eql(u8, la.path, pfx)) return exec.runBuiltin(p, la.cmd, p.active, "", la.arg); + for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, pfx)) { + p.leader_on = true; + }; // a path-less builtin is a row here too (it is the same index Help // reads), and SPC cannot reach one — so both scans skip it for (builtin_rows) |row| { @@ -7017,6 +7040,21 @@ pub const Pardes = struct { return; } + // The lists of places: into the asking text's query pane (made or + // reused), line 1 their word, the places in that text its places. + const listed: ?panes.Query.Source = switch (w.kind) { + .references => .refs, + .definition => .defs, + .implementation => .impls, + .diagnostics => .diagnostics, + else => null, + }; + if (listed) |source| if (pane.file != null and pane.query == null and !p.exec_header) { + p.fs.refilled = null; + panes.Query.fillList(p, w.pane, source, rows); + p.fs.lsp_result = if (panes.Query.ofOwner(p, pane.serial)) |qid| p.panes[qid].?.serial else null; + return; + }; const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); // A Callstack page that stops short ends in its marker: said as a // row naming the word that shows the next page, and kept. @@ -7285,6 +7323,11 @@ pub const Pardes = struct { p.jcur = @min(cur, w -| 1); const pane = p.panes[p.active] orelse return; + // A query being typed moves the owner's selection to show, never a + // jump; its pane is no place to come back to either. + if (pane.query) |q| if (!q.frozen) return; + const force = p.jump_force; + p.jump_force = false; const now: Loc = .{ .pane = @intCast(p.active), .serial = pane.serial, @@ -7292,14 +7335,14 @@ pub const Pardes = struct { .col = if (pane.pdfPage() != null) 0 else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_col) + 1) else 0, .path_hash = if (recentDot(pane)) |d| std.hash.Wyhash.hash(0, d.path) else 0, }; - if (p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { + if (!force and p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { p.jumps[p.jcur] = now; // same visit; the entry IS where you are return; } // a new jump made from the middle of the list drops everything ahead of // it, the way vim's does: the future you did not take is not history. if (p.njumps > 0) p.njumps = p.jcur + 1; - if (p.njumps >= 2 and p.samePlace(p.jumps[p.njumps - 2], now)) { + if (!force and p.njumps >= 2 and p.samePlace(p.jumps[p.njumps - 2], now)) { p.jumps[p.njumps - 2] = p.jumps[p.njumps - 1]; p.jumps[p.njumps - 1] = now; p.jcur = p.njumps - 1; @@ -7588,6 +7631,7 @@ pub const Pardes = struct { if (p.chrome_animation.isActive() or p.presentation.animating()) return next; // Places still to find resume on the next frame. for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; + if (panes.Query.busy(p)) return next; var frames: ?u64 = null; if (p.look_hover_wait) |waiting| { const delay = config.look_preview_delay_frames orelse return next; @@ -8003,11 +8047,13 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro const tag_before = try std.testing.allocator.dupe(Cell, p.surface.tag_layers[0].cells); defer std.testing.allocator.free(tag_before); - p.update(.{ .key = .{ .cp = '/' } }); + // `s` keeps a prompt on the band (a text's `/` is its query pane's + // line 1 now, Query.zig). + p.update(.{ .key = .{ .cp = 's' } }); p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); p.update(.{ .key = .{ .cp = Key.left } }); try std.testing.expect(pane.prompt == .search and pane.focus == .body); - try std.testing.expectEqualStrings(config.search_marker ++ "tw", pane.promptText().?); + try std.testing.expectEqualStrings(config.select_marker ++ "tw", pane.promptText().?); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); // The tagline is exactly what it was: nothing of the prompt is in it. diff --git a/src/tagline.zig b/src/tagline.zig index e668419d..89152a3a 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -35,6 +35,10 @@ pub const diff_view_tail = withFileCommands(" " ++ config.diff_view_builtins_str pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; pub const command_pane_tail = " " ++ config.command_pane_builtins_str; pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; +/// A query pane's while its rows are made (Query.zig), and once Enter froze +/// them into text a Save keeps; Unattach leaves it where it stands. +pub const query_live_tail = " Del"; +pub const query_frozen_tail = " Save Unattach Del"; /// A file with changes it has not saved. pub fn dirty(pane: *const panes.Pane) bool { const f = pane.file orelse return false; @@ -135,6 +139,9 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co var idbuf: [48]u8 = undefined; return std.fmt.allocPrint(arena, "{s} {s}", .{ (try shownDir(arena, pane)), exec.replId(&idbuf, pane) }); } + // A query pane: its name and where it is among its hits, `+Search + // 3/27` (Query.zig): its owner is right above it. + if (pane.query) |q| if (pane.file) |f| if (pane.prompt != .name) return panes.Query.tagPrefix(q, arena, f.path); // Unsaved text shows on the grip, as acme's modbutton does, not as a // mark in the text: the prefix is the name alone. if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; @@ -174,6 +181,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; + if (pane.query) |q| return if (q.frozen) query_frozen_tail else query_live_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; diff --git a/test/output.zig b/test/output.zig index 523e8129..8ba2f357 100644 --- a/test/output.zig +++ b/test/output.zig @@ -185,7 +185,7 @@ test "ranked choices and prose retain their supplied order" { } } -test "reference Look selects the next sorted row from the captured request and keeps navigation there" { +test "references fill the asking text's query pane: sorted under their files, the next after where it was asked current, the owner's places the refs in it" { if (!pardes.lsp.supports.contains(.references)) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -194,53 +194,38 @@ test "reference Look selects the next sorted row from the captured request and k try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "z.zig", .data = "z\n" }); var path_buf: [256]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/m.zig", .{tmp.sub_path}); - const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 80, .rows = 24 }); + const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 80, .rows = 40 }); defer p.deinit(); - p.locations_config.layout = .@"inline"; const source = p.panes[0].?; const response = "m.zig:5:5-8 later\nz.zig:1:1 last-file\nm.zig:1:7-10 earlier\nm.zig:3:5-8 current\na.zig:1:1 first-file\nm.zig:4:5-8 next\n"; - const sorted = "a.zig:1:1 first-file\nm.zig:1:7-10 earlier\nm.zig:3:5-8 current\nm.zig:4:5-8 next\nm.zig:5:5-8 later\nz.zig:1:1 last-file\n"; source.body.cur_row = 2; source.body.cur_col = 4; p.lspRequest(0, .references, ""); const request = p.lsp_wait.?.id; + // the cursor moves before the answer: it is placed by where it was asked source.body.cur_row = 4; p.lspResponse(request, response); - const rid = source.search_pane orelse return error.MissingResults; - const results = p.panes[rid].?; - try expectResultRows(sorted, &results.file.?); - try std.testing.expectEqual(@as(usize, 0), p.active); + const qid = panes.Query.ofOwner(p, source.serial) orelse return error.MissingResults; + const results = p.panes[qid].?; + const content = results.file.?.content; + try std.testing.expect(std.mem.startsWith(u8, content, "Refs \n")); + // under their files, in order + const a_at = std.mem.indexOf(u8, content, "\na.zig\n").?; + const m_at = std.mem.indexOf(u8, content, "\nm.zig\n").?; + const z_at = std.mem.indexOf(u8, content, "\nz.zig\n").?; + try std.testing.expect(a_at < m_at and m_at < z_at); + // the owner's places are its four refs; the current the one after line 3 + try std.testing.expectEqual(@as(usize, 4), source.places.hits.items.len); + try std.testing.expectEqual(@as(?usize, 2), source.places.current); try std.testing.expectEqual(@as(i32, 3), source.body.cur_row); - try std.testing.expect(source.body.vsel.active); - try std.testing.expectEqual(@as(i32, 4), @min(source.body.cur_col, source.body.vsel.col)); - try std.testing.expectEqual(@as(i32, 7), @max(source.body.cur_col, source.body.vsel.col)); - try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); - try std.testing.expectEqual(@as(usize, 3), source.search_row.?); - try std.testing.expectEqual(results.serial, p.look_walk_owner.?); - try std.testing.expectEqual(@as(i32, 3), results.look_at.?.row); - const available = p.freeSlot(); - lookKey(p, 'n'); - try std.testing.expectEqual(rid, p.active); - try std.testing.expectEqual(@as(i32, 4), results.body.cur_row); - try std.testing.expectEqual(available, p.freeSlot()); - lookKey(p, 'N'); - try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); - + try std.testing.expectEqual(@as(usize, 6), results.query.?.total); + // n in the owner steps them, round the end without a word p.active = 0; - source.body.cur_row = 4; - source.body.cur_col = 4; - p.lspRequest(0, .references, ""); - p.lspResponse(p.lsp_wait.?.id, response); - try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/z.zig")); - try std.testing.expectEqual(@as(i32, 5), results.body.cur_row); - try std.testing.expectEqual(@as(usize, 5), source.search_row.?); - const last = p.active; - p.lspRequest(last, .references, ""); - p.lspResponse(p.lsp_wait.?.id, response); - try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/a.zig")); - const wrapped = p.panes[p.panes[last].?.search_pane.?].?; - try std.testing.expectEqual(@as(i32, 0), wrapped.body.cur_row); - try std.testing.expectEqual(wrapped.serial, p.look_walk_owner.?); + p.update(.{ .key = .{ .cp = 'n' } }); + try std.testing.expectEqual(@as(?usize, 3), source.places.current); + p.update(.{ .key = .{ .cp = 'n' } }); + try std.testing.expectEqual(@as(?usize, 0), source.places.current); + try std.testing.expectEqual(@as(usize, 0), p.active); } test "location sorting leaves mixed prose alone and preserves newline shape" { -- cgit v1.3 From 1af098381515fbe3a4fe678cd023c7fd74418ae1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 12:43:02 -0300 Subject: Search converge 5/6: the old search pipeline phased out, the notice-band / for texts, Find/Grep prompts and walks on the loop, +Recent, n/N as Look-the-next-row; docs, tutor, Help and goldens to the query pane --- docs/helix-keys.md | 8 +- docs/typ/builtins-gui.json | 2 +- docs/typ/builtins-tty.json | 2 +- docs/typ/cheatsheet.typ | 6 +- docs/typ/guide.typ | 46 +++++- docs/typ/reference.typ | 28 ++-- src/Output.zig | 31 ++-- src/Query.zig | 176 +++++++++++++++------ src/builtins.zig | 41 ++--- src/config.zig | 7 +- src/fs.zig | 285 +---------------------------------- src/look.zig | 83 ++-------- src/ninep/ctl.zig | 50 +++--- src/normal.zig | 28 ++-- src/tagline.zig | 1 + src/tutor.txt | 16 +- test/output.zig | 9 ++ test/pdf.zig | 4 +- test/snapshots/builtins.snap | 23 +++ test/snapshots/dump.golden | 3 + test/snapshots/find.golden | 146 +++++++----------- test/snapshots/find.snap | 126 +++++----------- test/snapshots/fsearch.golden | 111 +++++++------- test/snapshots/fsearch.snap | 63 +++----- test/snapshots/grep.golden | 44 +++--- test/snapshots/grep.snap | 91 +++-------- test/snapshots/lookrange.golden | 47 +++--- test/snapshots/lookrange.snap | 22 ++- test/snapshots/lsp-client.golden | 23 +-- test/snapshots/lsp-client.snap | 11 +- test/snapshots/lspdebug.snap | 7 +- test/snapshots/lsprelpath.golden | 170 ++++++++++++--------- test/snapshots/lsprelpath.snap | 35 ++--- test/snapshots/msg.golden | 4 +- test/snapshots/msg.snap | 2 +- test/snapshots/stepgrain.golden | 123 ++++++++------- test/snapshots/stepgrain.snap | 59 ++------ test/snapshots/tagbottom.golden | 13 +- test/snapshots/tagbottomshort.golden | 38 ++--- test/snapshots/topbarexec.golden | 22 ++- 40 files changed, 858 insertions(+), 1148 deletions(-) (limited to 'src/fs.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 8155685f..fa06c9a6 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -134,14 +134,14 @@ language-backend queries, and the shell pipe. | `Space` (normal, body) | starts the pardes LEADER: a key path runs the same builtin words used by tags and the topbar. The main groups are `f` files, `h` docs, `c` columns, `t` toggles/effects, `a` panel animations, `s` session, `j` jumps, `l` language, and `w` directional focus; `SPC ?` lists every path and ` ?` lists one group in `+Help`. Neither `Exit` (quits the editor, acme's Exit) nor `Kill` (stops the commands pardes typed into terminals, acme's Kill) has a leader path: both are the topbar's and the root `ctl`'s. The pending path appears on the active pane's transient body/message row. Esc or an unmapped key abandons it. Paths, Help rows, and dispatch are all generated from the builtin registry at comptime; the leader applies only to a BODY in normal mode because tags and tty programs own their input | pardes-specific; helix spends Space on pickers/LSP (section C), while pardes uses acme-style executable words | | `SPC y` `SPC Y` `SPC p` `SPC P` `SPC R` | helix's clipboard menu on helix's own letters: yank the selection to the system clipboard (`ClipYank`) or the PRIMARY selection alone (`ClipYankMain`), paste the system clipboard after (`ClipPaste`) / before (`ClipPasteBefore`) the selection, replace the selection with it (`ClipReplace`) | the same as `"+y`, `"+p`, `"+P`, `"+R`: register `+` (and `*`) IS the desktop's clipboard, the only register that reaches it. `SPC y` writes `+` alone, as helix's does, not the default register too. Builtins rather than bare chords because a leader path names a builtin: they land in Help's index and are executable words like every other verb. The clipboard holds one text, so N values go out joined by newlines, as helix sends them. On a tty the write is OSC 52 out and the READ is OSC 52 back, which many terminals refuse or gate — so `SPC y` works there and `SPC p` can be a no-op | out of corpus | | a paste from the OUTER terminal | one `Event.paste`, spliced in at the cursor | the tty shell enables bracketed paste and coalesces `paste_start`..`paste_end` into a single event; before that the bytes arrived as individual key presses and normal mode RAN them, which is how a pasted `d` deleted a line. The bytes deliberately never enter the yank register — clipboard and default register are separate stores in both directions | pardes-specific | -| `/` (any pane) | pardes' own plain-substring search into a `+Search` output buffer: the pattern is typed on a line of its own on the pane's notice band, Enter fills the buffer, and its rows are ordinary look targets. Enter also goes to the first row using `Pardes.lookFirstHit`, so `/foo` lands on the first hit with the matched span selected. A pattern that matched nothing opens its empty buffer and moves nothing | kept as-is; not in the corpus (helix `/` is regex search). Find and Grep answer with other files and deliberately do not jump. `LookNext` / `LookPrev` select subsequent result rows | pardes-specific | -| `n` / `N` | next / previous regex match in the current text, using the last search register; counts repeat and ends wrap | only the primary selection is replaced; in select mode each match is added and becomes primary. Named registers work. `*` sets the pattern from selections with word boundaries, `Alt-*` without. The former Look ring is `LookNext` / `LookPrev`, `SPC j n` / `SPC j p`. The change is bookmarked `pardes-nN-helix`; its predecessor is `pardes-nN-before-helix`. PDFs retain their location-result navigation | helix-verified | +| `/` (a text) | a query pane under the pane (`src/Query.zig`): a `+Search` whose line 1 is the query, typed into; helix's regex with smart case, every match tinted and ticked on the rail as you type (the pane's places, `src/Places.zig`), the first after the cursor selected (helix's incremental preview). `Ctrl-n`/`Ctrl-p` step while typing; Enter lands, fills `/` and keeps the rows as text; Esc while typing restores the text and closes the pane. Line 1's first word names the source (`/`, `Find`, `Grep`, `Recent`, `Panes`, `Symbols`, `All`, `Refs`, `Def`, `Impl`, `Diagnostics`), helix's pickers as one pane. A terminal's and a PDF's `/` keep the notice-band prompt and its `+Search` | helix's `/` semantics (regex, smart case, preview); the pane is pardes' | pardes-specific | +| `n` / `N` | next / previous match of the text's places when a query pane fed them (a `/`, a list's places in this text: refs, diagnostics, a Grep's hits), round the ends without a message; else the last search register's regex in the current text, as before; counts repeat | only the primary selection is replaced; in select mode each match is added and becomes primary. Named registers work. `*` sets the pattern from selections with word boundaries (`Alt-*` without) and seeds the text's query pane with it, the keyboard staying. The former Look ring is `LookNext` / `LookPrev`, `SPC j n` / `SPC j p`. PDFs retain their location-result navigation | helix-verified | | insert: printable text | file: real edit; terminal: typed run splice | | helix-verified (file) | | insert: `Enter` | newline; keeps the current full indent levels and adds one 4-space logical tab when the text before the cursor ends in `(`, `[`, `{`, or `)` (including `})`) | plain lines match `insert_newline`; delimiter heuristic is pardes-specific | helix-verified (plain) / pardes-specific (delimiter) | | insert: `Backspace` (+ `Shift-Backspace`) | delete prev char, joins lines at col 0; in a line's leading blanks, back to the previous 4-column indent stop (a whole unit when on one; a tab still goes alone) | matches `delete_char_backward` and its dedent; `Ctrl-h` alias in B | helix-verified | | insert: `Up` `Down` `Left` `Right` | move cursor | matches helix's "not recommended" insert arrows | helix-verified | -| `gd` `gD` `gy` `gi` `gr` | LSP definition / declaration / type-definition / implementation / references. One answer jumps straight there; several fill `+Search`, where `LookNext` / `LookPrev` walk and Enter opens | Ctrl+left-click is the mouse spelling of `gd`; language support depends on the configured backend | out of corpus | +| `gd` `gD` `gy` `gi` `gr` | LSP definition / declaration / type-definition / implementation / references. One answer jumps straight there; several (definition, implementation, references) fill the text's query pane, line 1 `Def`/`Impl`/`Refs`, their places in the text tinted and stepped by `n`/`N`; the others fill `+Search`, where `LookNext` / `LookPrev` walk and Enter opens | Ctrl+left-click is the mouse spelling of `gd`; language support depends on the configured backend | out of corpus | | `]d` `[d` / `]D` `[D` | step the diagnostics list / go to its last or first; if no list is up, asking the backend for one is part of the press | | out of corpus | | `=` | `format_selections` — writes a `- old` / `+ new` diff into `+Lsp` | deliberate divergence: the seam returns ROWS, not edits, so this SHOWS the formatting instead of applying it. Not in the corpus, so there is no waiver to name — the query leaves the core as an effect the headless harness has no shell to perform | out of corpus | | `Ctrl-o` / `Ctrl-i` | jumplist back / forward (also Mouse4 / Mouse5 in SDL, macOS and web); successful navigation clears selections in both panes and places the cursor at the saved location; raw tty forwards both to the child — the `Back` / `Forward` builtins, also on `SPC j o` / `SPC j i`, with `SPC j l` rendering the stack as a buffer; a closed file's entry stays, marked `(closed)`, and a jump to it opens the file again at its place | helix binds both keys (`jump_backward` / `jump_forward`) but to a POSITION jumplist; pardes' stack is over panes and focus, so the keys agree and the semantics do not. `Ctrl-i` and Tab are the same byte under the legacy encoding; there Tab keeps meaning execute, and the pair only separates where the host speaks the kitty keyboard protocol | pardes-specific | @@ -353,7 +353,7 @@ text. | Key(s) | Helix behavior | Reason | | --- | --- | --- | -| `?` | reverse search prompt | pardes keeps its own `/` plain substring search into an output buffer. `*`, `Alt-*` and search-repeat `n`/`N` are implemented and verified above | +| `?` | reverse search prompt | pardes' `/` is a query pane (above); `N` steps backward. `*`, `Alt-*` and search-repeat `n`/`N` are implemented and verified above | | `Space` mode: `f F e . b j g G ' w c C Alt-c / ?` | pickers, global search, palette | pickers and the command palette do not exist here — but the KEY is taken: pardes' own leader runs the acme builtins (section A). Two halves of helix's space mode DO exist and are in section A: the clipboard menu (`y Y p P R`, helix's letters on helix's leader) and the LSP menu, moved one prefix deeper to `SPC l k/r/a/h/s/S/d/D` because `d`, `k`, `s` and `h` were already pardes' most-pressed keys | | Popup `Ctrl-u`/`Ctrl-d`, Completion menu, Signature help tables | LSP popups | LSP | | Picker table (all rows), Prompt table (all rows) | picker / prompt internals | pickers — pardes' tag line is its own one-line editor | diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index c238955c..88c9d864 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -51,7 +51,7 @@ {"name": "Forward", "leader": "SPC j i", "also": ["C-i"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-i: one step forward again, up to wherever Back started."}, {"name": "Get", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Get: the pane's file read again, its unsaved edits refused once as Del refuses them."}, {"name": "Grain", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off, 0-3", "doc": "The page takes a fine, still grain, like paper: a level, 0 (off) through 3."}, - {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches file CONTENTS under every pane's directory at once."}, + {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches the LINES of those files, on the disk engine's worker."}, {"name": "GripWidth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The grip and scrollbar width, as a percent of the theme's rail."}, {"name": "Help", "leader": "SPC ?", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the help: every key and every builtin."}, {"name": "Hover", "leader": "SPC l k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Ask the language server about the symbol under the cursor."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 791eef63..01ae6bc5 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -45,7 +45,7 @@ {"name": "FocusTint", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The focused pane's and column's tags are tinted, on or off."}, {"name": "Forward", "leader": "SPC j i", "also": ["C-i"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-i: one step forward again, up to wherever Back started."}, {"name": "Get", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Get: the pane's file read again, its unsaved edits refused once as Del refuses them."}, - {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches file CONTENTS under every pane's directory at once."}, + {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches the LINES of those files, on the disk engine's worker."}, {"name": "Help", "leader": "SPC ?", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the help: every key and every builtin."}, {"name": "Hover", "leader": "SPC l k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Ask the language server about the symbol under the cursor."}, {"name": "InactiveDim", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Fade the unfocused panes' text by a percentage, 0 through 100, 0 off."}, diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index 7b140a04..76f4b866 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -59,7 +59,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla [#keys("i", "a", "I", "A", "o", "O")], [insert; #key("Esc") back to normal], [#keys("s", "S")], [regex: a cursor per match, split], [#keys("C", ",")], [cursor on next line; keep primary], - [#keys("/", "n", "N")], [search, next, previous], + [#keys("/", "n", "N")], [search (a query pane), next, previous], [#keys("m i", "m m")], [textobject, matching bracket], [#key("|")], [pipe each selection through the shell], [#keys("g d", "g r")], [definition, references (language server)], @@ -87,6 +87,8 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla key("SPC f f"), word("Find"), key("SPC f g"), word("Grep"), key("SPC f r"), word("Recent"), + key("SPC b b"), word("Panes"), + key("SPC s s"), [declarations], key("SPC f c"), word("Config"), key("SPC d"), word("Del"), key("SPC n t"), word("Tty"), @@ -119,7 +121,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla `git diff` output is a diff: #btn("B3") on a file line, an `@@` or a line's `+`/`-` jumps there. #doc("tags", section: "reviewing-diffs") == Finding things -- #word("Find") `name`, #word("Grep") `text` (literal): a `+Search` listing. #word("Recent"): files lately. #word("Help"), #word("Tutor"). +- A query pane under the pane: line 1 the query, its first word the source: `/pat`, `Find name` (fuzzy), `Grep text` (literal), `Recent`, `Panes`, `Symbols`, `All`. #keys("Ctrl-n", "Ctrl-p") step, #key("Enter") lands and keeps the rows, #key("Esc") puts things back. #word("Help"), #word("Tutor"). == Sessions `pardes --detach=work`; `--attach=work` or #word("Attach") `work`; #word("Detach") leaves it running. #doc("detached") diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index e60b4231..65c7334d 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -20,9 +20,9 @@ [the session's directory], [where pardes started, or the directory `pardes DIR` named; workspace and column tags run there], [active column], [where the next new pane goes (below)], [command pane], [a terminal that runs one command line and shows its output], - [`+` names], [panes pardes makes, named in their directory: `+New` a scratch (text with no file yet), `+Search` a listing of places, `+Pager` paged text, `+Errors` output, `+Unsaved` the panes holding unsaved text], + [`+` names], [panes pardes makes, named in their directory: `+New` a scratch (text with no file yet), `+Search` a query pane or a listing of places, `+Pager` paged text, `+Errors` output, `+Unsaved` the panes holding unsaved text], [serial], [a pane's number, never reused: the `3` in `@p3:12` and in 9P paths], - [message row], [the line where pardes says what happened, and asks: answer a prompt (a search, #word("Save")'s path) with #key("Enter"), cancel it with #key("Esc")], + [message row], [the line where pardes says what happened, and asks: answer a prompt (#key("s")'s regex, #word("Save")'s path) with #key("Enter"), cancel it with #key("Esc")], ) = Modes @@ -166,11 +166,45 @@ on the cheatsheet. A relative path is found in the directory of the pane the #word("Look") came from, then of each pane on the jump list, most recent first. += Search + +#key("/") opens a query pane under the pane: a `+Search` whose first line +is the query, typed into, and whose rows are what it finds, made again at +each key. It takes its rows from the pane it searches and from no other, +is born #word("SearchRows") rows tall and never resizes itself; nothing +found is a count of `0` in its tag, not an exit. + #pairs( - [#key("/") `TODO` #key("Enter")], [a `+Search` of the lines holding `TODO`, the cursor on the first; #keys("n", "N") select the next or previous match], - [#word("Find") `conf`], [a `+Search` of the files below the pane's directory with `conf` in their names], - [#word("Grep") `TODO`], [a `+Search` of the lines holding `TODO`, literally, under every pane's directory], + [#key("/") `vw`], [every match in the text tinted and ticked on its scroll rail, the first after the cursor selected; the rows under line 1 are the lines holding it, a line number in the gutter, each under the declaration it is in], + [#keys("Ctrl-n", "Ctrl-p")], [the next or previous match, typing; the text follows it], + [#key("Enter")], [the keyboard on the match, the pattern in `/`, the rows kept as text (#word("Save") keeps them as a file)], + [#keys("n", "N")], [the next or previous match in the text, round the end without a word], + [#key("Esc")], [typing: the text as it was, the query pane closed], + [#key("*")], [the selection as line 1, the keyboard staying in the text], ) + +Line 1's first word names what it searches, and editing the word changes it: + +#pairs( + [`/pat`], [the pane's own text: a regex, any case unless it has a capital (#key("/"))], + [`Find name`], [the files below the pane's directory, by a fuzzy match of their names (#key("SPC f f"), #word("Find"))], + [`Grep text`], [the lines of those files holding `text`, literally (#key("SPC f g"), #word("Grep")); past 2000 lines #word("More") goes on], + [`Recent name`], [the files opened lately (#key("SPC f r"), #word("Recent"))], + [`Panes name`], [the open panes (#key("SPC b b"), #word("Panes"))], + [`Symbols name`], [the text's declarations (#key("SPC s s"))], + [`All pat`], [every open pane's text, its rows under each pane (#key("SPC /"))], + [`Refs`, `Def`, `Impl`, `Diagnostics`], [the language server's lists; their places in the text tinted as a `/`'s are, `]d` stepping the diagnostics], +) + +A row in a file no pane shows is shown in a `+Preview` under the query +pane, following #keys("Ctrl-n", "Ctrl-p") and #btn("B1"), never the +pointer; #key("Enter") makes the preview that file's pane where it stands. +#btn("B3") on a row's line number looks at the row; #btn("B2") on line 1 +runs it again. The next search from the same pane reuses its query pane, +its kept rows back on #key("Esc") (#word("SearchPane") `new`: a pane each; +#word("SearchPlace") `column`: in a finder column at the right). A PDF's +and a terminal's #key("/") still ask on the message row and list a +`+Search`. #clip("search") = Unsaved panes @@ -281,7 +315,7 @@ refusals and `--nested` are in the reference. [#key("w") #key("d")], [select a word, delete it: motions select, edits act on the selection], [#key("x"), #key("v"), #key(";")], [select the line; extend; collapse to the cursor], [#key("s")], [a cursor per regex match; every edit acts at each], - [#key("/"), #keys("n", "N")], [substring search; repeat the search in the current text, wrapping at the ends], + [#key("/"), #keys("n", "N")], [search the text in a query pane (#link()[Search]); step its matches, round the ends], [#keys("SPC j n", "SPC j p")], [#word("LookNext") / #word("LookPrev"): select locations across panes; #key("Enter") opens one], [#key("g l")], [line end], [`12G`], [line 12; a bare #key("G") does nothing], diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index c14ad659..386b9f0f 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -909,7 +909,8 @@ at 200, ending in `…`. Control characters become spaces. pane from the root). - #file("/recent"): up to 200 files, PDFs and images, most recent first, `open ` or `closed `; kept in `$XDG_STATE_HOME/pardes/recent`. - #word("Recent") shows them in a pane, an open one at its dot now and a + #word("Recent") lists them in a query pane (line 1 `Recent`, the rest + narrowing them by a fuzzy match), an open one at its dot now and a closed one at its last (a PDF's is its page); a #word("Look") of a row reopens it there. - #file("/status"): `pid`, `version`, `panes`. @@ -972,15 +973,22 @@ one a #file("exec") open still holds is never reused. In a command pane, #key("n = Find and Grep -#word("Find") matches file names, #word("Grep") the text of lines, both literally and -ignoring ASCII case. #word("Grep") reads whole files and stops at 512 -hits, #word("Find") at 512 names. The walk stops at 20000 files or 100000 entries, -16 deep, and passes over `.git`, `.jj`, `target`, `node_modules`, -`.venv`, `__pycache__`, `.zig-cache` and `zig-out`. A cap hit, or a -directory it could not open, is said at the end: `cut at 512 hits`, `walk cut at N entries`, `N -directories skipped: permission denied`. A search that finds nothing and -skipped nothing fails, `Grep: text not found`, and leaves the `+Search` as -it was. +Both fill the asking pane's query pane (#doc("guide", section: "search")), +line 1 `Find name` or `Grep text`, and run on a worker thread, never on +the loop that draws: `rg` when it is on `PATH` (`rg --files` and `rg --json +--fixed-strings --smart-case`, so `.gitignore` is honoured and hidden files +are passed over), else pardes's own walk, sorted, 16 deep, passing over +dot-directories, `.git`, `.jj`, `target`, `node_modules`, `.venv`, +`__pycache__`, `.zig-cache` and `zig-out`. #word("Find") lists the files once +and matches their names fuzzily at each key (the best first, 200 shown); +#word("Grep") matches the text of lines literally, any case unless the text +has a capital, once the typing pauses (80 ms), and stops at 2000 lines: +#word("More") (in the query pane's tag) goes on for 2000 more. A directory the +walk could not open is said under the rows: `N directories skipped: +permission denied`. A new query cancels the last; rows of a query no +longer asked never land. Written to #file("exec") (a script) the search runs +to its end before the write is answered, and one that finds nothing fails, +`Grep: text not found`, `Find: name not found`, its query pane's count `0`. = On screen diff --git a/src/Output.zig b/src/Output.zig index 1e62b04a..01e3e0f1 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -857,15 +857,6 @@ pub fn dropUnsaved(p: *Pardes, gone: *const Pane) void { } } -/// Recent: the one +Recent, filled again when it is there (as Find and -/// Grep's +Search is), else opened below the asking pane. -pub fn openRecent(p: *Pardes, id: usize) !void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try recentText(p, &out.writer, true); - try refillOrOpen(p, id, .{ .cmd = .Recent }, try out.toOwnedSlice()); -} - /// The one stepped output from `from`, filled again with `content` when it /// is there (Recent, Jumplist), or opened when it is not. fn refillOrOpen(p: *Pardes, id: usize, from: Origin, content: []u8) !void { @@ -971,6 +962,28 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { } if (show_calls_help) try w.writeAll(calls_help); if (prefix.len == 0) try w.writeAll(language_footer); + // The paths that run a builtin with a word (config.leader_args), and how + // a query pane is driven: under SPC f, b, s and in the whole listing. + const search_group = for (config.leader_args) |la| { + if (std.mem.startsWith(u8, la.path, prefix)) break true; + } else std.mem.eql(u8, prefix, "f"); + if (prefix.len == 0 or search_group) { + try w.writeAll("\nsearch: a query pane under the text,\nits line 1 the query, its first word\nthe source (/ Find Grep Recent Panes\nSymbols All Refs Def Impl Diagnostics)\n"); + for (config.leader_args) |la| { + if (!std.mem.startsWith(u8, la.path, prefix)) continue; + var keys: [16]u8 = @splat(' '); + for (la.path, 0..) |c, i| keys[2 * i] = c; + try w.print("{s} {s} {s}\n", .{ keys[0..8], @tagName(la.cmd), la.arg }); + } + if (prefix.len == 0) try w.writeAll( + "/ * the text (* seeds it)\n" ++ + "C-n C-p Up Down step, typing on line 1\n" ++ + "n N step the text's places\n" ++ + "Enter land there, keep the rows\n" ++ + "Esc put every view back\n" ++ + "More a Grep past 2000 lines\n", + ); + } return out.toOwnedSlice(); } diff --git a/src/Query.zig b/src/Query.zig index 48378a18..3a75a7f5 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -153,8 +153,10 @@ window: struct { lo: usize = 0, hi: usize = 0 } = .{}, /// made every third, the frame's time going to the finding. waited: u8 = 0, names: Names = .{}, -/// A Grep's lines, as the disk engine sends them (Stream.zig, `take`). +/// A Grep's lines, as the disk engine sends them (Stream.zig, `take`), and +/// the current one's index among them. found: std.ArrayList(Found) = .empty, +grep_at: usize = 0, found_bytes: std.ArrayList(u8) = .empty, grep_gen: u32 = 0, /// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave @@ -256,6 +258,10 @@ pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: boo File.setContent(p, f, new); q.reset(p); if (rp.collapsed) layout.toggleCollapse(p, id); + // A source that previews gets its +Preview now, at the key that + // asked, not under the typing later. + if (previews(source) and previewOf(p, id) == null) + _ = makePreview(p, id, @max(pardes.BOX_H, rp.tag_rows) + p.settings.search_rows, layout.groupRoot(p, id)); } else { if (existing) |old| { // SearchPane new: the last one stays where it is, a result of @@ -297,8 +303,20 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize const body: u16 = 1 + p.settings.search_rows; const tag = @max(pardes.BOX_H, np.tag_rows); const with_preview = previews(source); - // The preview, made right after, takes its own rows from the owner. - const want = tag + body; + // The preview, made right after, takes its own rows from the owner: + // when the owner has not the rows for both, they share what it has, so + // the group is whole from the first key and nothing moves later. + var want: u16 = tag + body; + var preview_rows: u16 = tag + p.settings.search_rows; + if (with_preview) { + layout.compute(p); + const spare = p.rects[owner_id].h -| layout.minRows(p, owner_id); + if (spare < want + preview_rows) { + const both = want + preview_rows; + want = @max(tag + 2, @as(u16, @intCast(@as(u32, spare) * want / both))); + preview_rows = spare -| want; + } + } if (p.settings.search_place == .column) { // The finder column (phase 6): until it exists, under the owner. if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); @@ -307,7 +325,7 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize // new pane is, the one place a search moves another pane. exec.placeNew(p, owner_id, owner_id, free, .doc); } - if (with_preview) _ = makePreview(p, free); + if (with_preview) _ = makePreview(p, free, preview_rows, owner_id); return free; } @@ -495,9 +513,14 @@ fn produce(p: *Pardes, id: usize, tick: bool) void { q.found.clearRetainingCapacity(); q.found_bytes.clearRetainingCapacity(); q.grep_gen +%= 1; + q.grep_at = 0; q.current = null; // On the disk engine's worker, once the typing pauses. - if (a.pat.len > 0) Stream.query(p, rp.serial, .grep, a.pat, dir, .typed) else if (p.stream.target == rp.serial) { + // A script's (a 9P write): run to its end before it answers. + if (a.pat.len > 0) { + Stream.query(p, rp.serial, .grep, a.pat, dir, if (p.fs.serving) .now else .typed); + if (p.fs.serving) Stream.step(p); + } else if (p.stream.target == rp.serial) { _ = p.stream.stop(); } feedGrepPlaces(p, q, rp.serial, a.pat); @@ -548,7 +571,10 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz switch (source) { // The files under the directory, listed once on the disk engine's // worker (rg --files, else the walk); each keystroke scores them. - .find => Stream.query(p, rp.serial, .files, "", dir, .now), + .find => { + Stream.query(p, rp.serial, .files, "", dir, .now); + if (p.fs.serving) Stream.step(p); + }, .recent => { var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); @@ -828,7 +854,9 @@ fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { // Grouped once a parse of the text exists: asked of the worker now. if (ownerDecls(p, &owner.file.?, false) == null) Stream.parseFor(p, oid); const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); - const from = if (full) 0 else at -| live_rows / 2; + // While typed, a window of rows from just before the current place, so + // it sits under line 1. + const from = if (full) 0 else at -| 2; q.window = .{ .lo = from, .hi = from }; if (set.started and set.from == rp.serial) { if (from > 0) { @@ -856,7 +884,9 @@ fn showPlacesCurrent(p: *Pardes, id: usize) void { const owner = p.panes[p.paneBySerial(q.owner) orelse return].?; const set = &owner.places; q.total = if (set.from == rp.serial) set.hits.items.len else 0; - q.more = q.more or (set.from == rp.serial and !set.complete()); + // still counting: the places not all found yet (the rows' own cut is + // said in a row of theirs) + q.more = set.from == rp.serial and !set.complete(); q.k = if (set.current) |c| c + 1 else 0; if (set.from != rp.serial) q.k = 0; q.current = null; @@ -995,6 +1025,7 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { } } if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + if (q.source == .find) try skippedRow(p, q, rp, &out, &rows); setRows(p, rp, &out, &rows); const f = &rp.file.?; f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; @@ -1004,7 +1035,7 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { q.current = if (shown > 0) 0 else null; countCurrent(q); showCurrent(rp); - showTarget(p, id); + if (q.current == null) blankPreview(p, id) else showTarget(p, id); } /// A Grep keeps this many lines: the rest wait (the disk engine's `More`). @@ -1016,14 +1047,14 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { const rp = p.panes[id].?; const q = rp.query.?; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; - const at: usize = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].hit else 0) else 0; + const at: usize = @min(q.grep_at, q.found.items.len -| 1); q.items.clearRetainingCapacity(); var out: std.ArrayList(u8) = .empty; defer out.deinit(p.gpa); var rows: std.ArrayList(locations.Row) = .empty; var last_path: []const u8 = ""; var pathbuf: [4096 + 8]u8 = undefined; - const lo = if (full) 0 else at -| live_rows / 2; + const lo = if (full) 0 else at -| 2; const hi = if (full) q.found.items.len else @min(q.found.items.len, lo + live_rows); if (lo > 0) { var hb: [64]u8 = undefined; @@ -1048,12 +1079,23 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} lines after these", .{q.found.items.len - hi}) catch " ..."); } if (p.stream.target == rp.serial and p.stream.state == .capped) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: More in the tag goes on"); + try skippedRow(p, q, rp, &out, &rows); setRows(p, rp, &out, &rows); q.total = q.found.items.len; q.more = p.stream.busyFor(rp.serial); q.current = current orelse firstHit(q); countGrepCurrent(q); showCurrent(rp); + if (q.current == null) blankPreview(p, id); +} + +/// What the disk walk passed over, said under the rows: a search that +/// found nothing where it could not look says so, never just nothing. +fn skippedRow(p: *Pardes, q: *Query, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) !void { + const n = p.stream.skipped; + if (p.stream.target != rp.serial or n == 0) return; + var hb: [96]u8 = undefined; + try noteRow(p, q, out, rows, std.fmt.bufPrint(&hb, " {d} director{s} skipped: permission denied", .{ n, if (n == 1) "y" else "ies" }) catch " directories skipped"); } /// `k` for a Grep: the current row's line among all the lines sent. @@ -1128,7 +1170,9 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v const line = lineOne(rp.file.?.content); const a = parse(line) orelse return; makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); - toLineOne(p, qid); + // A list to pick from, typed into; diagnostics are a jump (]d): the + // keyboard stays on the place in the text. + if (source != .diagnostics) toLineOne(p, qid) else p.active = owner_id; } fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { @@ -1141,8 +1185,10 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { var rows: std.ArrayList(locations.Row) = .empty; const owner_id = p.paneBySerial(q.owner); const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else ""; - var feed: std.ArrayList(Places.Hit) = .empty; - defer feed.deinit(p.gpa); + // Each open file's places in the list, its tints and n/N: the owner's + // and any other pane's the rows land in. + var feeds: [pardes.MAX_PANES]std.ArrayList(Places.Hit) = @splat(.empty); + defer for (&feeds) |*f| f.deinit(p.gpa); // In order: by path, then place, as a list of places reads. var sorted: std.ArrayList([]const u8) = .empty; defer sorted.deinit(p.gpa); @@ -1174,27 +1220,28 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { } const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); const col0 = t.at.col -| 1; - try q.items.append(p.gpa, .{ .kind = .hit, .n = 1 }); - // The row's text: the line in the owner when it is the owner's, - // else as the server said it. + // The row's text: the line as an open pane has it, when one shows + // the file, else as the server said it. var code: []const u8 = rest; - var col = col0; - var end = if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1; - if (owner_id) |oid| if (std.mem.eql(u8, path, owner_path)) { - const owner_f = &p.panes[oid].?.file.?; - if (t.at.line <= File.nlines(p.gpa, owner_f)) { - const ls = File.lineStart(p.gpa, owner_f, t.at.line - 1); - const nx = File.lineStart(p.gpa, owner_f, t.at.line); - const le = if (nx > ls and owner_f.content[nx - 1] == '\n') nx - 1 else nx; - code = owner_f.content[ls..le]; - col = @min(col0, code.len); - end = @min(@max(end, col + 1), code.len); - feed.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; - } - } else { - col = 0; - end = 0; - }; + var col = @min(col0, rest.len); + var end = @min(if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1, rest.len); + var shown_in: u32 = 0; + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + const tf = &tp.file.?; + if (tf.output != null or !std.mem.eql(u8, tf.path, path) or t.at.line > File.nlines(p.gpa, tf)) continue; + const ls = File.lineStart(p.gpa, tf, t.at.line - 1); + const nx = File.lineStart(p.gpa, tf, t.at.line); + const le = if (nx > ls and tf.content[nx - 1] == '\n') nx - 1 else nx; + code = tf.content[ls..le]; + col = @min(col0, code.len); + end = @min(@max(end, col + 1), code.len); + feeds[i].append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; + shown_in = tp.serial; + break; + } + try q.items.append(p.gpa, .{ .kind = .hit, .n = 1, .serial = shown_in }); try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); n += 1; } @@ -1203,12 +1250,14 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { q.total = n; q.more = false; q.current = firstHit(q); + for (p.panes, 0..) |slot, i| if (slot) |tp| { + if (feeds[i].items.len > 0) tp.places.feed(p, tp, rp.serial, feeds[i].items, null) else if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + }; if (owner_id) |oid| { const owner = p.panes[oid].?; // Current: the first place after where it was asked (the answer // may come after the cursor moved), shown in the owner. const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner); - owner.places.feed(p, owner, rp.serial, feed.items, null); const hits = owner.places.hits.items; var next: ?usize = null; for (hits, 0..) |h, i| if (h.start > asked_at) { @@ -1261,6 +1310,13 @@ fn showCurrent(rp: *Pane) void { }; const r: i32 = @intCast(c + 1); rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + // Typed into, line 1 stays in view whatever the current row: what you + // type is never scrolled away (the live rows start just before the + // current one, so it sits under line 1). Frozen, the row is scrolled to. + if (!q.frozen) { + if (rp.scroll() != 0) rp.scrollBy(-rp.scroll()); + return; + } const off = rp.scroll(); const shown = off + @as(i32, rp.rows) - 1; if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); @@ -1296,6 +1352,7 @@ fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { const q = rp.query.?; q.current = i; const it = q.items.items[i]; + if (q.source == .grep and it.kind == .hit) q.grep_at = it.hit; const rows = rp.file.?.location_rows; if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| { const tp = p.panes[tid].?; @@ -1325,6 +1382,17 @@ pub fn step(p: *Pardes, id: usize, delta: i32) void { return; } }; + // A Grep: by its lines, the window made again when the next is past it. + if (q.source == .grep and q.found.items.len > 0) { + const n = q.found.items.len; + q.grep_at = if (delta > 0) (q.grep_at + 1) % n else (q.grep_at + n - 1) % n; + const in_window = for (q.items.items) |it| { + if (it.kind == .hit and it.hit == q.grep_at) break true; + } else false; + if (!in_window) makeGrepRows(p, id, q.frozen) catch {}; + for (q.items.items, 0..) |it, i| if (it.kind == .hit and it.hit == q.grep_at) return setCurrent(p, id, i, true); + return; + } const items = q.items.items; if (items.len == 0) return; var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0); @@ -1335,6 +1403,26 @@ pub fn step(p: *Pardes, id: usize, delta: i32) void { setCurrent(p, id, i, true); } +/// Nothing current (a query that matches nothing): the +Preview shows +/// nothing, rather than a file the query no longer names. +fn blankPreview(p: *Pardes, qid: usize) void { + const pid = previewOf(p, qid) orelse return; + const pane = p.panes[pid].?; + const f = &pane.file.?; + if (f.content.len == 0) return; + const dir = std.fs.path.dirname(p.panes[qid].?.file.?.path) orelse "/"; + const path = std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ dir, config.preview_buffer }) catch return; + const empty = p.gpa.alloc(u8, 0) catch { + p.gpa.free(path); + return; + }; + p.gpa.free(f.path); + f.path = path; + File.setContent(p, f, empty); + f.saved_revision = f.revision; + f.scroll = 0; +} + /// Where the current row points, shown with the keyboard left where it is: /// a place in an open pane's text selected there (its places' current), /// in view; a file an open pane shows, its line there; any other file in @@ -1399,8 +1487,11 @@ pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { return null; } -/// A +Preview made under query pane `qid`, out of its rows alone. -fn makePreview(p: *Pardes, qid: usize) ?usize { +/// A +Preview made under query pane `qid`, `rows` tall, out of `giver`'s +/// rows: the text that asked, at the key that asked; the query pane itself +/// when its source word was edited to one that previews while typing (its +/// line 1 stays where it is). +fn makePreview(p: *Pardes, qid: usize, rows: u16, giver: usize) ?usize { const rp = p.panes[qid].?; const free = p.freeSlot() orelse return null; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; @@ -1410,10 +1501,7 @@ fn makePreview(p: *Pardes, qid: usize) ?usize { return null; }; layout.compute(p); - const rows = @max(pardes.BOX_H, np.tag_rows) + p.settings.search_rows; - // Out of the group's root, the text that asked: the query pane keeps - // the rows it was typed into with (made later, for a reused pane). - if (!layout.attachFrom(p, qid, free, rows, layout.groupRoot(p, qid))) { + if (!layout.attachFrom(p, qid, free, rows, giver)) { p.removePane(free, qid) catch {}; return null; } @@ -1425,7 +1513,7 @@ fn makePreview(p: *Pardes, qid: usize) ?usize { /// file open in a pane would be shown there instead), the place centred /// and selected. Made when the pane has none and its owner has the rows. fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void { - const id = previewOf(p, qid) orelse makePreview(p, qid) orelse return; + const id = previewOf(p, qid) orelse makePreview(p, qid, p.rects[qid].h / 2, qid) orelse return; const pane = p.panes[id].?; const f = &pane.file.?; if (!std.mem.eql(u8, f.path, path)) { @@ -1706,8 +1794,8 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { land(p, id, null); return true; } - const down = (k.cp == Key.down and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'n'); - const up = (k.cp == Key.up and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'p'); + const down = hit(k, config.query_next); + const up = hit(k, config.query_prev); if (down or up) { step(p, id, if (down) 1 else -1); return true; diff --git a/src/builtins.zig b/src/builtins.zig index c8909e66..cda962de 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1712,38 +1712,42 @@ const e_search_miss_grep = "Grep: text not found"; /// List the files below this pane's directory whose names hold its argument, in a +Search. pub const Find = struct { pub const takes_arg = true; + // A script's Find names what to find (bare, it is a key's prompt). pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true }; pub fn run(c: Ctx) void { + // A query pane under this pane, line 1 `Find ` and the word: bare + // (SPC f f) typed into; with a word (B2, a script) listed, the + // keyboard left where it was, a script told of a miss. const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (pat.len > 0) { - const rows = look.runSearch(c.p, c.id, pat, .find, .top, false) catch |err| return c.p.reportError(c.id, "Find", err); - if (rows == 0) c.p.reportFailure(c.id, e_search_miss_find); - return; - } - // Bare (SPC f f): the query pane, line 1 `Find `, typed into. - panes.Query.open(c.p, c.id, .find, "", true); + panes.Query.open(c.p, c.id, .find, pat, pat.len == 0); + if (pat.len > 0) missed(c, e_search_miss_find); } }; /// Find's sibling: Find matches file NAMES under this pane's directory, Grep -/// matches file CONTENTS under every pane's directory at once. +/// matches the LINES of those files, on the disk engine's worker. pub const Grep = struct { pub const takes_arg = true; pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (pat.len > 0) { - const rows = look.runSearch(c.p, c.id, pat, .grep, .top, false) catch |err| return c.p.reportError(c.id, "Grep", err); - if (rows == 0) c.p.reportFailure(c.id, e_search_miss_grep); - return; - } - // Bare (SPC f g): the query pane, line 1 `Grep `, typed into. - panes.Query.open(c.p, c.id, .grep, "", true); + panes.Query.open(c.p, c.id, .grep, pat, pat.len == 0); + if (pat.len > 0) missed(c, e_search_miss_grep); } }; +/// A script's Find or Grep (a 9P write runs it to its end before it +/// answers) that found nothing fails as one: the query pane stays, its +/// count 0, and the write hears `not found`. +fn missed(c: Ctx, text: []const u8) void { + if (!c.p.fs.serving) return; + const qid = panes.Query.ofOwner(c.p, c.pane.serial) orelse return; + const q = c.p.panes[qid].?.query.?; + if (q.total == 0) c.p.reportFailure(c.id, text); +} + /// Search in a query pane under this pane, line 1 the argument (`Panes`, /// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. pub const Search = struct { @@ -1898,11 +1902,10 @@ pub const Last = struct { pub const Recent = struct { pub const scope: Scope = .session; pub const takes_arg = true; - pub const output: OutputTraits = .{ .name = config.recent_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { - // From a pane: the query pane under it, line 1 `Recent `, typed - // into; from a header, which no pane owns, the +Recent list. - if (c.p.exec_header or c.p.panes[c.id] == null) return panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + // The query pane under the pane the keyboard is in, line 1 + // `Recent `, typed into; what follows the word narrows the files. + if (c.p.panes[c.id] == null) return c.p.reportFailure(c.id, "Recent: open a pane to search from"); panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; diff --git a/src/config.zig b/src/config.zig index 25c9dc5a..fff99ad2 100644 --- a/src/config.zig +++ b/src/config.zig @@ -365,6 +365,11 @@ pub const command_line: []const Chord = &.{.{ .cp = ':' }}; pub const search: []const Chord = &.{.{ .cp = '/' }}; pub const search_next: []const Chord = &.{.{ .cp = 'n' }}; pub const search_prev: []const Chord = &.{.{ .cp = 'N' }}; +/// Typing on a query pane's line 1 (Query.zig): the next and the previous +/// hit current, the text following (helix's prompt walks its history with +/// these; a query has none). Tab stays the exec chord. +pub const query_next: []const Chord = &.{ .{ .cp = 'n', .ctrl = true }, .{ .cp = Key.down } }; +pub const query_prev: []const Chord = &.{ .{ .cp = 'p', .ctrl = true }, .{ .cp = Key.up } }; pub const search_selection: []const Chord = &.{.{ .cp = '*', .alt = true }}; pub const search_selection_word: []const Chord = &.{.{ .cp = '*' }}; pub const pipe_selection: []const Chord = &.{.{ .cp = '|' }}; @@ -526,8 +531,6 @@ pub const comment_tokens: []const struct { exts: []const []const u8, token: []co }; pub const search_marker = " /"; -pub const find_marker = " Find /"; -pub const grep_marker = " Grep /"; pub const rename_marker = " Rename /"; pub const symbol_marker = " WsSymbols /"; pub const save_marker = " Save "; diff --git a/src/fs.zig b/src/fs.zig index cb813262..08379697 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1115,297 +1115,16 @@ pub const WalkNotes = struct { } }; const find_max_depth = 16; -const find_max_steps = 100_000; -/// One root's Find or Grep rows at most: its hits, each a path and a line. -pub const search_root_output_bytes = find_max_hits * (4096 + 320); pub const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", ".venv", "__pycache__", ".zig-cache", "zig-out", }; -/// A directory the walk may not open or read is passed over and counted in -/// `notes.skipped`, its siblings' hits kept: one locked directory is not -/// every search's failure. A cap the walk hit is noted too. -pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u8, notes: *WalkNotes) !usize { - var hits: [find_max_hits][]const u8 = undefined; - var hits_len: usize = 0; - if (platform_has_fs) { - pardes.turn.yield(); - defer pardes.turn.back(); - const io = std.Io.Threaded.global_single_threaded.io(); - var root = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); - defer root.close(io); - var w = try root.walkSelectively(arena); - defer w.deinit(); - var steps: usize = 0; - walk: while (steps < find_max_steps and hits_len < hits.len) { - steps += 1; // an unreadable dir burns a step too, so it cannot spin - const e = (w.next(io) catch { - notes.skipped += 1; - continue; - }) orelse break; - if (std.ascii.findIgnoreCase(e.basename, pat) != null) { - hits[hits_len] = try arena.dupe(u8, e.path); - hits_len += 1; - } - if (e.kind != .directory or e.depth() >= find_max_depth) continue; - for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - w.enter(io, e) catch { - notes.skipped += 1; - }; - } - if (hits_len >= hits.len) notes.hits_cut = true; - if (steps >= find_max_steps) notes.walk_cut = find_max_steps; - } else { - for (sources) |s| { - if (hits_len >= hits.len) break; - if (std.ascii.findIgnoreCase(std.fs.path.basename(s.path), pat) != null) { - hits[hits_len] = s.path; - hits_len += 1; - } - } - } - std.mem.sort([]const u8, hits[0..hits_len], {}, struct { - fn lt(_: void, a: []const u8, b: []const u8) bool { - return std.mem.lessThan(u8, a, b); - } - }.lt); - var written: usize = 0; - for (hits[0..hits_len]) |h| { - if (h.len + 1 > out.len - written) break; - @memcpy(out[written..][0..h.len], h); - written += h.len; - out[written] = '\n'; - written += 1; - } - return written; -} - -const grep_max_bytes = 256 * 1024; +// Find and Grep walk on the disk engine's worker now (Stream.zig); what is +// left here is what their notes and skips were. const grep_max_files = 20_000; -const GrepResult = struct { bytes: usize, hits: usize }; - -/// `text` starts at line `first_line` + 1 of its file. -fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize, first_line: usize) GrepResult { - var result: GrepResult = .{ .bytes = 0, .hits = 0 }; - var line: usize = first_line; - var it = std.mem.splitScalar(u8, text, '\n'); - while (it.next()) |raw| { - line += 1; - if (result.hits >= budget) break; - const at = std.ascii.findIgnoreCase(raw, pat) orelse continue; - const ln = std.mem.trimEnd(u8, raw, " \t\r"); - var cut = @min(ln.len, 200); - while (cut > 0 and cut < ln.len and ln[cut] & 0xc0 == 0x80) cut -= 1; - const row = std.fmt.bufPrint(out[result.bytes..], "{s}:{d}:{d}{c}{d} {s}\n", .{ - path, line, at + 1, config.range_sep, at + pat.len, ln[0..cut], - }) catch break; - result.bytes += row.len; - result.hits += 1; - } - return result; -} - -pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, base: []const u8, pat: []const u8, out: []u8, notes: *WalkNotes) !usize { - var hits: usize = 0; - var written: usize = 0; - if (!platform_has_fs) { - for (sources) |s| { - if (hits >= find_max_hits or written == out.len) break; - const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits, 0); - hits += result.hits; - written += result.bytes; - } - return written; - } - const root_path = std.mem.trimEnd(u8, dir, "/"); - const home = std.mem.trimEnd(u8, base, "/"); - const files = try arena.alloc([]const u8, grep_max_files); - var files_len: usize = 0; - // A walk and thousands of reads: the turn goes out for all of it. - pardes.turn.yield(); - defer pardes.turn.back(); - { - const io = std.Io.Threaded.global_single_threaded.io(); - var root = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); - defer root.close(io); - var w = try root.walkSelectively(arena); - defer w.deinit(); - var steps: usize = 0; - walk: while (steps < find_max_steps and files_len < files.len) { - steps += 1; - const e = (w.next(io) catch { - notes.skipped += 1; - continue; - }) orelse break; - if (e.kind == .directory) { - if (e.depth() >= find_max_depth) continue; - for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - w.enter(io, e) catch { - notes.skipped += 1; - }; - continue; - } - if (e.kind != .file) continue; - files[files_len] = try std.fmt.allocPrint(arena, "{s}/{s}", .{ root_path, e.path }); - files_len += 1; - } - if (files_len >= files.len) notes.walk_cut = grep_max_files else if (steps >= find_max_steps) notes.walk_cut = find_max_steps; - } - std.mem.sort([]const u8, files[0..files_len], {}, struct { - fn lt(_: void, a: []const u8, b: []const u8) bool { - return std.mem.lessThan(u8, a, b); - } - }.lt); - const buf = try gpa.alloc(u8, grep_max_bytes); - defer gpa.free(buf); - for (files[0..files_len]) |path| { - if (hits >= find_max_hits or written == out.len) { - notes.hits_cut = true; - break; - } - var pathbuf: [4096]u8 = undefined; - const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{path}, 0) catch return error.PathTooLong; - const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NONBLOCK = true }); - if (fd < 0) continue; - defer _ = libc.close(fd); - // The whole file, a buffer at a time: each searched through its last - // whole line, the rest carried into the next. - const shown = lsp.rel(home, path); - var len: usize = 0; - var lines_before: usize = 0; - var first = true; - file: while (true) { - var eof = false; - while (len < buf.len) { - const n = libc.read(fd, buf[len..].ptr, buf.len - len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - break :file; - } - if (n == 0) { - eof = true; - break; - } - len += @intCast(n); - } - if (first and std.mem.indexOfScalar(u8, buf[0..@min(len, 1024)], 0) != null) break; - first = false; - // A line longer than the buffer is searched in buffer-sized parts. - const end = if (eof) len else if (std.mem.lastIndexOfScalar(u8, buf[0..len], '\n')) |nl| nl + 1 else len; - const result = grepText(shown, buf[0..end], pat, out[written..], find_max_hits - hits, lines_before); - hits += result.hits; - written += result.bytes; - if (eof or hits >= find_max_hits or written == out.len) break; - lines_before += std.mem.count(u8, buf[0..end], "\n"); - std.mem.copyForwards(u8, buf[0 .. len - end], buf[end..len]); - len -= end; - } - if (hits >= find_max_hits) notes.hits_cut = true; - } - return written; -} - -test "grep skips a file it cannot read instead of abandoning the search" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a-locked.txt", .data = "needle here\n" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b-open.txt", .data = "needle here\n" }); - var locked_buf: [std.fs.max_path_bytes]u8 = undefined; - const locked = try std.fmt.bufPrintSentinel(&locked_buf, "{s}/a-locked.txt", .{dir}, 0); - if (libc.chmod(locked, 0) != 0) return; - const probe = libc.open(locked, .{ .ACCMODE = .RDONLY }); - if (probe >= 0) { - _ = libc.close(probe); - _ = libc.chmod(locked, 0o644); - return error.SkipZigTest; - } - - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 64 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - const n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - _ = libc.chmod(locked, 0o644); // so `tmp.cleanup` can remove it - - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "b-open.txt") != null); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "a-locked.txt") == null); -} - -test "a directory the walk may not open is skipped and counted: Grep and Find keep every other hit" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - try tmp.dir.createDirPath(std.testing.io, "locked"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "locked/needle-in.txt", .data = "needle\n" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "needle-out.txt", .data = "needle\n" }); - var locked_buf: [std.fs.max_path_bytes]u8 = undefined; - const locked = try std.fmt.bufPrintSentinel(&locked_buf, "{s}/locked", .{dir}, 0); - if (libc.chmod(locked, 0) != 0) return; - defer _ = libc.chmod(locked, 0o755); // so `tmp.cleanup` can remove it - if (isDir(locked)) return error.SkipZigTest; // root reads it anyway - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 64 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt:1:") != null); - try std.testing.expectEqual(@as(usize, 1), notes.skipped); - notes = .{}; - n = try find(arena.allocator(), dir, "needle", out, ¬es); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt") != null); - try std.testing.expectEqual(@as(usize, 1), notes.skipped); -} - -test "Grep reads a long file to its end, and says when its hits were cut" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - // A match past the first buffer of a long file, on its own line number. - const long = try gpa.alloc(u8, grep_max_bytes + 64); - defer gpa.free(long); - @memset(long, 'x'); - for (0..long.len / 64) |i| long[i * 64] = '\n'; - @memcpy(long[long.len - 8 ..][0..7], "needle\n"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "long.txt", .data = long }); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 256 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - var want_buf: [64]u8 = undefined; - const want = try std.fmt.bufPrint(&want_buf, "long.txt:{d}:", .{std.mem.count(u8, long, "\n")}); - try std.testing.expect(std.mem.startsWith(u8, out[0..n], want)); - // More hits than the cap. - var many: std.ArrayList(u8) = .empty; - defer many.deinit(gpa); - for (0..find_max_hits + 10) |_| try many.appendSlice(gpa, "needle\n"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "many.txt", .data = many.items }); - notes = .{}; - n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expect(notes.hits_cut); - var said: [256]u8 = undefined; - const lines = said[0..notes.write(&said)]; - try std.testing.expectEqualStrings("cut at 512 hits\n", lines); - try std.testing.expect(WalkNotes.isNote("cut at 512 hits") and WalkNotes.isNote("2 directories skipped: permission denied") and !WalkNotes.isNote("src/2 directories.txt")); -} - fn isDir(path: [*:0]const u8) bool { const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true }); if (fd < 0) return false; diff --git a/src/look.zig b/src/look.zig index eed3dbd9..cd8df4fc 100644 --- a/src/look.zig +++ b/src/look.zig @@ -532,7 +532,6 @@ pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { return .{ .state = .done, .c0 = vcol, .c1 = vcol, .r0 = vrow, .r1 = vrow }; } -const Search = enum { text, find, grep }; const SearchStart = enum { top, cursor }; @@ -550,20 +549,13 @@ pub fn submitSearch(p: *Pardes, id: usize) void { const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return; if (std.mem.startsWith(u8, armed, config.rename_marker)) return p.lspRequest(id, .rename, armed[slash + 1 ..]); if (std.mem.startsWith(u8, armed, config.symbol_marker)) return p.lspRequest(id, .workspace_symbols, armed[slash + 1 ..]); - const kind: Search = if (std.mem.startsWith(u8, armed, config.find_marker)) - .find - else if (std.mem.startsWith(u8, armed, config.grep_marker)) - .grep - else - .text; - _ = runSearch(p, id, armed[slash + 1 ..], kind, .top, true) catch |err| return p.reportError(id, "search", err); - if (kind == .text) { - var pattern: std.ArrayList(u8) = .empty; - normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch return; - p.registers.put(p.gpa, '/', pattern.items, 0, 1, true); - p.registers.last_search = '/'; - lookFirstHit(p, id); - } + // A PDF's `/` and a terminal's: a text's is its query pane (Query.zig). + _ = runSearch(p, id, armed[slash + 1 ..], .top, true) catch |err| return p.reportError(id, "search", err); + var pattern: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch return; + p.registers.put(p.gpa, '/', pattern.items, 0, 1, true); + p.registers.last_search = '/'; + lookFirstHit(p, id); } fn lookFirstHit(p: *Pardes, id: usize) void { @@ -589,7 +581,7 @@ fn lookFirstHit(p: *Pardes, id: usize) void { /// of rows: past it, the rows stop and say where. pub const search_text_output_bytes = 16 << 20; -pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart, open_empty: bool) !usize { +pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, start: SearchStart, open_empty: bool) !usize { const pane = p.panes[id] orelse return 0; // Blanks at either end are the pattern's (a look of an indented line); // a builtin's argument comes trimmed already. @@ -607,49 +599,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start var nrows: usize = 0; var anchor: ?usize = null; var notes: filesystem.WalkNotes = .{}; - if (kind == .grep) { - var roots: [MAX_PANES][]const u8 = undefined; - var nroots: usize = 0; - for (p.panes) |slot| { - const pp = slot orelse continue; - // A pane of the served tree (/virtual/, /n//) has no - // directory on this host to walk, and one that named `/` would - // swallow every other root: passed over. - const d = filesystem.localPath(Pardes.paneDir(pp)) orelse continue; - if (filesystem.isVirtual(if (pp.file) |f| f.path else d)) continue; - var covered = false; - var k: usize = 0; - while (k < nroots) { - if (pathUnder(d, roots[k])) { - covered = true; - break; - } - if (pathUnder(roots[k], d)) { // this one swallows a root already kept - nroots -= 1; - roots[k] = roots[nroots]; - continue; - } - k += 1; - } - if (covered) continue; - roots[nroots] = d; - nroots += 1; - } - out = try @import("memory.zig").unfilled(arena, @max(1, nroots) * filesystem.search_root_output_bytes); - // A pane's directory that is not there (a scratch named into one - // not made yet, a peer's) has nothing to grep: passed over, not the - // search's failure. - for (roots[0..nroots]) |r| - out_len += filesystem.grep(arena, p.gpa, r, dir, pat, out[out_len..], ¬es) catch |err| switch (err) { - error.FileNotFound, error.NotDir, error.AccessDenied => continue, - else => return err, - }; - nrows = std.mem.count(u8, out[0..out_len], "\n"); - } else if (kind == .find) { - out = try @import("memory.zig").unfilled(arena, filesystem.search_root_output_bytes); - out_len = try filesystem.find(arena, dir, pat, out, ¬es); - nrows = std.mem.count(u8, out[0..out_len], "\n"); - } else if (pane.hasPdf()) { + if (pane.hasPdf()) { out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); if (comptime pdf_enabled) { const found = try panes.Pdf.searchRows( @@ -700,19 +650,10 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start const noted = notes.write(out[out_len..]); out_len += noted; nrows += std.mem.count(u8, out[out_len - noted .. out_len], "\n"); - // A Find or Grep that finds nothing leaves its directory's +Search as - // it was: the failure says why, and the last search's rows are still - // that search's (its tag names it). + // A word looked for that is nowhere opens nothing. if (!open_empty and nrows == 0) return 0; const content = try p.gpa.dupe(u8, out[0..out_len]); - // the buffer records WHICH search filled it, pattern and all: Find and - // Grep are builtins (words you can execute), the bare `/` is a key - const from: panes.Output.Origin = switch (kind) { - .text => .search, - .find => .{ .cmd = .Find }, - .grep => .{ .cmd = .Grep }, - }; - try panes.Output.fillResults(p, id, dir, from, pat, content, anchor); + try panes.Output.fillResults(p, id, dir, .search, pat, content, anchor); return nrows; } @@ -1466,7 +1407,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: if (p.settings.look_word == .search and pane.file != null) return lookWord(p, id, pane, text); p.word_look = true; defer p.word_look = false; - const rows = runSearch(p, id, text, .text, .cursor, false) catch |err| { + const rows = runSearch(p, id, text, .cursor, false) catch |err| { p.reportError(id, "search", err); return; }; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 45336a1e..635e03a6 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -3017,7 +3017,7 @@ test "a builtin that needs its argument, written bare to an exec, is EINVAL as t } } -test "Grep with no hit says grep: no match and opens nothing, a missing pane directory passed over" { +test "a script's Grep and Find fill the pane's one query pane, a row a line under its file; a miss says not found and opens nothing" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); var tmp = testing.tmpDir(.{}); @@ -3028,22 +3028,26 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line: [4200]u8 = undefined; _ = wr(p, Node.of(serialOf(p), .name), try std.fmt.bufPrint(&line, "{s}/a.txt\n", .{dir})); - // A hit opens its +Search, a row a line: exec reads it back. Find and - // Grep share it, a directory's one +Search, each run replacing it. + // A hit fills the pane's query pane, line 1 the command, its rows under + // the file they are in: exec reads it back. Find and Grep share it, the + // pane's one query pane, each run replacing it. try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Grep bravo\n").reply.status); const grepped = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - try testing.expectEqual(@as(usize, 2), std.mem.count(u8, grepped.file.?.content, "other.txt:")); - try testing.expect(std.mem.indexOf(u8, grepped.file.?.content, "other.txt:2") != null); - try testing.expect(std.mem.indexOf(u8, grepped.file.?.content, "other.txt:3") != null); + const rows = grepped.file.?.content; + try testing.expect(std.mem.startsWith(u8, rows, "Grep bravo\n")); + try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt\n") != null); + try testing.expect(std.mem.indexOf(u8, rows, "2 bravo here\n") != null); + try testing.expect(std.mem.indexOf(u8, rows, "3 three bravo\n") != null); + try testing.expectEqual(@as(usize, 2), grepped.query.?.total); try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status); const found = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - try testing.expect(std.mem.indexOf(u8, found.file.?.content, "other.txt") != null); try testing.expectEqual(grepped.serial, found.serial); + try testing.expect(std.mem.indexOf(u8, found.file.?.content, "\nother.txt\n") != null); try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") == null); - // The same Find again reads back the +Search, not the pane it ran in. + // The same Find again reads back the query pane, not the pane it ran in. try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status); try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{found.serial}), rd(p, root_exec, 0, 64).bytes); - // A Grep run from the +Search itself fills that one, never a second. + // A Grep run from the query pane itself fills that one, never a second. try testing.expectEqual(Status.ok, wr(p, Node.of(found.serial, .exec), "Grep bravo\n").reply.status); try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{found.serial}), rd(p, root_exec, 0, 64).bytes); var searches: usize = 0; @@ -3052,23 +3056,19 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir }; try testing.expectEqual(@as(usize, 1), searches); try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") != null); - // A second pane in a directory that is not there. - const other = try th.newPane(p); - _ = wr(p, Node.of(other, .name), "/tmp/pardes-no-such-dir-zz/b.txt\n"); var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); + // A miss: said to the script, the query pane's count 0, nothing opened. const missed = wr(p, Node.of(serialOf(p), .exec), "Grep zzqqnomatchzz\n"); try testing.expectEqual(E.NOENT, missed.errno()); try testing.expectEqualStrings("Grep: text not found", missed.reply.ename); + try testing.expectEqual(@as(usize, 0), found.query.?.total); const unfound = wr(p, Node.of(serialOf(p), .exec), "Find zzqqnomatchzz\n"); try testing.expectEqual(E.NOENT, unfound.errno()); try testing.expectEqualStrings("Find: name not found", unfound.reply.ename); var after: usize = 0; for (p.panes) |slot| after += @intFromBool(slot != null); try testing.expectEqual(count, after); - // The +Search a miss would have filled keeps the last search's rows: - // the miss is said, and its tag names what they are of. - try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") != null); } test "Unmount of a name not mounted says no such mount, which a mount reads as ENOENT" { @@ -4911,7 +4911,7 @@ test "a Rename the server answered for this file alone, with other open files sa try testing.expect(th.logHas(p, "Rename: previewed, not applied: the server renamed in this file only, and 1 other open file(s) say the name")); } -test "Find ends with what it skipped, and a Find or Grep that finds nothing leaves the +Search as it was" { +test "Find says what it skipped under its names, and a script's Find that finds nothing is told so" { if (comptime !pardes.hosted) return; const gpa = testing.allocator; var tmp = testing.tmpDir(.{}); @@ -4928,18 +4928,18 @@ test "Find ends with what it skipped, and a Find or Grep that finds nothing leav const path = try std.fmt.bufPrint(&path_buf, "{s}/zz-needle.txt", .{dir}); const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 30 }); defer p.deinit(); - try testing.expect(p.executeBuiltinLine(0, "Find needle")); - const search = p.panes[p.panes[0].?.search_pane.?].?; + // the walk's own skips are what is said (rg would pass over in silence) + p.stream.engine = .walk; + try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find needle\n").reply.status); + const search = p.panes[pardes.panes.Query.ofOwner(p, p.panes[0].?.serial).?].?; const listed = search.file.?.content; try testing.expect(std.mem.endsWith(u8, listed, "1 directory skipped: permission denied\n")); - try testing.expect(std.mem.startsWith(u8, listed, "zz-needle.txt\n")); - // Nothing found where it looked, and nothing passed over: the miss is - // said, and the +Search keeps the last search's rows. + try testing.expect(std.mem.startsWith(u8, listed, "Find needle\nzz-needle.txt\n")); + // Nothing found: the miss is said, the query pane's count 0. _ = std.c.chmod(locked, 0o755); - const before = try gpa.dupe(u8, listed); - defer gpa.free(before); - try testing.expect(p.executeBuiltinLine(0, "Find nosuchname")); - try testing.expectEqualStrings(before, search.file.?.content); + const missed = wr(p, Node.of(serialOf(p), .exec), "Find nosuchname\n"); + try testing.expectEqual(E.NOENT, missed.errno()); + try testing.expectEqual(@as(usize, 0), search.query.?.total); try testing.expect(th.logHas(p, "Find: name not found")); } diff --git a/src/normal.zig b/src/normal.zig index ebace536..f5bdb9dc 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -757,22 +757,18 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .add_newline => |newline| return edit.addNewline(p, t, newline.direction == .forward, newline.count), .diagnostic => |diagnostic| { const fwd = diagnostic.direction == .forward; - if (!diagnostic.endpoint) { - if (panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics }) and - look.searchStep(p, p.active, if (fwd) 1 else -1)) return; - return p.lspRequest(p.active, .diagnostics, ""); - } - if (!panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics })) - return p.lspRequest(p.active, .diagnostics, ""); - if (!fwd) { - pane.search_row = null; - _ = look.searchStep(p, p.active, 1); - return; - } - const rp = p.panes[pane.search_pane orelse return] orelse return; - const rf = rp.file orelse return; - pane.search_row = std.mem.count(u8, rf.content, "\n"); - _ = look.searchStep(p, p.active, -1); + // Once a Diagnostics query fed them, the diagnostics are this + // text's places: ]d and [d step them as n and N do, ]D and [D + // go to the last and the first. Until then, asked for. + const set = &pane.places; + const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid| + (if (p.panes[qid].?.query) |q| q.source == .diagnostics else false) + else + false; + if (!fed) return p.lspRequest(p.active, .diagnostics, ""); + if (!diagnostic.endpoint) return set.step(p, pane, fwd, 1, false); + if (set.hits.items.len == 0) return; + set.goTo(pane, if (fwd) set.hits.items.len - 1 else 0, false); }, .move => |move| switch (move.motion) { .left => { diff --git a/src/tagline.zig b/src/tagline.zig index 3c8dd3e1..c057772d 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -184,6 +184,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; if (pane.query) |q| return if (q.frozen) query_frozen_tail else if (q.capped) query_capped_tail else query_live_tail; + if (pane.file) |file| if (file.output) |out| if (out.from == .preview) return query_live_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; diff --git a/src/tutor.txt b/src/tutor.txt index 083a5028..188a485d 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -101,8 +101,10 @@ 1. `Look` :20 here: the cursor goes to line 20 of this pane. 2. Drag across :/^=.*UNSAVED/ with B3 held: `Look` takes exactly what you swept, a regex here, and goes to Part 7's heading. - 3. Press /, type keys, press Enter: a +Search lists the lines with - keys and the cursor goes to the first. n and N select search matches. + 3. Press / and type keys: a +Search opens under this pane, its first + line the query; each match lights up and is listed as you type, and + Ctrl-n steps. Enter puts the cursor on it and keeps the list; n and N + step them. Esc while typing puts everything back. -> Guide: Look @@ -259,9 +261,9 @@ typed ] p, [ p step by paragraph; ] d, [ d by diagnostic ] space a blank line below; [ space above | filter every selection through the shell - / case-insensitive SUBSTRING search, one hit a line; the - regex lives on s and S - n / N next/previous search match (Helix); v adds matches + / search in a query pane under the text: a regex, any + case unless it has a capital; line 1 is the query + n / N next/previous match, round the end; v adds matches SPC j n/p `LookNext`/`LookPrev`: select locations; Enter opens Ctrl-c comment or uncomment the lines @@ -344,11 +346,11 @@ typed ; collapses first bare G does nothing; ge is the START of the last line s / S regex cursors; m i/a textobjects; m s/r/d surround - / is a case-insensitive SUBSTRING search, not a regex + / opens a query pane: line 1 the query, Enter lands SPC is the leader (SPC ? is `Help`) vs HELIX selection is LINE-first (x), v for characters; / is a - substring search; n/N repeat it in the current text. + pane: Find, Grep, Recent are its line 1's first word. vs VIM no verb+noun: the motion already selected, so wd is what dw was; Esc goes back a pane; bare G does nothing. vs BOTH a terminal is just a pane, and the session can outlive diff --git a/test/output.zig b/test/output.zig index 8ba2f357..8eb389c8 100644 --- a/test/output.zig +++ b/test/output.zig @@ -219,6 +219,15 @@ test "references fill the asking text's query pane: sorted under their files, th try std.testing.expectEqual(@as(?usize, 2), source.places.current); try std.testing.expectEqual(@as(i32, 3), source.body.cur_row); try std.testing.expectEqual(@as(usize, 6), results.query.?.total); + // Ctrl-n on line 1, Enter: the keyboard on that ref in the text + try std.testing.expectEqual(qid, p.active); + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expectEqual(@as(?usize, 3), source.places.current); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 4), source.body.cur_row); + p.update(.{ .key = .{ .cp = 'N' } }); + try std.testing.expectEqual(@as(?usize, 2), source.places.current); // n in the owner steps them, round the end without a word p.active = 0; p.update(.{ .key = .{ .cp = 'n' } }); diff --git a/test/pdf.zig b/test/pdf.zig index ea23f90a..d4efdfaf 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -1053,7 +1053,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expect(pane.pdf.?.document_scroll_y > before_height_scroll); const revision_before_search = active_raster.revision; - _ = try pardes.look.runSearch(p, 0, "Pardes", .text, .top, true); + _ = try pardes.look.runSearch(p, 0, "Pardes", .top, true); try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query); try std.testing.expectEqual(revision_before_search, active_raster.revision); const results_id = pane.search_pane orelse return error.MissingPdfSearchResults; @@ -1915,7 +1915,7 @@ test "PDF n/N addresses and reveals distinct MuPDF hits on one page" { p.locations_config.context = 2; p.locations_config.tscontext = true; - _ = try pardes.look.runSearch(p, 0, "Pardes", .text, .top, true); + _ = try pardes.look.runSearch(p, 0, "Pardes", .top, true); const results_id = pane.search_pane orelse return error.MissingPdfSearchResults; const results = p.panes[results_id].?.file.?; var found: [3]bool = @splat(false); diff --git a/test/snapshots/builtins.snap b/test/snapshots/builtins.snap index 73509c24..cf367c5a 100644 --- a/test/snapshots/builtins.snap +++ b/test/snapshots/builtins.snap @@ -37,6 +37,29 @@ wheel up 110 50 wheel up 110 50 wheel up 110 50 wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 wait 10000 Look enter, right-click wait 10000 Exec tab, middle-click wait 10000 Filter diff --git a/test/snapshots/dump.golden b/test/snapshots/dump.golden index 571bacbc..72bb85a7 100644 --- a/test/snapshots/dump.golden +++ b/test/snapshots/dump.golden @@ -37,6 +37,7 @@ .collapsed = false, .serial = 1, .tag_tail = null, + .attached_to = null, .terminal = .{ .cwd = "/tmp/pardes-snap/dump/cwd", .shell = "", @@ -62,6 +63,7 @@ .collapsed = false, .serial = 2, .tag_tail = null, + .attached_to = null, .terminal = .{ .cwd = "/tmp/pardes-snap/dump/cwd", .shell = "", @@ -87,6 +89,7 @@ .collapsed = false, .serial = 3, .tag_tail = null, + .attached_to = null, .terminal = .{ .cwd = "/tmp/pardes-snap/dump/cwd", .shell = "", diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index 47480b83..e5c11193 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -2,91 +2,61 @@ | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del -| 1 Find SPC f -== snap armed grid=120x41 cursor=119,4 -|3: 1 Find Find -|4: Find / -== snap typing grid=120x41 cursor=119,3 -|3: 1 Find Find /zqm -|4: -== snap results grid=120x41 cursor=7,3 -|3: 1 Find -|5: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del -|6: 1 sub/ZQMARK-beta.txt -|7: 2 sub/nest/zqmark-gamma.txt -|8: 3 zqmark-alpha.txt -|9: 4 -== snap first grid=120x41 cursor=7,10 -|9: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Tty Collapse Del -|10: 1 beta body -== style first grid=120x41 -|0: 0-1 d,#1d2824, 2-119 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-119 #becfc4,#314738, -|2: 0-1 d,#496656, 2-27 #b2c3b8,#1d2824, 28-36 #d3b0d9,#1d2824, 37-119 #b2c3b8,#1d2824, -|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-119 d,#0d1410, -|5: 0-1 d,#496656, 2-27 #b2c3b8,#1d2824, 28-35 #d3b0d9,#1d2824, 36-119 #b2c3b8,#1d2824, -|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|9: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-47 #dfbce5,#314738, 48-119 #becfc4,#314738, -|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-119 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-119 d,#0d1410, -|12: 0-0 d,#608269, 1-119 d,#0d1410, -|13: 0-0 d,#608269, 1-119 d,#0d1410, -|14: 0-0 d,#608269, 1-119 d,#0d1410, -|15: 0-0 d,#608269, 1-119 d,#0d1410, -|16: 0-0 d,#608269, 1-119 d,#0d1410, -|17: 0-0 d,#608269, 1-119 d,#0d1410, -|18: 0-0 d,#608269, 1-119 d,#0d1410, -|19: 0-0 d,#608269, 1-119 d,#0d1410, -|20: 0-0 d,#608269, 1-119 d,#0d1410, -|21: 0-0 d,#608269, 1-119 d,#0d1410, -|22: 0-0 d,#608269, 1-119 d,#0d1410, -|23: 0-0 d,#608269, 1-119 d,#0d1410, -|24: 0-0 d,#608269, 1-119 d,#0d1410, -|25: 0-0 d,#608269, 1-119 d,#0d1410, -|26: 0-0 d,#608269, 1-119 d,#0d1410, -|27: 0-0 d,#608269, 1-119 d,#0d1410, -|28: 0-0 d,#608269, 1-119 d,#0d1410, -|29: 0-0 d,#608269, 1-119 d,#0d1410, -|30: 0-0 d,#608269, 1-119 d,#0d1410, -|31: 0-0 d,#608269, 1-119 d,#0d1410, -|32: 0-0 d,#608269, 1-119 d,#0d1410, -|33: 0-0 d,#608269, 1-119 d,#0d1410, -|34: 0-0 d,#608269, 1-119 d,#0d1410, -|35: 0-0 d,#608269, 1-119 d,#0d1410, -|36: 0-0 d,#608269, 1-119 d,#0d1410, -|37: 0-0 d,#608269, 1-119 d,#0d1410, -|38: 0-0 d,#608269, 1-119 d,#0d1410, -|39: 0-0 d,#608269, 1-119 d,#0d1410, -|40: 0-0 d,#608269, 1-119 d,#0d1410, -== snap second grid=120x41 cursor=7,13 -|12: /tmp/pardes-snap/find/cwd/sub/nest/zqmark-gamma.txt Save Tty Collapse Del -|13: 1 gamma body -== snap third grid=120x41 cursor=7,16 -|15: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Save Tty Collapse Del -|16: 1 alpha body -== snap back grid=120x41 cursor=7,13 -== snap word grid=120x41 cursor=7,13 -|3: 1 Find Find -|4: Find / -== snap cancel grid=120x41 cursor=7,7 -|3: 1 Find Find / -|4: -|13: 1 gamma body Last -== snap nomatch grid=120x41 cursor=7,3 -|3: 1 Find -|6: 1 -|7: -|8: -|13: 1 gamma body -== snap refit grid=120x41 cursor=7,3 -|6: 1 sub/ZQMARK-beta.txt -|7: 2 sub/nest/zqmark-gamma.txt -|8: 3 zqmark-alpha.txt -== snap topbar grid=120x41 cursor=12,16 -|6: 1 zqmark-alpha.txt -|7: 2 -|8: -|16: 1 alpha body Find +| 1 Find zqm SPC f +== snap armed grid=120x41 cursor=7,23 +|3: 1 Find zqm Find +|22: ^ +Search 1/5 Del +|23: Find +|24: here.txt +|25: other.txt +|26: sub/ZQMARK-beta.txt +|27: sub/nest/zqmark-gamma.txt +|28: zqmark-alpha.txt +|32: /tmp/pardes-snap/find/cwd/+Preview Del +|33: 1 +== snap typing grid=120x41 cursor=10,23 +|3: 1 Find zqm +|22: ^ +Search 1/3 Del +|23: Find zqm +|24: zqmark-alpha.txt +|25: sub/ZQMARK-beta.txt +|26: sub/nest/zqmark-gamma.txt +|27: +|28: +|32: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Del +|33: 1 alpha body +== snap next grid=120x41 cursor=10,23 +|22: ^ +Search 2/3 Del +|32: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Del +|33: 1 beta body +== snap promoted grid=120x41 cursor=7,33 +|22: +Search 2/3 Save Unattach Del +|32: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Tty Collapse Del +== snap nomatch grid=120x41 cursor=11,14 +|13: ^ +Search 0 Del +|14: Find zzqq +|22: +|23: /tmp/pardes-snap/find/cwd/+Preview Del +|24: 1 +|25: +|26: +== snap cancel grid=120x41 cursor=7,3 +|13: +|14: +|22: +Search 2/3 Save Unattach Del +|23: Find zqm +|24: zqmark-alpha.txt +|25: sub/ZQMARK-beta.txt +|26: sub/nest/zqmark-gamma.txt +== snap topbar grid=120x41 cursor=14,3 +|3: 1 Find zqm Find +|13: +Search 1/3 Del +|14: Find zqm +|15: zqmark-alpha.txt +|16: sub/ZQMARK-beta.txt +|17: sub/nest/zqmark-gamma.txt +|22: +|23: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Del +|24: 1 alpha body +|25: +|26: diff --git a/test/snapshots/find.snap b/test/snapshots/find.snap index b2e36973..17470040 100644 --- a/test/snapshots/find.snap +++ b/test/snapshots/find.snap @@ -1,19 +1,18 @@ -# The Find builtin (SPC f f) = `fd`, in-core: it arms the SAME tag input `/` -# does, but Enter walks the pane's DIRECTORY instead of its text and writes one -# matching path per row into a "+Search" OUTPUT BUFFER. Every row is therefore -# an ordinary look target, which is the whole point: n/N SELECT the next/prev -# one with no code of their own, and the look chord — Enter, the same one that -# opens a path anywhere else — is what OPENS it. Focus then follows the file -# that opened, but the look was made FROM the results buffer, so the next n -# resumes stepping that same list. Where each pane lands is acme's placement -# (docs/typ/guide.typ, where new panes go): under the text of the pane with the -# most blank rows. The walk skips .git, matches the NAME -# case-insensitively, and sorts (readdir order is not stable). `SPC f s` is -# Save, which moved out of `w` to make this group. +# SPC f f: a query pane under the pane (Query.zig), line 1 `Find `, typed +# into. The files below the pane's directory are listed once, on the disk +# engine's worker (rg --files when it is on PATH, else the sorted walk: both +# pass over .git), and each key scores them fuzzily (pick's scorer), the best +# first, the matched letters tinted. The current one is shown in the +# +Preview under the query pane, born with it so nothing moves later; +# Ctrl-n / Ctrl-p step it, never the pointer. Enter makes the preview the +# file's pane where it stands. Esc while typing closes the query pane and +# gives its rows back. A query that matches nothing is a count of 0, not an +# exit. B2 on `Find` with a selection asks with that word, the keyboard +# staying in the text. dirmk sub dirmk sub/nest dirmk .git -file here.txt Find +file here.txt Find zqm file zqmark-alpha.txt alpha body file sub/ZQMARK-beta.txt beta body file sub/nest/zqmark-gamma.txt gamma body @@ -22,108 +21,51 @@ file .git/zqmark-hidden.txt hidden body start 41 120 here.txt wait 8000 here.txt stable 700 20000 -# SPC f is a GROUP now (Find + New + Save): the indicator stays on the tag +# SPC f is a group (Find, New, Save, Recent, Grep): the indicator waits key space key f stable 400 5000 snap group -# ... and the second f arms the input, marker visible in the tag +# the second f opens the query pane: every file listed, line 1 `Find ` key f -stable 400 5000 +wait 10000 zqmark-alpha.txt +stable 700 15000 snap armed text zqm -stable 400 5000 -snap typing -# Enter walks: three hits, sorted, .git's copy skipped, other.txt not matched -key enter -wait 10000 zqmark-alpha.txt stable 700 15000 -snap results -# n SELECTS row 1 and Enter looks it — a path, so the file OPENS, under the -# list's text, and each file after it under the one before. -key space j n -key enter +snap typing +# the next one current, its text in the preview +key c-n wait 10000 beta body stable 700 15000 -snap first -snapstyle first -key space j n -key enter -wait 10000 gamma body -stable 700 15000 -snap second -key space j n -key enter -wait 10000 alpha body -stable 700 15000 -snap third -# N walks back up one row; Enter looks it, and the file is already open, so -# the look just focuses it -key space j p +snap next +# Enter: the preview is that file's pane now, where it stood key enter stable 700 15000 -snap back -# executing the WORD Find (middle-click in a body) arms the same input — the -# enum IS the dispatch — and Esc abandons it. The input is its own line, so an -# abandoned one leaves nothing behind in the tag -press middle 8 4 -release middle 8 4 -stable 700 10000 -snap word -key esc -settle 100 -stable 400 5000 -snap cancel -# every search is asked from a PANE, and both a look and now a step leave you -# somewhere else — so click back into here.txt first. That is not bookkeeping: -# a search never refills the buffer it was asked FROM (fillResults skips it), -# so `owned by here.txt` is the whole premise of the two steps below. +snap promoted +# a second Find from here.txt reuses its query pane; nothing found is 0 press left 8 4 release left 8 4 stable 400 5000 -# a no-match walk opens an empty list of its own, under the last file's text. key space key f key f text zzqq -key enter -stable 700 10000 -# n does not stop on the empty list, because the walk is a RING across panes -# rather than one buffer's rows: with nothing look-able here it carries on -# into the list that DOES have some — the zqm one — and resumes it one row -# past where the N above left it. Nothing opens; only the selection moved. -key space j n -stable 400 5000 +stable 700 15000 snap nomatch -# ... and asking for `zqm` AGAIN re-arms the list it ALREADY filled instead of -# stacking an identical twin under the empty one — even though the step above -# left the cursor sitting in the zqm list, so the reuse is by what a buffer -# HOLDS (this search, this pattern, this directory), not by which one anything -# happens to point at. Asked from here.txt again (the click, as above), and -# the LIST it rewrites is therefore the `nomatch` frame unchanged, down to the -# byte — only the cursor comes back with it. -press left 8 4 -release left 8 4 -stable 400 5000 -key space -key f -key f -text zqm -key enter -wait 10000 zqmark-alpha.txt +# Esc: the kept rows of the last query are back +key esc +settle 100 stable 700 15000 -snap refit -# Find is a TOPBAR word too: the same -# builtin the leader path runs, reached with the mouse. Chorded — a selection -# held when it runs IS the argument — so dragging over `alpha` and clicking -# Find walks for that name with nothing typed and no input armed. Row 17 is -# `alpha body`: the three found files stack in the order the looks above -# OPENED them, which is beta, gamma, alpha down the column. -press left 8 17 -drag left 13 17 -release left 13 17 +snap cancel +# B2 on Find with `zqm` selected in here.txt: the query pane under it, the +# keyboard still in here.txt +press left 13 4 +drag left 15 4 +release left 15 4 stable 400 5000 press middle @Find 1 release middle @Find 1 +wait 10000 Find zqm stable 700 15000 snap topbar diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index 62c37c25..5de12bab 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -19,78 +19,69 @@ | /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls | g.txt -== snap typing grid=180x31 cursor=89,7 -|7: 1 l1 /MARK -== snap results grid=180x31 cursor=10,8 -|7: 1 l1 -|21: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse LocationsConfig Del -|22: 1 g.txt:2:1-4 -|23: 2 MARK a -|24: 3 g.txt:6:1-4 -|25: 4 MARK b -|26: 5 g.txt:10:1-4 -|27: 6 MARK c -|28: 7 -== style results grid=180x31 +== snap slash grid=180x31 cursor=3,10 +|9: ^ +Search 0 Del +|10: / +|11: +|12: +|13: +|14: +|15: +|16: +== snap typing grid=180x31 cursor=7,10 +|9: ^ +Search 1/3 Del +|10: /MARK +|11: 2 MARK a +|12: 6 MARK b +|13: 10 MARK c +== style typing grid=180x31 |0: 0-1 d,#1d2824, 2-179 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-89 #becfc4,#314738, 90-91 #becfc4,#887455, 92-179 #b2c3b8,#1d2824, |2: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-89 #b2c3b8,#1d2824, 90-91 #b2c3b8,#496656, 92-120 #b2c3b8,#1d2824, 121-129 #d3b0d9,#1d2824, 130-179 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|6: 0-1 d,#add38a, 2-30 #becfc4,#314738, 31-36 #dfbce5,#314738, 37-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|6: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-36 #d3b0d9,#1d2824, 37-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, +|7: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|8: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|9: 0-1 #000000,#add38a, 2-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-12 #f7e4a5,#5e4923, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-12 #f7e4a5,#352e19, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-8 #59675c,#0d1410, 9-12 #f7e4a5,#352e19, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|15: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|16: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, |17: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|21: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-38 #d3b0d9,#1d2824, 39-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, -|22: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, -|23: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-11 #f7e4a5,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, -|25: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-11 #f7e4a5,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|26: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, -|27: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-11 #f7e4a5,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|28: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, +|21: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|22: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|23: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|24: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|25: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|26: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|27: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|28: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, |29: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, |30: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -== snap second grid=180x31 cursor=10,12 -== snap third grid=180x31 cursor=10,12 +== snap ctrln grid=180x31 cursor=7,10 |7: 5 l5 |8: 6 MARK b -|9: 7 l7 -|10: 8 l8 -|11: 9 l9 -|12: 10 MARK c -|13: 11 l11 -|14: 12 l12 -|15: -|16: -== snap back grid=180x31 cursor=10,12 -|7: 1 l1 -|8: 2 MARK a -|9: 3 l3 -|10: 4 l4 -|11: 5 l5 -|12: 6 MARK b -|13: 7 l7 -|14: 8 l8 -|15: 9 l9 -|16: 10 MARK c -== snap cancel grid=180x31 cursor=10,12 -== snap nomatch grid=180x31 cursor=7,26 -|11: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse LocationsConfig Del -|12: 1 +|9: ^ +Search 2/3 Del +== snap landed grid=180x31 cursor=10,8 +|9: +Search 2/3 Save Unattach Del +== snap n grid=180x31 cursor=10,8 +|7: 9 l9 +|8: 10 MARK c +== snap N grid=180x31 cursor=10,7 +|7: 6 MARK b +|8: 7 l7 +== snap cancel grid=180x31 cursor=10,7 +== snap nomatch grid=180x31 cursor=7,10 +|9: ^ +Search 0 Del +|10: /zzqq +|11: +|12: |13: -|14: -|15: -|16: diff --git a/test/snapshots/fsearch.snap b/test/snapshots/fsearch.snap index 431e7126..fbb9baeb 100644 --- a/test/snapshots/fsearch.snap +++ b/test/snapshots/fsearch.snap @@ -1,13 +1,13 @@ -# `/` file search: the pattern types into the tag (persistent, no popup); -# Enter searches the buffer in-core and writes `path:LINE:COL-ENDCOL text` into -# a +Search OUTPUT BUFFER (a file pane with no file behind it — no Save in its -# tag) — AND GOES TO THE FIRST HIT, which is the step `n` is and the look Enter -# is, run for you in that buffer. From there n/N SELECT the next/prev row and -# open nothing, and Enter — the look chord — is what scrolls the file pane to -# the hit AND SELECTS IT: the row names the match's whole span, not just where -# it starts. Esc abandons the input; a no-match search opens an EMPTY buffer -# (every search gets its own, stacked under the pane) with nothing in it for n -# to stop on, and goes nowhere. +# `/` in a file: its query pane under it (Query.zig), line 1 `/` and the +# pattern, typed into; nothing on the notice band. Each key searches the +# file again (a regex, any case unless it has a capital): every match is +# tinted and ticked on the scroll rail, the first at or after the cursor +# selected and in view, and the rows under line 1 are the lines holding a +# match, a line number in the gutter. Ctrl-n steps while typing; Enter puts +# the keyboard on the match, the pattern in `/`, and keeps the rows as text; +# n / N then step the matches in the file, round the end without a word. A +# later `/` reuses the pane; Esc while typing brings the kept rows back. A +# pattern that matches nothing is a count of 0, not an exit. file g.txt l1\nMARK a\nl3\nl4\nl5\nMARK b\nl7\nl8\nl9\nMARK c\nl11\nl12 # Builtins announce themselves by default, and an announcement is a band at # the top of the body -- which moves every row this script clicks. What the @@ -30,51 +30,32 @@ release right 6 9 wait 10000 MARK a stable 700 15000 snap opened -# / starts the search input in the tag; the pattern is visible while typing key / stable 400 5000 +snap slash text MARK stable 400 5000 snap typing +snapstyle typing +key c-n +stable 400 5000 +snap ctrln key enter -# Locations stack the target under its line now, so the two halves are -# two rows: wait for both rather than for one joined line. -wait 10000 g.txt:2:1-4 -wait 10000 MARK a stable 700 10000 -# ...and the submit already looked result 1: the file scrolled to line 2 and -# the four cells the pattern matched there came up selected — the styles below -# are what prove the second half of that. No `n` was pressed to get here. -snap results -snapstyle results -# n/N walk on from there, one row of the list per press, Enter looking what -# the step selected -key space j n -key enter -stable 700 15000 -snap second -key space j n -key enter -stable 700 15000 -snap third -# N walks back up to result 2 (line 6), Enter looks it -key space j p -key enter -stable 700 15000 -snap back -# Esc abandons the input: the tag tail is restored +snap landed +text n +stable 400 5000 +snap n +text N +stable 400 5000 +snap N key / text zz key esc settle 100 stable 400 5000 snap cancel -# a no-match search: nothing in the empty list for n to stop on, so the ring -# carries it back into the list that has rows and it resumes there key / text zzqq -key enter stable 700 10000 -key space j n -stable 400 5000 snap nomatch diff --git a/test/snapshots/grep.golden b/test/snapshots/grep.golden index 957096c3..6dbe19fa 100644 --- a/test/snapshots/grep.golden +++ b/test/snapshots/grep.golden @@ -19,22 +19,28 @@ | /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del | ls | a.txt noise.txt sub -== snap typing grid=180x31 cursor=89,7 -|7: 1 hello TARGET one Grep /TARGET -== snap results grid=180x31 cursor=7,7 -|7: 1 hello TARGET one -|21: /tmp/pardes-snap/grep/cwd/+Search Save Tty Collapse LocationsConfig Del -|22: 1 a.txt:1:7-12 hello TARGET one -|23: 2 a.txt:3:6-11 last TARGET line -|24: 3 sub/b.txt:2:1-6 TARGET inside sub -|25: 4 -== snap first grid=180x31 cursor=18,7 -== snap opened-hit grid=180x31 cursor=12,12 -|10: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Tty Collapse Del -|11: 1 deep -|12: 2 TARGET inside sub -== snap nomatch grid=180x31 cursor=2,4 -|25: /tmp/pardes-snap/grep/cwd/sub/+Search Save Tty Collapse LocationsConfig Del -|26: 1 -== snap chordsel grid=180x31 cursor=19,7 -== snap chord grid=180x31 cursor=19,7 +== snap typing grid=180x31 cursor=13,10 +|9: ^ +Search 1/3 Del +|10: Grep TARGET +|11: a.txt +|12: 1 hello TARGET one +|13: /tmp/pardes-snap/grep/cwd/+Preview Del +|14: 1 +== snap second grid=180x31 cursor=13,10 +|7: 2 nothing here +|8: 3 last TARGET line +|9: ^ +Search 2/3 Del +== snap preview grid=180x31 cursor=13,10 +|9: ^ +Search 3/3 Del +|13: /tmp/pardes-snap/grep/cwd/sub/b.txt Del +|14: 1 deep +|15: 2 TARGET inside sub +== snap opened-hit grid=180x31 cursor=12,15 +|9: +Search 3/3 Save Unattach Del +|13: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Tty Collapse Del +== snap nomatch grid=180x31 cursor=11,15 +|14: ^ +Search 0 Del +|15: Grep zzqq +== snap esc grid=180x31 cursor=12,15 +|14: 1 deep +|15: 2 TARGET inside sub diff --git a/test/snapshots/grep.snap b/test/snapshots/grep.snap index b3ce2947..16e61d20 100644 --- a/test/snapshots/grep.snap +++ b/test/snapshots/grep.snap @@ -1,31 +1,20 @@ -# The Grep builtin (topbar word, `SPC f g`): `grep -R`, in-core. It arms the -# SAME tag input `/` and Find use, but the walk reads file CONTENTS under every -# pane's directory at once — minus any directory another pane's already -# contains, so a tree two panes sit in is searched ONCE and every hit appears -# once. A row is `path:LINE:COL-ENDCOL text` — the match's whole span, so -# looking it SELECTS the hit — with the path RELATIVE to the directory -# of the pane that asked — the same directory its results buffer is named in, -# so the short name resolves; only a hit from outside that tree stays absolute. -# n/N SELECT the next/prev row like any other result list and open nothing — -# one press per row, the location at its head, never the matched text after it; -# Enter looks what they leave selected, and a row pointing into a file nothing -# has open yet opens it. +# The Grep builtin (topbar word, `SPC f g`): the query pane under the pane +# that asked, line 1 `Grep ` and the text, the lines of the files below its +# directory holding it (literally, any case unless it has a capital), on the +# disk engine's worker once the typing pauses: rg --json when it is on PATH, +# else the sorted walk. The rows sit under their file's name, a line number +# in the gutter. A hit in a file an open pane shows is shown there; one in a +# file nothing shows, in the +Preview under the query pane, which Enter makes +# the file's pane. A query that matches nothing is a count of 0, and Esc +# while typing brings the kept rows back. dirmk sub file a.txt hello TARGET one\nnothing here\nlast TARGET line file sub/b.txt deep\nTARGET inside sub file noise.txt nothing to see -# Builtins announce themselves by default, and an announcement is a band at -# the top of the body -- which moves every row this script clicks. What the -# verbs do is what is under test, not the announcement. config Verbose off -# The stacked layout spends two rows on each hit, which puts the third one -# below the fold of this results pane; the claim here is which hits there are. -config LocationsConfig layout:inline start 31 180 -n 3 wait 8000 a.txt stable 700 20000 -# open a.txt: a SECOND pane, whose directory the shell's cwd already covers — -# its root is dropped, which is what keeps the hits below un-duplicated press left 5 9 release left 5 9 stable 400 5000 @@ -39,70 +28,34 @@ release right 6 9 wait 10000 hello TARGET stable 700 15000 snap opened -# middle-click Grep on the topbar: the input -# arms on the ACTIVE pane's tag, exactly where `/` would have typed +# middle-click Grep on the topbar: the query pane under a.txt, typed into press middle @Grep 1 release middle @Grep 1 stable 400 5000 text TARGET -stable 400 5000 -snap typing -# Enter walks: two hits in a.txt, one in sub/b.txt, sorted by path — and the -# file that holds none of them contributes no row. -key enter -wait 10000 sub/b.txt:2:1 +# three lines (the pane is short: its count says how many) +wait 10000 +Search 1/3 stable 700 15000 -snap results -# n selects the first row and Enter looks it: absolute path, line 1, columns -# 7..12 (`TARGET`), and those six cells come up selected -key space j n -key enter +snap typing +# a.txt's hits are shown in a.txt; sub/b.txt's in the preview +key c-n stable 700 15000 -snap first -# ...and stepping on into sub/b.txt, then looking it, opens the file nothing -# had open -key space j n -key enter +snap second +key c-n +wait 10000 deep stable 700 15000 -key space j n +snap preview key enter -wait 10000 TARGET inside sub stable 700 15000 snap opened-hit -# a pattern nothing holds: an empty list of its own, with nothing in it for n -# to stop on — so the ring carries that step out of it and on round. It lands -# in the SHELL, whose `ls` row is free text and steps word by word: the TARGET -# list is standing on its last row, and a row-grained walk has nothing left in -# it to offer. The look above is why these read the way they do: it left the -# cursor in sub/b.txt, so the empty list is named in sub/ rather than cwd/, and -# it left the hit SELECTED there (a ranged result row is one a look selects). -# Armed from the LEADER, not the topbar word, because of that selection: a -# topbar execute chords whatever is selected into its argument, so a -# middle-click here would run `Grep TARGET` and never ask for a pattern at -# all. The leader path runs the builtin with no argument, which is what this -# step is about; the chord itself is the last two snaps below. key space key f key g stable 400 5000 text zzqq -key enter stable 700 10000 -key space j n -stable 400 5000 snap nomatch -# the acme chord: a builtin executed with a SELECTION held takes it as the -# argument, so dragging over `TARGET` in a.txt and then clicking Grep runs the -# walk on that word at once — no tag input, nothing typed. TARGET already has -# a list open from above, so this refills THAT one; only the zzqq list below is -# a second buffer, because only it is a different search. -press left @TARGET 8 -drag left @TARGET+6 8 -release left @TARGET+6 8 +key esc +settle 100 stable 400 5000 -snap chordsel -press middle @Grep 1 -release middle @Grep 1 -wait 10000 sub/b.txt:2:1 -stable 700 15000 -snap chord +snap esc diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index 4a286faa..86a4b0ac 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -68,28 +68,31 @@ |12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-149 #f5f7ee,#3c614a, |16: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-149 #f5f7ee,#0d1410, -== snap hit1 grid=150x31 cursor=15,14 -|17: /tmp/pardes-snap/lookrange/cwd/+Search Save Tty Collapse LocationsConfig Del -|18: 1 r.txt:7:4-9 -|19: 2 gg NEEDLE gg -|20: 3 r.txt:8:6-11 -|21: 4 hhhh NEEDLE -|22: 5 +== snap hit1 grid=150x31 cursor=17,15 +|21: +Search 2/2 Save Unattach Del +|22: /NEEDLE +|23: 7 gg NEEDLE gg +|24: 8 hhhh NEEDLE == style hit1 grid=150x31 -|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-16 #f5f7ee,#0d1410, 17-149 #e5eee5,#0d1410, -|15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-40 #d3b0d9,#1d2824, 41-149 #b2c3b8,#1d2824, -|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #f7e4a5,#5e4923, 16-16 #f7e4a5,#0d1410, 17-149 #e5eee5,#0d1410, -|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|21: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#5e4923, 18-149 #f7e4a5,#0d1410, -|22: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -== snap hit2 grid=150x31 cursor=17,15 -== style hit2 grid=150x31 -|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 #f5f7ee,#0d1410, -== snap back grid=150x31 cursor=15,14 -== style back grid=150x31 +|16: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|18: 0-0 d,#e5eee5, 1-149 d,#0d1410, +|21: 0-1 d,#496656, 2-149 #b2c3b8,#1d2824, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#352e19, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#3c614a, 6-149 #f5f7ee,#3c614a, +== snap hit2 grid=150x31 cursor=15,14 +== style hit2 grid=150x31 |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-16 #f5f7ee,#0d1410, 17-149 #e5eee5,#0d1410, -|15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-17 #e5eee5,#352e19, 18-149 #e5eee5,#0d1410, +|16: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|18: 0-0 d,#5e4923, 1-149 d,#0d1410, +|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#5e4923, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, +== snap back grid=150x31 cursor=17,15 +== style back grid=150x31 +|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 #f5f7ee,#0d1410, +|16: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|18: 0-0 d,#e5eee5, 1-149 d,#0d1410, +|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#352e19, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, diff --git a/test/snapshots/lookrange.snap b/test/snapshots/lookrange.snap index eb1db60a..5133e911 100644 --- a/test/snapshots/lookrange.snap +++ b/test/snapshots/lookrange.snap @@ -51,28 +51,24 @@ release right 12 7 stable 700 15000 snap stale snapstyle stale -# --- and now the first consumer. The look above left r.txt focused, so `/` -# arms on it: the rows it writes carry the match's span, and the submit goes -# straight to the first of them — with the word itself selected, which is the -# whole reason the row spells a range and not a position. +# --- and `/`: its query pane under r.txt, line 1 the pattern, the lines +# holding it as rows (a line number in the gutter, the match tinted); Enter +# puts the keyboard on the match after the cursor, the word itself selected. key / text NEEDLE -key enter -# Locations stack the target under its line now: two rows, two waits. -wait 10000 r.txt:7:4-9 wait 10000 gg NEEDLE gg stable 700 15000 +key enter +stable 700 15000 snap hit1 snapstyle hit1 -# n selects the next row, and the Enter after it goes to that hit -key space j n -key enter +# n: the next match in the text, selected +text n stable 700 15000 snap hit2 snapstyle hit2 -# N walks back onto the first hit; Enter looks it, still selected -key space j p -key enter +# N walks back onto the first, still selected +text N stable 700 15000 snap back snapstyle back diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index c9fad7b7..18ccd775 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -15,15 +15,16 @@ | 3 a + b | 4 } | 5 -== snap gr-list grid=100x25 cursor=21,6 +== snap gr-list grid=100x25 cursor=7,14 |3: 1 mod lib; -|15: /tmp/pardes-snap/lsp-client/cwd/+Search Save Tty Collapse LocationsConfig Del -|16: 1 lib.rs:2:8-10 -|17: 2 pub fn add(a: i32, b: i32) -> i32 { -|18: 3 main.rs:4:13-15 -|19: 4 let x = add(1, 2); -|20: 5 main.rs:5:13-15 -|21: 6 let y = add(3, 4); -|22: 7 -== snap gr-opened grid=100x25 cursor=21,7 -== snap gr-back grid=100x25 cursor=21,6 +|13: ^ +Search 1/3 Del +|14: Refs +|15: lib.rs +|16: 2 pub fn add(a: i32, b: i32) -> i32 { +|17: main.rs +|18: 4 let x = add(1, 2); +|19: /tmp/pardes-snap/lsp-client/cwd/+Preview Del +|20: 1 +== snap gr-opened grid=100x25 cursor=21,6 +|13: +Search 2/3 Save Unattach Del +== snap gr-back grid=100x25 cursor=21,7 diff --git a/test/snapshots/lsp-client.snap b/test/snapshots/lsp-client.snap index db94525e..d9827a2a 100644 --- a/test/snapshots/lsp-client.snap +++ b/test/snapshots/lsp-client.snap @@ -6,7 +6,8 @@ # gd on a cross-file Location -> a look: lib.rs opens with `add` selected, # and the message row still carries the server's settled state # ("lsp lspmock: ready") because nothing has cleared it yet. -# gr -> sorted rows, selecting the next occurrence; n/N continue there. +# gr -> the text's query pane, line 1 `Refs`, rows under their files, +# the next occurrence current; n/N step the places in the text. file main.rs mod lib;\n\nfn main() {\n let x = add(1, 2);\n let y = add(3, 4);\n let _ = x + y;\n}\n file lib.rs // mock fixture\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n start 25 100 main.rs @@ -26,12 +27,12 @@ key r wait 10000 add(3, 4) stable 700 15000 snap gr-list -# step from the selected middle row to the last hit, then return -key space j n +# Ctrl-n on line 1 steps to the next hit, Enter lands there; N in the text +# goes back to the one before, round the places in main.rs +key c-n key enter stable 700 15000 snap gr-opened -key space j p -key enter +text N stable 700 15000 snap gr-back diff --git a/test/snapshots/lspdebug.snap b/test/snapshots/lspdebug.snap index ec8d136d..22fa097b 100644 --- a/test/snapshots/lspdebug.snap +++ b/test/snapshots/lspdebug.snap @@ -39,11 +39,8 @@ text client queries key enter wait 10000 client queries wait 10000 definition -# the report sits between the source and the results, so Del asks where its -# rows go: k, back to the source above -key space d -key k -key space w j enter +# Enter left the keyboard in the report, on the match; its query pane is +# attached to it, so one Del closes both, their rows back to the source key space d stable 700 15000 snap report-closed diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index d961d6bd..59a3c5d0 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,4 +1,4 @@ -== snap absrow grid=100x35 cursor=21,16 +== snap absrow grid=100x35 cursor=7,17 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse TreeContext Def Refs Del @@ -9,56 +9,70 @@ | 5 | 6 }; | 7 } -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse LocationsConfig Del -| 1 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:1:11-15 -| 2 pub const Shade = enum { -| 3 parent.zig:3:22-26 -| 4 pub fn pick(s: shade.Shade) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse TreeContext Def Refs Del -| 1 pub const Shade = enum { -| 2 verdigris, -| 3 cinnabar, -| 4 }; -| 5 -== snap abslook grid=100x35 cursor=32,5 +| 8 +| +| +| +| +| +|^ +Search 2/2 Del +| Refs +| /tmp/pardes-snap/lsprelpath/cwd/shade.zig +| 1 pub const Shade = enum { +| parent.zig +| 3 pub fn pick(s: shade.Shade) u8 { +| +| +| +| +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Preview Del +| 1 +== snap abslook grid=100x35 cursor=21,27 |3: 1 const shade = @import("../shade.zig"); +|16: +Search 1/2 Save Unattach Del +|26: /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse TreeContext Def Refs Del +|27: 1 pub const Shade = enum { +|28: 2 verdigris, +|29: 3 cinnabar, +|30: 4 }; +|31: 5 == style abslook grid=100x35 |0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-37 #becfc4,#314738, 38-48 #dfbce5,#314738, 49-99 #becfc4,#314738, +|2: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-48 #d3b0d9,#1d2824, 49-99 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-27 #c9a7ed,#0d1410, 28-28 #e5eee5,#0d1410, 29-42 #b8d88a,#0d1410, 43-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f5f7ee,#3c614a, 33-99 #e5eee5,#0d1410, -|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f5f7ee,#3c614a, 33-99 #e5eee5,#0d1410, +|6: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|10: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-45 #d3b0d9,#1d2824, 46-99 #b2c3b8,#1d2824, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-21 #f7e4a5,#5e4923, 22-22 #f7e4a5,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, -|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f7e4a5,#5e4923, 33-99 #e5eee5,#0d1410, -|15: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-43 #d3b0d9,#1d2824, 44-99 #b2c3b8,#1d2824, -|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-21 #f5f7ee,#3c614a, 22-22 #f5f7ee,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, -|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|21: 0-0 d,#608269, 1-99 d,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|11: 0-0 d,#608269, 1-99 d,#0d1410, +|12: 0-0 d,#608269, 1-99 d,#0d1410, +|13: 0-0 d,#608269, 1-99 d,#0d1410, +|14: 0-0 d,#608269, 1-99 d,#0d1410, +|15: 0-0 d,#608269, 1-99 d,#0d1410, +|16: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-20 #e5eee5,#0d1410, 21-25 #f7e4a5,#5e4923, 26-26 #f7e4a5,#0d1410, 27-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-31 #e5eee5,#0d1410, 32-36 #f7e4a5,#5e4923, 37-99 #e5eee5,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, |23: 0-0 d,#608269, 1-99 d,#0d1410, |24: 0-0 d,#608269, 1-99 d,#0d1410, |25: 0-0 d,#608269, 1-99 d,#0d1410, -|26: 0-0 d,#608269, 1-99 d,#0d1410, -|27: 0-0 d,#608269, 1-99 d,#0d1410, -|28: 0-0 d,#608269, 1-99 d,#0d1410, -|29: 0-0 d,#608269, 1-99 d,#0d1410, -|30: 0-0 d,#608269, 1-99 d,#0d1410, -|31: 0-0 d,#608269, 1-99 d,#0d1410, +|26: 0-1 d,#add38a, 2-33 #becfc4,#314738, 34-43 #dfbce5,#314738, 44-99 #becfc4,#314738, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-16 #e5eee5,#0d1410, 17-21 #f5f7ee,#3c614a, 22-22 #f5f7ee,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|31: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |32: 0-0 d,#608269, 1-99 d,#0d1410, |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, -== snap subrow grid=100x35 cursor=20,16 +== snap subrow grid=100x35 cursor=7,17 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse TreeContext Def Refs Del @@ -69,53 +83,67 @@ | 5 | 6 }; | 7 } -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse LocationsConfig Del -| 1 inner/tint.zig:1:11-14 -| 2 pub const Tint = enum { -| 3 subdir.zig:3:20-23 -| 4 pub fn hue(t: tint.Tint) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse TreeContext Def Refs Del -| 1 pub const Tint = enum { -| 2 ochre, -| 3 indigo, -| 4 }; -| 5 -== snap sublook grid=100x35 cursor=29,5 +| 8 +| +| +| +| +| +|^ +Search 2/2 Del +| Refs +| inner/tint.zig +| 1 pub const Tint = enum { +| subdir.zig +| 3 pub fn hue(t: tint.Tint) u8 { +| +| +| +| +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Preview Del +| 1 +== snap sublook grid=100x35 cursor=20,27 |3: 1 const tint = @import("inner/tint.zig"); +|16: +Search 1/2 Save Unattach Del +|26: /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse TreeContext Def Refs Del +|27: 1 pub const Tint = enum { +|28: 2 ochre, +|29: 3 indigo, +|30: 4 }; +|31: 5 == style sublook grid=100x35 |0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-37 #becfc4,#314738, 38-48 #dfbce5,#314738, 49-99 #becfc4,#314738, +|2: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-48 #d3b0d9,#1d2824, 49-99 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-26 #c9a7ed,#0d1410, 27-27 #e5eee5,#0d1410, 28-43 #b8d88a,#0d1410, 44-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f5f7ee,#3c614a, 30-99 #e5eee5,#0d1410, -|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f5f7ee,#3c614a, 30-99 #e5eee5,#0d1410, +|6: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|10: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-45 #d3b0d9,#1d2824, 46-99 #b2c3b8,#1d2824, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-20 #f7e4a5,#5e4923, 21-21 #f7e4a5,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, -|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f7e4a5,#5e4923, 30-99 #e5eee5,#0d1410, -|15: 0-1 d,#496656, 2-43 #b2c3b8,#1d2824, 44-52 #d3b0d9,#1d2824, 53-99 #b2c3b8,#1d2824, -|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-20 #f5f7ee,#3c614a, 21-21 #f5f7ee,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, -|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|21: 0-0 d,#608269, 1-99 d,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|11: 0-0 d,#608269, 1-99 d,#0d1410, +|12: 0-0 d,#608269, 1-99 d,#0d1410, +|13: 0-0 d,#608269, 1-99 d,#0d1410, +|14: 0-0 d,#608269, 1-99 d,#0d1410, +|15: 0-0 d,#608269, 1-99 d,#0d1410, +|16: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-20 #e5eee5,#0d1410, 21-24 #f7e4a5,#5e4923, 25-25 #f7e4a5,#0d1410, 26-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-29 #e5eee5,#0d1410, 30-33 #f7e4a5,#5e4923, 34-99 #e5eee5,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, |23: 0-0 d,#608269, 1-99 d,#0d1410, |24: 0-0 d,#608269, 1-99 d,#0d1410, |25: 0-0 d,#608269, 1-99 d,#0d1410, -|26: 0-0 d,#608269, 1-99 d,#0d1410, -|27: 0-0 d,#608269, 1-99 d,#0d1410, -|28: 0-0 d,#608269, 1-99 d,#0d1410, -|29: 0-0 d,#608269, 1-99 d,#0d1410, -|30: 0-0 d,#608269, 1-99 d,#0d1410, -|31: 0-0 d,#608269, 1-99 d,#0d1410, +|26: 0-1 d,#add38a, 2-43 #becfc4,#314738, 44-52 #dfbce5,#314738, 53-99 #becfc4,#314738, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-16 #e5eee5,#0d1410, 17-20 #f5f7ee,#3c614a, 21-21 #f5f7ee,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|31: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |32: 0-0 d,#608269, 1-99 d,#0d1410, |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, -== snap clicked grid=100x35 cursor=15,12 +== snap clicked grid=100x35 cursor=29,5 diff --git a/test/snapshots/lsprelpath.snap b/test/snapshots/lsprelpath.snap index a83abf46..8420e134 100644 --- a/test/snapshots/lsprelpath.snap +++ b/test/snapshots/lsprelpath.snap @@ -8,7 +8,8 @@ # short to be called. # # A row in the SAME directory shortens to a bare basename; the two that a -# prefix strip can actually get wrong are here, one app each, as `gr` rows: +# prefix strip can actually get wrong are here, one app each, as `gr` rows +# (the file headers of the asking text's query pane, line 1 `Refs`): # # PARENT the enum is one level UP from the asking file, so nothing is # stripped and the row carries `/tmp/.../cwd/shade.zig`. This is @@ -32,26 +33,25 @@ file sub/subdir.zig const tint = @import("inner/tint.zig");\n\npub fn hue(t: tin start 35 100 sub/parent.zig wait 8000 fn pick stable 700 20000 -# `gr` on `Shade` in the signature (file line 3, click row 6): its -# declaration's row is in the parent directory. press left 31 6 release left 31 6 stable 400 5000 key g key r -wait 15000 cwd/shade.zig:1: +# the query pane under parent.zig, line 1 `Refs`, the rows under each file: +# shade.zig's spelled whole, its directory being above +wait 15000 cwd/shade.zig stable 700 15000 snap absrow -key esc -settle 100 -# An absolute row has to keep resolving — it is the spelling every row had -# before this, and the one every hit outside the tree still has. -key space j n +# the current row is parent.zig's own; the one before it is shade.zig's, +# shown in the +Preview, which Enter makes shade.zig's pane +key c-p +wait 10000 verdigris +stable 700 15000 key enter stable 700 15000 snap abslook snapstyle abslook -# ---- SUBDIRECTORY: under it, so the strip leaves `inner/tint.zig` ---- start 35 100 sub/subdir.zig wait 8000 fn hue stable 700 20000 @@ -60,23 +60,16 @@ release left 29 6 stable 400 5000 key g key r -wait 15000 inner/tint.zig:1: +wait 15000 inner/tint.zig stable 700 15000 snap subrow -key esc -settle 100 -key space j n +key c-p +wait 10000 ochre +stable 700 15000 key enter stable 700 15000 snap sublook snapstyle sublook -# The mouse spelling, on the OTHER row (grid row 12, 1-based click row 13). A -# right click expands to the file-ish word under the cursor -# (config.wordBounds), which has to take `inner/tint.zig:3:5-10` WHOLE — the -# separator inside a stripped path is a file char, so the scan runs back over -# `inner/` and stops on the space of the line-number prefix. A look focuses -# what it opens, so the header's cursor is the assertion: the end of `indigo` -# on line 3 of tint.zig. press right 12 13 release right 12 13 stable 700 15000 diff --git a/test/snapshots/msg.golden b/test/snapshots/msg.golden index 24018546..950c4d67 100644 --- a/test/snapshots/msg.golden +++ b/test/snapshots/msg.golden @@ -37,10 +37,10 @@ |8: |9: == snap prompt grid=70x17 cursor=69,3 -|3: 1 EXTERNAL /EXT +|3: 1 EXTERNAL Select /EXT == snap prompt-wins grid=70x17 cursor=69,4 |3: 1 AGAIN --:--:-- reloaded /tmp/pardes-snap/msg/cwd/a.txt -|4: 2 /EXT +|4: 2 Select /EXT == snap esc grid=70x17 cursor=7,4 |3: 1 AGAIN |4: 2 diff --git a/test/snapshots/msg.snap b/test/snapshots/msg.snap index 5252508a..64a77bb2 100644 --- a/test/snapshots/msg.snap +++ b/test/snapshots/msg.snap @@ -58,7 +58,7 @@ snap reloaded # its builtins instead of losing them to a long pattern. Note the tag row above # ends at `Del`: the marker and the pattern are no longer on it at all. (The # `/` keystroke also cleared the reload message, which is the rule above.) -key / +key s text EXT stable 700 15000 snap prompt diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index 3101b920..43445ed4 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -1,43 +1,55 @@ -== snap results grid=150x31 cursor=7,3 +== snap results grid=150x31 cursor=13,13 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/stepgrain/cwd/a.txt Save Tty Collapse Del | 1 hello ZQMARK one | 2 see also sub/b.txt for ZQMARK two -| /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse LocationsConfig Del -| 1 a.txt:1:7-12 -| 2 hello ZQMARK one -| 3 a.txt:2:24-29 -| 4 see also sub/b.txt for ZQMARK two -| 5 sub/b.txt:1:1-6 -| 6 ZQMARK inside sub -| 7 -== snap step-row1 grid=150x31 cursor=7,6 -== style step-row1 grid=150x31 +| +| +| +| +| +| +| +|^ +Search 1/3 Del +| Grep ZQMARK +| a.txt +| 1 hello ZQMARK one +| 2 see also sub/b.txt for ZQMARK two +| sub/b.txt +| 1 ZQMARK inside sub +| +| +| +| /tmp/pardes-snap/stepgrain/cwd/+Preview Del +| 1 +== snap step-row2 grid=150x31 cursor=13,13 +|12: ^ +Search 2/3 Del +== style step-row2 grid=150x31 |0: 0-1 d,#1d2824, 2-149 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-149 #becfc4,#314738, |2: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-38 #d3b0d9,#1d2824, 39-149 #b2c3b8,#1d2824, -|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|5: 0-1 d,#add38a, 2-32 #becfc4,#314738, 33-40 #dfbce5,#314738, 41-149 #becfc4,#314738, -|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #f5f7ee,#3c614a, 19-149 #f5f7ee,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-18 #f7e4a5,#5e4923, 19-19 #f7e4a5,#0d1410, 20-149 #e5eee5,#0d1410, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-29 #e5eee5,#0d1410, 30-35 #f7e4a5,#5e4923, 36-36 #f7e4a5,#0d1410, 37-149 #e5eee5,#0d1410, -|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-12 #f7e4a5,#5e4923, 13-13 #f7e4a5,#0d1410, 14-149 #e5eee5,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|13: 0-0 d,#608269, 1-149 d,#0d1410, -|14: 0-0 d,#608269, 1-149 d,#0d1410, -|15: 0-0 d,#608269, 1-149 d,#0d1410, -|16: 0-0 d,#608269, 1-149 d,#0d1410, -|17: 0-0 d,#608269, 1-149 d,#0d1410, -|18: 0-0 d,#608269, 1-149 d,#0d1410, +|3: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-18 #e5eee5,#352e19, 19-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-29 #e5eee5,#0d1410, 30-35 #f5f7ee,#3c614a, 36-36 #f5f7ee,#0d1410, 37-149 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-149 d,#0d1410, +|6: 0-0 d,#608269, 1-149 d,#0d1410, +|7: 0-0 d,#e5eee5, 1-149 d,#0d1410, +|8: 0-0 d,#608269, 1-149 d,#0d1410, +|9: 0-0 d,#608269, 1-149 d,#0d1410, +|10: 0-0 d,#608269, 1-149 d,#0d1410, +|11: 0-0 d,#608269, 1-149 d,#0d1410, +|12: 0-1 #000000,#add38a, 2-149 #becfc4,#314738, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-16 #e5eee5,#0d1410, 17-22 #f7e4a5,#5e4923, 23-23 #f7e4a5,#0d1410, 24-149 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-33 #e5eee5,#0d1410, 34-39 #f7e4a5,#5e4923, 40-40 #f7e4a5,#0d1410, 41-149 #e5eee5,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-16 #f7e4a5,#5e4923, 17-17 #f7e4a5,#0d1410, 18-149 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-149 d,#0d1410, |20: 0-0 d,#608269, 1-149 d,#0d1410, |21: 0-0 d,#608269, 1-149 d,#0d1410, -|22: 0-0 d,#608269, 1-149 d,#0d1410, -|23: 0-0 d,#608269, 1-149 d,#0d1410, +|22: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-41 #d3b0d9,#1d2824, 42-149 #b2c3b8,#1d2824, +|23: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, |24: 0-0 d,#608269, 1-149 d,#0d1410, |25: 0-0 d,#608269, 1-149 d,#0d1410, |26: 0-0 d,#608269, 1-149 d,#0d1410, @@ -45,29 +57,32 @@ |28: 0-0 d,#608269, 1-149 d,#0d1410, |29: 0-0 d,#608269, 1-149 d,#0d1410, |30: 0-0 d,#608269, 1-149 d,#0d1410, -== snap step-row2 grid=150x31 cursor=7,8 -== style step-row2 grid=150x31 -|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 #f5f7ee,#0d1410, -== snap step-row3 grid=150x31 cursor=7,10 -== snap step-wrap grid=150x31 cursor=7,6 -== snap blank-in-path grid=150x31 cursor=7,6 -|5: /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del -|6: 1 two words.txt -|7: 2 -|8: -|9: -|10: -|11: -|12: +== snap step-row3 grid=150x31 cursor=13,13 +|12: ^ +Search 3/3 Del +|22: /tmp/pardes-snap/stepgrain/cwd/sub/b.txt Del +|23: 1 ZQMARK inside sub +== snap step-wrap grid=150x31 cursor=13,13 +|12: ^ +Search 1/3 Del +== snap blank-in-path grid=150x31 cursor=12,13 +|12: ^ +Search 1/1 Del +|13: Find words +|14: two words.txt +|15: +|16: +|17: +|18: +|22: /tmp/pardes-snap/stepgrain/cwd/two words.txt Del +|23: 1 == style blank-in-path grid=150x31 -|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 #f5f7ee,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|8: 0-0 d,#608269, 1-149 d,#0d1410, -|9: 0-0 d,#608269, 1-149 d,#0d1410, -|10: 0-0 d,#608269, 1-149 d,#0d1410, -|11: 0-0 d,#608269, 1-149 d,#0d1410, -|12: 0-0 d,#608269, 1-149 d,#0d1410, -== snap blank-opened grid=150x31 cursor=7,9 -|8: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del -|9: 1 +|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-149 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 #e5eee5,#0d1410, 6-10 #f7e4a5,#5e4923,b 11-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-149 d,#0d1410, +|16: 0-0 d,#608269, 1-149 d,#0d1410, +|17: 0-0 d,#608269, 1-149 d,#0d1410, +|18: 0-0 d,#608269, 1-149 d,#0d1410, +|22: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-46 #d3b0d9,#1d2824, 47-149 #b2c3b8,#1d2824, +== snap blank-opened grid=150x31 cursor=7,23 +|12: +Search 1/1 Save Unattach Del +|22: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del diff --git a/test/snapshots/stepgrain.snap b/test/snapshots/stepgrain.snap index 0f555ff8..e807981c 100644 --- a/test/snapshots/stepgrain.snap +++ b/test/snapshots/stepgrain.snap @@ -1,22 +1,11 @@ -# WHAT ONE PRESS OF `n` TAKES, and why that is not one answer. A pane's rows -# decide it (output_pane.Grain, read in Pardes.lookSpanIn): +# ONE PRESS, ONE ROW. A query pane's rows are one a line with a hit, the +# hit's line under a gutter number, and Ctrl-n / Ctrl-p (typing on line 1) +# step them a row at a time, round the end: row 2 below matched on a line +# that mentions `sub/b.txt`, and the step does not stop on that word, as the +# old word-grained walk did; the fourth press wraps back to row 1. # -# free text — a terminal, a file, a PDF — is stepped WORD by word, several -# stops to a line, because a line of it may name several places at once (the -# `ls` row in ttylook.snap hops big.txt -> plain.txt -> sub); -# -# a RESULTS BUFFER is stepped ROW by row, on the location at the head of the -# row, because a row there IS one location and the words after it are the -# MATCHED TEXT — the same hit, spelled out. That text is full of look-able -# words, and stopping on them was stopping on the same result twice. -# -# This script is the second rule. Row 2 below matched on a line that mentions -# `sub/b.txt`, so the old word-grained walk stopped there before it ever -# reached row 3; now `n` presses and rows correspond one to one, and the fourth -# press wraps the ring back to row 1. -# -# LARGEST from the head, so a path with a BLANK in it is one span rather than -# the word in front of it: `two words.txt` selects whole and opens. +# A path with a BLANK in it is one name: `two words.txt` is found whole by +# Find and Enter opens exactly it. dirmk sub file a.txt hello ZQMARK one\nsee also sub/b.txt for ZQMARK two file sub/b.txt ZQMARK inside sub @@ -24,52 +13,36 @@ run touch 'two words.txt' start 31 150 a.txt wait 8000 hello ZQMARK stable 700 20000 -# Grep from the leader: three hits, sorted by path, the empty file contributing -# none. Row 2 is the one whose TEXT holds a path. +# Grep from the leader: three hits, under their files, the empty file +# contributing none. Row 2 is the one whose TEXT holds a path. key space key f key g stable 400 5000 text ZQMARK -key enter -wait 10000 sub/b.txt:1:1 +wait 10000 ZQMARK inside sub stable 700 15000 snap results -# one press, one row: the head of row 1... -key space j n -stable 400 5000 -snap step-row1 -snapstyle step-row1 -# ...the head of row 2, and NOT the `sub/b.txt` sitting in its matched text — -# the cursor column is the assertion -key space j n +key c-n stable 400 5000 snap step-row2 snapstyle step-row2 -# ...row 3, and then the ring comes round to row 1 again -key space j n +key c-n stable 400 5000 snap step-row3 -key space j n +key c-n stable 400 5000 snap step-wrap -# Back into the file, so the Find below is asked from a pane that is not a -# results buffer (fillResults never refills the buffer it was asked from). -press left 8 4 -release left 8 4 +key esc +settle 100 stable 400 5000 -# A path with a blank in it: the row is one span from its first cell, because -# the walk asks about the LONGEST run of the row first and the filesystem is -# what vouches for it. Enter then opens exactly what is selected. +# Find `words`: the name with a blank in it, whole key space key f key f text words -key enter wait 10000 two words.txt stable 700 15000 -key space j n -stable 400 5000 snap blank-in-path snapstyle blank-in-path key enter diff --git a/test/snapshots/tagbottom.golden b/test/snapshots/tagbottom.golden index ef1bab3a..cf690a40 100644 --- a/test/snapshots/tagbottom.golden +++ b/test/snapshots/tagbottom.golden @@ -150,10 +150,19 @@ |8: 8 hhh |9: 9 iii |10: 10 jjj -== snap search-prompt grid=100x31 cursor=99,12 -|12: 1 ZZONE /ZZ +== snap search-prompt grid=100x31 cursor=5,21 +|20: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Collapse Del +|21: /ZZ +|22: 1 ZZONE +|23: 2 ZZTWO +|30: ^ +Search 1/2 Del == snap leader grid=100x31 cursor=9,13 |12: 1 ZZONE SPC +|20: +|21: +|22: +|23: +|30: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Collapse Del == snap cut-down grid=100x31 cursor=7,5 |2: 1 aaa |3: 2 bbb diff --git a/test/snapshots/tagbottomshort.golden b/test/snapshots/tagbottomshort.golden index 00d8cad0..1979cc60 100644 --- a/test/snapshots/tagbottomshort.golden +++ b/test/snapshots/tagbottomshort.golden @@ -1,41 +1,41 @@ -== snap roomy grid=80x11 cursor=79,2 +== snap roomy grid=80x11 cursor=5,5 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| 1 one /ZZ +| 1 one | 2 two -| 3 three -| 4 four -| 5 five -| 6 six +| /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del +| /ZZ | | -| /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del -== snap two-body grid=80x5 cursor=79,2 +| +| +|^ +Search 0 Del +== snap two-body grid=80x5 cursor=5,3 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| 1 one /ZZ -| 2 two | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del -== snap one-body grid=80x4 cursor=79,2 +| /ZZ +|^ +Search 0 Del +== snap one-body grid=80x4 cursor=79,3 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| 1 one /ZZ | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del +|^ +Search 0 Del == snap tag-only grid=80x2 cursor=79,1 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del -== snap regrown grid=80x11 cursor=79,2 +== snap regrown grid=80x11 cursor=5,5 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| 1 one /ZZ +| 1 one | 2 two -| 3 three -| 4 four -| 5 five -| 6 six +| /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del +| /ZZ | | -| /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del +| +| +|^ +Search 0 Del == snap leader-one-body grid=80x4 cursor=7,2 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol diff --git a/test/snapshots/topbarexec.golden b/test/snapshots/topbarexec.golden index 5b7d2234..63ed382c 100644 --- a/test/snapshots/topbarexec.golden +++ b/test/snapshots/topbarexec.golden @@ -26,14 +26,20 @@ |8: │pinch 1.0000 │ |9: │tscroll 0.0000 │ |10: ╰────────────────────────────────────╯ -== snap arg-still-spliced grid=90x21 cursor=14,5 +== snap arg-still-spliced grid=90x21 cursor=14,4 |1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |2: /tmp/pardes-snap/topbarexec/cwd Tty+bash Sa /tmp/pardes-snap/topbarexec/cwd Tty+bash Sa |3: ve Mode Filter Collapse Del ve Mode Filter Collapse Del -|4: ls Find ls -|5: zmarkfile.txt zmarkfile.txt -|6: -|7: /tmp/pardes-snap/topbarexec/cwd/+Search Sav -|8: e Tty Collapse Del -|9: 1 zmarkfile.txt -|10: 2 +|4: zmarkfile.txt Find ls +|5: zmarkfile.txt +|6: +Search 1/1 Del +|7: Find zmarkfile.txt +|8: zmarkfile.txt +|9: /tmp/pardes-snap/topbarexec/cwd/zmarkfile.t +|10: xt Del +|11: 1 hay ZQNEEDLE stack +|12: +|13: /tmp/pardes-snap/topbarexec/cwd Tty+bash Sa +|14: ve Mode Filter Collapse Del +|15: ls +|16: zmarkfile.txt -- cgit v1.3