diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-22 09:50:43 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-22 10:03:24 -0300 |
| commit | a8b457a306a4442975210bcac3f04b56513c61c3 (patch) | |
| tree | 6e2026ecb15da2fb919a0202f5d8b38e3b36a595 /src | |
| parent | a8a1499bdffffc5b6919e24ec957e92fabaf003b (diff) | |
| parent | 7e9d2c4169245072265b483ffaa6aa05f23f08d3 (diff) | |
| download | pardes-a8b457a306a4442975210bcac3f04b56513c61c3.tar.gz pardes-a8b457a306a4442975210bcac3f04b56513c61c3.zip | |
Merge: Def/Refs, the diff viewer, Helix n/N, Callstack, Zig 0.17, Window mode and the terminal cwd fix onto 0.24
The docs keep both sides: 0.24's Ctrl-i fallbacks and typed ls with this
line's Window mode, raw Esc and Helix n/N wording. The CHANGELOG's
unreleased entries go above 0.24, Def/Refs and the context rows among
them. cheatsheet-a4.pdf rendered again; .scratch/ ignored.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'src')
73 files changed, 3822 insertions, 1090 deletions
diff --git a/src/9p_io.zig b/src/9p_io.zig index 18c51ece..446c24de 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1015,7 +1015,7 @@ pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { i += 1 + name.len; const pid = deadSocketPid(name).?; if (pid == libc.getpid()) continue; - if (std.posix.errno(std.c.kill(pid, @enumFromInt(0))) != .SRCH) continue; + if (std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; var path_buf: [sun_path_len:0]u8 = undefined; const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ dir, name }, 0) catch continue; const facts = statNoFollow(path) orelse continue; @@ -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 7d3811b4..efccc785 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -1,5 +1,70 @@ # Changelog +## Unreleased + +- Callstack (gc or Space l b) opens a readable static call hierarchy with + outermost callers first, tree-sitter signatures, depth guides and clickable call sites. + `gc` replaces the old move-to-viewport-center binding. + CallstackDepth sets the caller depth at runtime (1–64, default 8). + CallstackLayout stacked is the default, aligning snippets below their + locations with rounded tree corners; inline + keeps them beside the locations. CallstackCorners square restores sharp + tree corners; rounded remains the default. + Signatures use syntax colors; only calls to the queried function get + background emphasis, and tree guides continue through multiline signatures + and wrapped rows. Cross-directory call locations use shorter relative paths. +- A terminal follows the shell at its prompt (the tty's foreground group), + not the process pardes started: a shell that re-execs itself under a + wrapper (fish's `exec 9ns --mntgen -- fish`) no longer leaves the pane + in its first directory, where `b/c.txt` printed by `fd` after a `cd` + looked up nothing. +- Workspace, column and pane tags share a tighter text inset. +- A diff paged into a session (`git show | pardes -`) opens its `+Diff` + alone; the `+Pager` no longer stays folded under it. +- The workspace Pet wanders to a random spot, rests there a few seconds, + then sets off for another; the frog is drawn side-on and hops. +- A drag started on a file's line numbers copies only the text; the + numbers no longer come along with the first line. +- The GUI's scrollbar thumb moves by the pixel and follows a smooth + scroll as it glides, instead of jumping a row of the track at a time. +- A click in another pane glides the cursor once, straight to where it + was clicked, no longer first to that pane's old cursor. +- Esc in a raw terminal goes back to the previous pane, as it does from + normal mode; Shift-Esc sends the program its Esc. `ProgramEsc on` + restores the old way round. A terminal without the kitty keyboard + protocol sends Shift-Esc as a plain Esc, so under one a program gets + no Esc unless ProgramEsc is on. +- Window mode (`Window`, Ctrl-w or SPC w): each pane's tag box shows a + letter in place of its mode, and the focused pane's tag is outlined; h/j/k/l move the outline without + giving any pane the keys, Enter or Esc focuses the outlined pane, `:` + its tag, and a + pane's letter jumps straight to it. Ctrl-w h/j/k/l and SPC w h/j/k/l + no longer move the focus at once; on a column or workspace tag Ctrl-w + h/j/k/l still walk the tags. +- On Linux the GUI's pointer is the desktop's cursor theme (niri's or + XCURSOR_THEME's, at its size and scale): its default arrow, its hand + over a link, and its move cursor while a grip carries a pane, which + the plan9 theme draws as acme's box. Elsewhere acme's own bitmaps stay. + +- 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). + +- A file a language server speaks for (by its extension) has `Def` and + `Refs` in its tag: the definition and the references of the symbol at + the cursor, which `gd`, `gr` and a Ctrl-click run too. Chorded 2-1, they + ask at the selected symbol instead, its occurrence nearest the cursor. +- A scroll in the window never moves the tree-sitter context rows: the + body glides under them. + ## 0.24 - Edit runs all of acme's commands: `< | >` through your Shell (one undo diff --git a/src/Dir.zig b/src/Dir.zig index 36895bda..b994bc06 100644 --- a/src/Dir.zig +++ b/src/Dir.zig @@ -463,10 +463,10 @@ test "over 9P a directory pane is a text pane whose name ends in /, its body the defer s.p.deinit(); const p = s.p; var line_buf: [4200]u8 = undefined; - _ = th.wr(p, @intFromEnum(tree.TopFile.look), try std.fmt.bufPrint(&line_buf, "{s}\n", .{s.dir})); + _ = th.wr(p, @backingInt(tree.TopFile.look), try std.fmt.bufPrint(&line_buf, "{s}\n", .{s.dir})); p.sync(); const pane = p.panes[p.active].?; - const index = th.rd(p, @intFromEnum(tree.TopFile.index), 0, 8192).bytes; + const index = th.rd(p, @backingInt(tree.TopFile.index), 0, 8192).bytes; try testing.expect(std.mem.indexOf(u8, index, try std.fmt.bufPrint(&line_buf, "{d} text 0 {s}/ ", .{ pane.serial, s.dir })) != null); try testing.expectEqualStrings(".dot sub/ top.txt\n", th.rd(p, tree.Node.of(pane.serial, .body), 0, 4096).bytes); var fields = std.mem.tokenizeScalar(u8, th.rd(p, tree.Node.of(pane.serial, .ctl), 0, 4096).bytes, ' '); diff --git a/src/File.zig b/src/File.zig index 875d0f46..59b04e3f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -154,8 +154,11 @@ pub const State = struct { /// Its file was deleted on disk: said once (`deleted`) until it is /// written or found again. disk_gone: bool = false, - /// A +Pager pane (`pardes -`) whose text is a diff (`git diff`, `show`, - /// `log -p`): drawn and looked at as a diff (Pane.colorAlgo). + /// A +Pager pane (`pardes -`): no line numbers, its program's colours + /// through Filter until it is toggled off. + pager: bool = false, + /// A +Pager 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 @@ -248,8 +251,10 @@ pub fn dumpPane( 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)), + .kind = @fromBackingInt(@intCast(@backingInt(row.kind))), .declaration = row.declaration, + .mark_occurrence = row.mark_occurrence, + .source_column = row.source_column, .path = row.path, .line = row.at.line, .col = row.at.col, @@ -268,6 +273,10 @@ fn sameSavedLocation(a: dump.LocationRow, b: dump.LocationRow) bool { } fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow) ![]locations.Row { + return restoreOutputLocationRows(gpa, content, saved, false); +} + +fn restoreOutputLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow, callstack: bool) ![]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); @@ -283,40 +292,57 @@ fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []con 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 + if ((!callstack and 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; + if (callstack) { + if (row.location_end > 0) { + const prefix = locations.treePrefix(line); + const parsed = locations.parseRaw(line[prefix.end..]); + if (row.kind != .match or parsed.at.line == 0 or + !std.mem.eql(u8, parsed.path, row.path) or + parsed.at.line != row.line or parsed.at.col != row.col or + parsed.at.end_line != row.end_line or parsed.at.end_col != row.end_col or + prefix.end + parsed.end != row.location_end or + prefix.end + parsed.code_start != row.code_start) return error.InvalidLocationRows; + } else if (row.kind == .preview) { + if (index == 0 or saved[index - 1].kind != .match or !sameSavedLocation(saved[index - 1], row)) return error.InvalidLocationRows; + } else if (row.kind != .context or (row.path.len == 0 and (row.line != 0 or row.code_start != line.len))) return error.InvalidLocationRows; + } else { + 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; + for (colors) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidLocationRows; const path = try gpa.dupe(u8, row.path); out.* = .{ - .kind = @enumFromInt(@intFromEnum(row.kind)), + .kind = @fromBackingInt(@intCast(@backingInt(row.kind))), .declaration = row.declaration, + .mark_occurrence = row.mark_occurrence, + .source_column = row.source_column, .path = path, .at = .{ .line = row.line, .col = row.col, .end_line = row.end_line, .end_col = row.end_col }, .location_end = row.location_end, @@ -562,6 +588,10 @@ pub fn byteAtRowDisplay(pane: *const Pane, row: i32, from_raw: i32, display_col: pub fn gutterWidth(pane: *const Pane) u16 { if (pane.file == null) return 0; const file = &pane.file.?; + // A +Pager, and a +Diff (hunks.zig), show no line numbers, as a + // 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; 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; @@ -985,7 +1015,8 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { } 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); + const is_callstack = if (output) |state| std.meta.eql(state.from, Output.Origin{ .query = .callstack }) else false; + const location_rows = try restoreOutputLocationRows(p.gpa, content, saved.location_rows, is_callstack); errdefer locations.freeRows(p.gpa, location_rows); var mini: ?Mini.State = null; @@ -997,7 +1028,7 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { 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; + for (colors) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidMini; mini = .{ .source = source, .colors = colors }; } else if (saved.mini_colors_b64.len > 0) return error.InvalidMini; @@ -1164,7 +1195,7 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { f.highlights = &.{}; f.highlight_start = 0; f.syntax_dirty = true; - if (std.mem.endsWith(u8, f.path, "/+Pager")) f.pager_diff = looksLikeDiff(new[0..@min(new.len, 64 * 1024)]); + if (f.pager) f.pager_diff = looksLikeDiff(new[0..@min(new.len, 64 * 1024)]); for (twins[0..ntwins], 0..) |id, i| { const t = p.panes[id].?; const tf = &t.file.?; @@ -1434,6 +1465,7 @@ test "a +Pager pane holding a diff is drawn and looked at as one; holding other const f = &pane.file.?; p.gpa.free(f.path); f.path = try p.gpa.dupe(u8, "/tmp/+Pager"); + f.pager = true; setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n")); try std.testing.expect(pane.colorAlgo() == .diff); try std.testing.expect(pardes.look.diffLines(p, pane) != null); @@ -1699,9 +1731,16 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) 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 ""; + var guide_buffer: [1024]u8 = undefined; + const guide = if (at > 0 and width > 1 and f.output != null and + std.meta.eql(f.output.?.from, Output.Origin{ .query = .callstack })) + locations.treeContinuation(text, &guide_buffer, width - 1) + else + ""; + const pad = displayWidth(guide); // 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 end = if (width == 0 or context) text.len else fitEnd(text, at, width - pad); const cut = if (pane.hscroll > 0 and width == 0) modal.graphemeStart(text, @min(@as(usize, @intCast(pane.hscroll)), text.len)) else @@ -1709,13 +1748,14 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) 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_pad[i] = @intCast(pad); 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) { + if (at == 0 and prefix.len > 0) { var lineno = row + 1; var digit: usize = prefix.len - 1; while (true) { @@ -1727,6 +1767,8 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) } if (dst) |out| @memcpy(out[written..][0..prefix.len], prefix); written += prefix.len; + if (dst) |out| @memcpy(out[written..][0..guide.len], guide); + written += guide.len; const shown = text[cut..end]; if (dst) |out| @memcpy(out[written..][0..shown.len], shown); written += shown.len; @@ -1790,6 +1832,12 @@ const SynStyle = struct { fg: [3]u8, bold: bool }; pub const DiffTints = struct { added_bg: [3]u8, removed_bg: [3]u8, + /// The words a changed line changed (hunks.zig), on a stronger ground. + added_emph_bg: [3]u8, + removed_emph_bg: [3]u8, + /// A +Diff line added or removed whole: a faint ground. + added_line_bg: [3]u8, + removed_line_bg: [3]u8, added_fg: [3]u8, removed_fg: [3]u8, @@ -1804,6 +1852,10 @@ pub const DiffTints = struct { return .{ .added_bg = added_bg, .removed_bg = removed_bg, + .added_emph_bg = Colors.mixOklab(page, green, 0.28), + .removed_emph_bg = Colors.mixOklab(page, red, 0.28), + .added_line_bg = Colors.mixOklab(page, green, 0.07), + .removed_line_bg = Colors.mixOklab(page, red, 0.07), .added_fg = legible(green, ink, added_bg), .removed_fg = legible(red, ink, removed_bg), }; @@ -1818,9 +1870,9 @@ pub const DiffTints = struct { /// The row ground and prefix ink for a line's style byte, if it is an /// added or removed line. - pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8 } { - if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg }; - if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg }; + pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8, emph_bg: [3]u8, line_bg: [3]u8 } { + if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg, .emph_bg = t.added_emph_bg, .line_bg = t.added_line_bg }; + if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg, .emph_bg = t.removed_emph_bg, .line_bg = t.removed_line_bg }; return null; } }; @@ -1855,7 +1907,17 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); - const tints: ?DiffTints = if (pane.colorAlgo() == .diff and highlights.len > 0) DiffTints.of(p) else null; + // A diff's rows, and a +Diff's (hunks.zig): their markers coloured. + // A diff's whole row is tinted; a +Diff tints only the words a + // changed line changed. + const algo = pane.colorAlgo(); + const tints: ?DiffTints = if ((algo == .diff or algo == .locations) and highlights.len > 0) DiffTints.of(p) else null; + const row_tint = algo == .diff; + var filtered_storage: terminal.FilteredColors = undefined; + const filtered: ?*terminal.FilteredColors = if (comptime terminal.enabled) (if (pane.tty_filter and spans.len > 0) blk: { + filtered_storage = .init(p, null); + break :blk &filtered_storage; + } else null) else null; // 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); @@ -1893,7 +1955,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. t.forStyle(highlights[base - highlight_start]) 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); + if (tint) |t| if (prefix_width < tw) { + // A +Diff line added or removed whole: faintly (hunks.zig). + const whole = highlights[base - highlight_start] & syntax.diff_whole != 0; + if (row_tint or whole) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, if (row_tint) t.bg else t.line_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. @@ -1903,7 +1969,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. } }.before); var c: usize = 0; - var screen_c: usize = 0; + const pad: usize = if (vr < pane.wrap_n) pane.wrap_pad[vr] else 0; + for (0..@min(pad, tw -| prefix_width)) |col| { + s.at(tx + @as(u16, @intCast(prefix_width + col)), body_y + vr).style.fg = .{ .rgb = p.bodyChrome().diagnostic_info }; + } + var screen_c: usize = pad; 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]); @@ -1914,7 +1984,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (if (tint != null and hs + c == 0) SynStyle{ .fg = tint.?.fg, .bold = true } else - synStyle(p, @enumFromInt(highlights[hidx] & syntax.syn_bits))) |ss| + synStyle(p, @fromBackingInt(@intCast(highlights[hidx] & syntax.syn_bits)))) |ss| { var fill: usize = 0; while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { @@ -1924,6 +1994,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. cell.style.bold = ss.bold; } } + if (tint) |t| if (highlights[hidx] & syntax.diff_emph != 0) { + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) + s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph_bg }; + }; } } // Results keep their exact live text. Only the location, @@ -1945,10 +2020,16 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. 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; + // As a terminal pane's cell: through Filter, or a + // palette colour through the theme's sixteen and + // truecolor as it is. + if (filtered) |colors| { + if (st.fg != .default) cell.style.fg = colors.spanColor(st.fg, false); + if (st.bg != .default) cell.style.bg = colors.spanColor(st.bg, true); + } else { + 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; @@ -2108,7 +2189,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t // green is the tint's to say now: its code takes the page's ink. const paint: ?SynStyle = if (tint != null and prefix) .{ .fg = tint.?.fg, .bold = true } - else if (synStyle(p, @enumFromInt(style & syntax.syn_bits))) |ss| + else if (synStyle(p, @fromBackingInt(@intCast(style & syntax.syn_bits)))) |ss| ss else if (tint != null) .{ .fg = ink, .bold = false } @@ -2175,8 +2256,8 @@ pub fn paintWordSelection( 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); + const c0 = @as(i32, prefix_width) + here.pad + displayOffset(pane, row, here.at, lo); + const c1 = @as(i32, prefix_width) + here.pad + 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 = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); 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..6d064c93 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: ")); } @@ -721,7 +721,7 @@ test "with no frontend attached a message goes once it has lingered, on the cloc // line above it with it. p.unattended = true; // A read served meanwhile changes nothing; the session's loop expires. - _ = p.serveFs(.{ .tag = 1, .op = .read, .node = @intFromEnum(ctlfs.TopFile.index), .size = 64 }); + _ = p.serveFs(.{ .tag = 1, .op = .read, .node = @backingInt(ctlfs.TopFile.index), .size = 64 }); try std.testing.expect(pane.msg_len > 0); expireUnattended(p); try std.testing.expectEqual(@as(u16, 0), pane.msg_len); diff --git a/src/Output.zig b/src/Output.zig index 3bae9ecf..9ed33ebe 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -15,6 +15,8 @@ const build_options = @import("pardes_config"); const lsp = @import("lsp/lsp.zig"); const look = @import("look.zig"); const locations = @import("locations.zig"); +const layout = @import("layout.zig"); +const hunks = @import("hunks.zig"); const Pane = panes.Pane; const File = panes.File; @@ -51,13 +53,14 @@ const RowDecoration = struct { location_end: usize = 0, prefix_end: usize = 0, declaration: bool = false, + guide_end: usize = 0, mark_start: usize = 0, mark_end: usize = 0, severity: enum { none, err, warning, info, hint } = .none, /// Nothing in the row is decorated: most rows of most files. pub fn plain(row: RowDecoration) bool { - return !row.declaration and row.location_end == 0 and row.prefix_end == 0 and row.mark_end <= row.mark_start; + return row.guide_end == 0 and !row.declaration and row.location_end == 0 and row.prefix_end == 0 and row.mark_end <= row.mark_start; } /// `chrome` is the theme's own (Pardes.bodyChrome): body paper changes @@ -66,6 +69,7 @@ const RowDecoration = struct { /// working it out takes the contrast searches' pow calls. pub fn styleAt(row: RowDecoration, chrome: *const pardes.ChromeTheme, byte: usize) ?pardes.CellStyle { if (row.plain()) return null; + if (byte < row.guide_end) return .{ .fg = .{ .rgb = chrome.diagnostic_info } }; 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; @@ -89,32 +93,38 @@ fn rowDecoration(output: ?State, line: []const u8) RowDecoration { pub fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) RowDecoration { const origin = (output orelse return .{}).from; + const callstack = std.meta.eql(origin, Origin{ .query = .callstack }); + const prefix = locations.treePrefix(if (callstack) line else ""); + const trimmed = line[prefix.end..]; + const indent = prefix.end; if (!traits(origin).locations) return .{}; - const target = locations.parse(line); + const target = if (callstack) locations.parseRaw(trimmed) else locations.parse(trimmed); 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, + .guide_end = indent, + .location_end = if (metadata) |m| m.location_end else indent + target.end, + .prefix_end = if (metadata) |m| m.code_start else indent + target.end, .declaration = if (metadata) |m| m.declaration else false, }; - const source_start = if (metadata) |m| m.code_start else target.code_start; + const source_start = if (metadata) |m| m.code_start else indent + 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, + .definition, .declaration, .type_definition, .implementation, .references, .callstack => true, else => false, }, else => false, }; - if (mark_occurrence and spot.col > 0 and spot.end_line == spot.line and + if (mark_occurrence and (if (metadata) |m| m.mark_occurrence else !prefix.branch) 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 source_column = if (metadata) |m| m.source_column else 0; + row.mark_start = source_start +| ((spot.col - 1) -| source_column); + row.mark_end = @min(line.len, source_start +| (spot.end_col -| source_column)); } const is_diagnostic = switch (origin) { .query => |kind| kind == .diagnostics or kind == .workspace_diagnostics, @@ -133,6 +143,25 @@ pub fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) R return row; } +test "callstack guides and Look locations share result decoration" { + const from: State = .{ .from = .{ .query = .callstack } }; + const loc = rowDecoration(from, "└──┬ lib.rs:2:8-10 fn add() {"); + try std.testing.expectEqual(@as(usize, "└──┬ lib.rs:2:8-10".len), loc.location_end); + try std.testing.expect(!loc.declaration); + try std.testing.expect(!usesLocationsConfig(from.from)); + try std.testing.expect(!traits(from.from).jumps); + const call_line = " lib.rs:12:12-20 return calculate(value);"; + const call = rowDecoration(from, call_line); + try std.testing.expectEqualStrings("calculate", call_line[call.mark_start..call.mark_end]); + const reference = rowDecoration(.{ .from = .{ .query = .references } }, call_line[4..]); + try std.testing.expectEqual(reference.mark_start + 4, call.mark_start); + try std.testing.expectEqual(reference.mark_end + 4, call.mark_end); + try std.testing.expectEqual(reference.location_end + 4, call.location_end); + const tab_line = " tab.zig:4:9-11 \treturn run();"; + const tab_call = rowDecoration(from, tab_line); + try std.testing.expectEqualStrings("run", tab_line[tab_call.mark_start..tab_call.mark_end]); +} + test "result decoration follows source byte ranges and diagnostic provenance" { const row = 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]); @@ -235,6 +264,7 @@ pub fn traits(o: Origin) Traits { .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, .query => |k| switch (k) { .hover => .{ .name = config.hover_buffer }, + .callstack => .{ .name = "+Callstack", .steps = true, .locations = true }, // 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 }, @@ -265,7 +295,8 @@ 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 }); + !std.meta.eql(from, Origin{ .query = .completion }) and + !std.meta.eql(from, Origin{ .query = .callstack }); } pub fn fileTraits(out: ?State) Traits { @@ -531,13 +562,27 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] return; } } - if (usesLocationsConfig(from)) { - const formatted = try locations.format(p, dir, content, anchor, true); + if (usesLocationsConfig(from) or std.meta.eql(from, Origin{ .query = .callstack })) { + const formatted = if (std.meta.eql(from, Origin{ .query = .callstack })) + try locations.formatCallstack(p, dir, content) + else + try locations.format(p, dir, content, anchor, true); p.gpa.free(result_content); result_content = formatted.content; result_rows = formatted.rows; anchor = formatted.anchor; } + _ = try fillRows(p, id, dir, from, arg, result_content, result_rows, anchor); +} + +/// Rows already laid out (`content`, `rows` its metadata, both taken +/// when it succeeds, the caller's still when it fails) into the pane they +/// belong in: the one a run of `from` with `arg` in `dir` showed last, +/// refilled, else a new one placed by pane `id`. Its id. +pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { + const pane = p.panes[id] orelse return error.MissingPane; + if (arg.len > max_arg) return error.ArgumentTooLong; + const by_arg = std.meta.activeTag(from) != .query; for (p.panes, 0..) |slot, i| { const rp = slot orelse continue; const rf = if (rp.file) |*f| f else continue; @@ -578,7 +623,7 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] pane.search_row = anchor; look.armLookWalk(p, i); } - return; + return i; } const free = p.freeSlot() orelse return error.NoPaneSlots; const np = try open(p, free, dir, from, arg, result_content); @@ -590,6 +635,57 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] pane.search_row = anchor; look.armLookWalk(p, free); } + return free; +} + +/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a +/// diff viewer shows it (hunks.zig), in a +Diff where its files are found +/// (hunks.sourceRoot), placed by pane `id`, refilled when it is there. Its +/// arg names the diff (its base name, or its whole path when the +Diff +/// stands elsewhere), for Diff to go back to it. The +Diff's id; +/// NoHunks when there is none in it. +pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { + const dir = std.fs.path.dirname(path) orelse p.sessionDir(); + const root = hunks.sourceRoot(p, dir, content); + const result = try hunks.format(p, root, content); + errdefer { + p.gpa.free(result.content); + locations.freeRows(p.gpa, result.rows); + } + var has_hunk = false; + for (result.rows) |row| has_hunk = has_hunk or row.kind == .match; + if (!has_hunk) return error.NoHunks; + const arg = if (std.mem.eql(u8, root, dir) or path.len > max_arg) std.fs.path.basename(path) else path; + return fillRows(p, id, root, .{ .cmd = .Diff }, arg, result.content, result.rows, null); +} + +/// Diff on a +Diff: the diff it stacks, as text. A pane holding it +/// already (the newest: a +Pager folded under its +Diff unfolds) is +/// shown; else the file is opened as text, whatever DiffLook says. +pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void { + var newest: ?usize = null; + for (p.panes, 0..) |slot, i| { + const f = (slot orelse continue).file orelse continue; + if (!std.mem.eql(u8, f.path, source)) continue; + if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i; + } + if (newest) |i| { + if (p.panes[i].?.collapsed) layout.toggleCollapse(p, i); + p.active = i; + return; + } + p.look_text = true; + defer p.look_text = false; + look.lookAt(p, id, source); +} + +/// The diff a +Diff stacks (openDiff's arg): its path. +pub fn diffSource(p: *Pardes, f: *const File.State) ?[]const u8 { + const o = f.output orelse return null; + if (!std.meta.eql(o.from, Origin{ .cmd = .Diff })) return null; + const arg = o.arg(); + if (arg.len > 0 and arg[0] == '/') return arg; + return std.fs.path.join(p.scratch.allocator(), &.{ std.fs.path.dirname(f.path) orelse "", arg }) catch null; } pub fn openJumps(p: *Pardes, id: usize) !void { @@ -685,25 +781,15 @@ pub fn openUnsaved(p: *Pardes, id: usize, content: []u8) void { p.active = id; } -/// `pardes -`'s pane: the one `<dir>/+Pager`, emptied for the next paged -/// text when it is there (a directory's paged commands refill it, as its -/// command pane is reused), else made, named so before it is announced, -/// and placed wherever there is room without taking the keyboard. `dir` -/// empty (or not absolute): the session's directory. Its id; NoPaneRoom -/// or NoPaneSlots when it has no room at all. +/// `pardes -`'s pane: a new `<dir>/+Pager` for each paged text, as each +/// run of a pager is its own (one already there keeps its page), named so +/// before it is announced, its colours through Filter, and placed wherever +/// there is room without taking the keyboard. `dir` empty (or not +/// absolute): the session's directory. Its id; NoPaneRoom or NoPaneSlots +/// when it has no room at all. pub fn openPager(p: *Pardes, from: usize, dir_arg: []const u8) !usize { const dir = if (dir_arg.len > 0 and dir_arg[0] == '/') dir_arg else p.sessionDir(); const path = try std.fs.path.join(p.gpa, &.{ dir, "+Pager" }); - for (p.panes, 0..) |slot, i| { - const pane = slot orelse continue; - const f = if (pane.file) |*file| file else continue; - if (!std.mem.eql(u8, f.path, path)) continue; - p.gpa.free(path); - File.setContent(p, f, try p.gpa.alloc(u8, 0)); - resetBody(p, pane); - f.saved_revision = f.revision; - return i; - } const free = p.freeSlot() orelse { p.gpa.free(path); return error.NoPaneSlots; @@ -719,6 +805,8 @@ pub fn openPager(p: *Pardes, from: usize, dir_arg: []const u8) !usize { // The pane owns the name from here. p.gpa.free(pane.file.?.path); pane.file.?.path = path; + pane.file.?.pager = true; + pane.tty_filter = true; const keyboard = p.active; exec.placeNew(p, from, null, free, .fs); if (p.unplaced.isSet(free)) return error.NoPaneRoom; @@ -807,7 +895,7 @@ pub fn openThemes(p: *Pardes, id: usize) !void { 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 (usesLocationsConfig(state.from) or std.meta.eql(state.from, Origin{ .query = .callstack })) return isResultRow(file, row); if (!std.meta.eql(state.from, Origin{ .cmd = .Themes })) 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 ++ " "); @@ -845,11 +933,14 @@ fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void { 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 calls_help = "\nCallstack: static caller chains,\nwith signatures and clickable call sites.\nCallers / Callees: one direction at a time.\n"; + const show_calls_help = prefix.len == 0 or std.mem.eql(u8, prefix, "l"); const language_footer = "\nlanguage keys (motions, not words):\n" ++ "gd gD gy gi gr goto: definition,\n" ++ " declaration, type-def,\n" ++ " implementation, refs\n" ++ + "gc Callstack\n" ++ "]d [d ]D [D diagnostics: next,\n" ++ " prev, last, first\n" ++ "= format (applies, one\n" ++ @@ -862,6 +953,7 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { full_header.len + language_footer.len else group_header.len + prefix.len * 2 + 2; + if (show_calls_help) len += calls_help.len; 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 @@ -892,6 +984,10 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { 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; @@ -907,7 +1003,7 @@ pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { return openRead(p, id, .{ .cmd = .Help }, prefix, content); } -test "full Help renders every builtin row, then the language keys" { +test "full Help renders builtin rows, a call hierarchy guide, then language keys" { const content = try helpContent(std.testing.allocator, ""); defer std.testing.allocator.free(content); @@ -918,17 +1014,22 @@ test "full Help renders every builtin row, then the language keys" { 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. + // The short call guide disambiguates the three related commands. + try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("Callstack: static caller chains,", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("with signatures and clickable call sites.", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("Callers / Callees: one direction at a time.", lines.next() orelse return error.MissingCallHelp); + // The language keys close the page. try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingLanguageKeys); try std.testing.expectEqualStrings("language keys (motions, not words):", lines.next() orelse return error.MissingLanguageKeys); try std.testing.expect(std.mem.indexOf(u8, body, "\ngd gD gy gi gr goto: definition,\n") != null); - // the group view stays a pure filter: no footer under a prefix + // The language group also explains call commands, without the motion footer. 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); + try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); } pub fn openConfig(p: *Pardes, id: usize) !void { diff --git a/src/Presentation.zig b/src/Presentation.zig index 5cec73e0..2a75b66d 100644 --- a/src/Presentation.zig +++ b/src/Presentation.zig @@ -226,7 +226,7 @@ fn stamp(p: *const Pardes, track: Track) Track { switch (track.effect) { .slide, .zoom, .vertical => { const motion = animation.Motion.of(p.settings.motion); - stamped.motion = @intFromEnum(p.settings.motion) + 1; + stamped.motion = @backingInt(p.settings.motion) + 1; stamped.frame_count = @intFromFloat(@max(2, @round(@as(f32, @floatFromInt(track.effect.frames())) * motion.span))); }, else => {}, @@ -741,7 +741,7 @@ test "a pane past its mark never takes a neighbour's click" { // Bouncy, at its peak: pane 0 slides right to 0..40 and swings past it, // over the neighbour at 40..80. var presentation: Presentation = .{}; - var track: Track = .{ .serial = 7, .effect = .slide, .motion = @intFromEnum(animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = -40, .y = 0, .w = 40, .h = 20 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 20 } }; + var track: Track = .{ .serial = 7, .effect = .slide, .motion = @backingInt(animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = -40, .y = 0, .w = 40, .h = 20 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 20 } }; var peak: u16 = 0; var furthest: f32 = -1e9; while (track.frame < track.frames()) : (track.frame += 1) { @@ -807,7 +807,7 @@ test "presentation snapshots own compact body and tag rows across later edits" { } test "a move retargeted mid-way carries its speed into the new one" { - const smooth = @intFromEnum(animation.Motion.Flavour.smooth) + 1; + const smooth = @backingInt(animation.Motion.Flavour.smooth) + 1; const first: Track = .{ .serial = 1, .phase = .moving, .effect = .slide, .motion = smooth, .frame = 4, .frame_count = 14, .from = .{ .x = 0, .y = 1, .w = 40, .h = 20 }, .to = .{ .x = 40, .y = 1, .w = 40, .h = 20 } }; const was = first.velocity(); try std.testing.expect(was.x > 0.5); diff --git a/src/Registers.zig b/src/Registers.zig index d2a42434..3f2486cd 100644 --- a/src/Registers.zig +++ b/src/Registers.zig @@ -9,6 +9,7 @@ const std = @import("std"); const Registers = @This(); list: std.ArrayList(Reg) = .empty, +last_search: u21 = '/', pub const Reg = struct { name: u21, 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/animation.zig b/src/animation.zig index 19f7ce0b..547b9201 100644 --- a/src/animation.zig +++ b/src/animation.zig @@ -897,7 +897,7 @@ test "each flavour is its own motion: off lands at once, bouncy overshoots, play last = now; } try std.testing.expect(t < 1600 * ms); - settle[@intFromEnum(flavour)] = t; + settle[@backingInt(flavour)] = t; switch (flavour) { .crisp, .smooth => try std.testing.expect(peak <= 1.0005 and low >= 0), // Clearly past the mark, not a hint of it. @@ -909,8 +909,8 @@ test "each flavour is its own motion: off lands at once, bouncy overshoots, play // Smooth takes twice crisp's time and more: a character, not a tuning. // Yet as the default a pane's arrival (a slide's 12 frames, scaled) is // inside §8.1's 220 ms, and a lift is still before 300 ms. - try std.testing.expect(settle[@intFromEnum(Motion.Flavour.smooth)] > 2 * settle[@intFromEnum(Motion.Flavour.crisp)]); - try std.testing.expect(settle[@intFromEnum(Motion.Flavour.smooth)] <= 300 * ms); + try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] > 2 * settle[@backingInt(Motion.Flavour.crisp)]); + try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] <= 300 * ms); try std.testing.expect(@round(@as(f32, 12) * Motion.of(.smooth).span) * frame_ms <= 220); // A fixed-length move lands exactly on its mark, whatever the flavour. for (std.enums.values(Motion.Flavour)) |flavour| try std.testing.expectEqual(@as(f32, 1), Motion.of(flavour).ease(1)); @@ -920,7 +920,7 @@ test "a flavour's stretched pane lands exactly on its box, and a click finds the const from: Box = .{ .x = 0, .y = 2, .w = 30, .h = 10 }; const to: Box = .{ .x = 37.3, .y = 2, .w = 30, .h = 10 }; for (std.enums.values(Motion.Flavour)) |flavour| { - var track: Track = .{ .effect = .slide, .motion = @intFromEnum(flavour) + 1, .frame_count = 20, .from = from, .to = to }; + var track: Track = .{ .effect = .slide, .motion = @backingInt(flavour) + 1, .frame_count = 20, .from = from, .to = to }; track.frame = track.frames() - 1; const landed = track.presented(); // Bit for bit: no stretch or float residue once it lands. @@ -929,7 +929,7 @@ test "a flavour's stretched pane lands exactly on its box, and a click finds the // Playful at its most stretched: the pane is drawn wider than its box, // and the drawn place of a cell maps back to that cell (the pointer // inverts the same box: target + (x - shown.x) / shown.w * target.w). - var track: Track = .{ .effect = .slide, .motion = @intFromEnum(Motion.Flavour.playful) + 1, .frame_count = 20, .from = from, .to = to }; + var track: Track = .{ .effect = .slide, .motion = @backingInt(Motion.Flavour.playful) + 1, .frame_count = 20, .from = from, .to = to }; var most: u16 = 0; var widest: f32 = 0; while (track.frame < track.frames()) : (track.frame += 1) { @@ -1309,4 +1309,3 @@ test "retarget starts at the currently displayed value" { for (0..transition_steps) |_| tween.advance(); try std.testing.expectEqual(third, tween.displayed); } - diff --git a/src/body_layer.zig b/src/body_layer.zig index b24bd6ed..2aa8e5f8 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -113,8 +113,8 @@ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []c 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 = if (row.to_edge and hi == end) @as(i32, width) else prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start))); + var col = prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); + const last = if (row.to_edge and hi == end) @as(i32, width) else prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start))); while (col < last and col < width) : (col += 1) { const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); cell.default = false; @@ -399,14 +399,14 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane (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 + panes.File.lineDisplayOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.lo_col)))) + vpfx + w.pad else - vpfx; + vpfx + w.pad; const cend: i32 = if (w.line == bnd.hi_row and @as(usize, @intCast(@max(0, bnd.hi_col))) < past_view) (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 + panes.File.lineDisplayEndOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.hi_col)))) + vpfx + w.pad else @as(i32, tw) - 1; var col: i32 = @max(cstart, vpfx); @@ -432,7 +432,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane modal.lineSlice(body, @intCast(@max(0, cw.row))), @intCast(@max(0, cw.at)), @intCast(@max(0, sr.col)), - )) + vpfx; + )) + vpfx + cw.pad; if (crow >= pane.tag_rows 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 - pane.tag_rows))); cell.default = false; @@ -455,7 +455,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane const row: i32 = @intCast(pos.row); const wp = pane.wrapRow(row, @intCast(pos.col)); const cx = if (pane.file != null) - @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, wp.at, @intCast(pos.col)) + @as(i32, panes.File.gutterWidth(pane)) + wp.pad + panes.File.displayOffset(pane, row, wp.at, @intCast(pos.col)) else panes.File.lineDisplayOffset(modal.lineSlice(flat, pos.row), @intCast(@max(0, wp.at)), pos.col); if (wp.row >= 0 and wp.row < body_h and cx >= 0 and cx < tw) @@ -478,20 +478,20 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // Off the view, the cursor is not measured (its column may be // millions of bytes along a line whose start is shown). if (cwp.row >= 0 and prow < body_bottom and !pastView(pane, body, crow, cwp.row, cwp.at, ccol, tw)) { - // 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.body.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 >= 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 }; + // 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)) + cwp.pad + panes.File.displayOffset(pane, crow, cwp.at, ccol) + else if (pane.body.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 >= 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| { if (cur.y + pane.tag_rows < body_bottom and cur.x < tw) diff --git a/src/builtins.zig b/src/builtins.zig index 84904959..cc7d1d4a 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -46,6 +46,10 @@ pub const PaneKind = enum { /// An image pane, or a terminal, whose program's kitty graphics are /// pictures too. picture, + /// A terminal, or a +Pager: a program's colours. + program_colors, + /// A text pane showing a diff: a .diff, a .patch, a +Pager holding one. + diff, pub fn has(kind: PaneKind, pane: *const panes.Pane) bool { return switch (kind) { @@ -53,6 +57,9 @@ pub const PaneKind = enum { .pdf => pane.hasPdf(), .image => pane.image != null, .picture => pane.image != null or pane.isTerminal(), + .program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager), + .diff => if (pane.file) |f| pane.colorAlgo() == .diff or + (f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .cmd = .Diff })) else false, }; } @@ -62,6 +69,8 @@ pub const PaneKind = enum { .pdf => "a PDF", .image => "an image", .picture => "an image or a terminal", + .program_colors => "a terminal or a +Pager", + .diff => "a diff or a +Diff", }; } }; @@ -89,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"; } } } @@ -103,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; @@ -120,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; @@ -190,7 +199,7 @@ 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; + 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; } @@ -201,7 +210,7 @@ pub const registry = struct { /// 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 (@intFromEnum(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; + if (@backingInt(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; return false; } @@ -214,36 +223,36 @@ pub const registry = struct { /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are. pub fn needs(b: Builtin()) ?PaneKind { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; + if (@backingInt(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; return null; } 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; + if (@backingInt(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) { + if (@backingInt(b) == i) return switch (setting.action) { // a switch flips bare, a choice steps, and DumpDir and Shell bare // are the default .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 width (exec.applySettingBuiltin) - .tab => false, + // bare, it says the current value (exec.applySettingBuiltin) + .tab, .callstack_depth => false, }; 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; + if (@backingInt(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; return .session; // a setting } pub fn outputTraits(b: Builtin()) ?OutputTraits { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "output")) T.output else null; + if (@backingInt(b) == i) return if (@hasDecl(T, "output")) T.output else null; inline for (comptime settingList(), manualBuiltinCount()..) |_, i| - if (@intFromEnum(b) == i) return null; + if (@backingInt(b) == i) return null; unreachable; } @@ -251,15 +260,15 @@ pub const registry = struct { /// 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); + if (@backingInt(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); + if (@backingInt(b) == i) return T.run(c); inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); + if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } }; @@ -308,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; @@ -332,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]; @@ -735,15 +744,15 @@ pub const Restore = struct { // so a Restore that could never happen spends no warning. if (comptime pardes.hosted) { const bytes = @import("fs.zig").readRestore(c.p.gpa, path, c.p.settings.dump_dir.get()) catch |err| { - var buf: [limits.host_path_cap + 64]u8 = undefined; - var words: [128]u8 = undefined; - const why = switch (err) { - error.FileNotFound => "no such file", - error.PermissionDenied => "permission denied", - error.IsDirectory => "a directory, not a dump", - else => pardes.Messages.errorWords(err, &words), - }; - return c.p.reportFailure(c.id, std.fmt.bufPrint(&buf, "Restore: {s}: {s}", .{ path, why }) catch "Restore: cannot read the dump"); + var buf: [limits.host_path_cap + 64]u8 = undefined; + var words: [128]u8 = undefined; + const why = switch (err) { + error.FileNotFound => "no such file", + error.PermissionDenied => "permission denied", + error.IsDirectory => "a directory, not a dump", + else => pardes.Messages.errorWords(err, &words), + }; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&buf, "Restore: {s}: {s}", .{ path, why }) catch "Restore: cannot read the dump"); }; defer c.p.gpa.free(bytes); // Nor does a file that is not a dump, before any warning. @@ -1339,14 +1348,28 @@ pub const Del = struct { } }; -/// Recolour a terminal's program colours to the theme, or show them as sent, flipping between them. +/// Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them. pub const Filter = struct { - pub const needs: PaneKind = .terminal; + pub const needs: PaneKind = .program_colors; pub fn run(c: Ctx) void { c.pane.tty_filter = !c.pane.tty_filter; } }; +/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. +pub const Diff = struct { + pub const needs: PaneKind = .diff; + pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true }; + pub fn run(c: Ctx) void { + const f = &c.pane.file.?; + if (panes.Output.diffSource(c.p, f)) |source| return panes.Output.showDiffText(c.p, c.id, source); + _ = panes.Output.openDiff(c.p, c.id, f.path, f.content) catch |err| switch (err) { + error.NoHunks => c.p.reportFailure(c.id, "Diff: no hunk in it"), + else => c.p.reportError(c.id, "hunks", err), + }; + } +}; + /// Cycle the pane's input modes: terminals add raw tty mode to normal/insert. pub const Mode = struct { pub fn run(c: Ctx) void { @@ -1801,6 +1824,15 @@ pub const Right = struct { } }; +/// Window mode: h/j/k/l move an outline between the panes; Enter or Esc +/// focuses the outlined pane, `:` its tag, the letter shown on a pane that one. +pub const Window = struct { + pub fn run(c: Ctx) void { + tagline.exitHeader(c.p); + c.p.window_pick = if (c.p.panes[c.id] != null) c.id else c.p.active; + } +}; + // ---- the jump group ---- /// Ctrl-o: one step back into the history. @@ -1819,6 +1851,22 @@ pub const Forward = struct { } }; +/// Select the next Look location across panes; Enter opens it. +pub const LookNext = struct { + pub const quiet = true; + pub fn run(c: Ctx) void { + look.lookWalk(c.p, 1); + } +}; + +/// Select the previous Look location across panes; Enter opens it. +pub const LookPrev = struct { + pub const quiet = true; + pub fn run(c: Ctx) void { + look.lookWalk(c.p, -1); + } +}; + /// Go back to the last place jumped from in another pane. pub const Last = struct { pub fn run(c: Ctx) void { @@ -1856,6 +1904,28 @@ pub const Jumplist = struct { // ---- the language group ---- +/// Go to the definition of the symbol under the cursor; with an argument +/// (a 2-1 chord's selection), of that symbol, where it is nearest. +pub const Def = struct { + pub const takes_arg = true; + /// Its answer says what it found, a jump or a list or why not; its + /// name would only stack above it, as gd never did. + pub const quiet = true; + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .definition, std.mem.trim(u8, c.arg orelse "", " \t\r\n")); + } +}; + +/// 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. +pub const Refs = struct { + pub const takes_arg = true; + pub const quiet = true; // as Def + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .references, std.mem.trim(u8, c.arg orelse "", " \t\r\n")); + } +}; + /// Ask the language server about the symbol under the cursor. pub const Hover = struct { pub fn run(c: Ctx) void { @@ -1898,6 +1968,13 @@ pub const WsDiagnostics = struct { } }; +/// Show outermost callers first, with signatures and call sites (gc). +pub const Callstack = struct { + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .callstack, ""); + } +}; + /// List the callers of the function under the cursor. pub const Callers = struct { pub fn run(c: Ctx) void { diff --git a/src/colors.zig b/src/colors.zig index 2dcb906a..dd0d8938 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -126,9 +126,11 @@ test "every faithful port meets pardes's chrome floors in its own colours, with } test "a derived separator or tint keeps the theme's own when it already stands off" { - const forge = &themes[for (themes[0..native_count], 0..) |t, i| { - if (std.mem.eql(u8, t.name, "forge")) break i; - } else unreachable]; + const forge = &themes[ + for (themes[0..native_count], 0..) |t, i| { + if (std.mem.eql(u8, t.name, "forge")) break i; + } else unreachable + ]; const chrome = ChromeTheme.fromTheme(forge); try std.testing.expectEqual(forge.border.?, chrome.border); // forge's own tint is 1.23:1 off its tag: pushed on the way it leans. @@ -203,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 } ++ @@ -466,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; } @@ -499,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); @@ -512,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 @@ -675,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; } }; @@ -799,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; @@ -815,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) @@ -827,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]); @@ -845,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()); } @@ -929,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; } @@ -950,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) { @@ -1075,7 +1083,7 @@ test "render uses target content colors while chrome is in flight" { Color{ .rgb = source_chrome.tag_bg }, surface.at(0, 0).style.bg, ); - const topbar_cell = surface.at(0, 0); + const topbar_cell = surface.at(@import("pardes.zig").TAG_TEXT_INSET, 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]; @@ -1262,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 d6ea7358..a92aabb6 100644 --- a/src/config.zig +++ b/src/config.zig @@ -32,6 +32,8 @@ pub const leader_path = paths: { var table = std.EnumArray(Builtin, ?[]const u8).initDefault(@as(?[]const u8, undecided), .{ .Help = &[_]u8{leader_help}, .Hover = "lk", + .Def = null, // gd + .Refs = null, // gr .Rename = "lr", .CodeAction = "la", .SelectRefs = "lh", @@ -41,14 +43,18 @@ pub const leader_path = paths: { .WsDiagnostics = "lD", .Lspinfo = "li", .Lspwhy = "lw", + .Callstack = "lb", .Callers = "lc", .Callees = "lC", .Supertypes = "lt", .Subtypes = "lT", + .LookNext = "jn", + .LookPrev = "jp", .Del = "d", .DelAbove = null, .DelBelow = null, .Filter = null, + .Diff = null, .Mode = null, .Togglettymode = null, .Collapse = null, @@ -62,6 +68,9 @@ pub const leader_path = paths: { .Putall = null, .Incl = null, .Tab = null, + .CallstackDepth = null, + .CallstackLayout = null, + .CallstackCorners = null, .Zerox = null, .ClipYank = "y", .ClipYankMain = "Y", @@ -87,6 +96,7 @@ pub const leader_path = paths: { .BootShell = null, .LookWord = null, .DirLook = null, + .DiffLook = null, .Pager = null, .PagerColor = null, .TermImages = null, @@ -109,10 +119,11 @@ pub const leader_path = paths: { .Ascii = "ta", .Dump = "sd", .Restore = "sr", - .Left = "wh", - .Down = "wj", - .Up = "wk", - .Right = "wl", + .Left = null, + .Down = null, + .Up = null, + .Right = null, + .Window = "w", .Back = "jo", .Forward = "ji", .Last = "jj", @@ -143,6 +154,7 @@ pub const leader_path = paths: { table.set(.JumpTrail, null); table.set(.ChipShadow, null); table.set(.ThumbFlash, null); + table.set(.ProgramEsc, null); if (builtins.capabilities.lift) table.set(.Lift, null); table.set(.Motion, null); table.set(.InactiveDim, null); @@ -201,7 +213,7 @@ pub const leader_path = paths: { test "Space-k is unbound while Exit, Kill and other k chords remain available" { try std.testing.expect(leader_path.get(.Kill) == null); try std.testing.expectEqualStrings("q", leader_path.get(.Exit).?); - try std.testing.expectEqualStrings("wk", leader_path.get(.Up).?); + try std.testing.expectEqualStrings("w", leader_path.get(.Window).?); try std.testing.expectEqualStrings("lk", leader_path.get(.Hover).?); try std.testing.expectEqualStrings("d", leader_path.get(.Del).?); for (pardes.builtin_rows) |row| if (row.cmd == .Kill) { @@ -253,7 +265,8 @@ pub const select_button: Mouse.Button = .left; pub const look_cmd: Builtin = .Look; pub const exec_cmd: Builtin = .Exec; -// Ctrl-w remains available when a terminal owns printable keys. +// Ctrl-w: window mode (layout.windowKey), as SPC w; on a header it +// prefixes h/j/k/l, a move between the headers. pub const window_prefix: []const Chord = &.{.{ .cp = 'w', .ctrl = true }}; pub const window_keys = [_]struct { letter: Chord, arrow: Chord, cmd: Builtin }{ @@ -273,8 +286,9 @@ pub const jump_keys = [_]struct { chord: Chord, cmd: Builtin }{ }; /// Shift-Esc: the Esc nothing swallows. In every mode and pane it does what -/// Esc does from normal mode, back to the previous pane (Last); a raw -/// terminal's program never sees it. Ctrl-b alone toggles raw. +/// Esc does from normal mode, back to the previous pane (Last); in a raw +/// terminal plain Esc does it and Shift-Esc is the program's Esc, unless +/// ProgramEsc is on. Ctrl-b alone toggles raw. pub const back_out: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; @@ -301,6 +315,16 @@ pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump Theme 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"; +/// After a file's, on one a language server speaks for. +pub const lsp_pane_builtins_str = "Def Refs"; +/// A diff's (a .diff, a .patch, a +Pager holding one): Diff. +pub const diff_pane_builtins_str = "Save Tty Diff Collapse Del"; +/// A +Pager's (`pardes -`): Filter, as a terminal's. +pub const pager_pane_builtins_str = "Save Tty Filter Collapse Del"; +/// A +Pager holding a diff (`git show`): Diff too. +pub const pager_diff_pane_builtins_str = "Save Tty Filter Diff Collapse Del"; +/// A +Diff's: Diff again, the diff it stacks as text. +pub const diff_view_builtins_str = "Save Tty Diff Collapse Del"; pub const terminal_pane_builtins_str = "Tty Save Mode Filter Collapse Del"; pub const command_pane_builtins_str = "Kill Save Collapse Del"; /// A directory pane's (Dir.zig): Get reads it again, as acme's does. @@ -317,6 +341,8 @@ 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' }}; +pub const search_selection: []const Chord = &.{.{ .cp = '*', .alt = true }}; +pub const search_selection_word: []const Chord = &.{.{ .cp = '*' }}; pub const pipe_selection: []const Chord = &.{.{ .cp = '|' }}; pub const pipe_selection_to: []const Chord = &.{.{ .cp = '|', .alt = true }}; pub const insert_output: []const Chord = &.{.{ .cp = '!' }}; @@ -500,6 +526,7 @@ pub const unsaved_buffer = "+Unsaved"; pub const themes_buffer = "+Themes"; pub const fonts_buffer = "+Fonts"; pub const pdf_sections_buffer = "+PdfSections"; +pub const diff_buffer = "+Diff"; pub const pdf_links_buffer = "+Links"; pub const hover_buffer = "+Hover"; pub const lsp_buffer = "+Lsp"; @@ -561,7 +588,8 @@ pub const goto_line_down: []const Chord = &.{.{ .cp = 'j' }}; pub const goto_line_up: []const Chord = &.{.{ .cp = 'k' }}; pub const goto_column: []const Chord = &.{.{ .cp = '|' }}; pub const goto_view_top: []const Chord = &.{.{ .cp = 't' }}; -pub const goto_view_center: []const Chord = &.{.{ .cp = 'c' }}; +// gc opens Callstack; it no longer moves the cursor to the viewport center. +pub const goto_view_center: []const Chord = &.{}; pub const goto_view_bottom: []const Chord = &.{.{ .cp = 'b' }}; pub const goto_last_modification: []const Chord = &.{.{ .cp = '.' }}; pub const goto_word: []const Chord = &.{.{ .cp = 'w' }}; @@ -572,6 +600,7 @@ pub const goto_declaration: []const Chord = &.{.{ .cp = 'D' }}; pub const goto_type_definition: []const Chord = &.{.{ .cp = 'y' }}; pub const goto_implementation: []const Chord = &.{.{ .cp = 'i' }}; pub const goto_references: []const Chord = &.{.{ .cp = 'r' }}; +pub const goto_callstack: []const Chord = &.{.{ .cp = 'c' }}; pub const match_bracket: []const Chord = &.{.{ .cp = 'm' }}; pub const match_inside = 'i'; @@ -739,6 +768,9 @@ pub const Runtime = struct { /// T7: in a terminal, a pane's scroll thumb brightens as it scrolls and /// fades back (truecolor terminals). thumb_flash: bool = false, + /// In a raw terminal, Esc goes to the program and Shift-Esc backs out + /// (off, the default: Esc backs out and Shift-Esc is the program's). + program_esc: bool = false, /// How long a message stays after the key or click that dismisses it. message_linger_ms: u16 = 800, /// How long its fall into the row takes, easing out (§8.1: arriving, @@ -794,6 +826,10 @@ pub const Runtime = struct { /// A directory looked at: `pane`, acme's, a pane listing it (Dir.zig); /// `terminal`, what pardes did before, `ls` in a terminal there. dir_look: DirLook = .pane, + /// A .diff or .patch looked at (a look, `pardes FILE`, `--wait`): + /// `hunks`, a +Diff stacking its hunks (hunks.zig); `text`, the file + /// itself, as pardes showed it before. Diff goes from one to the other. + diff_look: DiffLook = .hunks, /// What a terminal's shell pages through (host_io.ChildEnv): `pardes`, /// PAGER and GIT_PAGER set to `pardes -`, a +Pager pane, where the /// user's environment set neither; `off`, the environment as it is. @@ -812,17 +848,23 @@ pub const Runtime = struct { /// acme's Tab: a tab's width in cells, in every pane (config.tab_now /// is what the drawing and the column arithmetic read). tab: u16 = tab_width, + callstack_layout: CallstackLayout = .stacked, + callstack_corners: CallstackCorners = .rounded, + callstack_depth: u8 = @import("lsp/lsp.zig").callstack_default_depth, pub const ShaderAnimation = enum { off, on, always }; pub const Placement = enum { acme, pardes }; pub const BootShell = enum { keep, replace }; pub const LookWord = enum { search, list }; pub const DirLook = enum { pane, terminal }; + pub const DiffLook = enum { hunks, text }; pub const Pager = enum { pardes, off }; pub const TermImages = enum { real, petscii }; pub const JumpScope = enum { file, all }; + pub const CallstackLayout = enum { @"inline", stacked }; + pub const CallstackCorners = @import("lsp/lsp.zig").CallstackCorners; /// 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, pager, term_images, jump_scope }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners }; /// 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 @@ -987,7 +1029,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, pager_color, 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, program_esc }; /// 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 }; @@ -1010,6 +1052,7 @@ pub const Runtime = struct { inactive_dim, grip_width, tab, + callstack_depth, transition: animation.Transition, scene: Scene, /// A Shadertoy file into the post chain or out of it; `off` empties @@ -1054,6 +1097,7 @@ pub const Runtime = struct { .{ .word = "JumpTrail", .action = .{ .toggle = .jump_trail }, .doc = "In a terminal, a jump of the cursor leaves a short trail that fades, on or off." }, .{ .word = "ChipShadow", .action = .{ .toggle = .chip_shadow }, .doc = "In a terminal, a notice chip casts a cell's shadow right and down, on or off." }, .{ .word = "ThumbFlash", .action = .{ .toggle = .thumb_flash }, .doc = "In a terminal, a pane's scroll thumb brightens as it scrolls and fades back, on or off." }, + .{ .word = "ProgramEsc", .action = .{ .toggle = .program_esc }, .doc = "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them." }, .{ .word = "Lift", .action = .lift, .availability = .lift, .doc = "How the focused pane stands off the page: off, shadow, rim or auto." }, .{ .word = "Motion", .action = .motion, .doc = "How animations move: off, crisp, smooth, bouncy or playful." }, .{ .word = "InactiveDim", .action = .inactive_dim, .doc = "Fade the unfocused panes' text by a percentage, 0 through 100, 0 off." }, @@ -1088,11 +1132,15 @@ pub const Runtime = struct { .{ .word = "Placement", .action = .{ .choice = .placement }, .doc = "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules." }, .{ .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 = "DiffLook", .action = .{ .choice = .diff_look }, .doc = "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other." }, .{ .word = "DirLook", .action = .{ .choice = .dir_look }, .doc = "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there." }, .{ .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." }, .{ .word = "JumpScope", .action = .{ .choice = .jump_scope }, .doc = "What Back and Forward keep to: file, the focused pane's file until it runs out that way, or all, every place in order." }, + .{ .word = "CallstackLayout", .action = .{ .choice = .callstack_layout }, .doc = "Callstack snippets below their locations (stacked, the default) or beside them (inline); bare, it switches layouts. Applies to the next Callstack query." }, + .{ .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." }, }; @@ -1294,6 +1342,12 @@ pub const Runtime = struct { 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; @@ -1336,6 +1390,7 @@ pub const Runtime = struct { .inactive_dim, .window_opacity, .window_blur => "0-100 (a percentage)", .grip_width => "50-300 (a percentage)", .tab => "1-16 (cells)", + .callstack_depth => "1-64 (levels)", .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", @@ -1498,6 +1553,7 @@ pub const Runtime = struct { try out.print("# {s} unsupported\n", .{setting.word}), .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 }) @@ -1787,14 +1843,18 @@ pub const Runtime = struct { .boot_shell => "replace", .look_word => "list", .dir_look => "terminal", + .diff_look => "text", .pager => "off", .term_images => "petscii", .jump_scope => "all", + .callstack_layout => "inline", + .callstack_corners => "square", }, .lift => "rim", .motion => "playful", .inactive_dim => "35", .grip_width => "200", + .callstack_depth => "16", .tab => "8", else => null, }; @@ -1824,6 +1884,7 @@ pub const Runtime = struct { .jump_trail => "JumpTrail on\n", .chip_shadow => "ChipShadow on\n", .thumb_flash => "ThumbFlash on\n", + .program_esc => "ProgramEsc on\n", }, .shell => "Shell fish\n", .tagline_size => "TaglineSize 73\n", @@ -1862,14 +1923,18 @@ pub const Runtime = struct { .boot_shell => "BootShell replace\n", .look_word => "LookWord list\n", .dir_look => "DirLook terminal\n", + .diff_look => "DiffLook text\n", .pager => "Pager off\n", .term_images => "TermImages petscii\n", .jump_scope => "JumpScope all\n", + .callstack_layout => "CallstackLayout inline\n", + .callstack_corners => "CallstackCorners square\n", }, .lift => "Lift rim\n", .motion => "Motion playful\n", .inactive_dim => "InactiveDim 35\n", .grip_width => "GripWidth 200\n", + .callstack_depth => "CallstackDepth 16\n", .tab => "Tab 8\n", .theme, .font => unreachable, }; @@ -2114,10 +2179,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); } @@ -2183,25 +2250,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; @@ -2235,7 +2303,7 @@ const doc_typ = struct { if (w.end > 0) w.writeByte(' ') catch return false; w.writeAll(x[0 .. std.mem.indexOfScalar(u8, x, '+') orelse x.len]) catch return false; } - const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str }; + const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, diff_pane_builtins_str, pager_pane_builtins_str, pager_diff_pane_builtins_str, diff_view_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str }; for (tags) |d| if (std.mem.eql(u8, d, w.buffered())) return true; return false; } @@ -2447,3 +2515,16 @@ test "reference.typ's #fstree is the tree the session serves, file for file" { }; if (drift) return error.FsTreeDrift; } + +test "CallstackDepth is bounded and keeps the last valid runtime limit" { + var state: Runtime = .{}; + try std.testing.expectEqual(@as(u8, 8), state.callstack_depth); + for ([_][]const u8{ "1", "8", "16", "64" }) |value| { + 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| { + 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/detached/client.zig b/src/detached/client.zig index 69ab2fdd..60950208 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; } } @@ -1209,7 +1209,7 @@ test "detached session: a frontend is never asked to fork, write, or watch" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(wire.ServerTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { std.debug.print("tag 0x{x:0>2} is decodable by a frontend and is not one of the nine\n", .{tag}); diff --git a/src/detached/server.zig b/src/detached/server.zig index 79d1189a..d6a1f553 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -660,7 +660,7 @@ pub const Session = struct { for (&s.ptys, 0..) |*pt, pane| { if (pt.fd < 0) continue; var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(pt.pid, &lbuf)) |cwd| s.core.setCwd(pane, cwd); + if (host_io.ttyCwd(pt.pid, pt.fd, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(pane, cwd); } } @@ -1049,7 +1049,7 @@ pub const Session = struct { } fn apply(s: *Session, c: *Client, slot: u8, tag: u8, payload: []const u8) wire.Error!void { - if (tag == @intFromEnum(wire.ClientTag.hello)) { + if (tag == @backingInt(wire.ClientTag.hello)) { if (c.attached) return error.BadValue; const claimed = try wire.helloVersion(payload); if (claimed != wire.version) { @@ -1124,7 +1124,7 @@ pub const Session = struct { if (entry.scene == null) break true; } else false; const compiled = s.shaders.sync(s.gpa, s.io, s.core, if (files) s.inotify() else s.inotify_fd, &s.watches, .{ .ctx = &s.mailbox, .call = wakeForExit }); - const key = @as(u64, s.shaders.revision) << 8 | @intFromEnum(s.core.settings.shader_animation); + const key = @as(u64, s.shaders.revision) << 8 | @backingInt(s.core.settings.shader_animation); var chain: wire.Post = .{ .animation = s.core.settings.shader_animation, .len = s.core.settings.post.len }; _ = s.shaders.view(&s.core.settings.post, &chain.passes); for (&s.clients) |*c| { diff --git a/src/detached/wire.zig b/src/detached/wire.zig index c9d9b578..d57a28be 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; @@ -567,13 +569,13 @@ pub fn framed(buf: []const u8) Error!?Framed { fn putColor(w: *Writer, c: pardes.Color) Error!void { switch (c) { - .default => try w.putByte(@intFromEnum(ColorTag.default)), + .default => try w.putByte(@backingInt(ColorTag.default)), .index => |i| { - try w.putByte(@intFromEnum(ColorTag.index)); + try w.putByte(@backingInt(ColorTag.index)); try w.putByte(i); }, .rgb => |v| { - try w.putByte(@intFromEnum(ColorTag.rgb)); + try w.putByte(@backingInt(ColorTag.rgb)); try w.putBytes(&v); }, } @@ -604,7 +606,7 @@ const Ul = @FieldType(pardes.CellStyle, "ul"); /// 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))), + inline else => |t| @backingInt(@field(UlTag, @tagName(t))), }); } @@ -616,7 +618,7 @@ fn getUl(r: *Reader) Error!Ul { fn putFont(w: *Writer, f: pardes.FontRole) Error!void { try w.putByte(switch (f) { - inline else => |t| @intFromEnum(@field(FontTag, @tagName(t))), + inline else => |t| @backingInt(@field(FontTag, @tagName(t))), }); } @@ -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 @@ -793,12 +795,12 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point std.debug.assert(cells.len == @as(usize, cols) * @as(usize, rows)); const full = prev.len != cells.len; var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(ServerTag.frame)); + const at = try beginMessage(&w, @backingInt(ServerTag.frame)); const header: FrameHeader = if (pointer_shape == .link) (if (full) .full_link else .diff_link) else (if (full) .full else .diff); - try w.putByte(@intFromEnum(header)); + try w.putByte(@backingInt(header)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, cursor, cols, rows); @@ -835,7 +837,7 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point for (tags) |layer| { if (layer.rows == 0) continue; if (layer.cells.len != @as(usize, layer.cols) * layer.rows) return error.BadValue; - try w.putByte(@intFromEnum(layer.kind)); + try w.putByte(@backingInt(layer.kind)); try w.putU16(layer.id); try w.putU32(layer.serial); try w.putU16(layer.viewport.x); @@ -850,7 +852,7 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point } try w.putU16(@intCast(regions.len)); for (regions) |region| { - try w.putByte(@intFromEnum(region.kind)); + try w.putByte(@backingInt(region.kind)); try w.putByte(region.owner); try w.putU32(region.serial); try w.putU16(region.rect.x); @@ -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); } @@ -1000,7 +1003,7 @@ fn getBodyHit(r: *Reader) Error!?pardes.Mouse.BodyHit { fn putTagHit(w: *Writer, hit: ?pardes.TagHit) Error!void { try w.putBool(hit != null); if (hit) |h| { - try w.putByte(@intFromEnum(h.kind)); + try w.putByte(@backingInt(h.kind)); try w.putU16(h.id); try w.putU32(h.serial); try w.putU16(h.col); @@ -1027,7 +1030,7 @@ fn getTagHit(r: *Reader) Error!?pardes.TagHit { pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(clientTag(msg))); + const at = try beginMessage(&w, @backingInt(clientTag(msg))); switch (msg) { .hello => |h| { try w.putU16(h.version); @@ -1045,10 +1048,10 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { }, .mouse => |m| { try w.putByte(switch (m.button) { - inline else => |t| @intFromEnum(@field(ButtonTag, @tagName(t))), + inline else => |t| @backingInt(@field(ButtonTag, @tagName(t))), }); try w.putByte(switch (m.kind) { - inline else => |t| @intFromEnum(@field(KindTag, @tagName(t))), + inline else => |t| @backingInt(@field(KindTag, @tagName(t))), }); try w.putU16(m.col); try w.putU16(m.row); @@ -1161,7 +1164,7 @@ fn serverTag(msg: ServerMsg) ServerTag { /// payload is a walk of two grids rather than a value (see `encodeFrame`). pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(serverTag(msg))); + const at = try beginMessage(&w, @backingInt(serverTag(msg))); switch (msg) { .welcome => |v| { try w.putU16(v.version); @@ -1169,7 +1172,7 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { try w.putU16(v.cols); try w.putU16(v.rows); }, - .refuse => |why| try w.putByte(@intFromEnum(why)), + .refuse => |why| try w.putByte(@backingInt(why)), // A frame's runs are not a value this union can hold; the server calls // encodeFrame directly and this arm exists so the switch stays // exhaustive over ServerMsg. @@ -1179,11 +1182,11 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { .read_clipboard => {}, .open_link => |u| try w.putSlice16(u), .post => |p| { - try w.putByte(@intFromEnum(p.animation)); + try w.putByte(@backingInt(p.animation)); try w.putByte(p.len); for (p.list()) |pass| { // 0 a file, else a bundled scene and one. - try w.putByte(if (pass.scene) |scene| @as(u8, @intFromEnum(scene)) + 1 else 0); + try w.putByte(if (pass.scene) |scene| @as(u8, @backingInt(scene)) + 1 else 0); try w.putByte(pass.level); try w.putByte(@intFromBool(pass.animated)); try w.putU32(pass.revision); @@ -1338,9 +1341,9 @@ test "detached wire: every Event variant round-trips" { // The tag space is the protocol's own, so assert the numbers themselves: // a renumbering here breaks every deployed frontend and must be a diff // somebody reads, not a silent change. - try testing.expectEqual(@as(u8, 0x01), @intFromEnum(ClientTag.hello)); - try testing.expectEqual(@as(u8, 0x10), @intFromEnum(ClientTag.key)); - try testing.expectEqual(@as(u8, 0x1d), @intFromEnum(ClientTag.pointer_leave)); + try testing.expectEqual(@as(u8, 0x01), @backingInt(ClientTag.hello)); + try testing.expectEqual(@as(u8, 0x10), @backingInt(ClientTag.key)); + try testing.expectEqual(@as(u8, 0x1d), @backingInt(ClientTag.pointer_leave)); { const got = try roundClient(&buf, .{ .hello = .{ .cols = 80, .rows = 24 } }); @@ -1503,7 +1506,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(ClientTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { std.debug.print("tag 0x{x:0>2} is decodable by a session and is not something a human did\n", .{tag}); @@ -1749,8 +1752,8 @@ test "detached wire: a truncated frame is refused at every length" { for (0..header_len + 1) |cut| try testing.expectEqual(@as(?Framed, null), try framed(copy[0..cut])); // A payload with bytes LEFT OVER is refused too: it is not this message. - try testing.expectError(error.Trailing, decodeClient(@intFromEnum(ClientTag.pointer_leave), "x")); - try testing.expectError(error.Trailing, decodeServer(@intFromEnum(ServerTag.quit), "x")); + try testing.expectError(error.Trailing, decodeClient(@backingInt(ClientTag.pointer_leave), "x")); + try testing.expectError(error.Trailing, decodeServer(@backingInt(ServerTag.quit), "x")); } test "detached wire: an unknown tag is refused, never guessed" { @@ -1762,9 +1765,9 @@ test "detached wire: an unknown tag is refused, never guessed" { } // A tag NESTED in a payload gets the same treatment: a color, an // underline style, a mouse button, a refusal reason. - try testing.expectError(error.BadTag, decodeServer(@intFromEnum(ServerTag.refuse), &.{0x7f})); + try testing.expectError(error.BadTag, decodeServer(@backingInt(ServerTag.refuse), &.{0x7f})); try testing.expectError(error.BadTag, decodeClient( - @intFromEnum(ClientTag.mouse), + @backingInt(ClientTag.mouse), &.{ 0xff, 0x00, 0, 0, 0, 0, 0 }, )); } @@ -1772,7 +1775,7 @@ test "detached wire: an unknown tag is refused, never guessed" { test "detached wire: an over-long length prefix is refused before it is believed" { // The prefix a hostile or corrupt peer sends to make the receiver allocate // or index by it. `framed` must refuse rather than wait for 4 GiB. - var head: [header_len]u8 = .{ @intFromEnum(ClientTag.paste), 0, 0, 0, 0 }; + var head: [header_len]u8 = .{ @backingInt(ClientTag.paste), 0, 0, 0, 0 }; std.mem.writeInt(u32, head[1..5], max_payload + 1, .little); try testing.expectError(error.Overlong, framed(&head)); std.mem.writeInt(u32, head[1..5], std.math.maxInt(u32), .little); @@ -1786,10 +1789,10 @@ test "detached wire: an over-long length prefix is refused before it is believed var paste: [8]u8 = undefined; std.mem.writeInt(u32, paste[0..4], 4096, .little); @memcpy(paste[4..8], "abcd"); - try testing.expectError(error.Truncated, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.Truncated, decodeClient(@backingInt(ClientTag.paste), &paste)); // ...and past the cap, which is refused rather than read. std.mem.writeInt(u32, paste[0..4], max_payload + 1, .little); - try testing.expectError(error.Overlong, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.Overlong, decodeClient(@backingInt(ClientTag.paste), &paste)); } test "detached wire: a frame that lies about its runs cannot walk out of the grid" { @@ -1834,13 +1837,13 @@ test "detached wire: a frame that lies about its runs cannot walk out of the gri // it is used to bound the walk. var head: [frame_head]u8 = undefined; var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, null, cols, rows); try w.putU32(0); // no body layers try w.putU32(9); - try testing.expectError(error.Overlong, decodeServer(@intFromEnum(ServerTag.frame), w.written())); + try testing.expectError(error.Overlong, decodeServer(@backingInt(ServerTag.frame), w.written())); // ...and a grid of the wrong size is the receiver's own bug, not a frame // it should paint half of. @@ -1882,7 +1885,7 @@ test "detached wire: a cursor outside the grid is refused, not painted" { var head: [frame_head]u8 = undefined; for ([_][2]u16{ .{ cols, 0 }, .{ 0, rows }, .{ 0xffff, 0xffff } }) |xy| { var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); // Written by hand: `putCursor` now refuses this too, which is the @@ -1894,19 +1897,19 @@ test "detached wire: a cursor outside the grid is refused, not painted" { try w.putU32(0); try testing.expectError( error.BadValue, - decodeServer(@intFromEnum(ServerTag.frame), w.written()), + decodeServer(@backingInt(ServerTag.frame), w.written()), ); } // The last cell IS in the grid, and a frame carrying it decodes. { var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, .{ .x = cols - 1, .y = rows - 1, .bar = true }, cols, rows); try w.putU32(0); // no body layers try w.putU32(0); - const got = (try decodeServer(@intFromEnum(ServerTag.frame), w.written())).frame; + const got = (try decodeServer(@backingInt(ServerTag.frame), w.written())).frame; try testing.expectEqual(@as(u16, cols - 1), got.cursor.?.x); try testing.expectEqual(@as(u16, rows - 1), got.cursor.?.y); } @@ -1930,25 +1933,25 @@ test "detached wire: values a field cannot mean are refused" { // A bool is 0 or 1. `2` used to be "true" in every hand-written codec that // ever silently accepted a corrupt stream. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 'a', 0, 0, 0, 0, 0, 2, 0, 0 }, )); // A codepoint past Unicode's last: @intCast into Key.cp's u21 would panic. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 0x00, 0x00, 0x11, 0x00, 0, 0, 0, 0, 0 }, )); // A pane the core cannot index. `pdf_scroll` reads its pane byte before the // f32 that follows, so a one-byte payload reaches the check this is about // rather than tripping `Truncated` first. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.pdf_scroll), + @backingInt(ClientTag.pdf_scroll), &.{pardes.MAX_PANES}, )); // A zero-column grid would collapse a shared session; an over-wide one is // past what this protocol carries. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.hello), + @backingInt(ClientTag.hello), &.{ 1, 0, 0, 0, 24, 0 }, )); { @@ -1956,15 +1959,15 @@ test "detached wire: values a field cannot mean are refused" { std.mem.writeInt(u16, hello[0..2], version, .little); std.mem.writeInt(u16, hello[2..4], max_cols + 1, .little); std.mem.writeInt(u16, hello[4..6], 24, .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.hello), &hello)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.hello), &hello)); } // A NaN scroll distance. `pinch` multiplies into a zoom the pane keeps. { var pinch: [4]u8 = undefined; std.mem.writeInt(u32, &pinch, @bitCast(std.math.nan(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.pinch), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.pinch), &pinch)); std.mem.writeInt(u32, &pinch, @bitCast(std.math.inf(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.touch_scroll), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.touch_scroll), &pinch)); } // A cell with the reserved attribute bit set, and one with an impossible // grapheme length. Both are bytes this protocol has no meaning for. diff --git a/src/diff.zig b/src/diff.zig index 362695d5..842a6b41 100644 --- a/src/diff.zig +++ b/src/diff.zig @@ -163,8 +163,8 @@ pub const Walk = struct { }; const meta_words = [_][]const u8{ - "index ", "new file mode ", "deleted file mode ", "old mode ", "new mode ", - "similarity index ", "rename from ", "rename to ", "copy from ", "copy to ", + "index ", "new file mode ", "deleted file mode ", "old mode ", "new mode ", + "similarity index ", "rename from ", "rename to ", "copy from ", "copy to ", "Binary files ", "dissimilarity ", }; diff --git a/src/draw.zig b/src/draw.zig index 9fcbb15f..3d0d4d3c 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -87,6 +87,8 @@ pub fn place(p: *Pardes, s: *Surface) void { const pos = (track_h * sb.offset) / total; rail.thumb_y = @intCast(@min(pos, track_h)); rail.thumb_h = @intCast(@min(len, track_h - rail.thumb_y)); + rail.thumb_at = @as(f32, @floatFromInt(sb.offset)) / @as(f32, @floatFromInt(total)); + rail.thumb_span = @as(f32, @floatFromInt(@max(1, sb.len))) / @as(f32, @floatFromInt(total)); } s.addRegion(rail); // Each notice a chip at the right edge, one to a row in the order @@ -280,15 +282,20 @@ fn glideCursor(p: *Pardes, s: *Surface) void { const seen = frame.unplace(old.place(at)); p.cursor_glide.shift(seen[0] - at[0], seen[1] - at[1]); p.cursor_crossing = true; + p.cursor_held = p.drag == .select; } p.cursor_view = .{ .serial = pane.serial, .line = line, .origin = origin, .inside = inside }; } - p.cursor_glide.aim(box, p.now_ns, motion, snap); + // A click that took focus places the cursor on its release; aimed at + // the pane's old cursor meanwhile, it would glide there first. + if (p.drag != .select) p.cursor_held = false; + if (!p.cursor_held) p.cursor_glide.aim(box, p.now_ns, motion, snap); _ = p.cursor_glide.step(p.now_ns); const moving = p.cursor_glide.moving(); - if (!moving) p.cursor_crossing = false; - // Drawn as the quad while it glides and while its pane moves. - s.chrome.cursor_glide = 2 | @as(u8, @intFromBool(moving or frame.moving())); + if (!moving and !p.cursor_held) p.cursor_crossing = false; + // Drawn as the quad while it glides, while its pane moves and while it + // waits for a click's release. + s.chrome.cursor_glide = 2 | @as(u8, @intFromBool(moving or frame.moving() or p.cursor_held)); // The shell blinks it, from how long ago the last key or click was. if (p.settings.cursor_blink) s.chrome.cursor_idle_ms = @intCast(@min(std.math.maxInt(u32) - 1, (p.now_ns -| p.input_ns) / std.time.ns_per_ms)); @@ -412,15 +419,15 @@ fn recede(p: *Pardes, s: *Surface, id: usize, amount: f32, focused: bool) void { } } const body = &s.body_layers[id]; - if (body.rows != 0) for (body.cells[0..@as(usize, body.cols) * body.rows]) |*cell| { + if (body.rows != 0) for (body.cells[0 .. @as(usize, body.cols) * body.rows]) |*cell| { if (!(focused and selected(cell, th.sel_bg))) fadeStyle(&cell.style, th.fg, th.bg, palette, amount, &memo); }; if (focused) return; const tag = &s.tag_layers[id]; - if (tag.rows != 0) for (tag.cells[0..@as(usize, tag.cols) * tag.rows]) |*cell| fadeStyle(&cell.style, chrome.tag_fg, tag.bg, palette, amount, &memo); + if (tag.rows != 0) for (tag.cells[0 .. @as(usize, tag.cols) * tag.rows]) |*cell| fadeStyle(&cell.style, chrome.tag_fg, tag.bg, palette, amount, &memo); for (0..Pane.Notices.max) |i| { const notice = &s.tag_layers[NOTICE_LAYER_BASE + id * Pane.Notices.max + i]; - if (notice.rows != 0) for (notice.cells[0..@as(usize, notice.cols) * notice.rows]) |*cell| fadeStyle(&cell.style, chrome.tag_fg, notice.bg, palette, amount, &memo); + if (notice.rows != 0) for (notice.cells[0 .. @as(usize, notice.cols) * notice.rows]) |*cell| fadeStyle(&cell.style, chrome.tag_fg, notice.bg, palette, amount, &memo); } } @@ -564,7 +571,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { .accent = chrome.box, .sel_fg = p.theme().sel_fg, .sel_bg = p.theme().sel_bg, - .lift_style = @intFromEnum(liftStyle(p)), + .lift_style = @backingInt(liftStyle(p)), .rule_px = p.theme().rule_px orelse 2, .grip_border = boxBorder(p), .grip_focus_ring = chrome.box, @@ -934,7 +941,9 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: .bg = .{ .rgb = band }, .font_role = .tagline, }); - s.set(r.x, tag_y, switch (pane.body.mode) { + // In window mode the box holds the pane's letter instead of its mode. + const label: ?u8 = if (p.window_pick != null) layout.windowLabel(p, id) else null; + s.set(r.x, tag_y, if (label) |*letter| @as(*const [1]u8, letter) else switch (pane.body.mode) { .normal => config.tag_normal, .insert => config.tag_insert, .tty => config.tag_tty, @@ -978,7 +987,12 @@ pub fn paintHeaders(p: *Pardes, s: *Surface, arena: std.mem.Allocator) !void { if (s.region(.workspace_tag, Region.none)) |region| { const top = if (p.header_focus and p.header_column == null) p.header_top else 0; const layer = &s.tag_layers[MAX_PANES + MAX_COLS]; - try renderHeaderLayer(p, arena, layer, .workspace, 0, region.rect, tagline.topbar(p), top, chrome.tag_bg, chrome.tag_fg); + var viewport = region.rect; + const inset = @min(TAG_TEXT_INSET, viewport.w); + s.fill(viewport.x, viewport.y, inset, viewport.h, .{ .bg = .{ .rgb = chrome.tag_bg }, .fg = .{ .rgb = chrome.tag_fg }, .font_role = .tagline }); + viewport.x += inset; + viewport.w -= inset; + try renderHeaderLayer(p, arena, layer, .workspace, 0, viewport, tagline.topbar(p), top, chrome.tag_bg, chrome.tag_fg); joinHeaderRows(s, layer, chrome.tag_fg); } const column_rows = p.columnBarHeight(); @@ -1162,7 +1176,7 @@ fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, layer: *pardes.Layer, const start = modal.lineStartOffset(text, index + top); const end = start + shown.len; if (mine and swept.lo < swept.hi and swept.hi > start and swept.lo < end) { - const button = @intFromEnum(sweep.button); + const button = @backingInt(sweep.button); var col = panes.File.rawDisplayCol(shown, @max(swept.lo, start) - start) -| scroll; const stop = panes.File.rawDisplayCol(shown, @min(swept.hi, end) - start) -| scroll; while (col < stop and col < columns) : (col += 1) { @@ -1196,6 +1210,16 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r @memset(storage, .{}); var temporary: Surface = .{ .cols = columns + TAG_TEXT_INSET, .rows = rows, .cells = storage }; try paintPaneTag(p, &temporary, arena, pane, .{ .x = 0, .y = 0, .w = columns + TAG_TEXT_INSET, .h = rows }, id, active, capacity); + // Window mode (layout.windowKey): the outlined pane's tag in the + // selection's colours. + if (p.window_pick == id) { + const th = p.theme(); + for (storage) |*cell| { + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + cell.default = false; + } + } const tag_fg: Color = .{ .rgb = if (active and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg }; // One layer, a row to each line the tag shows. const layer = &s.tag_layers[id]; @@ -1208,7 +1232,7 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r layer.cols = columns; layer.rows = rows; layer.context_rows = 0; - layer.bg = if (active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; + layer.bg = if (p.window_pick == id) p.theme().sel_bg else if (active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; layer.slide = 0; layer.fade = 1; layer.cursor = if (p.header_focus) null else if (temporary.cursor) |cursor| @@ -1348,8 +1372,7 @@ pub fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pa const at = modal.positionAt(shown.text, shown.fromReal(@intCast(@max(0, pane.input.cur_col)))); if (at.row < top or at.row >= top + rows) break :caret null; break :caret .{ .row = at.row - top, .at = @min(lines[at.row - top].len, at.col) }; - } - else if (pane.focus == .tag and pane.prompt == .none) caret: { + } else if (pane.focus == .tag and pane.prompt == .none) caret: { const real = modal.offsetAt(whole, .{ .row = @intCast(@max(0, pane.tag.cur_row)), .col = @intCast(@max(0, pane.tag.cur_col)) }); const at = modal.positionAt(shown.text, shown.fromReal(real)); if (at.row < top or at.row >= top + rows) break :caret null; @@ -1594,7 +1617,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); @@ -1709,7 +1732,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); @@ -1948,7 +1971,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(); @@ -2074,7 +2097,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. @@ -2097,10 +2120,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); @@ -2139,7 +2162,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); }, @@ -2169,7 +2192,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; @@ -2197,7 +2220,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; @@ -2246,7 +2269,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(); @@ -2349,6 +2372,40 @@ test "focus moved to another column glides from where the cursor was drawn" { try std.testing.expect(!p.cursor_glide.moving() and !p.cursor_crossing); } +test "a click that takes focus glides the cursor once, to where it lands on release" { + if (!builtins.capabilities.lift) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20 }); + defer p.deinit(); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + p.settings.motion = .smooth; + try twoColumns(p, &arena); + p.active = 0; + p.advance(3 * std.time.ns_per_s); + _ = arena.reset(.retain_capacity); + const before = try p.render(arena.allocator()); + const was: [2]f32 = .{ before.chrome.cursor_quad[0], before.chrome.cursor_quad[1] }; + // Pressed in the other column: focus moves, the cursor waits. + p.active = 1; + p.drag = .{ .select = .{ .id = 1, .button = config.select_button } }; + for (0..3) |_| { + p.advance(p.now_ns + 100 * std.time.ns_per_ms); + _ = arena.reset(.retain_capacity); + const held = try p.render(arena.allocator()); + try std.testing.expectApproxEqAbs(was[0], held.chrome.cursor_quad[0], 0.01); + try std.testing.expectApproxEqAbs(was[1], held.chrome.cursor_quad[1], 0.01); + } + // Released: one glide, from there to the placed cursor. + p.drag = .none; + _ = arena.reset(.retain_capacity); + _ = try p.render(arena.allocator()); + try std.testing.expect(p.cursor_glide.moving()); + p.advance(p.now_ns + 5 * std.time.ns_per_s); + _ = arena.reset(.retain_capacity); + const landed = try p.render(arena.allocator()); + try std.testing.expectApproxEqAbs(focusedCursorBox(p, landed).?.x, landed.chrome.cursor_quad[0], 0.01); +} + test "focus moving to a pane with no cursor while the cursor glides lets the session go idle" { if (!builtins.capabilities.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20 }); @@ -2382,7 +2439,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; @@ -2392,7 +2449,7 @@ test "a pane focus reaches brightens on the same spring the one it leaves dims o // The file's first glyph's ink, in whichever form its body has. fn of(s: *const Surface) [3]u8 { const body = &s.body_layers[0]; - const cells = if (body.rows != 0) body.cells[0..@as(usize, body.cols) * body.rows] else s.cells; + const cells = if (body.rows != 0) body.cells[0 .. @as(usize, body.cols) * body.rows] else s.cells; for (cells) |cell| if (!cell.default and cell.len == 1 and cell.text[0] == 's' and cell.style.font_role == .body) return switch (cell.style.fg) { .rgb => |rgb| rgb, else => .{ 0, 0, 0 }, diff --git a/src/dump.zig b/src/dump.zig index 201f5bf2..76a6de85 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -56,7 +56,7 @@ pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { const ds = es.getDaySeconds(); var stamp: [32]u8 = undefined; const base = std.fmt.bufPrint(&stamp, "pardes-{d:0>4}{d:0>2}{d:0>2}-{d:0>2}{d:0>2}{d:0>2}", .{ - yd.year, md.month.numeric(), @as(u8, md.day_index) + 1, + yd.year, md.month.numeric(), @as(u8, md.day_index) + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(), }) catch return null; return uniqueIn(buf, dir, base); @@ -194,6 +194,8 @@ pub const Terminal = struct { }; pub const LocationRow = struct { + mark_occurrence: bool = true, + source_column: usize = 0, kind: enum { match, context, preview }, declaration: bool = false, path: []const u8, @@ -419,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; @@ -434,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; @@ -1106,7 +1100,7 @@ test "a restored session's column and workspace tags take more than one selectio try std.testing.expect(restored.col_tags[0].reserveSels()); try std.testing.expect(restored.global_tag.reserveSels()); try std.testing.expect(restored.fs.started != 0); - const stat = th.call(restored, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(pardes.ctlfs.TopFile.index) }); + const stat = th.call(restored, .{ .tag = 1, .op = .getattr, .node = @backingInt(pardes.ctlfs.TopFile.index) }); try std.testing.expect(stat.reply.attr.mtime != 0); } @@ -1152,7 +1146,7 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and const node = if (std.mem.eql(u8, word, "Del") or std.mem.eql(u8, word, "get")) ctlfs.Node.of(restored.panes[id].?.serial, .ctl) else - @intFromEnum(ctlfs.TopFile.ctl); + @backingInt(ctlfs.TopFile.ctl); const line = if (std.mem.eql(u8, word, "Restore")) try std.fmt.bufPrint(&restore_line, "Restore {s}/d.zon\n", .{dir}) else if (std.mem.eql(u8, word, "Exit")) "Exit\n" else if (std.mem.eql(u8, word, "Del")) "Del\n" else "get\n"; const answer = th.wr(restored, node, line); try std.testing.expectEqual(ctlfs.Status.err, answer.reply.status); diff --git a/src/edit.zig b/src/edit.zig index b2909d87..466b5cdb 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -229,10 +229,10 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { const prefix: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; for (rows, 0..) |*row, index| { const visible = first + @as(i32, @intCast(index)); - // A stream: only the first row starts where the press was; the - // others start after the line numbers, and all but the last run on. + // A stream: only the first row starts where the press was, and no + // row takes in the line numbers; all but the last run on. const cols = sweepCols(gesture, visible + @as(i32, pane.tag_rows)).?; - const left: i32 = if (cols.first) cols.lo else prefix; + const left: i32 = if (cols.first) @max(cols.lo, prefix) 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 }; @@ -241,8 +241,8 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { 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)))); + const lo = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix - source.pad)))); + const at = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix - source.pad)))); row.* = .{ .row = source.line, .lo = lo, @@ -251,11 +251,6 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { .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; @@ -273,7 +268,7 @@ pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { 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); + total += @min(row.hi, line.len) - @min(row.lo, line.len); } const result = try arena.alloc(u8, total); var at: usize = 0; @@ -282,8 +277,6 @@ pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { 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); @@ -307,9 +300,9 @@ pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { ) != null; if (!first and !soft) try out.append(arena, '\n'); first = false; - // Past the first row a body row starts after its line numbers. + // A body row starts after its line numbers, wherever the press was. const gutter: i32 = if (pane.file != null and v >= pane.tag_rows) panes.File.gutterWidth(pane) else 0; - const lo: usize = @intCast(if (cols.first) cols.lo else gutter); + const lo: usize = @intCast(if (cols.first) @max(cols.lo, gutter) else gutter); const b0 = @min(panes.File.renderedLineByteCol(pane, v, line, lo), line.len); const b1 = if (cols.hi) |hi| @max(b0, modal.nextGrapheme(line, @min(panes.File.renderedLineByteCol(pane, v, line, @intCast(hi)), line.len))) diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig index 83cc7e4f..c8473e99 100644 --- a/src/edit_cmd.zig +++ b/src/edit_cmd.zig @@ -98,7 +98,9 @@ const World = struct { // A look opens it, or finds it open, where a look would; the // keyboard stays where the Edit ran. const was = p.active; + p.look_text = true; look.lookAt(p, w.from, path); + p.look_text = false; if (p.panes[was] != null) p.active = was; for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; @@ -516,7 +518,7 @@ test "Edit , | sort runs off the loop, through the session's shell in the file's 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()); + try testing.expectEqual(tree.E.INVAL, th.wr(p, @backingInt(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" { diff --git a/src/esp32p4.zig b/src/esp32p4.zig index 6772e75d..683d19e1 100644 --- a/src/esp32p4.zig +++ b/src/esp32p4.zig @@ -134,19 +134,19 @@ pub const GpioFn = *const fn (ctx: ?*anyopaque, pin: u16, was: *u8, now: *u8) ca var host_alloc: Allocator = undefined; fn hostAlloc(_: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { - return host_alloc.alloc(host_alloc.ctx, len, @intFromEnum(alignment)); + return host_alloc.alloc(host_alloc.ctx, len, @backingInt(alignment)); } fn hostResize(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool { - return host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment), new_len); + return host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment), new_len); } fn hostRemap(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) ?[*]u8 { - return if (host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment), new_len)) mem.ptr else null; + return if (host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment), new_len)) mem.ptr else null; } fn hostFree(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, _: usize) void { - host_alloc.free(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment)); + host_alloc.free(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment)); } const host_vtable: std.mem.Allocator.VTable = .{ @@ -447,19 +447,21 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { else => null, }; if (button) |b| { - c.update(.{ .mouse = .{ - .button = b, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, + c.update(.{ + .mouse = .{ + .button = b, + .kind = switch (m.type) { + .press => .press, + .release => .release, + .motion => .motion, + .drag => .drag, + }, + // Before the first cell (a drag past the edge): the edge. + .col = @intCast(@max(0, m.col)), + .row = @intCast(@max(0, m.row)), + .ctrl = m.mods.ctrl, }, - // Before the first cell (a drag past the edge): the edge. - .col = @intCast(@max(0, m.col)), - .row = @intCast(@max(0, m.row)), - .ctrl = m.mods.ctrl, - } }); + }); dirty = true; } }, @@ -506,7 +508,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/app.zig b/src/esp32p4/app.zig index 4ee131ec..800e7597 100644 --- a/src/esp32p4/app.zig +++ b/src/esp32p4/app.zig @@ -235,17 +235,17 @@ var gpa_heap: heapmod.Heap = undefined; fn cAlloc(_: ?*anyopaque, len: usize, log2_align: u8) callconv(.c) ?[*]u8 { const a = gpa_heap.allocator(); - return a.vtable.alloc(a.ptr, len, @enumFromInt(log2_align), @returnAddress()); + return a.vtable.alloc(a.ptr, len, @fromBackingInt(@intCast(log2_align)), @returnAddress()); } fn cResize(_: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8, new_len: usize) callconv(.c) bool { const a = gpa_heap.allocator(); - return a.vtable.resize(a.ptr, ptr[0..len], @enumFromInt(log2_align), new_len, @returnAddress()); + return a.vtable.resize(a.ptr, ptr[0..len], @fromBackingInt(@intCast(log2_align)), new_len, @returnAddress()); } fn cFree(_: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8) callconv(.c) void { const a = gpa_heap.allocator(); - a.vtable.free(a.ptr, ptr[0..len], @enumFromInt(log2_align), @returnAddress()); + a.vtable.free(a.ptr, ptr[0..len], @fromBackingInt(@intCast(log2_align)), @returnAddress()); } const editor_allocator: Allocator = .{ 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/esp32p4_9p.zig b/src/esp32p4_9p.zig index cd59b9df..5fcab85b 100644 --- a/src/esp32p4_9p.zig +++ b/src/esp32p4_9p.zig @@ -103,7 +103,7 @@ fn die(msg: []const u8) noreturn { .{ .rerror = .{ .ename = msg[0..@min(msg.len, ninep.errmax)] } }, ninep.notag, &buf, - // unreachable: the message is cut to errmax and buf is sized to it + // unreachable: the message is cut to errmax and buf is sized to it ) catch unreachable; uart.write(bytes); while (true) {} diff --git a/src/exec.zig b/src/exec.zig index 2a6bd55c..d03a4a48 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -140,7 +140,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l &pane.body, wrapped.line, wrapped.at, - clicked.c0 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), + clicked.c0 - wrapped.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), ) else clicked.c0; @@ -214,9 +214,9 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l const last = pane.wrapRow(row, hi - 1); if (first.row < 0 or last.row < 0) return result; expanded.r0 = first.row + @as(i32, pane.tag_rows); - expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, first.at, 0); + expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + first.pad + panes.File.displayOffset(pane, row, first.at, 0); expanded.r1 = last.row + @as(i32, pane.tag_rows); - expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayEndOffset(pane, row, last.at, hi - 1); + expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + last.pad + panes.File.displayEndOffset(pane, row, last.at, hi - 1); } else { const shown = if (raw) raw_line else line; expanded.c0 = 0; @@ -242,9 +242,9 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l const last = pane.wrapRow(row, hi - 1); if (first.row >= 0 and last.row >= 0) { expanded.r0 = first.row + @as(i32, pane.tag_rows); - expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, first.at, lo); + expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + first.pad + panes.File.displayOffset(pane, row, first.at, lo); expanded.r1 = last.row + @as(i32, pane.tag_rows); - expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayEndOffset(pane, row, last.at, hi - 1); + expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + last.pad + panes.File.displayEndOffset(pane, row, last.at, hi - 1); } result.preview = expanded; result.expanded = expanded; @@ -1120,6 +1120,12 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] } if (!p.settings.apply(setting, want)) p.reportFailure(p.active, "Shell: takes " ++ comptime config.Runtime.takes(.shell).?); }, + .callstack_depth => if (arg == null) { + var said: [40]u8 = undefined; + return p.setMessage(p.active, std.fmt.bufPrint(&said, "CallstackDepth {d}", .{p.settings.callstack_depth}) catch "CallstackDepth"); + } else if (!p.settings.apply(setting, arg)) { + p.reportFailure(p.active, "CallstackDepth: takes " ++ comptime config.Runtime.takes(.callstack_depth).?); + }, // Bare, it says the width, as acme's Tab does. .tab => if (arg == null) { var said: [32]u8 = undefined; diff --git a/src/fonts.zig b/src/fonts.zig index 098bf36f..88cde63a 100644 --- a/src/fonts.zig +++ b/src/fonts.zig @@ -324,7 +324,7 @@ fn sfntBase(head: []const u8) ?usize { fn scratchFont(buf: *[64:0]u8, ext: []const u8) [:0]const u8 { return std.fmt.bufPrintSentinel(buf, "/tmp/pardes-fonts-test-{d}{s}", .{ @as(u32, @intCast(libc.getpid())), ext, - // unreachable: 23 bytes, a u32 pid (10) and a short extension fit 64 + // unreachable: 23 bytes, a u32 pid (10) and a short extension fit 64 }, 0) catch unreachable; } @@ -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..17e8d7e9 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -610,30 +610,30 @@ 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. try std.testing.expectEqual(@offsetOf(GhosttyUniforms, "selection_background_color"), @offsetOf(Uniforms, "selection_foreground_color")); // The prefix's block, member by member, in ghostty's GLSL names and types. const glsl = [_]struct { []const u8, []const u8 }{ - .{ "vec3", "iResolution" }, .{ "float", "iTime" }, .{ "float", "iTimeDelta" }, - .{ "float", "iFrameRate" }, .{ "int", "iFrame" }, .{ "float", "iChannelTime[4]" }, - .{ "vec3", "iChannelResolution[4]" }, .{ "vec4", "iMouse" }, .{ "vec4", "iDate" }, - .{ "float", "iSampleRate" }, .{ "vec4", "iCurrentCursor" }, .{ "vec4", "iPreviousCursor" }, - .{ "vec4", "iCurrentCursorColor" }, .{ "vec4", "iPreviousCursorColor" }, .{ "int", "iCurrentCursorStyle" }, - .{ "int", "iPreviousCursorStyle" }, .{ "int", "iCursorVisible" }, .{ "float", "iTimeCursorChange" }, - .{ "float", "iTimeFocus" }, .{ "int", "iFocus" }, .{ "vec3", "iPalette[256]" }, - .{ "vec3", "iBackgroundColor" }, .{ "vec3", "iForegroundColor" }, .{ "vec3", "iCursorColor" }, - .{ "vec3", "iCursorText" }, .{ "vec3", "iSelectionForegroundColor" }, .{ "vec3", "iSelectionBackgroundColor" }, + .{ "vec3", "iResolution" }, .{ "float", "iTime" }, .{ "float", "iTimeDelta" }, + .{ "float", "iFrameRate" }, .{ "int", "iFrame" }, .{ "float", "iChannelTime[4]" }, + .{ "vec3", "iChannelResolution[4]" }, .{ "vec4", "iMouse" }, .{ "vec4", "iDate" }, + .{ "float", "iSampleRate" }, .{ "vec4", "iCurrentCursor" }, .{ "vec4", "iPreviousCursor" }, + .{ "vec4", "iCurrentCursorColor" }, .{ "vec4", "iPreviousCursorColor" }, .{ "int", "iCurrentCursorStyle" }, + .{ "int", "iPreviousCursorStyle" }, .{ "int", "iCursorVisible" }, .{ "float", "iTimeCursorChange" }, + .{ "float", "iTimeFocus" }, .{ "int", "iFocus" }, .{ "vec3", "iPalette[256]" }, + .{ "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 {").?; @@ -673,7 +673,6 @@ test "a moved cursor becomes the previous one, stamped with the time of the move try std.testing.expectEqual([4]f32{ 1.0 / 255.0, 2.0 / 255.0, 3.0 / 255.0, 1 }, post.uniforms.selection_foreground_color); } - test "a still pass asks for no idle frames; one that reads the clock does" { var post: Post = .{}; const fake: *Pipeline = @ptrFromInt(0x1000); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 65b3f926..f9921111 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; @@ -1873,6 +1869,7 @@ const Gui = struct { 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 its BODY rows, which a taller tag leaves fewer of + scroll_held_px: f32 = 0, // its tree-sitter context band, which never moves 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 @@ -1891,7 +1888,6 @@ const Gui = struct { sel_glow: SelGlow = .{}, hover_glow: SelGlow = .{}, /// G14: the cells last drawn and when each last changed. - /// The cursor's blink (blinkNow): when the frame drawn last arrived, /// a redraw owed for an edge, and this frame's cursor mode and alpha. frame_arrival_ns: u64 = 0, @@ -2294,7 +2290,7 @@ fn setTransitionFields( instance.present_y0 = presented[1]; instance.present_x1 = presented[2]; instance.present_y1 = presented[3]; - instance.effect = @intFromEnum(active.effect); + instance.effect = @backingInt(active.effect); instance.progress_bits = @bitCast(active.amount()); instance.serial = active.serial; instance.cell_coord = cell_coord; @@ -2371,12 +2367,23 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u defer c.SDL_DestroyWindow(window); updateDisplayScale(window); if (native_wayland) log.info("Wayland opacity: background-only transparent surface", .{}); - const arrow_cursor = c.SDL_CreateCursor(&p9_arrow_set, &p9_arrow_mask, 16, 16, 1, 1); + // On Linux the desktop's own cursor theme draws them (the compositor's + // cursor-shape protocol, else XCURSOR_THEME), at its size and scale: + // the arrow is its default, acme's box its move, as the plan9 theme + // has them. Elsewhere acme's bitmaps, at 16 pixels. + const themed_cursors = builtin.os.tag == .linux; + const arrow_cursor = if (themed_cursors) + c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_DEFAULT) + else + c.SDL_CreateCursor(&p9_arrow_set, &p9_arrow_mask, 16, 16, 1, 1); defer if (arrow_cursor) |cursor| c.SDL_DestroyCursor(cursor); const link_cursor = c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_POINTER); defer if (link_cursor) |cursor| c.SDL_DestroyCursor(cursor); // Its hot spot the middle, as acme's {-7, -7} offset puts it. - const box_cursor = c.SDL_CreateCursor(&p9_box_set, &p9_box_mask, 16, 16, 7, 7); + const box_cursor = if (themed_cursors) + c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_MOVE) + else + c.SDL_CreateCursor(&p9_box_set, &p9_box_mask, 16, 16, 7, 7); defer if (box_cursor) |cursor| c.SDL_DestroyCursor(cursor); if (arrow_cursor) |cur| { _ = c.SDL_SetCursor(cur); @@ -2973,6 +2980,9 @@ test "an attached frontend draws the session's chrome from its frame alone" { g.tagline_width = 6; g.tagline_height = 12; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); var groups = makeGroups(&.{}, false); try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); @@ -3359,8 +3369,8 @@ fn setStdinRaw() !void { term.lflag.ICANON = false; term.lflag.IEXTEN = false; term.lflag.ISIG = false; - term.cc[@intFromEnum(posix.V.MIN)] = 1; - term.cc[@intFromEnum(posix.V.TIME)] = 0; + term.cc[@backingInt(posix.V.MIN)] = 1; + term.cc[@backingInt(posix.V.TIME)] = 0; try posix.tcsetattr(0, .NOW, term); } @@ -4805,7 +4815,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); } @@ -4939,7 +4949,7 @@ fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { for (ptys, 0..) |slot, id| if (slot) |pt| { if (pt.fd < 0) continue; var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(pt.pid, &lbuf)) |cwd| core.setCwd(id, cwd); + if (host_io.ttyCwd(pt.pid, pt.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(id, cwd); }; } @@ -5130,7 +5140,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. @@ -5367,7 +5377,7 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { /// The glide's picture: the pane's body rows moved by the offset, and in /// the gap it opens the rows that left, as `emitScrollRows` draws a /// touchpad's fraction. -fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground) u32 { +fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground, held: u16) u32 { const glide = &g.glide; for (surface.panelTracks()) |track| if (track.active() and track.pane == glide.pane) return 0; @@ -5383,10 +5393,12 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde g.scroll_body_h = bh; var shifted = layout; shifted.y_off -= glide.offset * layout.h; + const kept = holdContext(g, surface, glide.pane, held, bh, layout); + shifted.y_off += kept.lift; const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else std.math.maxInt(u32); const cursor_bar = if (surface.cursor) |cu| cu.bar else false; var n: u32 = 0; - var row = y0; + var row = y0 + kept.rows; while (row < y0 + bh) : (row += 1) { const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; @@ -5400,9 +5412,9 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde // The gap: rows past the top while the picture lags a move down, past // the bottom for one up; as many as it opens. const gap: u16 = @intFromFloat(@min(@ceil(@abs(glide.offset)), @as(f32, @floatFromInt(bh)))); - const kept = if (glide.offset < 0) glide.nabove else glide.nbelow; + const nkept = if (glide.offset < 0) glide.nabove else glide.nbelow; const rows = if (glide.offset < 0) glide.above else glide.below; - for (0..@min(gap, kept)) |i| { + for (0..@min(gap, nkept)) |i| { const cells = rows[i * bw ..][0..bw]; // Row -1 - i above the body, or bh + i below it, in grid rows. const at_row: i32 = if (glide.offset < 0) @as(i32, y0) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); @@ -5485,7 +5497,6 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe try std.testing.expect(!g.glide.pending and !g.glide.moving()); } - fn resetScroll(g: *Gui) void { g.scroll_pane = null; g.scroll_delta = 0; @@ -5520,13 +5531,15 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { const down = left > 0; left += if (down) -1 else 1; const was = pane.scroll(); - core.update(.{ .mouse = .{ - .button = if (down) .wheel_down else .wheel_up, - .kind = .press, - .col = g.scroll_col, - .row = g.scroll_row, - .shift = true, // pardes's own scroll, never a program's wheel - } }); + core.update(.{ + .mouse = .{ + .button = if (down) .wheel_down else .wheel_up, + .kind = .press, + .col = g.scroll_col, + .row = g.scroll_row, + .shift = true, // pardes's own scroll, never a program's wheel + }, + }); if (pane.scroll() == was) { resetScroll(g); return; @@ -5560,8 +5573,9 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { if (g.scroll_lag == 0) resetScroll(g); } -fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground) u32 { - if (g.glide.offset != 0) return emitGlideRows(g, instances, base, surface, layout, win_w, win_h, page); +fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground, held: u16) u32 { + g.scroll_held_px = 0; + if (g.glide.offset != 0) return emitGlideRows(g, instances, base, surface, layout, win_w, win_h, page, held); const scroll_pane = g.scroll_pane orelse return 0; if (g.scroll_lag == 0) return 0; for (surface.panelTracks()) |track| @@ -5575,10 +5589,12 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pard 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; + const kept = holdContext(g, surface, scroll_pane, held, bh, layout); + shifted.y_off += kept.lift; const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else std.math.maxInt(u32); const cursor_bar = if (surface.cursor) |cu| cu.bar else false; var n: u32 = 0; - var row = y0; + var row = y0 + kept.rows; while (row < y0 + bh) : (row += 1) { const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; @@ -5600,12 +5616,52 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pard return n; } +/// A scrolling body's tree-sitter context rows hold still: the shifted +/// rows start under them and are clipped below their band, and where a +/// body layer stacks them at the tagline's height (TreeContextTagStyle) +/// the rows under them are drawn up to meet them, where the layer has them. +fn holdContext(g: *Gui, surface: *const pardes.Surface, id: usize, held: u16, bh: u16, layout: CellLayout) struct { rows: u16, lift: f32 } { + const rows = @min(held, bh); + const layered = id < surface.body_layers.len and surface.body_layers[id].rows != 0 and surface.body_layers[id].context_rows != 0; + const row_px = if (layered) std.math.clamp(@as(f32, @floatFromInt(g.tagline_height)), 1, @max(1, layout.h)) else layout.h; + g.scroll_held_px = @as(f32, @floatFromInt(rows)) * row_px; + return .{ .rows = rows, .lift = @as(f32, @floatFromInt(rows)) * (row_px - layout.h) }; +} + +test "a scroll's shifted rows start under the context rows, and its scissor below their band" { + var surface: pardes.Surface = .{}; + var g: Gui = undefined; + g.tagline_height = 12; + g.scroll_rect = .{ .x = 0, .y = 0, .w = 40, .h = 20 }; + g.scroll_body_y = 1; + g.scroll_body_h = 19; + const layout: CellLayout = .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }; + // On the grid, three body-high rows are held, and nothing moves up. + const grid = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(u16, 3), grid.rows); + try std.testing.expectEqual(@as(f32, 0), grid.lift); + const clip = scrollScissor(&g, layout, 400, 400); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y); + try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h); + // In a body layer they are tagline-high: the rows under them move up + // by what each is shorter, to where the layer draws them. + surface.body_layers[0].rows = 30; + surface.body_layers[0].context_rows = 3; + const layered = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y); + // None held: the whole body moves. + surface.body_layers[0].rows = 0; + try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows); + try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y); +} + fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect { const r = g.scroll_rect; const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; - const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h; + const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h + g.scroll_held_px; const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w; - const ph = @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h; + const ph = @max(0, @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h - g.scroll_held_px); 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))); @@ -6426,7 +6482,10 @@ fn renderFrame( } for (groups.items[0..groups.len], 0..) |group, index| std.debug.assert(cell_next[index] == group.cell_start + group.cell_count); - shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page); + // The body's context rows, which its scroll leaves where they are. + const scrolling: ?usize = if (g.glide.offset != 0) g.glide.pane else g.scroll_pane; + const held: u16 = if (core) |p| if (scrolling) |id| if (p.panes[id]) |pane| pane.context_rows else 0 else 0 else 0; + shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held); // Over a theme's plaques a see-through cell with no ink blends to // the plaque under it, so it draws nothing: its quad goes, and the // cells are drawn unblended (a third of the GPU's frame at 4K) @@ -7108,7 +7167,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| { @@ -7120,6 +7179,9 @@ test "every pixel of a grip column is band, button or ring, and the button sits var g: Gui = undefined; g.words = .{}; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = m.w; g.cell_h = m.h; @@ -7206,7 +7268,7 @@ test "a rising pane past its mark stays inside its box" { var g: Gui = undefined; g.cell_w = 10; g.cell_h = 20; - var track: pardes.animation.Track = .{ .serial = 3, .phase = .opening, .effect = .vertical, .motion = @intFromEnum(pardes.animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = 0, .y = 10, .w = 40, .h = 10 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 10 } }; + var track: pardes.animation.Track = .{ .serial = 3, .phase = .opening, .effect = .vertical, .motion = @backingInt(pardes.animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = 0, .y = 10, .w = 40, .h = 10 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 10 } }; var peak: u16 = 0; var highest: f32 = 1e9; while (track.frame < track.frames()) : (track.frame += 1) { @@ -7428,6 +7490,9 @@ test "lapis plaques stay in their tag's band, clear of every grip; only the focu try std.testing.expect(s.chrome.decor_box_border != null and s.chrome.decor_checker != null and s.chrome.decor_dots != null and s.chrome.decor_title != null); var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 16; g.cell_h = 32; @@ -7527,6 +7592,9 @@ test "insert cursor overlays without replacing the character beneath it" { const surface: pardes.Surface = .{ .cols = 5, .rows = 5, .cells = &cells, .cursor = .{ .x = 2, .y = 3, .bar = true } }; var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(std.testing.allocator); g.cell_w = 10; g.cell_h = 20; @@ -8743,7 +8811,6 @@ fn addPattern(g: *Gui, gpa: std.mem.Allocator, x0: f32, y0: f32, x1: f32, y1: f3 instance.effect |= checker_bit; } - /// How a lift of 0 to 1 stands off the page: the shadow's blur and offset /// in cell heights, and its darkest, where it leaves the caster's edge. /// Within §8.2's budget: sigma 0.4-0.8 cell, at most 30% darker at the edge. @@ -8881,7 +8948,6 @@ fn clipToBodies(g: *Gui, gpa: std.mem.Allocator, first: usize, bodies: []const [ }; } - /// Like shadowCeiling for a light colour laid over at `a` (sRGB blend, as /// the decor pipeline blends a colour that is not black): the largest `a` /// that keeps text and page apart by min(their contrast, 4.5). @@ -8989,6 +9055,9 @@ test "a lift never touches a tag, a grip or a header, on a light theme or a dark g.tagline_width = 6; g.tagline_height = 12; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); var groups = makeGroups(&.{}, false); try buildDecor(&g, gpa, settled, &groups, fixedCellLayout(&g), 800, 480, true); @@ -9274,7 +9343,19 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, gr try addChecker(g, gpa, column[0], y0, column[1], y1, chrome.scroll_track, gold, dp(@floatFromInt(@max(1, chrome.decor_checker_px))), track, win_w, win_h) else try addDecor(g, gpa, column[0], y0, column[1], y1, chrome.scroll_track, 1, track, win_w, win_h); - if (rail.thumb_h != 0) { + if (rail.thumb_h != 0 and rail.thumb_span > 0) { + // In pixels, not rows, and with the picture while it glides + // or lags behind the core's rows (both in rows of the body). + const lag: f32 = if (g.glide.offset != 0 and g.glide.pane == rail.owner) + g.glide.offset + else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; + const track_px = body_y1 - y0; + const size = @min(track_px, @max(layout.h, rail.thumb_span * track_px)); + const at = rail.thumb_at + lag * rail.thumb_span / @as(f32, @floatFromInt(rail.rect.h)); + const thumb_y0 = y0 + std.math.clamp(at * track_px, 0, track_px - size); + const thumb_y1 = if (thumb_y0 + size >= body_y1 - 0.5) y1 else thumb_y0 + size; + try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, track, win_w, win_h); + } else if (rail.thumb_h != 0) { const thumb_y0 = @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y)) * layout.h; const thumb_y1 = if (rail.thumb_y + rail.thumb_h == rail.rect.h) y1 else @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y + rail.thumb_h)) * layout.h; try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, track, win_w, win_h); @@ -9638,6 +9719,9 @@ test "decor less its holes covers each pixel of the rest once and none of the ho g.cell_w = 1; g.cell_h = 1; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); const holes = [_][4]f32{ .{ 3, 2, 9, 6 }, .{ 5, 4, 12, 8 }, .{ 30, 30, 40, 40 } }; try addDecorExcept(&g, gpa, .{ 1, 1, 11, 10 }, &holes, .{ 1, 2, 3 }, null, 16, 12); @@ -9829,6 +9913,9 @@ test "a theme's own rules and scrollbar are drawn at its widths: acme's 2px blac try std.testing.expectEqual(@as(u8, 18), s.chrome.rail_px); var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 16; g.cell_h = 20; @@ -9857,6 +9944,47 @@ test "a theme's own rules and scrollbar are drawn at its widths: acme's 2px blac try std.testing.expect(tracks >= 2); } +test "the scrollbar thumb moves by the pixel and follows a glide" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + const pane = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); + var g: Gui = undefined; + g.decor = .empty; + defer g.decor.deinit(gpa); + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; + g.cell_w = 10; + g.cell_h = 20; + g.tagline_width = 6; + g.tagline_height = 12; + const thumb = struct { + // The thumb's top, in window pixels. + fn top(gui: *Gui, p: *pardes.Pardes) !f32 { + gui.decor.clearRetainingCapacity(); + pardes.test_api.sync(p); + const s = try p.render(p.scratch.allocator()); + var groups = makeGroups(&.{}, false); + try buildDecor(gui, std.testing.allocator, s, &groups, fixedCellLayout(gui), 800, 480, true); + const ink = s.chrome.scroll_thumb; + for (gui.decor.items) |item| if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and + @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and + @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) return (1 - item.y0) / 2 * 480; + return error.TestExpectedThumb; + } + }; + pane.file.?.scroll = 10; + const at10 = try thumb.top(&g, core); + pane.file.?.scroll = 11; + const at11 = try thumb.top(&g, core); + // A line of a thousand moves it a fraction of a row, not 0 or 20 px. + try std.testing.expect(at11 > at10 and at11 - at10 < 1); + g.glide.pane = core.active; + g.glide.offset = -1; + 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" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); @@ -9871,6 +9999,9 @@ test "the rule between stacked panes stays in the tag band's slack, at any tagli for ([_]u32{ 12, 20 }) |tagline_h| { var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 10; g.cell_h = 20; @@ -9906,6 +10037,9 @@ test "an empty column is ruled on both sides, as between two filled ones" { const s = try core.render(core.scratch.allocator()); var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 10; g.cell_h = 20; @@ -9942,6 +10076,9 @@ test "at a 2x display every logical pixel is two: rules, the tag rule, the grip' defer display_scale = 1; var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 16; g.cell_h = 32; @@ -10006,6 +10143,9 @@ test "decor is read from the regions, each pane's in its own group" { const s = try core.render(core.scratch.allocator()); var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 10; g.cell_h = 20; @@ -10054,7 +10194,7 @@ test "decor is read from the regions, each pane's in its own group" { try std.testing.expect(tracked.decor_count >= 4); try std.testing.expectEqual(still, groups.items[0].decor_count + tracked.decor_count); for (g.decor.items[tracked.decor_start..][0..tracked.decor_count]) |item| - try std.testing.expectEqual(@as(u32, @intFromEnum(pardes.animation.Transition.slide)), item.effect); + try std.testing.expectEqual(@as(u32, @backingInt(pardes.animation.Transition.slide)), item.effect); // Cursors stand still while panes move. try std.testing.expectEqual(@as(u32, 0), groups.items[groups.ink].decor_count); } @@ -10071,6 +10211,9 @@ test "a pane on the move casts a shadow on the other panes' bodies alone, most a const s = try core.render(core.scratch.allocator()); var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 10; g.cell_h = 20; @@ -10107,7 +10250,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()); @@ -10124,6 +10267,9 @@ test "the selection glows round its block, on the body only, fading in over 100 s.cursor = null; var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 10; g.cell_h = 20; @@ -10157,7 +10303,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()); @@ -10176,6 +10322,9 @@ test "a hovered word glows along its foot, never over the cursor, fading in over s.cursor = .{ .x = body.rect.x + 8, .y = row }; var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 10; g.cell_h = 20; @@ -10207,7 +10356,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()); @@ -10219,6 +10368,9 @@ test "occlusion shades each body's edges, inside it, never a tag, a grip or the s.cursor = .{ .x = body.rect.x, .y = body.rect.y }; var g: Gui = undefined; g.decor = .empty; + g.glide = .{}; + g.scroll_pane = null; + g.scroll_lag = 0; defer g.decor.deinit(gpa); g.cell_w = 10; g.cell_h = 20; @@ -10246,7 +10398,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; @@ -10423,7 +10575,7 @@ fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, builder: *OverlayB fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pardes.Surface, builder: *OverlayBuilder) void { const p = core orelse return; - const kind: pet.Kind = @enumFromInt(@intFromEnum(p.settings.pet)); + const kind: pet.Kind = @fromBackingInt(@intCast(@backingInt(p.settings.pet))); if (kind == .off or surface.rows == 0 or surface.cols == 0) { g.pet_state = .{}; return; diff --git a/src/gui/pet.zig b/src/gui/pet.zig index 2b031f0e..a249d70f 100644 --- a/src/gui/pet.zig +++ b/src/gui/pet.zig @@ -8,6 +8,8 @@ pub const height = 9; pub const max_vertices = width * height * 6; pub const Lane = struct { left: f32, right: f32, top: f32, scale: f32 }; pub const Pose = struct { x: f32, y: f32, scale: f32, left: bool, walking: bool, frame: u8 }; +/// The frog's hop: sits two ticks, takes off, peaks for two, comes down, lands. +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. @@ -24,9 +26,11 @@ pub const State = struct { kind: Kind = .off, tick: ?u64 = null, x: f32 = 0, + target: f32 = 0, left: bool = false, idle: u8 = 12, frame: u8 = 0, + rng: std.Random.DefaultPrng = undefined, pub fn sample(s: *State, kind: Kind, now_ms: u64, area: ?Lane) ?Pose { const region = area orelse { @@ -39,9 +43,10 @@ pub const State = struct { } const tick = now_ms / 100; if (s.kind != kind or s.tick == null) { - s.* = .{ .kind = kind, .tick = tick, .x = region.left }; + s.* = .{ .kind = kind, .tick = tick, .x = region.left, .target = region.left, .rng = .init(now_ms) }; } s.x = std.math.clamp(s.x, region.left, region.right); + s.target = std.math.clamp(s.target, region.left, region.right); // Coming back from suspension never launches the pet across the tag. const steps = @min(tick -| s.tick.?, 2); s.tick = tick; @@ -49,15 +54,25 @@ pub const State = struct { s.frame +%= 1; if (s.idle > 0) { s.idle -= 1; + if (s.idle == 0) { + // Wander to a random spot of the lane; one too close + // would be a shuffle in place, so take the far end. + s.target = region.left + s.rng.random().float(f32) * (region.right - region.left); + if (@abs(s.target - s.x) < 8 * region.scale) + s.target = if (s.x - region.left > region.right - s.x) region.left else region.right; + s.left = s.target < s.x; + s.frame = 255; // the walk starts at frame 0 + } continue; } - const speed: f32 = if (kind == .cat) 1.8 else 1.3; - s.x += (if (s.left) -speed else speed) * region.scale; - if (s.x >= region.right or s.x <= region.left) { - s.x = std.math.clamp(s.x, region.left, region.right); - s.left = !s.left; - s.idle = if (kind == .cat) 18 else 24; + // The cat walks steadily; the frog travels only while airborne. + const phase = s.frame % hop_ticks; + if (kind == .cat or (phase >= 2 and phase < 6)) { + const step = (if (kind == .cat) @as(f32, 1.8) else 2.6) * region.scale; + s.x = if (s.left) @max(s.target, s.x - step) else @min(s.target, s.x + step); } + if (s.x == s.target and (kind == .cat or phase == hop_ticks - 1)) + s.idle = s.rng.random().intRangeAtMost(u8, 20, 60); } return .{ .x = @floor(s.x), .y = region.top, .scale = region.scale, .left = s.left, .walking = s.idle == 0, .frame = s.frame }; } @@ -76,14 +91,25 @@ const cat = [_][]const u8{ }; const frog = [_][]const u8{ " ", - " ## ## ", - " #o####o# ", - " ######## ", - " ###### ", - " ######## ", - " ########## ", - " ## ## ", - "### ###", + " ", + " ", + " ## ", + " #o## ", + " #########", + " ######### ", + " ##### ## ", + "###### ### ", +}; +const frog_leap = [_][]const u8{ + " ## ", + " #o## ", + " #######", + " ######## ", + " ####### ", + " ### ## ", + "## # ", + "# ", + " ", }; /// 0 transparent, 1 theme ink, 2 eye cutout. Walk legs and idle blinks are @@ -99,13 +125,16 @@ pub fn pixel(kind: Kind, pose: Pose, x_in: usize, y: usize) u2 { if (!pose.walking and breathing) { if (kind == .cat and y == 3 and x <= 1) return @intFromBool(x == 0); - if (kind == .frog and y == 4 and (x == 2 or x == 9)) return 1; - } - if (pose.walking and alternate and y >= 7) { - if (kind == .cat) return @intFromBool((y == 7 and (x == 3 or x == 7)) or (y == 8 and (x == 2 or x == 8))); - return @intFromBool((y == 7 and (x == 2 or x == 9)) or (y == 8 and (x <= 2 or x >= 9))); + if (kind == .frog and ((y == 6 and x == 11) or (y == 7 and x == 10))) return 1; } - const ch = (if (kind == .cat) cat else frog)[y][x]; + if (kind == .cat and pose.walking and alternate and y >= 7) + return @intFromBool((y == 7 and (x == 3 or x == 7)) or (y == 8 and (x == 2 or x == 8))); + // A hopping frog leaps two rows low at take-off and one on the way down. + const phase = pose.frame % hop_ticks; + const leaping = kind == .frog and pose.walking and phase >= 2 and phase < 6; + const sink: usize = if (!leaping) 0 else if (phase == 2) 2 else if (phase == 5) 1 else 0; + if (y < sink) return 0; + const ch = (if (kind == .cat) cat else if (leaping) frog_leap else frog)[y - sink][x]; return switch (ch) { '#' => 1, 'o' => if (!pose.walking and pose.frame % 30 >= 27) 1 else 2, @@ -150,6 +179,21 @@ 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).?; + var state: State = .{}; + var last = state.sample(.frog, 0, region).?; + var rested_midway = false; + for (1..3000) |i| { + const pose = state.sample(.frog, i * 100, region).?; + const phase = pose.frame % hop_ticks; + if (pose.x != last.x) try std.testing.expect(pose.walking and phase >= 2 and phase < 6); + rested_midway = rested_midway or (last.walking and !pose.walking and pose.x > region.left and pose.x < @floor(region.right)); + last = pose; + } + try std.testing.expect(rested_midway); +} + test "pet initial idle visibly animates without walking or leaving its tile" { const region = lane(1, 8, 400, 0, 16, false).?; for ([_]Kind{ .cat, .frog }) |kind| { diff --git a/src/host_io.zig b/src/host_io.zig index 7314affc..c593551b 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -136,6 +136,8 @@ pub const Lsp = struct { /// One language query, owned by the worker that runs it. pub const Job = struct { + callstack_depth: u8 = pardes.lsp.callstack_default_depth, + callstack_corners: pardes.lsp.CallstackCorners = .rounded, id: u32, kind: pardes.lsp.Kind, offset: u32, @@ -170,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); @@ -178,6 +180,8 @@ pub const Lsp = struct { const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root); errdefer gpa.free(root); job.* = .{ + .callstack_depth = core.settings.callstack_depth, + .callstack_corners = core.settings.callstack_corners, .id = req.id, .kind = req.kind, .offset = req.offset, @@ -206,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; }; @@ -234,6 +238,8 @@ pub const Lsp = struct { .arg = job.arg, .root = job.root, .others = job.others, + .callstack_depth = job.callstack_depth, + .callstack_corners = job.callstack_corners, }, &out.writer) catch { deliver(ctx, job.id, null); return; @@ -250,6 +256,8 @@ pub const Lsp = struct { const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); + core.settings.callstack_depth = 16; + core.settings.callstack_corners = .square; var needle: [6]u8 = "needle".*; const job = try snapshot(gpa, core, .{ .id = 7, @@ -260,6 +268,10 @@ pub const Lsp = struct { }); defer job.free(gpa); + core.settings.callstack_depth = 2; + core.settings.callstack_corners = .rounded; + try std.testing.expectEqual(pardes.lsp.CallstackCorners.square, job.callstack_corners); + try std.testing.expectEqual(@as(u8, 16), job.callstack_depth); try std.testing.expectEqual(@as(u32, 7), job.id); try std.testing.expectEqual(pardes.lsp.Kind.status, job.kind); try std.testing.expectEqualStrings("needle", job.arg); @@ -560,7 +572,7 @@ pub const Shell = struct { const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0); const pid = rcPid(name) orelse continue; if (pid == std.c.getpid()) continue; - if (std.posix.errno(std.c.kill(pid, @enumFromInt(0))) != .SRCH) continue; + if (std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; if (name.len >= 64 or n == dead.len) continue; @memcpy(dead[n][0..name.len], name); dead_len[n] = name.len; @@ -773,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")); } @@ -1224,8 +1236,8 @@ pub fn resetChildSignals() void { const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; var sig: u8 = 1; while (sig < 65) : (sig += 1) { - if (sig == @intFromEnum(posix.SIG.KILL) or sig == @intFromEnum(posix.SIG.STOP)) continue; - _ = std.c.sigaction(@enumFromInt(sig), &default, null); + if (sig == @backingInt(posix.SIG.KILL) or sig == @backingInt(posix.SIG.STOP)) continue; + _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); } const none = posix.sigemptyset(); posix.sigprocmask(posix.SIG.SETMASK, &none, null); @@ -1608,13 +1620,13 @@ pub fn forkShell( if (pid == 0) { resetChildSignals(); if (cwd_z) |path| if (chdir(path.ptr) != 0) { - const why = [_]u8{ 'c', @truncate(@intFromEnum(libc.errno(@as(c_int, -1)))) }; + const why = [_]u8{ 'c', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; _ = libc.write(told[1], &why, why.len); _exit(126); }; if (envp) |env| _ = execve(spawn.path, &spawn.argv, env); _ = execv(spawn.path, &spawn.argv); - const why = [_]u8{ 'x', @truncate(@intFromEnum(libc.errno(@as(c_int, -1)))) }; + const why = [_]u8{ 'x', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; _ = libc.write(told[1], &why, why.len); _exit(127); } @@ -1631,7 +1643,7 @@ pub fn forkShell( if (failed) |why| { _ = libc.close(master); _ = libc.waitpid(pid, null, 0); - const e: libc.E = @enumFromInt(why[1]); + const e: libc.E = @fromBackingInt(@intCast(why[1])); if (why[0] == 'c') return if (e == .NOENT or e == .NOTDIR) error.FileNotFound else error.AccessDenied; return switch (e) { // Itself, or its script's interpreter: told apart by whether it @@ -1650,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(.{}); @@ -1663,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)); } @@ -1708,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)]; @@ -1783,13 +1795,90 @@ pub fn shellCwd(pid: libc.pid_t, buf: []u8) ?[]const u8 { } } +/// Where a terminal is. The process forked for it, while it still runs the +/// shell pardes started (`shell_exe`), as ever: a job it runs, in another +/// directory (`(cd sub && make)`, a nested pardes), never names the pane. +/// One that exec'd into something else is a wrapper whose own directory +/// never moves (fish's `exec 9ns --mntgen -- fish`): the shell is the +/// foreground group when that is the same shell, and while a job holds the +/// foreground there is no answer, the last one standing. +pub fn ttyCwd(shell_pid: libc.pid_t, master_fd: c_int, shell_exe: []const u8, buf: []u8) ?[]const u8 { + var exe_buf: [std.fs.max_path_bytes]u8 = undefined; + var shell_buf: [std.fs.max_path_bytes]u8 = undefined; + const shell = realShell(shell_exe, &shell_buf) orelse return shellCwd(shell_pid, buf); + const exe = procExe(shell_pid, &exe_buf) orelse return shellCwd(shell_pid, buf); + if (std.mem.eql(u8, exe, shell)) return shellCwd(shell_pid, buf); + const fg = tcgetpgrp(master_fd); + if (fg <= 0 or fg == shell_pid) return null; + const fg_exe = procExe(fg, &exe_buf) orelse return null; + return if (std.mem.eql(u8, fg_exe, shell)) shellCwd(fg, buf) else null; +} + +/// `shell_exe` as /proc/<pid>/exe would read it: its links followed. +fn realShell(shell_exe: []const u8, buf: *[std.fs.max_path_bytes]u8) ?[]const u8 { + var z: [std.fs.max_path_bytes:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&z, "{s}", .{shell_exe}, 0) catch return null; + const r = libc.realpath(path, buf) orelse return null; + return std.mem.span(@as([*:0]const u8, @ptrCast(r))); +} + +test "a terminal is where its shell is: under a wrapper the foreground shell, never a job's directory" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh") or !haveFile("/usr/bin/timeout")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "start/a/b"); + var path_buf: [4096]u8 = undefined; + const start = path_buf[0..try tmp.dir.realPathFile(io, "start", &path_buf)]; + var inner_buf: [4096]u8 = undefined; + const inner = inner_buf[0..try tmp.dir.realPathFile(io, "start/a/b", &inner_buf)]; + const rcs: Shell.PromptFiles = .{}; + var result: [4096]u8 = undefined; + // A wrapper exec'd over the shell (timeout standing in for 9ns) runs + // another, two directories down, in the foreground. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80, null); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "exec timeout --foreground 30 /bin/sh -c 'cd a/b && printf \"\\160ardes-in-\\n\" && exec /bin/sh -i'\n")); + try std.testing.expect(sh.waitText("pardes-in-", 5_000)); + // printf runs before the inner shell takes the foreground. + var tries: usize = 0; + while (ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) == null and tries < 50) : (tries += 1) { + const ts: libc.timespec = .{ .sec = 0, .nsec = 20 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + try std.testing.expectEqualStrings(start, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(inner, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } + // A job of the shell's own, gone into a/b, leaves the pane where the + // shell is. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80, null); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "set -m; (cd a/b && printf '\\160ardes-job\\n' && exec sleep 30)\n")); + try std.testing.expect(sh.waitText("pardes-job", 5_000)); + try std.testing.expectEqualStrings(start, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } +} + test "shell cwd rejects truncation and preserves an owned child path longer than 1024 bytes" { if (comptime builtin.os.tag != .linux) return error.SkipZigTest; if (!haveFile("/bin/sh")) return error.SkipZigTest; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); - const nested = "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)]; @@ -2155,7 +2244,7 @@ pub fn reapExited(pid: libc.pid_t) ?struct { status: ?u8 } { if (got != pid) return .{ .status = null }; const s: u32 = @bitCast(status); if (libc.W.IFEXITED(s)) return .{ .status = @truncate(libc.W.EXITSTATUS(s)) }; - if (libc.W.IFSIGNALED(s)) return .{ .status = @truncate(128 + @as(u32, @intFromEnum(libc.W.TERMSIG(s)))) }; + if (libc.W.IFSIGNALED(s)) return .{ .status = @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))) }; return .{ .status = null }; } @@ -2182,7 +2271,7 @@ pub fn exitStatus(pid: libc.pid_t, wait_ms: u32) ?u8 { if (got == pid) { const s: u32 = @bitCast(status); if (libc.W.IFEXITED(s)) return @truncate(libc.W.EXITSTATUS(s)); - if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @intFromEnum(libc.W.TERMSIG(s)))); + if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))); return null; } if (got < 0 or waited >= wait_ms) return null; @@ -2710,8 +2799,8 @@ test "a retired shell that ignores the hangup is killed and reaped, not left a z retireShell(pid); // A zombie still answers kill(pid, 0); only a reaped pid is gone. var waited: i64 = 0; - while (libc.kill(pid, @enumFromInt(0)) == 0 and waited < 2000) : (waited += 10) sleepMs(10); - try std.testing.expect(libc.kill(pid, @enumFromInt(0)) != 0); + while (libc.kill(pid, @fromBackingInt(@intCast(0))) == 0 and waited < 2000) : (waited += 10) sleepMs(10); + try std.testing.expect(libc.kill(pid, @fromBackingInt(@intCast(0))) != 0); try std.testing.expect(waited >= 90); // it did ignore the hangup } diff --git a/src/hunks.zig b/src/hunks.zig new file mode 100644 index 00000000..73c0654a --- /dev/null +++ b/src/hunks.zig @@ -0,0 +1,808 @@ +//! A unified diff (`.diff`, `.patch`, a paged `git show`) stacked as a +//! diff viewer shows it (Diff): each hunk under its `path:line`, the +//! declarations around it from tree-sitter as a result's context +//! (locations.zig), its lines behind their `+`/`-` markers drawn red and +//! green, coloured as their file, and the words a changed line changed on +//! a tinted ground as delta emphasises them (its edits.rs and align.rs, here as `inferEdits` +//! and `Alignment`). +const std = @import("std"); +const pardes = @import("pardes.zig"); +const diff = @import("diff.zig"); +const syntax = @import("syntax.zig"); +const locations = @import("locations.zig"); + +const Pardes = pardes.Pardes; +const Row = locations.Row; + +/// The rows `content`, a diff, stacks to, for a pane in `dir`, with each +/// row's metadata (Output.fillRows). Text and rows are `p.gpa`'s; all else +/// is the step's scratch. +pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Result { + const arena = p.scratch.allocator(); + const styles = try syntax.highlightDiff(arena, content, 0, content.len); + var out: Out = .{ .p = p, .text = .init(p.gpa) }; + errdefer out.deinit(); + var walk: diff.Walk = .{}; + var hunk: Hunk = .{}; + var source: SourceMemo = .{}; + var at: usize = 0; + // The empty text after a last newline is no line. + while (at < content.len) { + const nl = std.mem.indexOfScalarPos(u8, content, at, '\n') orelse content.len; + const raw = content[at..nl]; + const got = walk.step(raw); + const line = std.mem.trimEnd(u8, raw, "\r"); + switch (got.kind) { + .context, .added, .removed => { + const skip = @intFromBool(line.len > 0 and std.mem.indexOfScalar(u8, " +-", line[0]) != null); + try hunk.lines.append(arena, .{ + .kind = got.kind, + .code = line[skip..], + .styles = styles[at + skip ..][0 .. line.len - skip], + .old = got.old, + .new = got.new, + }); + }, + // A `\ No newline` belongs to the line above, as delta shows it. + .no_newline => {}, + else => { + try flush(&out, &hunk, &source, dir); + switch (got.kind) { + .hunk => hunk = .{ + .path = walk.path(), + .deleted = walk.deleted(), + .old_start = got.old, + .new_start = got.new, + .header = gitContext(line), + }, + // What is said around the hunks, a mailed patch's + // headers, message and diffstat, as it was written. + .other => try out.row(line, "", .{ .kind = .context, .at = .{} }), + // A section's own words (a new file's mode, a rename, + // `Binary files ... differ`), muted; its `diff` and + // `index` lines say nothing the labels do not. + .meta => if (!std.mem.startsWith(u8, line, "diff ") and !std.mem.startsWith(u8, line, "index ")) + try out.row(line, "", .{ .kind = .context, .declaration = true, .at = .{} }), + else => {}, + } + }, + } + at = nl + 1; + } + try flush(&out, &hunk, &source, dir); + const rows = try out.rows.toOwnedSlice(p.gpa); + errdefer locations.freeRows(p.gpa, rows); + return .{ .content = try out.text.toOwnedSlice(), .rows = rows, .anchor = null }; +} + +const HunkLine = struct { + kind: diff.Kind, + code: []const u8, + /// Its code's style bytes, as the diff pane paints them (syntax.zig + /// highlightDiff), the emphasis bit added by `inferEdits`. + styles: []u8, + old: usize, + new: usize, + /// Paired with a line it changed (inferEdits): its words show that; + /// unpaired, the whole line was added or removed. + paired: bool = false, +}; + +const Hunk = struct { + path: []const u8 = "", + deleted: bool = false, + old_start: usize = 0, + new_start: usize = 0, + /// What git wrote after the `@@`'s second marker (its function line). + header: []const u8 = "", + lines: std.ArrayList(HunkLine) = .empty, +}; + +/// `@@ -a,b +c,d @@ fn foo()`: `fn foo()`. +fn gitContext(line: []const u8) []const u8 { + const close = std.mem.indexOfPos(u8, line, 2, "@@") orelse return ""; + return std.mem.trim(u8, line[close + 2 ..], " \t"); +} + +const Out = struct { + p: *Pardes, + text: std.Io.Writer.Allocating, + rows: std.ArrayList(Row) = .empty, + + 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); + } + + const Meta = struct { + kind: @FieldType(Row, "kind"), + declaration: bool = false, + at: @FieldType(Row, "at"), + location_end: usize = 0, + code_start: usize = 0, + colors: []const u8 = &.{}, + }; + + /// One row: its text, a newline, and its metadata. + fn row(out: *Out, text: []const u8, path: []const u8, meta: Meta) !void { + const gpa = out.p.gpa; + try out.text.writer.writeAll(text); + try out.text.writer.writeByte('\n'); + const owned_path = try gpa.dupe(u8, path); + errdefer gpa.free(owned_path); + const colors = try gpa.dupe(u8, meta.colors); + errdefer gpa.free(colors); + try out.rows.append(gpa, .{ + .kind = meta.kind, + .declaration = meta.declaration, + .path = owned_path, + .at = meta.at, + .location_end = meta.location_end, + .code_start = meta.code_start, + .colors = colors, + }); + } +}; + +/// The file a diff section names, as found from the pane's directory or +/// one above it (a patch kept in a subdirectory of its repository). +const SourceMemo = struct { + path: []const u8 = "", + /// The name a look from the pane's directory resolves; null when the + /// file is nowhere to be found. + shown: ?[]const u8 = null, + lines: []const []const u8 = &.{}, + declarations: []const syntax.ContextDeclaration = &.{}, +}; + +/// Where a +Diff of `content`, a diff in `dir`, stands: the directory its +/// first file is found from (`dir` or one above it, as `findSource` looks), +/// so its rows name their files as the diff does; `dir` when none is found. +pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { + var walk: diff.Walk = .{}; + var lines = std.mem.splitScalar(u8, content, '\n'); + const path = while (lines.next()) |line| { + if (walk.step(line).kind == .hunk and walk.path().len > 0) break walk.path(); + } else return dir; + var base: []const u8 = dir; + for (0..8) |_| { + if (locations.sourceText(p, p.scratch.allocator(), base, path) != null) return base; + base = std.fs.path.dirname(base) orelse return dir; + } + return dir; +} + +fn findSource(p: *Pardes, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { + if (std.mem.eql(u8, memo.path, path)) return; + const arena = p.scratch.allocator(); + memo.* = .{ .path = path }; + // ponytail: eight directories up; a repository deeper than that under + // its patch is looked for from the patch's own directory only. + var base: []const u8 = dir; + for (0..8) |_| { + if (locations.sourceText(p, arena, base, path)) |text| { + memo.shown = if (base.ptr == dir.ptr) path else try std.fs.path.relativePosix(arena, "/", dir, text.path); + var lines: std.ArrayList([]const u8) = .empty; + var split = std.mem.splitScalar(u8, text.bytes, '\n'); + while (split.next()) |line| try lines.append(arena, std.mem.trimEnd(u8, line, "\r")); + memo.lines = lines.items; + var hit = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, false) catch + locations.Cache.Hit{ .analysis = syntax.analyzeSource(arena, text.path, text.bytes, true, false) catch .{} }; + defer hit.deinit(p.tree_sitter_gpa); + // The cache's may go at its next use: kept for the section. + memo.declarations = try arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); + return; + } + base = std.fs.path.dirname(base) orelse return; + } +} + +/// Which side of the hunk the file on disk holds, the new one (the patch +/// applied) or the old one, and how far the file has moved it from where +/// the hunk says (`shift`, lines), as patch finds a hunk in a file edited +/// since. A file edited inside the hunk too still holds most of its lines: +/// the place holding the most of them wins (the nearer on a tie) if it +/// holds at least half. Only some, at the nearest place, could be a sibling +/// with the same lines (two functions with one signature's tail). The rows +/// are counted on that side, so moved. +const Side = enum { new, old, neither }; +const OnDisk = struct { side: Side, shift: i64 = 0 }; + +/// ponytail: a hunk moved more than this many lines is not looked for; +/// each try compares the hunk's lines, so a wider search costs that more. +const max_shift = 200; + +fn sideOnDisk(memo: *const SourceMemo, hunk: *const Hunk) OnDisk { + if (memo.shown == null) return .{ .side = .neither }; + var best: OnDisk = .{ .side = .neither }; + var best_held: usize = 0; + var best_of: usize = 1; + var shift: i64 = 0; + while (shift <= max_shift) : (shift += 1) { + for ([2]i64{ shift, -shift }) |by| { + inline for (.{ Side.new, Side.old }) |side| { + const start: i64 = @as(i64, @intCast((if (side == .new) hunk.new_start else hunk.old_start) -| 1)) + by; + if (start >= 0) { + const got = heldAt(memo, hunk, side, @intCast(start)); + if (got.held == got.of) return .{ .side = side, .shift = by }; + // A larger share only: the nearer keeps a tie. + if (got.held * best_of > best_held * got.of) { + best = .{ .side = side, .shift = by }; + best_held = got.held; + best_of = got.of; + } + } + } + if (shift == 0) break; + } + } + return if (best_held > 0 and best_held * 2 >= best_of) best else .{ .side = .neither }; +} + +/// How many of the hunk's `side` lines the file holds from row `start` on, +/// of how many: blank lines, which match anywhere, count for neither. +fn heldAt(memo: *const SourceMemo, hunk: *const Hunk, comptime side: Side, start: usize) struct { held: usize, of: usize } { + var row = start; + var held: usize = 0; + var of: usize = 0; + for (hunk.lines.items) |line| { + const skipped = if (side == .new) line.kind == .removed else line.kind == .added; + if (skipped) continue; + defer row += 1; + if (std.mem.trim(u8, line.code, " \t").len == 0) continue; + of += 1; + if (row < memo.lines.len and std.mem.eql(u8, memo.lines[row], line.code)) held += 1; + } + return .{ .held = held, .of = @max(of, 1) }; +} + +fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { + defer hunk.* = .{}; + if (hunk.path.len == 0 or hunk.lines.items.len == 0) return; + const p = out.p; + const arena = p.scratch.allocator(); + try findSource(p, memo, dir, hunk.path); + const disk = sideOnDisk(memo, hunk); + const side = disk.side; + // A line number of the hunk's, where the file has it now. + const moved = struct { + fn by(n: usize, shift: i64) usize { + return @intCast(@max(0, @as(i64, @intCast(n)) + shift)); + } + }.by; + const shown = if (side == .neither) hunk.path else memo.shown.?; + const lines = hunk.lines.items; + + // Where the hunk changes something, on the side its rows count: the + // place its label opens. + const first_change = for (lines) |line| { + if (line.kind != .context) break line; + } else lines[0]; + const on_old = side == .old or (side == .neither and hunk.deleted); + const start_row = moved(if (on_old) hunk.old_start else hunk.new_start, disk.shift) -| 1; + const change_row = moved(if (on_old) first_change.old else first_change.new, disk.shift) -| 1; + + // The declarations it stands in, outermost first, as a result's + // tree-sitter context: each one's header rows above the hunk. + var depth: usize = 0; + if (side != .neither) for (memo.declarations) |declaration| { + if (declaration.start_line >= start_row) break; + if (declaration.end_line < change_row) continue; + depth += 1; + var row = declaration.start_line; + while (row <= declaration.header_end_line and row < start_row) : (row += 1) { + const at: @FieldType(Row, "at") = .{ .line = row + 1 }; + if (row == declaration.start_line and p.locations_config.tslocations) { + const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); + try out.row(label, shown, .{ .kind = .context, .declaration = true, .at = at, .location_end = label.len, .code_start = label.len }); + } + // A blank where a hunk line has its marker: the code aligns. + try out.row(try std.fmt.allocPrint(arena, " {s}", .{memo.lines[row]}), shown, .{ .kind = .context, .declaration = true, .at = at }); + } + }; + + // The hunk's label: a step for n and N, and a look's place. + const line_no = change_row + 1; + var label: std.Io.Writer.Allocating = .init(arena); + try label.writer.print("{s}:{d}", .{ shown, line_no }); + const location_end = label.written().len; + if (depth > 0) { + try label.writer.writeByte(' '); + try label.writer.splatByteAll('*', depth); + } + try out.row(label.written(), shown, .{ .kind = .match, .at = .{ .line = line_no }, .location_end = location_end, .code_start = label.written().len }); + // No file to read declarations from: git's own function line, muted + // the same way. With one, git's guess (the last line before the hunk + // that looked like a function) would only contradict it. + if (side == .neither and hunk.header.len > 0) + try out.row(try std.fmt.allocPrint(arena, " {s}", .{hunk.header}), shown, .{ .kind = .context, .declaration = true, .at = .{ .line = line_no } }); + + // Each run of removed lines and the added lines after it: the words + // they changed. + var i: usize = 0; + while (i < lines.len) { + if (lines[i].kind == .context) { + i += 1; + continue; + } + const minus_start = i; + while (i < lines.len and lines[i].kind == .removed) i += 1; + const plus_start = i; + while (i < lines.len and lines[i].kind == .added) i += 1; + try inferEdits(arena, lines[minus_start..plus_start], lines[plus_start..i]); + } + + // Each line behind its marker, `+`, `-` or a blank, as the diff + // has it: the marker coloured, the line as its file's. + for (lines) |line| { + const flag: u8 = switch (line.kind) { + .added => syntax.diff_added, + .removed => syntax.diff_removed, + else => 0, + } | @as(u8, if (line.kind != .context and !line.paired) syntax.diff_whole else 0); + const text = try std.fmt.allocPrint(arena, "{c}{s}", .{ @as(u8, switch (line.kind) { + .added => '+', + .removed => '-', + else => ' ', + }), line.code }); + const colors = try arena.alloc(u8, text.len); + colors[0] = flag; + @memcpy(colors[1..], line.styles); + const on = moved(if (on_old) line.old else line.new, disk.shift); + try out.row(text, shown, .{ .kind = .preview, .at = .{ .line = @max(1, on) }, .colors = colors }); + } +} + +// ---- the words a changed line changed (delta's edits.rs) ---- + +/// delta's `max-line-distance`: a removed and an added line further apart +/// than this are not one line changed, and neither is emphasised. +const max_line_distance = 0.6; + +/// ponytail: a run of more removed or added lines than this, or a pair +/// whose token table is bigger than `max_cells`, is shown unemphasised +/// rather than aligned at a quadratic cost (delta aligns them all). +const max_run = 256; +const max_cells = 1 << 16; + +/// 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; + 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); + 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 (marks.distance > max_line_distance) continue; + for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { + b.* |= syntax.diff_emph; + }; + for (marks.plus) |r| for (plus[j].styles[r[0]..r[1]]) |*b| { + b.* |= syntax.diff_emph; + }; + m.paired = true; + plus[j].paired = true; + plus_index = j + 1; + break; + } + } +} + +/// delta's tokenize with its default `\w+`: a leading empty token, each +/// run of word characters one token, and every other character one. A +/// line starting with no word gets a second empty token, as delta's does. +/// ponytail: any byte past ASCII counts as a word character, close to +/// Unicode `\w` for letters; a non-ASCII punctuation mark joins a word. +fn tokenize(arena: std.mem.Allocator, line: []const u8) ![]const []const u8 { + var tokens: std.ArrayList([]const u8) = .empty; + try tokens.append(arena, ""); + if (line.len > 0 and !isWord(line[0])) try tokens.append(arena, ""); + var at: usize = 0; + while (at < line.len) { + var end = at + 1; + // A byte past ASCII is a word's, so what is left is one byte. + if (isWord(line[at])) while (end < line.len and isWord(line[end])) { + end += 1; + }; + try tokens.append(arena, line[at..end]); + at = end; + } + return tokens.items; +} + +fn isWord(c: u8) bool { + return std.ascii.isAlphanumeric(c) or c == '_' or c >= 0x80; +} + +const Op = enum(u2) { noop, deletion, insertion }; + +/// delta's align.rs: a Needleman-Wunsch table over two token lists, a +/// change costing more where it starts a new run, so changes group. +const Alignment = struct { + x: []const []const u8, + y: []const []const u8, + cells: []Cell, + width: usize, + + const Cell = struct { parent: u32, op: Op, cost: u32 }; + const deletion_cost = 2; + const insertion_cost = 2; + const initial_mismatch_penalty = 1; + const never = std.math.maxInt(u32); + + fn init(arena: std.mem.Allocator, x: []const []const u8, y: []const []const u8) !Alignment { + const width = x.len + 1; + const cells = try arena.alloc(Cell, width * (y.len + 1)); + @memset(cells, .{ .parent = 0, .op = .noop, .cost = 0 }); + var a: Alignment = .{ .x = x, .y = y, .cells = cells, .width = width }; + for (1..width) |i| cells[i] = .{ .parent = 0, .op = .deletion, .cost = @intCast(i * deletion_cost + initial_mismatch_penalty) }; + for (1..y.len + 1) |j| cells[j * width] = .{ .parent = 0, .op = .insertion, .cost = @intCast(j * insertion_cost + initial_mismatch_penalty) }; + for (x, 0..) |x_i, i| for (y, 0..) |y_j, j| { + const left = a.index(i, j + 1); + const diag = a.index(i, j); + const up = a.index(i + 1, j); + // Ties go to the first: an insertion, then a deletion, then a + // match, so a moved token reads as removed then added. + const candidates = [3]Cell{ + .{ .parent = @intCast(up), .op = .insertion, .cost = a.mismatchCost(up, insertion_cost) }, + .{ .parent = @intCast(left), .op = .deletion, .cost = a.mismatchCost(left, deletion_cost) }, + .{ .parent = @intCast(diag), .op = .noop, .cost = if (std.mem.eql(u8, x_i, y_j)) cells[diag].cost else never }, + }; + var best = candidates[0]; + for (candidates[1..]) |c| if (c.cost < best.cost) { + best = c; + }; + cells[a.index(i + 1, j + 1)] = best; + }; + return a; + } + + fn mismatchCost(a: *const Alignment, parent: usize, basic: u32) u32 { + const cell = a.cells[parent]; + return cell.cost +| basic +| @as(u32, if (cell.op == .noop) initial_mismatch_penalty else 0); + } + + fn index(a: *const Alignment, i: usize, j: usize) usize { + return j * a.width + i; + } + + /// The operations read back from the table's far corner, in order, + /// each run as one (op, count). + fn coalesced(a: *const Alignment, arena: std.mem.Allocator) ![]const struct { Op, usize } { + var ops: std.ArrayList(Op) = .empty; + var cell = a.cells[a.index(a.x.len, a.y.len)]; + while (true) { + try ops.append(arena, cell.op); + if (cell.parent == 0) break; + cell = a.cells[cell.parent]; + } + std.mem.reverse(Op, ops.items); + var runs: std.ArrayList(struct { Op, usize }) = .empty; + for (ops.items) |op| { + if (runs.items.len > 0 and runs.items[runs.items.len - 1][0] == op) { + runs.items[runs.items.len - 1][1] += 1; + } else try runs.append(arena, .{ op, 1 }); + } + return runs.items; + } +}; + +const Marks = struct { + /// Byte ranges of the removed and the added line to emphasise. + minus: []const [2]usize, + plus: []const [2]usize, + distance: f64, +}; + +/// delta's annotate: walk the alignment's runs over both lines, marking +/// what each deleted and inserted, and a run of blanks between two changes +/// with them; the distance is the changed width over the whole width (a +/// kept section counting on both lines). +fn annotate(arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u8, plus_line: []const u8) !Marks { + var minus: std.ArrayList([2]usize) = .empty; + var plus: std.ArrayList([2]usize) = .empty; + var x_off: usize = 0; + var y_off: usize = 0; + var m_byte: usize = 0; + var p_byte: usize = 0; + var numer: usize = 0; + var denom: usize = 0; + var minus_prev: Op = .noop; + var plus_prev: Op = .noop; + const Take = struct { + fn section(tokens: []const []const u8, off: *usize, byte: *usize, n: usize, line: []const u8) [2]usize { + const start = byte.*; + const end_tok = @min(tokens.len, off.* + n); + for (tokens[@min(off.*, end_tok)..end_tok]) |t| byte.* += t.len; + off.* = end_tok; + byte.* = @min(byte.*, line.len); + return .{ start, byte.* }; + } + }; + for (try a.coalesced(arena)) |run| { + const op, const n = run; + switch (op) { + .deletion => { + const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); + const w = trimmedWidth(minus_line[r[0]..r[1]]); + numer += w; + denom += w; + try minus.append(arena, r); + minus_prev = .deletion; + }, + .noop => { + const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); + const section = minus_line[r[0]..r[1]]; + denom += 2 * trimmedWidth(section); + const is_space = std.mem.trim(u8, section, " \t").len == 0; + const coalesce = is_space and + ((minus_prev == .deletion and plus_prev == .insertion and + (x_off < a.x.len -| 1 or y_off < a.y.len -| 1)) or + (minus_prev == .noop and plus_prev == .noop)); + if (coalesce and minus_prev == .deletion) try minus.append(arena, r); + const pr = Take.section(a.y, &y_off, &p_byte, n, plus_line); + if (coalesce and plus_prev == .insertion) try plus.append(arena, pr); + minus_prev = .noop; + plus_prev = .noop; + }, + .insertion => { + const r = Take.section(a.y, &y_off, &p_byte, n, plus_line); + const w = trimmedWidth(plus_line[r[0]..r[1]]); + numer += w; + denom += w; + try plus.append(arena, r); + plus_prev = .insertion; + }, + } + } + const distance: f64 = if (denom > 0) @as(f64, @floatFromInt(numer)) / @as(f64, @floatFromInt(denom)) else 0; + return .{ .minus = minus.items, .plus = plus.items, .distance = distance }; +} + +fn trimmedWidth(section: []const u8) usize { + return pardes.panes.File.displayWidth(std.mem.trim(u8, section, " \t")); +} + +// ---- tests ---- + +const testing = std.testing; + +fn emphasised(line: HunkLine) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.diff_emph != 0) c else '.'); + return out.toOwnedSlice(testing.allocator); +} + +fn expectEmphasis(minus: []const u8, plus: []const u8, want_minus: []const u8, want_plus: []const u8) !void { + var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + var m = [_]HunkLine{.{ .kind = .removed, .code = minus, .styles = try arena.alloc(u8, minus.len), .old = 1, .new = 1 }}; + var p = [_]HunkLine{.{ .kind = .added, .code = plus, .styles = try arena.alloc(u8, plus.len), .old = 2, .new = 1 }}; + @memset(m[0].styles, 0); + @memset(p[0].styles, 0); + try inferEdits(arena, &m, &p); + const got_minus = try emphasised(m[0]); + defer testing.allocator.free(got_minus); + const got_plus = try emphasised(p[0]); + defer testing.allocator.free(got_plus); + try testing.expectEqualStrings(want_minus, got_minus); + try testing.expectEqualStrings(want_plus, got_plus); +} + +test "delta's emphasis: the word a line changed, in both lines" { + try expectEmphasis(" let x = foo(1);", " let x = bar(1);", "............foo....", "............bar...."); + try expectEmphasis("a b c", "a x c", "..b..", "..x.."); +} + +test "delta's emphasis: lines too far apart are no change of one another" { + try expectEmphasis("completely different text", "nothing alike here at all", ".........................", "........................."); +} + +test "delta's emphasis: a word added keeps the rest plain" { + try expectEmphasis("fn run(a: u32)", "fn run(a: u32, b: u32)", "..............", "............., b: u32."); +} + +test "delta's alignment: kitten to sitting, as align.rs has it" { + var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + // One token a letter, as delta's test splits them, behind the empty one. + const x = [_][]const u8{ "", "k", "i", "t", "t", "e", "n" }; + const y = [_][]const u8{ "", "s", "i", "t", "t", "i", "n", "g" }; + const a = try Alignment.init(arena, &x, &y); + var ops: std.ArrayList(Op) = .empty; + for (try a.coalesced(arena)) |run| for (0..run[1]) |_| try ops.append(arena, run[0]); + try testing.expectEqualSlices(Op, &.{ .noop, .deletion, .insertion, .noop, .noop, .noop, .deletion, .insertion, .noop, .insertion }, ops.items); +} + +test "a diff stacks to a label a hunk and its lines, markers gone, tinted and stepped" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const patch = + \\diff --git a/nowhere/x.txt b/nowhere/x.txt + \\--- a/nowhere/x.txt + \\+++ b/nowhere/x.txt + \\@@ -1,3 +1,3 @@ section one + \\ keep + \\-old value + \\+new value + \\ tail + \\ + ; + const result = try format(p, "/pardes-surely-missing-dir", patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expectEqualStrings("nowhere/x.txt:2\n section one\n keep\n-old value\n+new value\n tail\n", result.content); + try testing.expectEqual(@as(usize, 6), result.rows.len); + try testing.expectEqual(.match, result.rows[0].kind); + try testing.expectEqual(@as(usize, "nowhere/x.txt:2".len), result.rows[0].location_end); + try testing.expect(result.rows[1].declaration); + const removed = result.rows[3]; + try testing.expect(removed.colors[0] & syntax.diff_removed != 0); + // Paired with the line it changed: no whole-line tint. + try testing.expect(removed.colors[0] & syntax.diff_whole == 0); + try testing.expect(removed.colors[1] & syntax.diff_emph != 0); + try testing.expect(removed.colors[5] & syntax.diff_emph == 0); + try testing.expect(result.rows[4].colors[0] & syntax.diff_added != 0); + try testing.expect(result.rows[2].colors[0] & (syntax.diff_added | syntax.diff_removed) == 0); +} + +test "a hunk the file has moved since is found where it went, inside its declaration" { + if (!syntax.supportsPath("a.zig")) return error.SkipZigTest; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + // Two lines more above it than the patch knows of. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = "// one\n// two\nconst S = struct {\n fn f() void {\n a();\n b();\n }\n};\n" }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = + \\--- a.zig + \\+++ a.zig + \\@@ -3,3 +3,3 @@ git's guess + \\ fn f() void { + \\- c(); + \\+ a(); + \\ b(); + \\ + ; + const result = try format(p, dir, patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expect(std.mem.indexOf(u8, result.content, "a.zig:3\n const S = struct {\na.zig:5 *\n") != null); + try testing.expect(std.mem.indexOf(u8, result.content, "git's guess") == null); +} + +test "a mailed patch keeps its headers, message and diffstat above its hunks" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const patch = + \\From 0123 Mon Sep 17 00:00:00 2001 + \\Subject: [PATCH] change x + \\ + \\Why it changed. + \\--- + \\ x.txt | 2 +- + \\ + \\diff --git a/x.txt b/x.txt + \\index 1..2 100644 + \\--- a/x.txt + \\+++ b/x.txt + \\@@ -1 +1 @@ + \\-a + \\+b + \\ + ; + const result = try format(p, "/pardes-surely-missing-dir", patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); +} + +test "DiffLook hunks: a .patch looked at opens its +Diff; Diff goes to the text and back; DiffLook text opens the text" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "x.txt", .data = "b\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "c.patch", .data = "--- x.txt\n+++ x.txt\n@@ -1 +1 @@\n-a\n+b\n" }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = try std.fs.path.join(testing.allocator, &.{ dir, "c.patch" }); + defer testing.allocator.free(patch); + const hunks_path = try std.fs.path.join(testing.allocator, &.{ dir, "+Diff" }); + defer testing.allocator.free(hunks_path); + const Count = struct { + fn of(pp: *Pardes, path: []const u8) usize { + var n: usize = 0; + for (pp.panes) |slot| if (slot) |pane| if (pane.file) |f| { + n += @intFromBool(std.mem.eql(u8, f.path, path)); + }; + return n; + } + }; + try testing.expectEqual(pardes.config.Runtime.DiffLook.hunks, p.settings.diff_look); + pardes.look.lookAt(p, 0, patch); + try testing.expectEqual(@as(usize, 1), Count.of(p, hunks_path)); + try testing.expectEqual(@as(usize, 0), Count.of(p, patch)); + const hid = p.active; + try testing.expectEqualStrings(hunks_path, p.panes[hid].?.file.?.path); + try testing.expectEqualStrings("x.txt:1\n-a\n+b\n", p.panes[hid].?.file.?.content); + // Diff on it: the patch as text. + try testing.expect(p.executeBuiltinLine(hid, "Diff")); + try testing.expectEqual(@as(usize, 1), Count.of(p, patch)); + const raw = p.active; + try testing.expectEqualStrings(patch, p.panes[raw].?.file.?.path); + // Diff on the text: the +Diff again, refilled, not another. + try testing.expect(p.executeBuiltinLine(raw, "Diff")); + try testing.expectEqual(@as(usize, 1), Count.of(p, hunks_path)); + // DiffLook text: a look opens the text (here the pane already open). + try testing.expect(p.executeBuiltinLine(0, "DiffLook text")); + try p.removePane(raw, null); + pardes.look.lookAt(p, 0, patch); + try testing.expectEqual(@as(usize, 1), Count.of(p, patch)); +} + +test "a hunk edited since, beside siblings with its signature's tail, is found in its own function" { + if (!syntax.supportsPath("a.rs")) return error.SkipZigTest; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + // Three functions ending in one signature's tail; the patch is for the + // third, which has moved down a line and had a line inside it edited. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.rs", .data = + \\// moved + \\fn one( + \\ limit: usize, + \\) -> u32 { + \\ 1 + \\} + \\fn two( + \\ limit: usize, + \\) -> u32 { + \\ 2 + \\} + \\fn three( + \\ limit: usize, + \\) -> u32 { + \\ let guard = enter(); + \\ let a = 3; + \\ let b = a + 1; + \\ let c = b * 2; // edited since + \\ c + \\} + \\ + }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = + \\--- a.rs + \\+++ a.rs + \\@@ -12,7 +12,8 @@ git's guess + \\ limit: usize, + \\ ) -> u32 { + \\+ let guard = enter(); + \\ let a = 3; + \\ let b = a + 1; + \\ let c = b * 2; + \\ c + \\ + ; + const result = try format(p, dir, patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expect(std.mem.indexOf(u8, result.content, "a.rs:12\n fn three(\na.rs:15 *\n") != null); +} 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/layout.zig b/src/layout.zig index a2211dfd..6345c91a 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -27,8 +27,19 @@ pub const MovePlacement = struct { above_h: u16, }; +pub const Dir = enum { left, right, up, down }; + /// Move the keyboard to the nearest pane in `dir`; false when there is none. -pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) bool { +pub fn focusDir(p: *Pardes, from: usize, dir: Dir) bool { + const b = nearest(p, from, dir) orelse return false; + p.active = b; + // a count typed before the hop was meant for the pane you left + p.panes[b].?.body.normal.clear(); + return true; +} + +/// The pane next to `from` in `dir`, by the screen. +pub fn nearest(p: *const Pardes, from: usize, dir: Dir) ?usize { const a = p.rects[from]; var best: ?usize = null; var best_d: i32 = 0; @@ -55,11 +66,60 @@ pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) bo best_d = d; } } - const b = best orelse return false; - p.active = b; - // a count typed before the hop was meant for the pane you left - p.panes[b].?.body.normal.clear(); - return true; + return best; +} + +/// Window mode's labels, one a pane in reading order (columns left to +/// right, each top to bottom); h, j, k and l move instead. ponytail: a +/// pane past the 22nd has no label and is reached by moving. +pub const window_labels = "asdfgqwertyuiopzxcvbnm"; + +/// The letter window mode shows on pane `id`. +pub fn windowLabel(p: *const Pardes, id: usize) ?u8 { + var n: usize = 0; + for (0..p.ncol) |c| for (p.col_panes[c][0..p.col_n[c]]) |pane| { + if (n == window_labels.len) return null; + if (pane == id) return window_labels[n]; + n += 1; + }; + return null; +} + +/// Window mode (SPC w, Ctrl-w): h/j/k/l (or the arrows) move an outline +/// from pane to pane and nothing else gets the keys; Enter or Esc focuses +/// the outlined pane, `:` its tag, and a pane's label letter that one. Up past a +/// column's top pane goes on to its tag, as the Up word does. Any other +/// key changes nothing. +pub fn windowKey(p: *Pardes, key: pardes.Key) void { + const at = p.window_pick orelse return; + if (p.panes[at] == null) { + p.window_pick = null; + return; + } + if (key.ctrl or key.alt) return; + for (config.window_keys) |wk| if (pardes.hit(key, &.{ wk.letter, wk.arrow })) { + const dir: Dir = switch (wk.cmd) { + .Left => .left, + .Down => .down, + .Up => .up, + else => .right, + }; + if (nearest(p, at, dir)) |next| { + p.window_pick = next; + } else if (dir == .up) { + p.window_pick = null; + p.active = at; + pardes.exec.runBuiltin(p, .Up, at, "", null); + } + return; + }; + const chosen = if (key.cp == pardes.Key.enter or key.cp == pardes.Key.escape or key.cp == ':') at else for (0..p.panes.len) |id| { + if (p.panes[id] != null and key.cp < 128 and windowLabel(p, id) == @as(u8, @intCast(key.cp))) break id; + } else return; + p.window_pick = null; + p.active = chosen; + p.panes[chosen].?.body.normal.clear(); + if (key.cp == ':') tagline.enterTag(p, p.panes[chosen].?); } /// Column `c`'s serial, handed out the first time it is asked for. @@ -266,6 +326,28 @@ pub fn setColumnWeights(p: *Pardes, col: usize, heights: *const [MAX_PANES]u16) } } +/// Give a newly opened report enough rows to read, borrowing only space +/// above the other panes' usable minima. Keep their tags and bodies visible. +pub fn givePaneRows(p: *Pardes, id: usize, wanted: u16, context: usize) void { + const at = findPane(p, id) orelse return; + compute(p); + var heights: [MAX_PANES]u16 = @splat(0); + for (p.col_panes[at.col][0..p.col_n[at.col]]) |other| heights[other] = p.rects[other].h; + var missing = wanted -| heights[id]; + for (p.col_panes[at.col][0..p.col_n[at.col]]) |other| { + if (other == id or p.panes[other].?.collapsed) continue; + const body_rows: u16 = if (other == context) 6 else 3; + const minimum = @max(minRows(p, other), p.panes[other].?.tag_rows + body_rows); + const take = @min(missing, heights[other] -| minimum); + heights[other] -= take; + heights[id] += take; + missing -= take; + if (missing == 0) break; + } + setColumnWeights(p, at.col, &heights); + p.sync(); +} + pub fn applyRowSplit(p: *Pardes, cc: usize, k: usize, cur_y: u16) void { if (k + 1 >= p.col_n[cc]) return; const a = p.panes[p.col_panes[cc][k]] orelse return; diff --git a/src/linux/v9fs.zig b/src/linux/v9fs.zig index 5e031bfe..0d1e2e33 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; @@ -89,7 +89,7 @@ var sudo_pid: std.atomic.Value(c_int) = .init(-1); fn forwardSignal(sig: std.posix.SIG) callconv(.c) void { const pid = sudo_pid.load(.monotonic); - if (pid > 0) _ = kill(pid, @intCast(@intFromEnum(sig))); + if (pid > 0) _ = kill(pid, @intCast(@backingInt(sig))); } fn launch(arena: std.mem.Allocator, args: []const [:0]const u8) !u8 { @@ -123,8 +123,8 @@ fn launch(arena: std.mem.Allocator, args: []const [:0]const u8) !u8 { const default: std.posix.Sigaction = .{ .handler = .{ .handler = std.posix.SIG.DFL }, .mask = std.posix.sigemptyset(), .flags = 0 }; var sig: u8 = 1; while (sig < 65) : (sig += 1) { - if (sig == @intFromEnum(std.posix.SIG.KILL) or sig == @intFromEnum(std.posix.SIG.STOP)) continue; - _ = std.c.sigaction(@enumFromInt(sig), &default, null); + if (sig == @backingInt(std.posix.SIG.KILL) or sig == @backingInt(std.posix.SIG.STOP)) continue; + _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); } const none = std.posix.sigemptyset(); std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, null); diff --git a/src/locations.zig b/src/locations.zig index 6a604907..2828566d 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -16,6 +16,8 @@ pub fn isContextLine(line: []const u8) bool { pub const Row = struct { kind: enum { match, context, preview }, declaration: bool = false, + mark_occurrence: bool = true, + source_column: usize = 0, path: []u8, at: look.Spot, location_end: usize, @@ -34,7 +36,7 @@ pub fn freeRows(gpa: std.mem.Allocator, rows: []Row) void { pub fn equalRows(a: []const Row, b: []const Row) bool { if (a.len != b.len) return false; for (a, b) |left, right| { - if (left.kind != right.kind or left.declaration != right.declaration or !std.meta.eql(left.at, right.at) or + if (left.kind != right.kind or left.declaration != right.declaration or left.mark_occurrence != right.mark_occurrence or left.source_column != right.source_column or !std.meta.eql(left.at, right.at) or left.location_end != right.location_end or left.code_start != right.code_start or !std.mem.eql(u8, left.path, right.path) or !std.mem.eql(u8, left.colors, right.colors)) return false; } @@ -119,7 +121,8 @@ pub fn parse(line: []const u8) Parsed { return parseRaw(line); } -fn parseRaw(line: []const u8) Parsed { +/// Native producer rows have one separator byte before untouched source. +pub fn parseRaw(line: []const u8) Parsed { var at: usize = 1; while (at < line.len) : (at += 1) { if (line[at] != ':' or at + 1 == line.len or !std.ascii.isDigit(line[at + 1])) continue; @@ -148,6 +151,8 @@ const Pending = struct { original: ?usize, hidden: bool = false, declaration: bool = false, + mark_occurrence: bool = true, + source_column: usize = 0, depth: usize = 0, colors: []const u8 = &.{}, @@ -159,7 +164,9 @@ const Pending = struct { const Source = struct { path: []const u8, bytes: []const u8 }; -fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path: []const u8) ?Source { +/// A file's text as a look from `dir` finds it: an open pane's, unsaved +/// edits and all, else the disk's. Null for a PDF or one not there. +pub fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path: []const u8) ?Source { if (std.ascii.eqlIgnoreCase(std.fs.path.extension(path), ".pdf")) return null; const lexical = std.fs.path.resolvePosix(arena, &.{ dir, path }) catch return null; var pathbuf: [4096]u8 = undefined; @@ -172,6 +179,174 @@ fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path return .{ .path = lexical, .bytes = arena.dupe(u8, bytes) catch return null }; } +/// Byte boundary after the guides in a call tree, independent of source indentation. +pub fn treePrefix(line: []const u8) struct { end: usize, branch: bool } { + var at: usize = 0; + while (at < line.len) { + for ([_][]const u8{ "╰──┬ ", "├──╮ ", "╰──╮ ", "├─── ", "╰─── ", "├──┬ ", "└──┬ ", "└─── " }) |branch| { + if (std.mem.startsWith(u8, line[at..], branch)) return .{ .end = at + branch.len, .branch = true }; + } + if (std.mem.startsWith(u8, line[at..], "├─ ") or std.mem.startsWith(u8, line[at..], "└─ ") or std.mem.startsWith(u8, line[at..], "╰─ ")) + return .{ .end = at + "└─ ".len, .branch = false }; + if (std.mem.startsWith(u8, line[at..], "│")) { + at += "│".len; + } else if (line[at] == ' ') { + at += 1; + } else break; + } + return .{ .end = at, .branch = false }; +} + +/// The same tree columns carried across a soft-wrapped display row. This is +/// presentation only: source bytes and Look addresses remain untouched. +pub fn treeContinuation(line: []const u8, buffer: []u8, max_cells: usize) []const u8 { + const prefix = line[0..treePrefix(line).end]; + var out: std.Io.Writer = .fixed(buffer); + var it = (std.unicode.Utf8View.init(prefix) catch return "").iterator(); + var cells: usize = 0; + var end: usize = 0; + while (it.nextCodepoint()) |cp| { + if (cells >= max_cells) break; + out.writeAll(if (cp == '│' or cp == '├' or cp == '┬' or cp == '╮') "│" else " ") catch break; + cells += 1; + if (cp != ' ') end = out.buffered().len; + } + if (end == 0) return ""; + // Keep one cell between the continuation and the wrapped source text. + if (end < out.buffered().len) end += 1; + return out.buffered()[0..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 { + const arena = p.scratch.allocator(); + 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); + } + const stacked = p.settings.callstack_layout == .stacked; + var sources: std.StringHashMap(?Source) = .init(arena); + var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); + while (lines.next()) |raw| { + 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; + const prefix = treePrefix(line); + const target = parseRaw(line[prefix.end..]); + if (target.at.line == 0) { + try out.writer.print("{s}\n", .{line}); + 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 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; + if (stacked) { + const end = prefix.end + target.end; + try out.writer.print("{s}\n", .{line[0..end]}); + try appendMetadata(p.gpa, &rows, .{ .path = target.path, .at = target.at, .label = "", .code = "", .original = null, .mark_occurrence = false }, .match, end, end, false); + } + var header_lines = std.mem.splitScalar(u8, code, '\n'); + var first = true; + var color_offset: usize = 0; + while (header_lines.next()) |code_line| { + const start = out.written().len; + if (stacked) { + var guide_buf: [1024]u8 = undefined; + const guide = treeContinuation(line, &guide_buf, std.math.maxInt(usize)); + try out.writer.writeAll(guide); + const width = pardes.panes.File.displayWidth(line[0..prefix.end]); + try out.writer.splatByteAll(' ', width -| pardes.panes.File.displayWidth(guide)); + } else if (first) { + try out.writer.writeAll(line[0 .. prefix.end + target.end]); + try out.writer.writeByte(' '); + } else { + const branch_start = prefix.end - "└──┬ ".len; + try out.writer.writeAll(line[0..branch_start]); + try out.writer.writeAll(if (std.mem.startsWith(u8, line[branch_start..], "├")) "│ " else " "); + try out.writer.writeAll(if (std.mem.endsWith(u8, line[0..prefix.end], "┬ ") or std.mem.endsWith(u8, line[0..prefix.end], "╮ ")) "│ " else " "); + try out.writer.splatByteAll(' ', pardes.panes.File.displayWidth(line[prefix.end..][0..target.end]) + 1); + } + const code_start = out.written().len - start; + const trim = @min(source_indent, code_line.len - std.mem.trimStart(u8, code_line, " \t").len); + try out.writer.writeAll(code_line[trim..]); + const recursion_note = recursion and first and !std.mem.endsWith(u8, code_line, " ↻ recursion"); + if (recursion_note) try out.writer.writeAll(" ↻ recursion"); + try out.writer.writeByte('\n'); + try appendMetadata(p.gpa, &rows, .{ + .path = target.path, + .at = if (first) target.at else .{ .line = source_row + 1 }, + .label = "", + .code = code_line[trim..], + .source_column = trim, + .original = null, + .mark_occurrence = focus and !prefix.branch, + .colors = if (colors.len >= color_offset + code_line.len) colors[color_offset + trim ..][0 .. code_line.len - trim] else &.{}, + }, if (first) (if (stacked) .preview else .match) else .context, if (first and !stacked) prefix.end + target.end else 0, code_start, true); + // Recursion notes are prose, outside the source snapshot. + if (recursion_note) { + const added = " ↻ recursion".len; + const row = &rows.items[rows.items.len - 1]; + if (row.colors.len > 0) { + const expanded = try p.gpa.alloc(u8, row.colors.len + added); + @memcpy(expanded[0..row.colors.len], row.colors); + @memset(expanded[row.colors.len..], 0); + p.gpa.free(row.colors); + row.colors = expanded; + } + } + color_offset += code_line.len + 1; + source_row += 1; + first = false; + } + } + const owned_rows = try rows.toOwnedSlice(p.gpa); + errdefer freeRows(p.gpa, owned_rows); + return .{ .content = try out.toOwnedSlice(), .rows = owned_rows, .anchor = null }; +} + /// Inputs are sorted results. Expand each source group, merge context with /// matches, then align groups of eight matches. All temporary source data /// stays in the caller's scratch arena; returned text and rows are owned. @@ -332,7 +507,7 @@ fn appendMetadata(gpa: std.mem.Allocator, rows: *std.ArrayList(Row), pending: Pe errdefer gpa.free(path); const colors = try gpa.dupe(u8, if (source) pending.colors else &.{}); errdefer gpa.free(colors); - try rows.append(gpa, .{ .kind = kind, .declaration = pending.declaration, .path = path, .at = pending.at, .location_end = location_end, .code_start = code_start, .colors = colors }); + try rows.append(gpa, .{ .kind = kind, .declaration = pending.declaration, .mark_occurrence = pending.mark_occurrence, .source_column = pending.source_column, .path = path, .at = pending.at, .location_end = location_end, .code_start = code_start, .colors = colors }); } const alignment_entries = 8; @@ -412,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; @@ -429,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)), @@ -634,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 41cfdc0c..f4fbe52e 100644 --- a/src/look.zig +++ b/src/look.zig @@ -524,7 +524,7 @@ pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { const w = pane.wrapRow(pane.body.cur_row, pane.body.cur_col); const vrow = w.row + @as(i32, pane.tag_rows); const vcol = if (pane.file != null) - panes.File.displayOffset(pane, pane.body.cur_row, w.at, pane.body.cur_col) + @as(i32, panes.File.gutterWidth(pane)) + w.pad + panes.File.displayOffset(pane, pane.body.cur_row, w.at, pane.body.cur_col) + @as(i32, panes.File.gutterWidth(pane)) else blk: { const lines = edit.paneCursorLines(p, &pane.body) catch break :blk pane.body.cur_col; const local = pane.body.cur_row; @@ -542,7 +542,10 @@ pub fn submitSearch(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; if (normal.selRegexArmed(pane)) |a| { // helix keeps the pattern in `/` - if (a.pat.len > 0) p.registers.put(p.gpa, '/', a.pat, 0, 1, true); + if (a.pat.len > 0) { + p.registers.put(p.gpa, '/', a.pat, 0, 1, true); + p.registers.last_search = '/'; + } return if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); } const armed = pane.promptText() orelse return; @@ -556,7 +559,13 @@ pub fn submitSearch(p: *Pardes, id: usize) void { else .text; _ = runSearch(p, id, armed[slash + 1 ..], kind, .top, true) catch |err| return p.reportError(id, "search", err); - if (kind == .text) lookFirstHit(p, id); + 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); + } } fn lookFirstHit(p: *Pardes, id: usize) void { @@ -662,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"), }); @@ -883,7 +892,13 @@ fn lookSpanIn(p: *Pardes, pane: *Pane, from: LookFrom, delta: i32, budget: *usiz if (grain == .whole) break :span wholeRowSpan(ln); if (pane.file) |f| if (@as(usize, @intCast(r)) < f.location_rows.len) { const end = f.location_rows[@intCast(r)].location_end; - if (end > 0) break :span @as(?Span, .{ .start = 0, .end = end }); + if (end > 0) { + const start_byte = if (f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .query = .callstack })) + @import("locations.zig").treePrefix(ln).end + else + 0; + break :span @as(?Span, .{ .start = start_byte, .end = end }); + } }; break :span lineSpan(p, ln, dir, &realbuf); } orelse continue; @@ -1048,6 +1063,7 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, ke if (id >= MAX_PANES) return; const pane = p.panes[id] orelse return; p.active = id; + if (pane.collapsed) layout.toggleCollapse(p, id); pane.body.normal.clear(); if (pane.hasPdf()) { if (landing == .keep) return; @@ -1257,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/")); @@ -1869,6 +1885,18 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const before = p.active; var opened: ?usize = null; if (!focusPaneByPath(p, target.path, target.at)) { + // A .diff or .patch looked at bare: its hunks stacked in a + // +Diff (DiffLook hunks), which takes the keyboard as the + // file would; one with none in it opens as text. + if (p.settings.diff_look == .hunks and !p.look_text and target.at.line == 0 and + (std.mem.endsWith(u8, target.path, ".diff") or std.mem.endsWith(u8, target.path, ".patch"))) + if (filesystem.read(p, target.path)) |bytes| { + defer p.gpa.free(bytes); + if (panes.Output.openDiff(p, id, target.path, bytes)) |hid| { + p.active = hid; + return; + } else |_| {} + } else |_| {}; const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots); const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return lookOpenFailed(p, id, target.path, err); @@ -2157,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. @@ -2527,7 +2555,7 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5 const line = modal.lineSlice(case.text, case.row); // A diff line written whole; a place, as a script writes it. const written = if (std.mem.eql(u8, case.name, "change.diff")) line else line[case.sweep[0] .. case.sweep[1] + 1]; - _ = th.wr(p, @intFromEnum(pardes.ctlfs.TopFile.look), written); + _ = th.wr(p, @backingInt(pardes.ctlfs.TopFile.look), written); }, .event_write_back => { const body = pane.file.?.content; @@ -2656,7 +2684,7 @@ test "Incl's directories find a name found nowhere else, <name> too; bare Incl l try std.testing.expectEqual(@as(usize, 0), p.incl.items.len); } -test "n in a command pane walks its own file:line places, whoever walked last" { +test "LookNext in a command pane walks its own file:line places, whoever walked last" { if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2685,12 +2713,12 @@ test "n in a command pane walks its own file:line places, whoever walked last" { cmd.focus = .body; cmd.body.mode = .normal; for ([_]u21{ 'g', 'g' }) |cp| p.update(.{ .key = .{ .cp = cp } }); - p.update(.{ .key = .{ .cp = 'n' } }); + exec.runBuiltin(p, .LookNext, p.active, "", null); try std.testing.expectEqual(dst, p.active); const first = cmd.look_at orelse return error.NoSpot; const lines = try edit.paneCursorLines(p, &cmd.body); try std.testing.expect(std.mem.startsWith(u8, lines[@intCast(first.row)][@intCast(first.col0)..], "x.c:3:1")); - p.update(.{ .key = .{ .cp = 'n' } }); + exec.runBuiltin(p, .LookNext, p.active, "", null); try std.testing.expectEqual(dst, p.active); const second = cmd.look_at orelse return error.NoSpot; try std.testing.expect(std.mem.startsWith(u8, lines[@intCast(second.row)][@intCast(second.col0)..], "y.c:2:1")); @@ -2740,7 +2768,6 @@ test "Look on a diff under each git prefix opens the repository's file, and a re } } - test "Look on a diff line is the look of the address it names, selected by hand: a cached patch, the checkout elsewhere" { if (!platform_has_fs) return; const io = std.testing.io; diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 8dc4da4f..4a70efe5 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -16,6 +16,7 @@ pub const Kind = enum { format, select_refs, completion, + callstack, incoming_calls, outgoing_calls, supertypes, @@ -24,7 +25,14 @@ pub const Kind = enum { explain, }; +pub const callstack_match = "@callstack-match "; +pub const CallstackCorners = enum { rounded, square }; +pub const callstack_default_depth: u8 = 8; +pub const callstack_max_depth: u8 = 64; + pub const Req = struct { + callstack_depth: u8 = callstack_default_depth, + callstack_corners: CallstackCorners = .rounded, kind: Kind, path: []const u8, source: [:0]const u8, @@ -46,7 +54,7 @@ pub const Doc = struct { path: []const u8, source: [:0]const u8 }; /// file of the server's language is synced before it is asked. pub fn reachesOtherFiles(kind: Kind) bool { return switch (kind) { - .rename, .references, .implementation, .workspace_symbols, .incoming_calls, .outgoing_calls, .supertypes, .subtypes => true, + .rename, .references, .implementation, .workspace_symbols, .callstack, .incoming_calls, .outgoing_calls, .supertypes, .subtypes => true, else => false, }; } @@ -84,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 561195fe..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 @@ -521,7 +521,8 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io }; 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 }; + 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 }; + 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), }); @@ -642,6 +643,7 @@ 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), @@ -869,6 +871,184 @@ fn sortEdits(edits: []PutEdit) void { }.lt); } +/// 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 { + 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); +} + +const CallTree = struct { + const Site = struct { range: std.json.Value, focus: bool }; + const Node = struct { + item: std.json.Value, + ranges: std.ArrayList(Site) = .empty, + children: std.ArrayList(usize) = .empty, + cycle: bool = false, + }; + nodes: std.ArrayList(Node) = .empty, + 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, + siblings: [lsp.callstack_max_depth]bool = @splat(false), + rendered: usize = 0, + + /// Incoming paths arrive nearest-first. Insert them outermost-first, + /// sharing common caller prefixes and retaining all their call sites. + fn addPath(tree: *CallTree, arena: std.mem.Allocator, path: []const std.json.Value, cycle: bool) Err!void { + var parent: ?usize = null; + var at = path.len; + while (at > 0) { + at -= 1; + const entry = path[at]; + 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; + } else null; + const id = found orelse blk: { + const id = tree.nodes.items.len; + try tree.nodes.append(arena, .{ .item = item }); + if (parent) |pid| { + try tree.nodes.items[pid].children.append(arena, id); + } else try tree.roots.append(arena, id); + break :blk id; + }; + const node = &tree.nodes.items[id]; + node.cycle = node.cycle or (cycle and at == 0); + 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).?)) { + other.focus = other.focus or at == 0; + break; + } + } else try node.ranges.append(arena, .{ .range = range, .focus = at == 0 }); + } + parent = id; + } + } +}; + +fn sameCall(a: std.json.Value, b: std.json.Value) bool { + const au = str(get(a, "uri")) orelse return false; + 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); +} + +fn callPrefix(out: *std.Io.Writer, tree: *const CallTree, depth: usize) Err!void { + for (tree.siblings[0..depth]) |more| try out.writeAll(if (more) "│ " else " "); +} + +fn validCaller(entry: std.json.Value) bool { + const from = get(entry, "from") orelse return false; + const uri = str(get(from, "uri")) orelse return false; + return std.mem.startsWith(u8, uri, "file:") and + 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 { + 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; + if (items(prepared).len == 0) return lsp.none(cx.out, "no function at this position", .{}); + 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"); + 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"); + 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 { + var count: usize = 0; + for (items(incoming)) |entry| { + if (tree.visited >= 64) { + tree.limited = true; + 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; + } else false; + tree.path[depth] = entry; + tree.visited += 1; + count += 1; + var children: usize = 0; + if (!cycle) { + if (depth + 1 == tree.depth_limit or tree.visited >= 64) { + 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); + } + } + if (children == 0) try tree.addPath(arena, tree.path[0 .. depth + 1], cycle); + } + return count; +} + +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")).?); + if (uri_order != .eq) return uri_order == .lt; + return callRangeLess({}, get(left, "selectionRange") orelse get(left, "range").?, get(right, "selectionRange") orelse get(right, "range").?); +} + +fn callRangeLess(_: void, a: std.json.Value, b: std.json.Value) bool { + const left = rangeOf(a).?; + const right = rangeOf(b).?; + 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) { + 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 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); + 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); + } + }.less); + for (node.ranges.items, 0..) |site, site_index| { + 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 renderCallers(cx, enc, tree, node.children.items, depth + 1); + } +} + const Hier = enum { incoming, outgoing, supers, subs }; /// The two-step hierarchy kinds: prepare at the cursor, then follow every @@ -894,17 +1074,7 @@ fn hierarchy(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []cons const b = try atPos(arena, uri, pos); const prepared = (try call(c, arena, prepare, b.items, deadline)) orelse return; for (items(prepared)) |item| { - // the item goes back VERBATIM — servers hide resolution state in - // `data` and a re-serialized subset would come back unresolvable. - // But only if it can round-trip: Stringify panics past its nesting - // limit, so a server that nests a bomb in `data` gets no rows for - // that item, not a dead editor. - if (jsonDepth(item, 0) > 96) continue; - var body: std.ArrayList(u8) = .empty; - try app(&body, arena, "\"item\":"); - const item_json = std.json.Stringify.valueAlloc(arena, item, .{}) catch return error.OutOfMemory; - try app(&body, arena, item_json); - const result = (try call(c, arena, follow, body.items, deadline)) orelse return; + const result = (try hierarchyResult(c, 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 @@ -965,6 +1135,8 @@ const Cx = struct { cur_src: []const u8, out: *std.Io.Writer, rows: usize = 0, + relative_parents: bool = false, + callstack_corners: lsp.CallstackCorners = .rounded, files: std.ArrayList(struct { path: []const u8, text: []const u8 }) = .empty, fn text(cx: *Cx, path: []const u8) ?[]const u8 { @@ -1018,7 +1190,10 @@ fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: [ const lntext: []const u8 = if (src) |t| t[@min(bol, t.len)..@min(eol, t.len)] else ""; const col = colBytes(lntext, r.sc, enc); - const shown = lsp.rel(cx.base, path); + const shown = if (cx.relative_parents) blk: { + const relative = std.fs.path.relativePosix(cx.arena, "/", cx.base, path) catch break :blk path; + break :blk if (relative.len < path.len) relative else path; + } else lsp.rel(cx.base, path); // A same-line exclusive end byte offset is also the displayed inclusive // one-based column. Multi-line ranges display only their starting address. const end_col = if (r.el == r.sl and r.ec > r.sc) colBytes(lntext, r.ec, enc) else col; @@ -2131,6 +2306,68 @@ fn coord(v: ?std.json.Value) ?u32 { // ----------------------------------------------------------------- tests +test "caller trees reverse incoming paths and merge shared callers and sites" { + 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, "[{\"from\":{\"name\":\"left\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}]},{\"from\":{\"name\":\"right\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":2,\"character\":0},\"end\":{\"line\":2,\"character\":4}}]},{\"from\":{\"name\":\"main\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}]}]", .{}); + const entries = items(fixture); + var tree: CallTree = .{}; + try tree.addPath(arena, &.{ entries[0], entries[2], entries[4] }, false); + try tree.addPath(arena, &.{ entries[1], entries[3], entries[4] }, false); + 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.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); + try std.testing.expectEqual(@as(usize, 2), page.ranges.items.len); + try std.testing.expect(!root.ranges.items[0].focus); + for (page.ranges.items) |site| try std.testing.expect(!site.focus); + for (page.children.items) |id| try std.testing.expect(tree.nodes.items[id].ranges.items[0].focus); + var out: std.Io.Writer.Allocating = .init(arena); + var cx: Cx = .{ .arena = arena, .base = "/", .cur_path = "/test.c", .cur_src = "main_call();\npage_left();\npage_right();\nleft_call();\nright_call();\n", .out = &out.writer }; + try renderCallers(&cx, .utf8, &tree, tree.roots.items, 0); + const text = out.written(); + try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, lsp.callstack_match)); + const main_at = std.mem.indexOf(u8, text, " main\n").?; + const page_at = std.mem.indexOf(u8, text, " page\n").?; + const left_at = std.mem.indexOf(u8, text, " left\n").?; + const right_at = std.mem.indexOf(u8, text, " right\n").?; + try std.testing.expect(main_at < page_at and page_at < left_at and left_at < right_at); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "main_call();")); + try std.testing.expect(std.mem.indexOf(u8, text, "page_left();").? < std.mem.indexOf(u8, text, "page_right();").?); + try std.testing.expect(std.mem.indexOf(u8, text, "├──┬ test.c:4:") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "╰──┬ test.c:1:") != null); + cx.callstack_corners = .square; + tree.rendered = 0; + const square_start = out.written().len; + try renderCallers(&cx, .utf8, &tree, tree.roots.items, 0); + const square = out.written()[square_start..]; + try std.testing.expect(std.mem.indexOf(u8, square, "├──┬ test.c:4:") != null); + try std.testing.expect(std.mem.indexOf(u8, square, "└──┬ test.c:1:") != null); + try std.testing.expect(std.mem.indexOf(u8, square, "╰") == null); + try std.testing.expect(std.mem.indexOf(u8, square, "╮") == null); + var recursive: CallTree = .{}; + try recursive.addPath(arena, &.{ entries[0], entries[0] }, true); + try std.testing.expect(!recursive.nodes.items[recursive.roots.items[0]].cycle); + try std.testing.expect(recursive.nodes.items[1].cycle); +} + +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(); + const arena = arena_state.allocator(); + const range = try std.json.parseFromSliceLeaky(std.json.Value, arena, + \\{"start":{"line":1,"character":3},"end":{"line":1,"character":6}} + , .{}); + var out: std.Io.Writer.Allocating = .init(arena); + var cx: Cx = .{ .arena = arena, .base = "/workspace/merkle-tree/src", .cur_path = "", .cur_src = "", .out = &out.writer, .relative_parents = true }; + try emitRange(&cx, .utf8, "file:///workspace/entry/src/entry.rs", range, "fn run()"); + try std.testing.expectEqualStrings("../../entry/src/entry.rs:2:4-6 fn run()\n", out.written()); +} + test "LSP client rename and format propagate incomplete edit encoding" { const gpa = std.testing.allocator; const uri = "file:///file.c"; diff --git a/src/macos.zig b/src/macos.zig index 20463481..50fa04fa 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; } @@ -1110,7 +1110,7 @@ fn refreshCwds(ctx: ?*anyopaque) void { stale.* = false; const pt = st.ptys[id] orelse continue; var buf: [1024]u8 = undefined; - if (host_io.shellCwd(pt.pid, &buf)) |wd| st.core.setCwd(id, wd); + if (host_io.ttyCwd(pt.pid, pt.file.handle, st.core.settings.shell.effective.get(), &buf)) |wd| st.core.setCwd(id, wd); } } @@ -1717,18 +1717,20 @@ fn mouseWithHit(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u3 3 => .drag, else => return, }; - st.core.update(.{ .mouse = .{ - .body_hit = hit, - .tag_hit = tag_hit, - .button = button, - .kind = kind, - .col = col, - .row = row, - .ctrl = mods & 1 != 0, - // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). - .alt = mods & 2 != 0, - .super = mods & 8 != 0, - } }); + st.core.update(.{ + .mouse = .{ + .body_hit = hit, + .tag_hit = tag_hit, + .button = button, + .kind = kind, + .col = col, + .row = row, + .ctrl = mods & 1 != 0, + // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, + }, + }); } export fn pardes_pointer_leave() void { @@ -2156,7 +2158,7 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { const layer = &st.core.surface.tag_layers[index]; return switch (field) { 0 => layer.cols, - 1 => @intFromEnum(layer.kind), + 1 => @backingInt(layer.kind), 2 => layer.id, 3 => layer.serial, 4 => layer.viewport.x, @@ -2238,7 +2240,7 @@ 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); + return @backingInt(st.core.surface.pointer_shape); } export fn pardes_cursor_y() i32 { @@ -2646,7 +2648,7 @@ fn encodeAttrs(style: pardes.CellStyle) u16 { attrs |= @as(u16, @intFromBool(style.reverse)) << 4; attrs |= @as(u16, @intFromBool(style.invisible)) << 5; attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; - attrs |= @as(u16, @intFromEnum(style.ul)) << 8; + attrs |= @as(u16, @backingInt(style.ul)) << 8; return attrs; } @@ -2871,22 +2873,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); @@ -2896,21 +2898,21 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u8, c.PARDES_CELL_HOVER), cell_flag_hover); try expectEqual(@as(u16, c.PARDES_TOPBAR_H), pardes.TOPBAR_H); try expectEqual(@as(u32, c.PARDES_SCENE_CRT), scene_flag_crt); - try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @intFromEnum(animation.Phase.opening)); - try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @intFromEnum(animation.Phase.moving)); - try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @intFromEnum(animation.Phase.closing)); - try expectEqual(@as(u8, c.PARDES_PANEL_OFF), @intFromEnum(animation.Transition.off)); - try expectEqual(@as(u8, c.PARDES_PANEL_SLIDE), @intFromEnum(animation.Transition.slide)); - try expectEqual(@as(u8, c.PARDES_PANEL_ZOOM), @intFromEnum(animation.Transition.zoom)); - try expectEqual(@as(u8, c.PARDES_PANEL_DISSOLVE), @intFromEnum(animation.Transition.dissolve)); - try expectEqual(@as(u8, c.PARDES_PANEL_ASCII), @intFromEnum(animation.Transition.ascii)); - try expectEqual(@as(u8, c.PARDES_PANEL_VERTICAL), @intFromEnum(animation.Transition.vertical)); - try expectEqual(@as(u8, c.PARDES_PANEL_EDGES), @intFromEnum(animation.Transition.edges)); - try expectEqual(@as(u8, c.PARDES_PANEL_FALL), @intFromEnum(animation.Transition.fall)); - try expectEqual(@as(u8, c.PARDES_PANEL_WAVE), @intFromEnum(animation.Transition.wave)); - try expectEqual(@as(u8, c.PARDES_PANEL_CURTAIN), @intFromEnum(animation.Transition.curtain)); - try expectEqual(@as(u8, c.PARDES_PANEL_SCRAMBLE), @intFromEnum(animation.Transition.scramble)); - try expectEqual(@as(u8, c.PARDES_PANEL_TYPEWRITER), @intFromEnum(animation.Transition.typewriter)); + try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @backingInt(animation.Phase.opening)); + try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @backingInt(animation.Phase.moving)); + try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @backingInt(animation.Phase.closing)); + try expectEqual(@as(u8, c.PARDES_PANEL_OFF), @backingInt(animation.Transition.off)); + try expectEqual(@as(u8, c.PARDES_PANEL_SLIDE), @backingInt(animation.Transition.slide)); + try expectEqual(@as(u8, c.PARDES_PANEL_ZOOM), @backingInt(animation.Transition.zoom)); + try expectEqual(@as(u8, c.PARDES_PANEL_DISSOLVE), @backingInt(animation.Transition.dissolve)); + try expectEqual(@as(u8, c.PARDES_PANEL_ASCII), @backingInt(animation.Transition.ascii)); + try expectEqual(@as(u8, c.PARDES_PANEL_VERTICAL), @backingInt(animation.Transition.vertical)); + try expectEqual(@as(u8, c.PARDES_PANEL_EDGES), @backingInt(animation.Transition.edges)); + try expectEqual(@as(u8, c.PARDES_PANEL_FALL), @backingInt(animation.Transition.fall)); + try expectEqual(@as(u8, c.PARDES_PANEL_WAVE), @backingInt(animation.Transition.wave)); + try expectEqual(@as(u8, c.PARDES_PANEL_CURTAIN), @backingInt(animation.Transition.curtain)); + try expectEqual(@as(u8, c.PARDES_PANEL_SCRAMBLE), @backingInt(animation.Transition.scramble)); + try expectEqual(@as(u8, c.PARDES_PANEL_TYPEWRITER), @backingInt(animation.Transition.typewriter)); try expectEqual(@as(u21, c.PARDES_KEY_ENTER), pardes.Key.enter); try expectEqual(@as(u21, c.PARDES_KEY_ESCAPE), pardes.Key.escape); @@ -2926,24 +2928,24 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u21, c.PARDES_KEY_PAGE_DOWN), pardes.Key.page_down); try expectEqual(@as(u21, c.PARDES_KEY_DELETE), pardes.Key.delete); - try expectEqual(c.PARDES_MOUSE_LEFT, @intFromEnum(pardes.Mouse.Button.left)); - try expectEqual(c.PARDES_MOUSE_MIDDLE, @intFromEnum(pardes.Mouse.Button.middle)); - try expectEqual(c.PARDES_MOUSE_RIGHT, @intFromEnum(pardes.Mouse.Button.right)); - try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @intFromEnum(pardes.Mouse.Button.wheel_up)); - try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @intFromEnum(pardes.Mouse.Button.wheel_down)); - try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @intFromEnum(pardes.Mouse.Button.wheel_left)); - try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @intFromEnum(pardes.Mouse.Button.wheel_right)); - try expectEqual(c.PARDES_MOUSE_NONE, @intFromEnum(pardes.Mouse.Button.none)); - try expectEqual(c.PARDES_MOUSE_BACK, @intFromEnum(pardes.Mouse.Button.back)); - try expectEqual(c.PARDES_MOUSE_FORWARD, @intFromEnum(pardes.Mouse.Button.forward)); - try expectEqual(c.PARDES_MOUSE_PRESS, @intFromEnum(pardes.Mouse.Kind.press)); - try expectEqual(c.PARDES_MOUSE_RELEASE, @intFromEnum(pardes.Mouse.Kind.release)); - try expectEqual(c.PARDES_MOUSE_MOTION, @intFromEnum(pardes.Mouse.Kind.motion)); - try expectEqual(c.PARDES_MOUSE_DRAG, @intFromEnum(pardes.Mouse.Kind.drag)); + try expectEqual(c.PARDES_MOUSE_LEFT, @backingInt(pardes.Mouse.Button.left)); + try expectEqual(c.PARDES_MOUSE_MIDDLE, @backingInt(pardes.Mouse.Button.middle)); + try expectEqual(c.PARDES_MOUSE_RIGHT, @backingInt(pardes.Mouse.Button.right)); + try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @backingInt(pardes.Mouse.Button.wheel_up)); + try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @backingInt(pardes.Mouse.Button.wheel_down)); + try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @backingInt(pardes.Mouse.Button.wheel_left)); + try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @backingInt(pardes.Mouse.Button.wheel_right)); + try expectEqual(c.PARDES_MOUSE_NONE, @backingInt(pardes.Mouse.Button.none)); + try expectEqual(c.PARDES_MOUSE_BACK, @backingInt(pardes.Mouse.Button.back)); + try expectEqual(c.PARDES_MOUSE_FORWARD, @backingInt(pardes.Mouse.Button.forward)); + try expectEqual(c.PARDES_MOUSE_PRESS, @backingInt(pardes.Mouse.Kind.press)); + try expectEqual(c.PARDES_MOUSE_RELEASE, @backingInt(pardes.Mouse.Kind.release)); + try expectEqual(c.PARDES_MOUSE_MOTION, @backingInt(pardes.Mouse.Kind.motion)); + try expectEqual(c.PARDES_MOUSE_DRAG, @backingInt(pardes.Mouse.Kind.drag)); - try expectEqual(c.PARDES_HAPTIC_NONE, @intFromEnum(pardes.Haptic.none)); - try expectEqual(c.PARDES_HAPTIC_EXEC, @intFromEnum(pardes.Haptic.exec)); - try expectEqual(c.PARDES_HAPTIC_LOOK, @intFromEnum(pardes.Haptic.look)); + try expectEqual(c.PARDES_HAPTIC_NONE, @backingInt(pardes.Haptic.none)); + try expectEqual(c.PARDES_HAPTIC_EXEC, @backingInt(pardes.Haptic.exec)); + try expectEqual(c.PARDES_HAPTIC_LOOK, @backingInt(pardes.Haptic.look)); try expectEqual(@as(u16, c.PARDES_ATTR_BOLD), encodeAttrs(.{ .bold = true })); try expectEqual(@as(u16, c.PARDES_ATTR_DIM), encodeAttrs(.{ .dim = true })); @@ -3177,7 +3179,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 ed70b624..64614daa 100644 --- a/src/main.zig +++ b/src/main.zig @@ -102,7 +102,7 @@ const help_text = ; /// `pardes -` inside a session: `text`, stdin as it came, escapes and all, -/// into the directory's one +Pager (/pager, refilled when it is there): +/// into a new +Pager of the directory (/pager): /// 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, @@ -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 @@ -493,7 +499,7 @@ fn nativeMain(init: std.process.Init) !void { if (!outside) { 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; + if (pid <= 0 or std.c.kill(pid, @fromBackingInt(@intCast(0))) != 0) break :forwarding; } // Can I reach it? That is the other two, and it is a separate answer. 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/mini.zig b/src/mini.zig index 8af64201..ce291c99 100644 --- a/src/mini.zig +++ b/src/mini.zig @@ -130,7 +130,7 @@ pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) 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; + for (styles) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidMiniColors; const len = try render(null, source, styles); const content = try gpa.alloc(u8, len); errdefer gpa.free(content); @@ -248,17 +248,17 @@ 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); + styles[0] = @backingInt(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); + styles[0] = @backingInt(syntax.Syn.string); + styles[1] = @backingInt(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); + styles[3] = @backingInt(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); diff --git a/src/modal.zig b/src/modal.zig index 316a66fa..82f1a3a0 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -36,6 +36,7 @@ pub const Normal = struct { goto_type_definition, goto_implementation, goto_references, + goto_callstack, view_top, view_center, @@ -157,10 +158,12 @@ pub const Normal = struct { search, search_next, search_prev, + search_selection, + search_selection_word, }; pub const Input = struct { - roles: std.EnumSet(Role) = .initEmpty(), + roles: std.EnumSet(Role) = .empty, cp: u21, ctrl: bool = false, alt: bool = false, @@ -318,7 +321,7 @@ pub const Normal = struct { undo, redo, }; - pub const Lsp = enum { definition, declaration, type_definition, implementation, references, format }; + pub const Lsp = enum { definition, declaration, type_definition, implementation, references, callstack, format }; pub const Counted = struct { count: u32, @@ -355,7 +358,8 @@ pub const Normal = struct { command_line, pipe_selection: PipeBehavior, search, - search_step: Direction, + search_step: struct { direction: Direction, count: u32 }, + search_selection: bool, goto_word, macro_record, macro_replay: u32, @@ -373,6 +377,7 @@ pub const Normal = struct { .pipe_selection, .search, .search_step, + .search_selection, .macro_record, .macro_replay, .node, @@ -467,6 +472,7 @@ pub const Normal = struct { if (key.has(.goto_type_definition)) return resultAction(.{ .lsp = .type_definition }); if (key.has(.goto_implementation)) return resultAction(.{ .lsp = .implementation }); if (key.has(.goto_references)) return resultAction(.{ .lsp = .references }); + if (key.has(.goto_callstack)) return resultAction(.{ .lsp = .callstack }); return .ignored; }, .view => { @@ -676,8 +682,10 @@ pub const Normal = struct { if (key.has(.macro_replay)) return resultAction(.{ .macro_replay = count }); if (key.has(.repeat_insert)) return resultAction(.{ .repeat_insert = count }); if (key.has(.search)) return resultAction(.search); - if (key.has(.search_next)) return resultAction(.{ .search_step = .forward }); - if (key.has(.search_prev)) return resultAction(.{ .search_step = .backward }); + if (key.has(.search_selection)) return resultAction(.{ .search_selection = false }); + if (key.has(.search_selection_word)) return resultAction(.{ .search_selection = true }); + if (key.has(.search_next)) return resultAction(.{ .search_step = .{ .direction = .forward, .count = count } }); + if (key.has(.search_prev)) return resultAction(.{ .search_step = .{ .direction = .backward, .count = count } }); return .unbound; } @@ -1420,6 +1428,17 @@ fn wordClassAt(text: []const u8, off: usize) WordClass { }; } +pub fn searchWordAt(text: []const u8, off: usize) bool { + return off < text.len and wordClassAt(text, off) == .word; +} + +pub fn searchWordBefore(text: []const u8, off: usize) bool { + if (off == 0) return false; + var previous = off - 1; + while (previous > 0 and text[previous] & 0xc0 == 0x80) previous -= 1; + return searchWordAt(text, previous); +} + fn isWordWhitespace(c: WordClass) bool { // Rust char::is_whitespace (includes line endings) return c == .ws or c == .eol; } diff --git a/src/mouse.zig b/src/mouse.zig index 8020fda8..76c65a16 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -100,7 +100,7 @@ pub const HeaderSweep = struct { /// as a pane tag's sweep stays on its tag. fn headerPoint(p: *Pardes, column: ?usize, mcol: u16, mrow: u16, clamp: bool) ?struct { t: *panes.Text, text: []const u8, line: u16, at: usize } { const t = if (column) |c| &p.col_tags[c] else &p.global_tag; - const x = if (column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; + const x = if (column) |c| p.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET; const focused = p.header_focus and p.header_column == column; const text = edit.flatSurface(p, t) catch return null; const base = if (column != null) p.topBarHeight() else 0; @@ -379,7 +379,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { .none => null, else => return false, }; - const bit: u3 = if (button) |b| @as(u3, 1) << @intCast(@intFromEnum(b)) else 0; + const bit: u3 = if (button) |b| @as(u3, 1) << @intCast(@backingInt(b)) else 0; const at = p.presentation.pointer(p.screen_w, p.screen_h, @min(m.col, p.screen_w -| 1), @min(m.row, p.screen_h -| 1)); var mods: panes.terminal.MouseMods = .{ .shift = m.shift, .alt = m.alt, .ctrl = m.ctrl }; var buf: [64]u8 = undefined; @@ -465,6 +465,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { var m = event; // 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) p.window_pick = null; if (m.kind == .press and switch (m.button) { .left, .middle, .right => true, else => false, @@ -588,7 +589,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { p.header_drag = false; return; }; - const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; + const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET; const text = edit.flatSurface(p, t) catch return; // `row` is the header's row on screen, `line` the line of its text // shown there. @@ -612,7 +613,8 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { pane.closePrompt(); }; var column: ?usize = null; - var x: u16 = 0; + var x: u16 = TAG_TEXT_INSET; + if (mcol < x) return; 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; @@ -700,7 +702,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { // 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; + t.sel[@backingInt(config.look_button)].state = .none; if (comptime pdf_enabled) panes.Pdf.pointerCancel(t, p.drag.select.pdf); } @@ -811,7 +813,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { // 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; + t.sel[@backingInt(p.drag.select.button)].state = .none; if (comptime pdf_enabled) panes.Pdf.pointerCancel(t, p.drag.select.pdf); } @@ -832,8 +834,8 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { 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; + pane.clearPointerSelection(@backingInt(m.button)); + pane.sel[@backingInt(m.button)] = pointed.sel; p.drag = .{ .select = .{ .id = id, @@ -905,7 +907,7 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo .select => |*s| { if (p.panes[s.id]) |pane| { const r = p.rects[s.id]; - const b = @intFromEnum(s.button); + const b = @backingInt(s.button); const tag_rows: i32 = pane.tag_rows; if (pane.body_rows > 0 and pane.sel[b].r0 >= tag_rows) if (body_hit) |supplied| { const mapped_hit = bodyHitForPane(p, s.id, supplied, true) orelse return; @@ -1047,7 +1049,7 @@ fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: const top = lead[0] - @as(i32, pane.tag_rows); if (top < 0) break :lead null; const w = pane.wrapAt(top); - const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane)); + const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane) - w.pad); break :lead .{ .row = @intCast(@max(0, w.line)), .col = @intCast(@max(0, col)), @@ -1154,7 +1156,7 @@ fn sweepPoint(p: *Pardes, pane: *panes.Pane, r: i32, c: i32) ?modal.Cursor { if (visible < 0) return null; const w = pane.wrapAt(visible); if (w.line < 0) return null; - const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, c - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0)); + const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, c - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0)); return .{ .row = @intCast(w.line), .col = @intCast(@max(0, col)) }; } @@ -1234,10 +1236,10 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } if (s.chorded) { // a cut/paste chord consumed this drag; the release is inert - pane.sel[@intFromEnum(s.button)].state = .none; + pane.sel[@backingInt(s.button)].state = .none; return; } - const b = @intFromEnum(s.button); + const b = @backingInt(s.button); pane.sel[b].state = .done; if (s.button == config.select_button) { const sl = pane.sel[sel_slot]; @@ -1268,7 +1270,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { &pane.body, w.line, w.at, - sl.c1 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), + sl.c1 - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), ); pane.body.cur_pinned = true; if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); @@ -1288,7 +1290,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[sel_slot].state = .none; pane.body.vsel = .{ .active = true, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; }; - if (s.ctrl) p.lspRequest(s.id, .definition, ""); + if (s.ctrl) exec.runBuiltin(p, .Def, s.id, "", null); } } else { const clk = pane.sel[b]; @@ -1312,7 +1314,14 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[b] = expanded else if (operand.text == null) pane.sel[b].state = .none; - if (s.button == config.look_button and clk.r0 >= pane.tag_rows and pane.body.mode != .tty) { + if (s.button == config.look_button and clk.r0 >= pane.tag_rows and pane.body.mode != .tty and operand.expanded != null) { + // This click chose a new word. An old keyboard anchor + // must not stretch to it; borrowed selections retain + // their original cursor and extent. + pane.body.vsel.active = false; + pane.body.msel.active = false; + pane.body.nsel = 0; + pane.body.select = false; pane.body.cur_row = operand.row; pane.body.cur_col = operand.col; if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); @@ -1431,8 +1440,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, pane.tag_rows))); const row0 = w0.line; const row1 = w1.line; - const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx); - const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx); + const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad); + const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad); pane.body.cur_row = row1; pane.body.cur_col = col1; pane.body.cur_pinned = true; @@ -1493,7 +1502,7 @@ test "plain left click clears explicit modal selection" { try std.testing.expectEqual(@as(i32, 3), pane.body.cur_col); try std.testing.expect(!pane.body.vsel.active); try std.testing.expect(!pane.body.msel.active); - try std.testing.expectEqual(.none, pane.sel[@intFromEnum(config.select_button)].state); + try std.testing.expectEqual(.none, pane.sel[@backingInt(config.select_button)].state); } test "selection drag and queued release do not enter panel pending state" { diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index b78c46e7..86d2d49e 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -638,15 +638,15 @@ test "the address language, form by form" { } // Each failure says which it is. for ([_][2][]const u8{ - .{ "zzz", e_syntax }, .{ "/nomatch/", e_no_match }, .{ "99", e_range }, - .{ "#999", e_range }, .{ "/a[/", e_regexp }, .{ "/(a/", e_regexp }, - .{ "/*a/", e_regexp }, .{ "99:1", e_range }, .{ "2:0", e_col_zero }, + .{ "zzz", e_syntax }, .{ "/nomatch/", e_no_match }, .{ "99", e_range }, + .{ "#999", e_range }, .{ "/a[/", e_regexp }, .{ "/(a/", e_regexp }, + .{ "/*a/", e_regexp }, .{ "99:1", e_range }, .{ "2:0", e_col_zero }, }) |c| { _ = th.wr(p, addr, "#0"); 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..6f5bee23 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -34,7 +34,7 @@ pub fn writeLayout(p: *Pardes, w: *std.Io.Writer) !void { const active = activeColumn(p); for (0..p.ncol) |c| { try w.print("{d} {d} {d} {d} {s} {s}", .{ - layout.columnSerial(p, c), c, p.col_x[c], p.col_w[c], + layout.columnSerial(p, c), 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}); @@ -229,8 +229,8 @@ test "Joincol is refused when the joined column cannot give each pane its tag an const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} - const ctl = @intFromEnum(tree.TopFile.ctl); - const focus = @intFromEnum(tree.TopFile.focus); + const ctl = @backingInt(tree.TopFile.ctl); + const focus = @backingInt(tree.TopFile.focus); // Two panes in the first column, then a second column of two. const a = try th.newPane(p); _ = a; @@ -257,10 +257,10 @@ test "pane/new takes rows from a pane in another column before refusing ENOSPC" while (p.nextEffect()) |_| {} const first = p.panes[p.active].?.serial; // A second column holding one tall pane. - try testing.expectEqual(tree.Status.ok, th.wr(p, @intFromEnum(tree.TopFile.ctl), "Newcol\n").reply.status); + try testing.expectEqual(tree.Status.ok, th.wr(p, @backingInt(tree.TopFile.ctl), "Newcol\n").reply.status); const tall = try th.newPane(p); const tall_col = layout.findPane(p, p.paneBySerial(tall).?).?.col; - const focus = @intFromEnum(tree.TopFile.focus); + const focus = @backingInt(tree.TopFile.focus); var digits: [16]u8 = undefined; // From the first column, until pane/new is refused. var moved = false; @@ -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"; - for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @intFromEnum(tree.TopFile.tag) }) |node| { + const text = &@as([4096]u8, @splat('w')) ++ "\n"; + for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @backingInt(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,12 +316,12 @@ 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(); - const ctl = @intFromEnum(tree.TopFile.ctl); - const focus = @intFromEnum(tree.TopFile.focus); + const ctl = @backingInt(tree.TopFile.ctl); + const focus = @backingInt(tree.TopFile.focus); var digits: [16]u8 = undefined; const own = try std.fmt.bufPrint(&digits, "{d}\n", .{pane.serial}); var refused = false; @@ -349,7 +349,7 @@ test "a Newcol refused because the tags would not fit logs its err alone and spe test "a tagexec word that makes, acts on and focuses no pane reads back nothing" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, "Newcol\n").reply.status); try testing.expectEqualStrings("", th.rd(p, tagexec, 0, 64).bytes); // A column's New makes one, and answers it. @@ -362,7 +362,7 @@ test "a tagexec word that makes, acts on and focuses no pane reads back nothing" test "New written to a column's ctl reads back the new pane alone, as its exec does" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_exec = @intFromEnum(tree.TopFile.exec); + const root_exec = @backingInt(tree.TopFile.exec); _ = th.wr(p, root_exec, "Msg before\n"); const ctl_node = tree.Node.ofCol(layout.columnSerial(p, 0), .ctl); try testing.expectEqual(tree.Status.ok, th.wr(p, ctl_node, "New\n").reply.status); @@ -390,7 +390,7 @@ test "a pane's word written to /tagexec or a column's exec is refused, and acts const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); - for ([_]u64{ @intFromEnum(tree.TopFile.tagexec), col_exec }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tagexec), col_exec }) |node| { for ([_][]const u8{ "Undo\n", "Msg hi\n", "Redo\n" }) |line| { const refused = th.wr(p, node, line); try testing.expectEqual(E.INVAL, refused.errno()); @@ -411,7 +411,7 @@ test "Help and Find at /tagexec act in the session's directory, not the keyboard const session = buf[0..try tmp.dir.realPath(testing.io, &buf)]; @memcpy(p.session_dir[0..session.len], session); p.session_dir_len = @intCast(session.len); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); for ([_][]const u8{ "Help\n", "Find needle\n" }) |line| { try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, line).reply.status); const made = p.panes[p.active].?.file.?.path; @@ -427,7 +427,7 @@ test "a shell command at /tagexec or a column's exec is a command pane in the se const term = p.panes[p.active].?; try testing.expect(pardes.exec.takesCommandLine(p, p.active)); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); - for ([_]u64{ @intFromEnum(tree.TopFile.tagexec), col_exec }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tagexec), col_exec }) |node| { p.active = p.paneBySerial(term.serial).?; const before = p.next_serial; const r = th.wr(p, node, "echo from-the-tag\n"); @@ -443,7 +443,7 @@ test "a shell command at /tagexec or a column's exec is a command pane in the se test "New and Tty run at /tagexec and a column's exec, with no pane at all too" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); for ([_]u64{ tagexec, col_exec }) |node| for ([_][]const u8{ "New\n", "Tty\n" }) |line| { const before = p.next_serial; @@ -469,7 +469,7 @@ test "every pane word a tag no pane owns does not hold is refused there, Edit in const Builtin = pardes.builtins.registry.Builtin(); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); for ([_]struct { node: u64, own: []const u8 }{ - .{ .node = @intFromEnum(tree.TopFile.tagexec), .own = pardes.config.topbar_str }, + .{ .node = @backingInt(tree.TopFile.tagexec), .own = pardes.config.topbar_str }, .{ .node = col_exec, .own = tagline.column_tag_default }, }) |tag_file| { var checked: usize = 0; @@ -517,7 +517,7 @@ test "layout lists each column's place, panes and state, and the active one" { const first_serial = layout.columnSerial(p, 0); const new_serial = layout.columnSerial(p, 1); try testing.expect(first_serial != new_serial); - const layout_node = @intFromEnum(tree.TopFile.layout); + const layout_node = @backingInt(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, "{d} 0 {d} {d} notcurrent full {d}\n", .{ first_serial, p.col_x[0], p.col_w[0], p.panes[0].?.serial }); @@ -528,19 +528,19 @@ test "layout lists each column's place, panes and state, and the active one" { try testing.expect(text.len > 0); try testing.expectEqual(@as(u64, 0), th.call(p, .{ .tag = 1, .op = .getattr, .node = layout_node }).reply.attr.size); // generated by each read // /index says which column each pane is in, by its serial, last. - try testing.expect(std.mem.endsWith(u8, th.rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, " {d}\n", .{first_serial}))); + try testing.expect(std.mem.endsWith(u8, th.rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, " {d}\n", .{first_serial}))); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "newcol {d}\n", .{new_serial}))); // A column that closes takes its name with it; the others keep theirs. try p.removeColumn(1); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "delcol {d}\n", .{new_serial}))); - try testing.expectEqual(E.NOENT, th.look_up(p, @intFromEnum(tree.TopFile.col), try std.fmt.bufPrint(&want, "{d}", .{new_serial})).errno()); + try testing.expectEqual(E.NOENT, th.look_up(p, @backingInt(tree.TopFile.col), try std.fmt.bufPrint(&want, "{d}", .{new_serial})).errno()); try testing.expectEqual(first_serial, layout.columnSerial(p, 0)); } 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); + const col_dir = @backingInt(tree.TopFile.col); const serial = layout.columnSerial(p, 0); var name: [16]u8 = undefined; try testing.expectEqual(tree.Status.ok, th.look_up(p, col_dir, try std.fmt.bufPrint(&name, "{d}", .{serial})).reply.status); @@ -557,7 +557,7 @@ test "a column's tag and the workspace's read, replace and append as a pane tag // `>>` appends; a newline in a one-line tag is a space. _ = th.wr(p, tag, " Lint\nNow"); try testing.expectEqualStrings("Make Lint Now", th.rd(p, tag, 0, 4096).bytes); - const top = @intFromEnum(tree.TopFile.tag); + const top = @backingInt(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)); @@ -574,11 +574,11 @@ test "a focus write makes its pane's column the active one: layout says so and p p.sync(); try testing.expectEqual(@as(usize, 1), layout.findPane(p, p.active).?.col); var digits: [16]u8 = undefined; - _ = th.wr(p, @intFromEnum(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{left})); + _ = th.wr(p, @backingInt(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{left})); var want: [32]u8 = undefined; - const text = th.rd(p, @intFromEnum(tree.TopFile.layout), 0, 4096).bytes; + const text = th.rd(p, @backingInt(tree.TopFile.layout), 0, 4096).bytes; try testing.expect(std.mem.endsWith(u8, text, try std.fmt.bufPrint(&want, "active {d}\n", .{layout.columnSerial(p, 0)}))); - const made = th.call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(tree.TopFile.new) }).reply.handle; + const made = th.call(p, .{ .tag = 1, .op = .open, .node = @backingInt(tree.TopFile.new) }).reply.handle; try testing.expectEqual(@as(usize, 0), layout.findPane(p, p.paneBySerial(made).?).?.col); } } @@ -588,9 +588,9 @@ 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| { + for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @backingInt(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); @@ -651,13 +651,13 @@ test "a column's ctl and exec act on it as its tag would, and rmdir closes it on try testing.expectEqual(@as(?usize, 0), layout.columnBySerial(p, right)); try testing.expect(std.mem.endsWith(u8, headerText(p, right).?, " Mine")); // The root's ctl points a column word at the column's own. - try testing.expect(std.mem.endsWith(u8, th.wr(p, @intFromEnum(tree.TopFile.ctl), "Delcol\n").reply.ename, "write it to col/<serial>/ctl")); + try testing.expect(std.mem.endsWith(u8, th.wr(p, @backingInt(tree.TopFile.ctl), "Delcol\n").reply.ename, "write it to col/<serial>/ctl")); } test "tagexec runs a word as a click in the workspace tag; exec files read back what they touched; their messages are the session's" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); 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); @@ -680,7 +680,7 @@ test "a word run from the workspace's or a column's tag runs in the session's di defer p.deinit(); const session = p.sessionDir(); try testing.expect(!std.mem.eql(u8, session, pardes.Pardes.paneDir(p.panes[0].?))); // the file is elsewhere - const dirs = [_]u64{ @intFromEnum(tree.TopFile.tagexec), Node.ofCol(layout.columnSerial(p, 0), .exec) }; + const dirs = [_]u64{ @backingInt(tree.TopFile.tagexec), Node.ofCol(layout.columnSerial(p, 0), .exec) }; for (dirs) |node| { try testing.expectEqual(tree.Status.ok, th.wr(p, node, "true\n").reply.status); const made = p.paneBySerial(p.fs.results[0]).?; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 105de07c..733d9c8e 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -554,6 +554,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? .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, + .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth, else => probe: { var probe = p.settings; break :probe probe.apply(setting, if (arg.len > 0) arg else null); @@ -662,6 +663,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) .motion => try w.print("{s} {s}\n", .{ word, @tagName(s.motion) }), .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 }), .tab => try w.print("{s} {d}\n", .{ word, s.tab }), } } @@ -682,7 +684,7 @@ 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 +/// session's) gets a new +Pager; the serial is what a /// 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 { @@ -742,6 +744,17 @@ pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfM panes.File.setContent(p, f, page.text); f.pager_spans = page.spans; f.saved_revision = f.revision; + // A diff paged (`git show`, difftui's patches): its hunks stacked in a + // +Diff (DiffLook hunks) in the +Pager's place, the +Pager closed. The + // keyboard stays where it was, as a page's. + if (f.pager_diff and p.settings.diff_look == .hunks) { + const keyboard = p.active; + if (panes.Output.openDiff(p, id, f.path, f.content)) |hid| { + // ponytail: the text is gone with it; Diff on the +Diff says no such file. + p.removePane(id, hid) catch {}; + } else |_| {} + if (p.panes[keyboard] != null) p.active = keyboard; + } } /// The editor's step: the text of /pager opens closed unread goes in. @@ -1265,15 +1278,15 @@ const withFile = th.withFile; const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; -const root_status = @intFromEnum(tree.TopFile.status); -const root_look = @intFromEnum(tree.TopFile.look); -const root_exec = @intFromEnum(tree.TopFile.exec); +const root_status = @backingInt(tree.TopFile.status); +const root_look = @backingInt(tree.TopFile.look); +const root_exec = @backingInt(tree.TopFile.exec); test "a control character in a write to any ctl refuses the whole write, and a quoted line shows a tab as a blank" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const col = layout.columnSerial(p, 0); - for ([_]u64{ @intFromEnum(tree.TopFile.ctl), Node.of(serialOf(p), .ctl), Node.ofCol(col, .ctl) }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.ctl), Node.of(serialOf(p), .ctl), Node.ofCol(col, .ctl) }) |node| { const r = wr(p, node, "Wrap off\nbo\x01gus\n"); try testing.expectEqual(E.INVAL, r.errno()); try testing.expectEqualStrings(e_control, r.reply.ename); @@ -1313,7 +1326,7 @@ test "pane ctl read is acme's fields -- index's five, width in cells, font, tab test "commands lists every builtin with its argument and the ctl that takes it" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const node = @intFromEnum(tree.TopFile.commands); + const node = @backingInt(tree.TopFile.commands); const listed = rd(p, node, 0, 1 << 16); try testing.expectEqual(@as(u64, listed.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size); try testing.expectEqual(E.PERM, wr(p, node, "Del\n").errno()); @@ -1360,7 +1373,7 @@ test "focus reads the pane with the keyboard, and a serial written to it moves t defer p.deinit(); const first = serialOf(p); const second = try th.newPane(p); - const focus = @intFromEnum(tree.TopFile.focus); + const focus = @backingInt(tree.TopFile.focus); var line: [16]u8 = undefined; try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{second}), rd(p, focus, 0, 64).bytes); try testing.expectEqual(@as(u64, rd(p, focus, 0, 64).bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = focus }).reply.attr.size); @@ -1435,7 +1448,7 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(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); @@ -1443,6 +1456,8 @@ 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); + try testing.expect(std.mem.indexOf(u8, settings, "CallstackDepth 8\n") != null); + try testing.expectEqual(Status.ok, wr(p, root_ctl, "CallstackDepth").reply.status); // 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); @@ -1485,7 +1500,6 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi try testing.expectEqual(Status.ok, wr(p, root_ctl, "Verbose off").reply.status); } - test "a second lock is refused until the holder unlocks or closes, and binds nobody else" { const p = try withFile(testing.allocator, "one\ntwo\n"); defer p.deinit(); @@ -1562,7 +1576,7 @@ test "a write of an Edit block carries it whole, to a pane's ctl, the root's ctl try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Edit ,x/foo/{\ni/[/\na/]/\n}\n").reply.status); try testing.expectEqualStrings("[foo] x\n[foo] y\n", rd(p, body, 0, 64).bytes); p.active = p.paneBySerial(serial).?; - try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "Edit ,x/\\[/{\nc/</\n}\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.ctl), "Edit ,x/\\[/{\nc/</\n}\n").reply.status); try testing.expectEqualStrings("<foo] x\n<foo] y\n", rd(p, body, 0, 64).bytes); try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), "Edit $a\nend\n.\n").reply.status); try testing.expectEqualStrings("<foo] x\n<foo] y\nend\n", rd(p, body, 0, 64).bytes); @@ -1590,11 +1604,11 @@ test "a message from a root ctl write is the session's in the log" { 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 log = @backingInt(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); + try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.ctl), "Kill\n").reply.status); // What it said, the session's; its own words name it, so its Verbose // announcement gives way to them. try testing.expectEqualStrings("msg - Kill: nothing running\n", call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .off = frozen, .size = 4096 }).bytes); @@ -1648,7 +1662,7 @@ test "the root look's file:/re/ goes on from the dot, and a miss leaves the dot const p = try withFile(gpa, "foo x foo y\nfoo\n"); defer p.deinit(); const dot = Node.of(serialOf(p), .dot); - const root = @intFromEnum(tree.TopFile.look); + const root = @backingInt(tree.TopFile.look); var line: [256]u8 = undefined; const path = p.panes[0].?.file.?.path; const again = try std.fmt.bufPrint(&line, "{s}:/foo/\n", .{path}); @@ -1664,14 +1678,14 @@ test "a look's miss repeats the path whole up to 256 bytes, then gives up its mi const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const root = @intFromEnum(tree.TopFile.look); + const root = @backingInt(tree.TopFile.look); const long = "some/deeply/nested/directory/that/goes/on/and/on/with/a_rather_long_file_name.txt"; 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" { @@ -1913,7 +1927,7 @@ test "Zerox makes a second pane on one buffer: one text, undo and dirty state, i const a = p.panes[0].?; const b = p.panes[twin_id].?; // Both in the index, each its serial, one name. - const index = rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes; + const index = rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes; try testing.expectEqual(@as(usize, 2), std.mem.count(u8, index, "/z.txt")); // b's cursor on `three`; a line written above it in a moves it down. b.body.cur_row = 2; @@ -2028,7 +2042,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); @@ -2057,7 +2071,7 @@ test "a bad Tab width and a bad Incl directory are refused invalid, changing not defer config.tab_now = config.tab_width; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); for ([_][]const u8{ "Tab 0\n", "Tab 17\n", "Tab x\n" }) |line| { try testing.expectEqual(E.INVAL, wr(p, root_ctl, line).errno()); // Run from a pane, as a tag click runs it: said invalid too. @@ -2140,7 +2154,7 @@ test "round 39's small refusals: one name an open, small scratches unasked, twin 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); + try testing.expectEqual(Status.ok, wr(p, @backingInt(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")); @@ -2217,7 +2231,7 @@ test "Mount with no dial is wrong #args, and a dial that is no address says bad if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); const bare = wr(p, root_ctl, "Mount work\n"); try testing.expectEqual(E.INVAL, bare.errno()); try testing.expectStringStartsWith(bare.reply.ename, "wrong #args"); @@ -2259,7 +2273,8 @@ test "a builtin for one kind of pane is refused on another, and still acts on it .{ "Petscii\n", "Petscii: only an image or a terminal pane takes it" }, .{ "Palette\n", "Palette: only an image pane takes it" }, .{ "Ascii\n", "Ascii: only an image pane takes it" }, - .{ "Filter\n", "Filter: only a terminal pane takes it" }, + .{ "Filter\n", "Filter: only a terminal or a +Pager pane takes it" }, + .{ "Diff\n", "Diff: only a diff or a +Diff pane takes it" }, .{ "Togglettymode\n", "Togglettymode: only a terminal pane takes it" }, }; for (cases) |case| { @@ -2312,7 +2327,7 @@ test "a refusal's +Unsaved goes in the session's directory when the active pane' const serial = serialOf(p); try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/pardes-no-such-dir-zz/x.txt\n").reply.status); try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .body), "edited\n").reply.status); - try testing.expectEqual(Status.err, wr(p, @intFromEnum(tree.TopFile.ctl), "Exit\n").reply.status); + try testing.expectEqual(Status.err, wr(p, @backingInt(tree.TopFile.ctl), "Exit\n").reply.status); const unsaved = for (p.panes) |slot| { const pane = slot orelse continue; const f = pane.file orelse continue; @@ -2343,7 +2358,7 @@ test "a look at a file it may not read fails the write naming the file" { test "Pager is a setting of the root ctl: pardes by default, off taken, anything else refused with its choices" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); try testing.expect(std.mem.indexOf(u8, rd(p, root_ctl, 0, 1 << 16).bytes, "Pager pardes\n") != null); try testing.expectEqual(Status.ok, wr(p, root_ctl, "Pager off\n").reply.status); try testing.expectEqual(config.Runtime.Pager.off, p.settings.pager); @@ -2354,7 +2369,7 @@ test "Pager is a setting of the root ctl: pardes by default, off taken, anything test "a bad setting value is quoted, so two different bad values log as two records, never one counted twice" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); _ = wr(p, root_ctl, "Verbose maybe\n"); _ = wr(p, root_ctl, "Verbose nope\n"); try testing.expect(th.logHas(p, "takes on, off \"maybe\"\n")); @@ -2480,14 +2495,14 @@ test "look and exec read back what the last command touched, a ctl write's too" const made = p.panes[p.active].?.serial; try testing.expect(made != serial); try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), rd(p, root_exec, 0, 64).bytes); - try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), rd(p, @intFromEnum(tree.TopFile.look), 0, 64).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{d}\n", .{made}), rd(p, @backingInt(tree.TopFile.look), 0, 64).bytes); // 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.expectEqual(tree.Status.ok, wr(p, @backingInt(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); + try testing.expectEqualStrings("", rd(p, @backingInt(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" { @@ -2554,7 +2569,7 @@ test "an error's words give the errno a mount reads: EINVAL for what is malforme test "DumpConfig's whole report writes back to the root ctl, line by line, with no error" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); try testing.expectEqual(Status.ok, wr(p, root_ctl, "DumpConfig\n").reply.status); const report = for (p.panes) |slot| { const pane = slot orelse continue; @@ -2580,7 +2595,7 @@ test "a Restore asks again for the ThemeFile the dump names, as a /ctl write of const p = try withFile(gpa, "x\n"); defer p.deinit(); const good = "/tmp/pardes-restored-theme.zon"; - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "ThemeFile " ++ good ++ "\n"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "ThemeFile " ++ good ++ "\n"); var custom = pardes.themes[0]; custom.name = "restored"; var encoded: std.Io.Writer.Allocating = .init(gpa); @@ -2608,7 +2623,7 @@ test "a ThemeFile that fails to load changes nothing: the root ctl still names t const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); // None loaded: a failed one leaves Theme as it was. _ = wr(p, root_ctl, "ThemeFile /tmp/pardes-no-such-theme.zon\n"); pardes.colors.failThemeFile(p, p.theme_file_generation, error.FileNotFound); @@ -2634,7 +2649,7 @@ test "after a ThemeFile the root ctl and DumpConfig say ThemeFile and its path, const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); const path = "/tmp/pardes-mine-theme.zon"; try testing.expectEqual(Status.ok, wr(p, root_ctl, "ThemeFile " ++ path ++ "\n").reply.status); var custom = pardes.themes[0]; @@ -2668,7 +2683,7 @@ test "Joincol with no column to the right and Theme with no such theme say so" { const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); const joined = wr(p, root_ctl, "Joincol\n"); try testing.expectEqual(tree.Status.err, joined.reply.status); try testing.expectStringStartsWith(joined.reply.ename, "Joincol: no column to the right"); @@ -2717,10 +2732,10 @@ test "a look after Newcol fills the empty column the keyboard is on" { var line: [4200]u8 = undefined; // Newcol makes an empty column and gives its tag the keyboard; no pane // has it, so focus reads empty. - try testing.expectEqual(tree.Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "Newcol\n").reply.status); + try testing.expectEqual(tree.Status.ok, wr(p, @backingInt(tree.TopFile.ctl), "Newcol\n").reply.status); try testing.expectEqual(@as(usize, 0), p.col_n[p.ncol - 1]); - try testing.expectEqualStrings("", rd(p, @intFromEnum(tree.TopFile.focus), 0, 64).bytes); - try testing.expectEqual(tree.Status.ok, wr(p, @intFromEnum(tree.TopFile.look), try std.fmt.bufPrint(&line, "{s}/f.txt\n", .{at})).reply.status); + try testing.expectEqualStrings("", rd(p, @backingInt(tree.TopFile.focus), 0, 64).bytes); + try testing.expectEqual(tree.Status.ok, wr(p, @backingInt(tree.TopFile.look), try std.fmt.bufPrint(&line, "{s}/f.txt\n", .{at})).reply.status); try testing.expectEqual(@as(usize, 1), p.col_n[p.ncol - 1]); try testing.expectEqual(p.active, p.col_panes[p.ncol - 1][0]); } @@ -2793,7 +2808,7 @@ test "a Restore of a file that is no dump fails the write before any warning, an const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line_buf: [4200]u8 = undefined; const line = try std.fmt.bufPrint(&line_buf, "Restore {s}/notes.txt\n", .{dir}); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); const refused = wr(p, root_ctl, line); try testing.expectEqual(E.IO, refused.errno()); try testing.expect(std.mem.indexOf(u8, refused.reply.ename, "not a pardes dump: line 1: ") != null); @@ -2813,7 +2828,7 @@ test "a Restore of a file that is no dump fails the write before any warning, an test "a setting this frontend cannot show says GUI-only, and DumpDir reads back the directory in effect" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); if (!builtins.capabilities.lift) { try testing.expectEqualStrings("Lift is GUI-only, invalid here \"Lift\"", wr(p, root_ctl, "Lift on\n").reply.ename); try testing.expectEqualStrings("GripWidth is GUI-only, invalid here \"GripWidth\"", wr(p, root_ctl, "GripWidth 120\n").reply.ename); @@ -2838,7 +2853,7 @@ test "a setting this frontend cannot show says GUI-only, and DumpDir reads back test "Shell refuses a path that is no executable, and bare it goes back to the default" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); const refused = wr(p, root_ctl, "Shell /nonexistent/zzsh\n"); 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); @@ -2861,9 +2876,9 @@ test "a builtin that fails a ctl write logs only its err, so the same failure ag defer p.deinit(); p.update(.tick); // the pane's `new` is logged first while (p.nextEffect()) |_| {} - const ctl_node = @intFromEnum(tree.TopFile.ctl); + const ctl_node = @backingInt(tree.TopFile.ctl); for (0..3) |_| try testing.expectEqual(Status.err, wr(p, ctl_node, "Unmount zzz\n").reply.status); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(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: Unmount: no such mount zzz (x3)\n")); @@ -2874,7 +2889,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); @@ -2882,7 +2897,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" { @@ -2901,7 +2916,7 @@ test "Edit's p and = never fail for want of room for +Errors: the text is logged test "size sets the screen of a session no frontend is attached to, and only of one" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); try testing.expectEqual(E.INVAL, wr(p, root_ctl, "size 120 40\n").errno()); // a frontend's p.unattended = true; try testing.expectEqual(Status.ok, wr(p, root_ctl, "size 120 40\n").reply.status); @@ -2923,7 +2938,7 @@ test "size sets the screen of a session no frontend is attached to, and only of test "Mount dials its peer and fails, mounting nothing, when none answers; a look through a peer gone says dial failed" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); const dead = "/tmp/pardes-test-no-such-peer.sock"; // A socket path not there is said so; one there that does not answer // (a directory here) is a dial that failed. @@ -2941,7 +2956,7 @@ test "Mount dials its peer and fails, mounting nothing, when none answers; a loo try testing.expectEqualStrings("get: /n/away/f.txt: dial failed: no answer", got.reply.ename); // Mounted when it answered, gone since: a look through it says so. try p.fs.mounts.append(p.gpa, .{ .name = try p.gpa.dupe(u8, "gone"), .dial = try p.gpa.dupe(u8, dead) }); - const looked = wr(p, @intFromEnum(tree.TopFile.look), "/n/gone/f.txt\n"); + const looked = wr(p, @backingInt(tree.TopFile.look), "/n/gone/f.txt\n"); try testing.expect(looked.errno() != 0); try testing.expect(th.logHas(p, "look: /n/gone/f.txt: dial failed: no answer")); } @@ -2991,7 +3006,7 @@ test "Tty in a directory that is not there fails and makes no pane; a shell that test "a builtin that needs its argument, written bare to an exec, is EINVAL as through ctl" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - for ([_]u64{ root_exec, Node.of(serialOf(p), .exec), @intFromEnum(tree.TopFile.tagexec) }) |node| { + for ([_]u64{ root_exec, Node.of(serialOf(p), .exec), @backingInt(tree.TopFile.tagexec) }) |node| { const refused = wr(p, node, "Mount\n"); try testing.expectEqual(E.INVAL, refused.errno()); try testing.expectEqualStrings("wrong #args in control message \"Mount\"", refused.reply.ename); @@ -3055,7 +3070,7 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir test "Unmount of a name not mounted says no such mount, which a mount reads as ENOENT" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const refused = wr(p, @intFromEnum(tree.TopFile.ctl), "Unmount nothere\n"); + const refused = wr(p, @backingInt(tree.TopFile.ctl), "Unmount nothere\n"); try testing.expectEqual(E.NOENT, refused.errno()); try testing.expectStringStartsWith(refused.reply.ename, "Unmount: no such mount nothere"); } @@ -3092,7 +3107,7 @@ test "a terminal with text typed at its prompt is never typed into: a look at it while (p.nextEffect()) |_| {} var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); - try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.look), "/tmp\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.look), "/tmp\n").reply.status); var typed_into = false; while (p.nextEffect()) |effect| if (effect == .write and effect.write.pane == term) { typed_into = true; @@ -3322,7 +3337,7 @@ test "+Unsaved drops a pane once it has closed" { const b = try th.newPane(p); _ = wr(p, Node.of(b, .name), "/tmp/pardes-unsaved-b.txt\n"); _ = wr(p, Node.of(b, .body), "edited\n"); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); try testing.expectEqual(Status.err, wr(p, root_ctl, "Exit\n").reply.status); var listed: ?*pardes.Pane = null; for (p.panes) |slot| if (slot) |q| if (q.file) |f| if (f.output) |o| if (o.from == .unsaved) { @@ -3403,7 +3418,7 @@ test "with no pane at all, the root look opens its file and the root exec runs i } }; try Empty.all(p); - const look_node = @intFromEnum(tree.TopFile.look); + const look_node = @backingInt(tree.TopFile.look); try testing.expectEqual(Status.ok, wr(p, look_node, "f.txt\n").reply.status); var want: [4200]u8 = undefined; const path = try std.fmt.bufPrint(&want, "{s}/f.txt", .{session}); @@ -3418,7 +3433,7 @@ test "with no pane at all, the root look opens its file and the root exec runs i try testing.expectEqual(@as(usize, 0), scratches); try Empty.all(p); - try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.exec), "echo hi\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.exec), "echo hi\n").reply.status); const made = p.panes[p.anyPane().?].?; try testing.expect(made.command != null); try testing.expectEqualStrings(session, made.cwdSlice()); @@ -3439,7 +3454,7 @@ test "a look at file:3:0 is refused as addr 3:0 is, a column counting from 1" { test "Kill with a name and nothing running says so and does not fail, as bare Kill does" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const r = wr(p, @intFromEnum(tree.TopFile.ctl), "Kill zzz\n"); + const r = wr(p, @backingInt(tree.TopFile.ctl), "Kill zzz\n"); try testing.expectEqual(Status.ok, r.reply.status); try testing.expect(th.logHas(p, "Kill: nothing running")); } @@ -3505,7 +3520,7 @@ test "a focus moved over 9P tells the programs that asked for focus reports, as p.update(.{ .output = .{ .pane = @intCast(shells[1]), .bytes = "\x1b[?1004h" } }); while (p.nextEffect()) |_| {} var digits: [16]u8 = undefined; - const moved = wr(p, @intFromEnum(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{p.panes[shells[1]].?.serial})); + const moved = wr(p, @backingInt(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{p.panes[shells[1]].?.serial})); try testing.expectEqual(Status.ok, moved.reply.status); try testing.expectEqual(shells[1], p.active); try testing.expectEqualStrings("\x1b[O\x1b[I", moved.pty_buf[0..moved.pty_len]); @@ -3522,7 +3537,7 @@ test "a Restore of a name in the DumpDir asks for, and logs, the whole path it r 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); + try testing.expectEqual(Status.ok, wr(p, @backingInt(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.?); } @@ -3532,11 +3547,11 @@ test "a line starting with # runs as nothing at an exec or a ctl, silently" { defer p.deinit(); const serial = serialOf(p); // The setup's own announcements are made by the first write's update. - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "# settle\n"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "# settle\n"); const before = p.next_serial; const log_before = try pardes.ctlfs.events.freezeLog(p); defer p.gpa.free(log_before.bytes); - for ([_]u64{ @intFromEnum(tree.TopFile.exec), Node.of(serial, .exec), @intFromEnum(tree.TopFile.ctl), Node.of(serial, .ctl), Node.ofCol(layout.columnSerial(p, 0), .ctl) }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.exec), Node.of(serial, .exec), @backingInt(tree.TopFile.ctl), Node.of(serial, .ctl), Node.ofCol(layout.columnSerial(p, 0), .ctl) }) |node| { try testing.expectEqual(Status.ok, wr(p, node, "# Platform: tty\n # indented too\n").reply.status); } try testing.expectEqual(before, p.next_serial); @@ -3560,7 +3575,7 @@ test "a builtin that takes no argument, written with one to an exec, is refused const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); - for ([_]u64{ @intFromEnum(tree.TopFile.exec), Node.of(serial, .exec) }) |node| for ([_][]const u8{ "Config extra\n", "DumpConfig extra\n" }) |line| { + for ([_]u64{ @backingInt(tree.TopFile.exec), Node.of(serial, .exec) }) |node| for ([_][]const u8{ "Config extra\n", "DumpConfig extra\n" }) |line| { const r = wr(p, node, line); try testing.expectEqual(E.INVAL, r.errno()); try testing.expectStringStartsWith(r.reply.ename, "wrong #args in control message"); @@ -3666,7 +3681,7 @@ test "every EINVAL a write gets says why, in its err record too; DEL is a contro const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(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{ @@ -3689,19 +3704,19 @@ test "/index shows a name as the log does: a newline in it is \\n, a control byt defer p.deinit(); const term = p.paneBySerial(serialOf(p)).?; p.setCwd(term, "/tmp/two\nlines\x07\x7f\xc2\x85\xff"); - const index = rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes; + const index = rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes; // Each byte as itself, so the name decodes to what it is. try testing.expect(std.mem.indexOf(u8, index, "/tmp/two\\nlines\\x07\\x7f\\xc2\\x85\\xff ") != null); try testing.expectEqual(@as(usize, 1), std.mem.count(u8, index, "\n")); try testing.expect(index.len > 0); - try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(tree.TopFile.index) }).reply.attr.size); + try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(tree.TopFile.index) }).reply.attr.size); // Its tag never carries the raw newline either. const tag = rd(p, Node.of(serialOf(p), .tag), 0, 4096).bytes; try testing.expect(std.mem.indexOf(u8, tag, "/tmp/two\\nlines") != null); // A backslash of the name's own is doubled: `\n` written in a name // reads back unlike a newline. p.setCwd(term, "/tmp/back\\nslash"); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, "/tmp/back\\\\nslash") != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, "/tmp/back\\\\nslash") != null); } test "a look at a ./ or ../ name that is not there is a miss naming the file; a plain one is looked for as text" { @@ -3752,7 +3767,7 @@ test "a served-tree pane spoils no Grep, and Look . from a gone directory is ENO test "a tag write refuses NUL and the other control characters" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - for ([_]u64{ @intFromEnum(tree.TopFile.tag), tree.Node.ofCol(pardes.layout.columnSerial(p, 0), .tag), Node.of(serialOf(p), .tag) }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tag), tree.Node.ofCol(pardes.layout.columnSerial(p, 0), .tag), Node.of(serialOf(p), .tag) }) |node| { const refused = wr(p, node, " a\x00b"); try testing.expectEqual(E.INVAL, refused.errno()); try testing.expectStringStartsWith(refused.reply.ename, "invalid tag text"); @@ -3801,7 +3816,7 @@ test "a column takes panes until their documented minimums fill it, not until no const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); defer p.deinit(); while (p.nextEffect()) |_| {} - const new = @intFromEnum(tree.TopFile.new); + const new = @backingInt(tree.TopFile.new); while (call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status == .ok) p.sync(); p.sync(); const avail = p.screen_h - (p.topBarHeight() + p.columnBarHeight()); @@ -3899,18 +3914,18 @@ test "a closed file is found again: Recent and /recent list it closed, a look at const opened = p.active; try testing.expectEqualStrings(a, p.panes[opened].?.file.?.path); var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{a})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{a})) != null); // Another file, so the jumplist has somewhere to come back from. try testing.expectEqual(Status.ok, wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/b.txt\n", .{dir})).reply.status); p.sync(); try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[opened].?.serial, .ctl), "Del\n").reply.status); p.sync(); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "closed {s}\n", .{a})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "closed {s}\n", .{a})) != null); // 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})).?; - const row = rows.file.?.content[at .. std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; + 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); p.sync(); @@ -3998,8 +4013,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; @@ -4031,8 +4046,8 @@ test "Back and Forward written to exec keep to the focused file, and JumpScope a .{ .word = "Forward", .file = "/b.txt", .line = 80 }, .{ .word = "Forward", .file = "/a.txt", .line = 80 }, }); - try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "JumpScope all\n").reply.status); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.ctl), 0, 8192).bytes, "JumpScope all\n") != null); + try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.ctl), "JumpScope all\n").reply.status); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.ctl), 0, 8192).bytes, "JumpScope all\n") != null); try walk(p, &.{ .{ .word = "Back", .file = "/b.txt", .line = 80 }, .{ .word = "Back", .file = "/a.txt", .line = 40 }, @@ -4088,14 +4103,14 @@ test "a new file saved shows in /recent, open, while it is" { try testing.expectEqual(Status.ok, wr(p, Node.of(made, .ctl), "Save\n").reply.status); p.perform(.{ .save_file = .{ .pane = @intCast(p.paneBySerial(made).?) } }); var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{path})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{path})) != null); } test "/recent shows a name as /index does, a newline in it escaped" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); p.recent.opened(p.recentGpa(), "/tmp/a\nb\\c"); - const text = rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes; + const text = rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes; try testing.expect(std.mem.indexOf(u8, text, "closed /tmp/a\\nb\\\\c\n") != null); } @@ -4149,11 +4164,11 @@ test "a remembered place is clamped to the file as it is now, its selection's tw _ = wr(p, root_exec, "Recent\n"); 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, "c.txt:").?; - const row = rows.file.?.content[at .. std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; + const row = rows.file.?.content[at..std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; // Both ends are in the row, a range. try testing.expect(std.mem.indexOfScalar(u8, row, '-') != null); var full: [4400]u8 = undefined; - const loc = try std.fmt.bufPrint(&full, "{s}/{s}\n", .{ dir, row[0 .. std.mem.indexOfScalar(u8, row, ' ').?] }); + const loc = try std.fmt.bufPrint(&full, "{s}/{s}\n", .{ dir, row[0..std.mem.indexOfScalar(u8, row, ' ').?] }); // A look at it opens the file, never a miss, clamped to its last line. try testing.expectEqual(Status.ok, wr(p, Node.of(rows.serial, .look), loc).reply.status); p.sync(); @@ -4177,8 +4192,8 @@ test "size is monotonic: growing is never refused, and a size once taken is take defer p.deinit(); while (p.nextEffect()) |_| {} p.unattended = true; - const root_ctl = @intFromEnum(tree.TopFile.ctl); - const new = @intFromEnum(tree.TopFile.new); + const root_ctl = @backingInt(tree.TopFile.ctl); + const new = @backingInt(tree.TopFile.new); // The dogfood's repro: Newcol, three pane/new, a Tty, then pane/new // until a column has no room (ENOSPC). try testing.expectEqual(Status.ok, wr(p, root_ctl, "Newcol\n").reply.status); @@ -4269,7 +4284,7 @@ test "a file changed on disk under unsaved edits is not reloaded: it says so, ge var want: [32]u8 = undefined; try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "changed {d}\n", .{serial}))); // Exit and get still ask about the edits. - try testing.expectEqual(Status.err, wr(p, @intFromEnum(tree.TopFile.ctl), "Exit\n").reply.status); + try testing.expectEqual(Status.err, wr(p, @backingInt(tree.TopFile.ctl), "Exit\n").reply.status); try testing.expect(std.mem.indexOf(u8, wr(p, Node.of(serial, .ctl), "get\n").reply.ename, "Modified") != null); // Save warns once before overwriting the newer file, then writes. const first = wr(p, Node.of(serial, .ctl), "Save\n"); @@ -4314,7 +4329,7 @@ test "a looked word is found in its own pane, next place after the dot, wrapping test "every word's /commands description is its own doc comment's first sentence, no citation" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const listed = rd(p, @intFromEnum(tree.TopFile.commands), 0, 1 << 16).bytes; + const listed = rd(p, @backingInt(tree.TopFile.commands), 0, 1 << 16).bytes; for ([_][]const u8{ "\nRepl arg pane -- Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run.\n", "\nJoincol root -- Fold the active pane's column into the one on its right, keeping its panes.\n", @@ -4340,7 +4355,7 @@ test "every word's /commands description is its own doc comment's first sentence undescribed += 1; continue; }; - const word = line[0 .. std.mem.indexOfScalar(u8, line, ' ').?]; + const word = line[0..std.mem.indexOfScalar(u8, line, ' ').?]; if (config.Runtime.find(word)) |setting| { try testing.expect(std.mem.endsWith(u8, line, setting.doc)); continue; @@ -4360,7 +4375,7 @@ test "Newcol at the column cap fails the write and says the cap" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); p.update(.{ .resize = .{ .cols = 4000, .rows = 30 } }); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); while (p.ncol < pardes.MAX_COLS) { // From the widest column's tag, so no column gets too narrow first. p.sync(); @@ -4389,7 +4404,7 @@ test "Save on a terminal asked over 9P is an ask in the log, answered with a pat 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 log = @backingInt(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 }); @@ -4415,7 +4430,7 @@ test "get names the path it could not read, logs the edits it threw away, and a pardes.panes.File.deleted(p, 0); pardes.panes.File.deleted(p, 0); var rec: [32]u8 = undefined; - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(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, try std.fmt.bufPrint(&rec, "changed {d} deleted\n", .{serial}))); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); @@ -4427,12 +4442,12 @@ test "a builtin that fails through exec, tagexec or a column's exec fails the wr 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| { + for ([_]u64{ root_exec, Node.of(serial, .exec), @backingInt(tree.TopFile.tagexec), Node.ofCol(pardes.layout.columnSerial(p, 0), .exec) }) |node| { const failed = wr(p, node, "Unmount zzz\n"); try testing.expectEqual(Status.err, failed.reply.status); try testing.expect(std.mem.indexOf(u8, failed.reply.ename, "Unmount: no such mount zzz") != null); } - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(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); @@ -4444,11 +4459,11 @@ test "a builtin that fails through exec, tagexec or a column's exec fails the wr // 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"); + _ = wr(p, @backingInt(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")); // The same miss again is that record counted, as any repeated err is. - _ = wr(p, @intFromEnum(tree.TopFile.look), "zzqqnotthere\n"); + _ = wr(p, @backingInt(tree.TopFile.look), "zzqqnotthere\n"); try testing.expect(th.logHas(p, "look: no match for \"zzqqnotthere\" (x2)\n")); } @@ -4469,7 +4484,7 @@ test "@p<serial>:<address> takes any sam address; a miss and an unknown serial a const p = try withFile(testing.allocator, "foo x foo y\nbar\n"); defer p.deinit(); const serial = serialOf(p); - const root = @intFromEnum(tree.TopFile.look); + const root = @backingInt(tree.TopFile.look); const dot = Node.of(serial, .dot); const Case = struct { addr: []const u8, want: []const u8 }; for ([_]Case{ @@ -4530,7 +4545,7 @@ test "@p<terminal>:<address> takes any address over the terminal's lines, select const id = p.paneBySerial(serial).?; p.update(.{ .output = .{ .pane = @intCast(id), .bytes = "one\r\ntwo MARK three\r\n" } }); const pane = p.panes[id].?; - const root = @intFromEnum(tree.TopFile.look); + const root = @backingInt(tree.TopFile.look); var line: [64]u8 = undefined; try testing.expectEqual(Status.ok, wr(p, root, try std.fmt.bufPrint(&line, "@p{d}:0/MARK/\n", .{serial})).reply.status); try testing.expectEqual(@as(i32, 1), pane.body.cur_row); @@ -4562,7 +4577,7 @@ test "a bad command inside an Edit block written whole is named, not the } after test "a refused Delcol changes nothing: no pane, no focus" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Newcol\n"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "Newcol\n"); const made = try th.newPane(p); _ = wr(p, Node.of(made, .name), "/tmp/pardes-delcol-refused.txt\n"); _ = wr(p, Node.of(made, .body), "edit\n"); @@ -4585,8 +4600,8 @@ test "a refused Delcol changes nothing: no pane, no focus" { test "pager answers its +Pager on the open that asked, whatever another client exec'd meanwhile" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const pager = @intFromEnum(tree.TopFile.pager); - const exec = @intFromEnum(tree.TopFile.exec); + const pager = @backingInt(tree.TopFile.pager); + const exec = @backingInt(tree.TopFile.exec); const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = pager, .handle = asked, .data = "/tmp\n" }).reply.status); const paged = for (p.panes) |slot| { @@ -4608,10 +4623,15 @@ test "pager answers its +Pager on the open that asked, whatever another client e 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. + // Resolved: `/tmp/../tmp/.` is /tmp, a +Pager of its own beside the + // one made above, which keeps its page. 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); + const second = call(p, .{ .tag = 13, .op = .read, .node = pager, .handle = resolved, .size = 64 }).bytes; + try testing.expect(!std.mem.eql(u8, want, second)); + const second_pane = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trim(u8, second, "\n"), 10)).?].?; + try testing.expectEqualStrings("/tmp/+Pager", second_pane.file.?.path); + try testing.expect(p.paneBySerial(paged) != null); _ = 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()); @@ -4634,7 +4654,7 @@ test "pager answers its +Pager on the open that asked, whatever another client e 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 pager = @backingInt(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. @@ -4668,15 +4688,24 @@ test "what a /pager open writes after its directory is the text: plain in the bo // 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 kept = try testing.allocator.dupe(u8, f.content); + defer testing.allocator.free(kept); 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); + // A new +Pager: the first keeps its page. + try testing.expectEqualStrings(kept, f.content); + const next = for (p.panes) |slot| { + const other = slot orelse continue; + if (other == pn) continue; + if (other.file) |*of| if (std.mem.eql(u8, of.path, "/tmp/+Pager")) break of; + } else return error.NoPager; + try testing.expectEqualStrings("", next.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); + try testing.expectEqualStrings("green\n", next.content); + try testing.expectEqual(@as(usize, 0), next.pager_spans.len); + try testing.expectEqual(next.revision, next.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" { @@ -4784,7 +4813,7 @@ test "a second LookWord list look in a directory refills its +Search rather than const path = try std.fmt.bufPrint(&path_buf, "{s}/words.txt", .{dir}); const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 30 }); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "LookWord list\n"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "LookWord list\n"); pardes.look.lookAt(p, 0, "alpha"); pardes.look.lookAt(p, 0, "beta"); var searches: usize = 0; @@ -4958,7 +4987,7 @@ test "DumpDir refuses a relative directory and one that may not be written, up f if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); try testing.expectEqual(E.INVAL, wr(p, root_ctl, "DumpDir dumps\n").errno()); try testing.expectEqual(E.INVAL, wr(p, root_ctl, "DumpDir /proc/1/root/dumps\n").errno()); try testing.expectEqual(Status.ok, wr(p, root_ctl, "DumpDir /tmp/pardes-dumps-test\n").reply.status); @@ -4970,7 +4999,7 @@ test "DumpDir refuses a relative directory and one that may not be written, up f test "a Mount dial with a network it does not know is a bad dial address, EINVAL" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const r = wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer nowhere!x\n"); + const r = wr(p, @backingInt(tree.TopFile.ctl), "Mount peer nowhere!x\n"); try testing.expectEqual(E.INVAL, r.errno()); try testing.expectStringStartsWith(r.reply.ename, "Mount: bad dial address: nowhere!x"); } @@ -5028,11 +5057,11 @@ test "a Mount of a socket path that is not there says no such socket, ENOENT" { if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const r = wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer unix!/tmp/pardes-surely-no-socket\n"); + const r = wr(p, @backingInt(tree.TopFile.ctl), "Mount peer unix!/tmp/pardes-surely-no-socket\n"); try testing.expectEqual(E.NOENT, r.errno()); try testing.expect(std.mem.indexOf(u8, r.reply.ename, "no such socket") != null); try testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); - try testing.expectEqual(E.INVAL, wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer rel/x.sock\n").errno()); + try testing.expectEqual(E.INVAL, wr(p, @backingInt(tree.TopFile.ctl), "Mount peer rel/x.sock\n").errno()); } test "the init file reads past a BOM, and every line it fails is a notice and an err, never silent" { diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 3910ac05..78788c3c 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -542,7 +542,7 @@ pub const Action = enum(u8) { tag_exec = 'x', pub fn char(a: Action) u8 { - return @intFromEnum(a); + return @backingInt(a); } pub fn fromChar(c: u8) ?Action { @@ -550,7 +550,7 @@ pub const Action = enum(u8) { } pub fn onTag(a: Action) bool { - return @intFromEnum(a) >= 'a'; + return @backingInt(a) >= 'a'; } }; @@ -889,7 +889,7 @@ test "a stream read at an offset inside its last answer gets the rest of it agai defer p.deinit(); p.update(.tick); while (p.nextEffect()) |_| {} - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const frozen: u64 = 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" }); @@ -897,7 +897,7 @@ test "a stream read at an offset inside its last answer gets the rest of it agai notePath(p, "dump", "/b"); const Read = struct { fn at(pp: *Pardes, h: u32, off: u64) []const u8 { - return call(pp, .{ .tag = 4, .op = .read, .node = @intFromEnum(tree.TopFile.log), .handle = h, .off = off, .size = 128 }).bytes; + return call(pp, .{ .tag = 4, .op = .read, .node = @backingInt(tree.TopFile.log), .handle = h, .off = off, .size = 128 }).bytes; } }; try testing.expectEqualStrings("dump /a\n", Read.at(p, f, frozen)); @@ -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); @@ -1130,7 +1130,7 @@ test "writing an event record back performs the action it names" { // A look written back sets what look reads back. _ = wr(p, event, "FL0 3\n"); var want_serial: [16]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&want_serial, "{d}\n", .{serial}), rd(p, @intFromEnum(tree.TopFile.look), 0, 64).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&want_serial, "{d}\n", .{serial}), rd(p, @backingInt(tree.TopFile.look), 0, 64).bytes); // Well formed but past the text: said so, not "bad event syntax". try testing.expectEqualStrings("range past end of body", wr(p, event, "MX0 999\n").reply.ename); @@ -1144,7 +1144,7 @@ test "the log records whether or not anyone reads, and an open that follows wait const gpa = testing.allocator; const p = try withFile(gpa, "logged\n"); defer p.deinit(); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); var expected: [4200]u8 = undefined; // Nobody holds /log open, and the pane is recorded anyway. @@ -1256,21 +1256,21 @@ test "a refused or failed write is an err record in the log, saying which file a p.update(.tick); // the pane's `new` is logged before the log is opened while (p.nextEffect()) |_| {} const serial = serialOf(p); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(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 = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); var want: [128]u8 = undefined; const next = struct { fn record(pp: *Pardes, h: u32, off: usize) []const u8 { - return call(pp, .{ .tag = 4, .op = .read, .node = @intFromEnum(tree.TopFile.log), .handle = h, .off = off, .size = 4096 }).bytes; + return call(pp, .{ .tag = 4, .op = .read, .node = @backingInt(tree.TopFile.log), .handle = h, .off = off, .size = 4096 }).bytes; } }; _ = 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, @intFromEnum(tree.TopFile.ctl), "Bogus"); + _ = wr(p, @backingInt(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"); + _ = wr(p, @backingInt(tree.TopFile.focus), "99999"); 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"); @@ -1373,7 +1373,7 @@ 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); + const log = @backingInt(tree.TopFile.log); 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()); @@ -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. @@ -1447,7 +1447,7 @@ test "follow new skips what the log held and waits for what comes after" { p.update(.tick); // the pane's `new` is logged first while (p.nextEffect()) |_| {} p.setMessage(0, "before the open"); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = log, .handle = h, .data = "follow new\n" }).reply.status); try testing.expectEqual(Status.again, call(p, .{ .tag = 3, .op = .read, .node = log, .handle = h, .size = 4096 }).reply.status); @@ -1459,9 +1459,9 @@ 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 log = @backingInt(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; const at = std.mem.lastIndexOf(u8, text, "msg ").?; @@ -1485,8 +1485,8 @@ 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"); - const log = @intFromEnum(tree.TopFile.log); + _ = wr(p, @backingInt(tree.TopFile.ctl), "Bogus" ++ std.mem.asBytes(&@as([40][8]u8, @splat("abcdefgh".*))) ++ "\n"); + const log = @backingInt(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; const at = std.mem.lastIndexOf(u8, text, "err - ctl: ").?; @@ -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..dc104e4b 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1104,7 +1104,7 @@ test "index lists serial kind dirty flag and name, and stats 0, a view generated const p = try withFile(gpa, "hello\nthere\n"); defer p.deinit(); const pane = p.panes[0].?; - const index = @intFromEnum(tree.TopFile.index); + const index = @backingInt(tree.TopFile.index); const a = rd(p, index, 0, 4096); try testing.expectEqual(Status.ok, a.reply.status); @@ -1138,7 +1138,7 @@ test "a terminal is listed as term with its directory as name" { var want: [64]u8 = undefined; try testing.expect(std.mem.indexOf( u8, - rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, + rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, "{d} term 0 /work/dir {d}\n", .{ pane.serial, columnOf(p, 0) }), ) != null); try testing.expectEqualStrings("/work/dir\n", rd(p, Node.of(pane.serial, .name), 0, 4096).bytes); @@ -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; @@ -1750,8 +1751,8 @@ test "name refreshes cached syntax for unchanged contents" { try testing.expectEqual(Status.ok, wr(p, Node.of(pane.serial, .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.expectEqual(@backingInt(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]); + try testing.expectEqual(@backingInt(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]); try testing.expectEqualStrings("fn check() void {}\n", pane.file.?.content); } diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index c58cf676..d80f7175 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -893,7 +893,7 @@ test "a shell that exits under a run answers its status, and the log says exit b const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; p.update(.{ .output = .{ .pane = 0, .bytes = prompt } }); while (p.nextEffect()) |_| {} - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(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 = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); @@ -984,7 +984,6 @@ test "a run's answer says cut when its output's start is gone, and reads a bound var got = sh.answered(p, node, h, into); try testing.expectEqualStrings("exit 0\nafter\n", got); - // 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"); @@ -1044,12 +1043,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; @@ -1092,7 +1091,7 @@ test "a terminal's ctl counts its body, and a new directory is a rename in the l _ = fields.next(); try testing.expectEqual(body_len, try std.fmt.parseInt(usize, fields.next().?, 10)); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 4, .op = .open, .node = log }).reply.handle; const frozen = call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 6, .op = .write, .node = log, .handle = f, .data = "follow" }); @@ -1146,7 +1145,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..ba676ded 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -95,7 +95,7 @@ const withTerm = th.withTerm; const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; -const screen_node = @intFromEnum(tree.TopFile.screen); +const screen_node = @backingInt(tree.TopFile.screen); test "listener addresses are readable canonical dials with bounded partial reads" { const gpa = testing.allocator; @@ -111,7 +111,7 @@ test "listener addresses are readable canonical dials with bounded partial reads try testing.expectEqualStrings(expected, bytes); try testing.expectError(error.ReadOnlyFilesystem, fs.write(p, path, "")); } - const node = @intFromEnum(tree.TopFile.listeners); + const node = @backingInt(tree.TopFile.listeners); var off: usize = 0; while (off < expected.len) { const part = rd(p, node, off, 3); @@ -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/testing.zig b/src/ninep/testing.zig index a35a9cf0..ec665130 100644 --- a/src/ninep/testing.zig +++ b/src/ninep/testing.zig @@ -71,7 +71,7 @@ pub fn logHas(p: *Pardes, needle: []const u8) bool { /// How many times the log, read whole from a fresh open, holds `needle`. pub fn logCount(p: *Pardes, needle: []const u8) usize { - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; defer _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; @@ -95,7 +95,7 @@ pub fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer { /// The open is what makes the pane; the handle it answers is the serial, which /// is also what a read of that fid reports. pub fn newPane(p: *Pardes) !u32 { - const made = call(p, .{ .tag = 8, .op = .open, .node = @intFromEnum(tree.TopFile.new) }); + const made = call(p, .{ .tag = 8, .op = .open, .node = @backingInt(tree.TopFile.new) }); if (made.reply.status != .ok or made.reply.handle == 0) return error.NoPane; return made.reply.handle; } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 8d3c599f..59ef5ef4 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -115,7 +115,7 @@ pub fn changesPane(p: *Pardes, req: Req) bool { return switch (req.op) { .write => true, .setattr => truncates(req), - .open => req.node == @intFromEnum(TopFile.new), + .open => req.node == @backingInt(TopFile.new), .release => req.remove or holdsLines(p, req) or holdsPage(p, req), .read => holdsPage(p, req), .lookup, .getattr, .readdir => false, @@ -258,7 +258,7 @@ pub const TopFile = enum(u5) { /// The files opened lately, closed ones too, a line each: /// `open|closed <path>`, most recent first. recent, - /// `pardes -`'s: a directory written, its +Pager made or emptied; a + /// `pardes -`'s: a directory written, a new +Pager made there; a /// read of the same open answers its serial. pager, @@ -279,7 +279,7 @@ pub const TopFile = enum(u5) { } }; -pub const root: u64 = @intFromEnum(TopFile.root); +pub const root: u64 = @backingInt(TopFile.root); /// Declaration order is readdir order. pub const PaneFile = enum(u5) { @@ -363,11 +363,11 @@ pub const Node = packed struct(u64) { pub fn of(serial: u32, file: PaneFile) u64 { std.debug.assert(serial != 0); - return @bitCast(Node{ .file = @intFromEnum(file), .serial = serial }); + return @bitCast(Node{ .file = @backingInt(file), .serial = serial }); } pub fn ofCol(serial: u32, file: ColFile) u64 { - return @bitCast(Node{ .file = @intFromEnum(file), .serial = col_bit | @as(u59, serial) }); + return @bitCast(Node{ .file = @backingInt(file), .serial = col_bit | @as(u59, serial) }); } pub fn target(node: u64) ?Target { @@ -424,9 +424,9 @@ pub fn resolveSelf(p: *Pardes, path: []const u8) ?u64 { // `new` is reached in /pane, where the panes it makes are. const top = std.meta.stringToEnum(TopFile, first) orelse return sources.node(normalized); if (top == .root or top == .new or top == .pane or parts.next() != null) return null; - return @intFromEnum(top); + return @backingInt(top); } - const next = parts.next() orelse return @intFromEnum(TopFile.pane); + const next = parts.next() orelse return @backingInt(TopFile.pane); // `new` is served on the wire but deliberately unreachable from an editor // path: this resolves Look targets and hover previews, and a preview that // opened `new` to see what was there would make a pane per hover. @@ -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")); } @@ -606,7 +606,7 @@ fn attrOf(p: *Pardes, target: Target) ?Reply.Attr { switch (target) { .top => |f| return .{ .name = f.fileName(), - .node = @intFromEnum(f), + .node = @backingInt(f), .dir = f.dir(), .mode = f.mode(), .size = topSize(p, f), @@ -695,11 +695,11 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { const parent: u64 = switch (target) { .top => |top| if (top.dir()) root else return Reply.fail(req.tag, E.NOTDIR), .pane => |t| switch (t.file) { - .dir => @intFromEnum(TopFile.pane), + .dir => @backingInt(TopFile.pane), .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), + .col => |c| if (c.file == .dir) @backingInt(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR), }; return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent }); } @@ -709,12 +709,12 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { .root => root: { if (std.mem.eql(u8, name, "os")) return fs.osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = fs.os_root }); // `new` is reached in /pane, where the panes it makes are. - if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new) break :root @intFromEnum(t); + if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new) break :root @backingInt(t); if (sources.node(name)) |n| return sources.handle(p, .{ .tag = req.tag, .op = .getattr, .node = n }); return Reply.fail(req.tag, E.NOENT); }, .pane => pane: { - if (std.mem.eql(u8, name, new_pane)) break :pane @intFromEnum(TopFile.new); + if (std.mem.eql(u8, name, new_pane)) break :pane @backingInt(TopFile.new); // A pane directory is its serial, in decimal digits and never 0. if (name.len > 10) return Reply.fail(req.tag, E.NOENT); for (name) |c| if (c < '0' or c > '9') return Reply.fail(req.tag, E.NOENT); @@ -778,13 +778,13 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { // 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.recent, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.layout, TopFile.tag, TopFile.tagexec, 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, @backingInt(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); sources.stage(p, out, "", &skip); }, .pane => { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(TopFile.new), false, TopFile.new.fileName()); + if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @backingInt(TopFile.new), false, TopFile.new.fileName()); var last: u32 = 0; while (nextSerialAfter(p, last)) |serial| { last = serial; @@ -1380,7 +1380,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); for ([_]TopFile{ .index, .layout, .recent, .ctl }) |file| { - const node = @intFromEnum(file); + const node = @backingInt(file); const whole = try testing.allocator.dupe(u8, th.rd(p, node, 0, 1 << 16).bytes); defer testing.allocator.free(whole); const h = th.call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle; @@ -1391,7 +1391,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha // Something changes between the chunks. const made = try th.newPane(p); _ = th.wr(p, Node.of(made, .name), "/tmp/pardes-frozen-listing.txt\n"); - _ = th.wr(p, @intFromEnum(TopFile.ctl), "Verbose off\n"); + _ = th.wr(p, @backingInt(TopFile.ctl), "Verbose off\n"); while (true) { const more = th.call(p, .{ .tag = 2, .op = .read, .node = node, .handle = h, .off = got.items.len, .size = 7 }).bytes; if (more.len == 0) break; @@ -1399,7 +1399,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha } _ = th.call(p, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true }); try testing.expectEqualStrings(whole, got.items); - _ = th.wr(p, @intFromEnum(TopFile.ctl), "Verbose on\n"); + _ = th.wr(p, @backingInt(TopFile.ctl), "Verbose on\n"); } } @@ -1420,7 +1420,7 @@ test "filesystem inspection preserves pending and displayed Look hover" { } }); try testing.expect(p.look_hover_wait != null); const body = Node.of(serialOf(p), .body); - const screen_node = @intFromEnum(TopFile.screen); + const screen_node = @backingInt(TopFile.screen); for (0..2) |phase| { if (phase == 1) { for (0..delay) |_| p.update(.tick); @@ -1431,7 +1431,7 @@ test "filesystem inspection preserves pending and displayed Look hover" { const requests = [_]Req{ .{ .tag = 1, .op = .lookup, .node = root, .data = "screen" }, .{ .tag = 1, .op = .lookup, .node = root, .data = "status" }, - .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.pane) }, + .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.pane) }, .{ .tag = 2, .op = .getattr, .node = body }, .{ .tag = 3, .op = .open, .node = body }, .{ .tag = 4, .op = .read, .node = body, .size = 5 }, @@ -1460,14 +1460,14 @@ test "log stats 0 however much it holds, a stream as acme's generated files are" 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); + try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(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, // and so must leave a pending hover alone. - .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 2, .op = .open, .node = @backingInt(TopFile.new) }, .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true }, }; for (requests) |request| { @@ -1494,17 +1494,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 = @fromBackingInt(@intCast(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 = @fromBackingInt(@intCast(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, @fromBackingInt(@intCast(value))).fileName()) != null else words.has(t.fileName()); if (!ok) { @@ -1532,8 +1532,8 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqualStrings(name, top[i].name); try testing.expectEqual(i >= 16, top[i].dir); } - try testing.expectEqual(@intFromEnum(TopFile.pane), top[16].node); - try testing.expectEqual(@intFromEnum(TopFile.col), top[17].node); + try testing.expectEqual(@backingInt(TopFile.pane), top[16].node); + try testing.expectEqual(@backingInt(TopFile.col), top[17].node); try testing.expectEqual(fs.os_root, top[18].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); @@ -1556,7 +1556,7 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = entry.node }).reply.status); try testing.expectEqual(before, p.next_serial); } - const panes_dir = rdir(p, @intFromEnum(TopFile.pane), 0); + const panes_dir = rdir(p, @backingInt(TopFile.pane), 0); const listed = th.dirents(panes_dir.bytes, &buf); var idname: [16]u8 = undefined; const own = th.nameAt(listed, try std.fmt.bufPrint(&idname, "{d}", .{serial})).?; @@ -1567,16 +1567,16 @@ test "readdir lists the root and a pane directory without creating anything" { // client that stats every name a listing gave it inert. const shown = th.nameAt(listed, new_pane).?; try testing.expect(!shown.dir); - try testing.expectEqual(Status.ok, look_up(p, @intFromEnum(TopFile.pane), new_pane).reply.status); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }).reply.status); + try testing.expectEqual(Status.ok, look_up(p, @backingInt(TopFile.pane), new_pane).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.new) }).reply.status); try testing.expectEqual(before, p.next_serial); const dir = rdir(p, Node.of(serial, .dir), 0); const files = th.dirents(dir.bytes, &buf); try testing.expectEqual(@as(usize, 18), files.len); for ([_][]const u8{ - "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", - "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", + "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", + "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", }, 0..) |name, i| try testing.expectEqualStrings(name, files[i].name); try testing.expect(th.nameAt(files, ".") == null); @@ -1590,7 +1590,7 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqual(before, p.next_serial); try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .body), 0).errno()); - try testing.expectEqual(E.NOTDIR, rdir(p, @intFromEnum(TopFile.index), 0).errno()); + try testing.expectEqual(E.NOTDIR, rdir(p, @backingInt(TopFile.index), 0).errno()); } test "lookup resolves top files, pane serials and pane files" { @@ -1599,7 +1599,7 @@ test "lookup resolves top files, pane serials and pane files" { defer p.deinit(); const serial = serialOf(p); - try testing.expectEqual(@as(u64, @intFromEnum(TopFile.index)), look_up(p, root, "index").reply.attr.node); + try testing.expectEqual(@as(u64, @backingInt(TopFile.index)), look_up(p, root, "index").reply.attr.node); 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); @@ -1609,17 +1609,17 @@ test "lookup resolves top files, pane serials and pane files" { try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno()); try testing.expectEqual(E.NOENT, look_up(p, root, "self").errno()); try testing.expectEqual(E.NOENT, look_up(p, root, "cons").errno()); - try testing.expectEqual(E.NOTDIR, look_up(p, @intFromEnum(TopFile.index), "x").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, @backingInt(TopFile.index), "x").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, @intFromEnum(TopFile.pane), serial_name); + const dir = look_up(p, @backingInt(TopFile.pane), serial_name); try testing.expectEqual(Node.of(serial, .dir), dir.reply.attr.node); try testing.expect(dir.reply.attr.dir); try testing.expectEqualStrings(serial_name, dir.reply.attr.name); - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(TopFile.pane), "99999").errno()); - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(TopFile.pane), "0").errno()); + try testing.expectEqual(E.NOENT, look_up(p, @backingInt(TopFile.pane), "99999").errno()); + try testing.expectEqual(E.NOENT, look_up(p, @backingInt(TopFile.pane), "0").errno()); const body = look_up(p, Node.of(serial, .dir), "body"); try testing.expectEqual(Node.of(serial, .body), body.reply.attr.node); @@ -1636,19 +1636,19 @@ test "opening /pane/new makes a pane and removing one closes it" { const p = try withFile(gpa, "first\n"); defer p.deinit(); const before = p.next_serial; - const panes_dir = @intFromEnum(TopFile.pane); + const panes_dir = @backingInt(TopFile.pane); // Browsing /pane creates nothing, and neither does walking or stat-ing // `new` itself: only an open does. That is what lets `new` be listed at // all, since `ls -l` stats every name a listing handed it. try testing.expectEqual(Status.ok, rdir(p, panes_dir, 0).reply.status); try testing.expectEqual(Status.ok, look_up(p, panes_dir, new_pane).reply.status); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.new) }).reply.status); try testing.expectEqual(before, p.next_serial); // The open makes the pane and hands back its serial; the read only // observes, so two reads of one fid answer the same pane. - const made = call(p, .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }); + const made = call(p, .{ .tag = 2, .op = .open, .node = @backingInt(TopFile.new) }); try testing.expectEqual(Status.ok, made.reply.status); try testing.expectEqual(before + 1, p.next_serial); const serial = before + 1; @@ -1656,7 +1656,7 @@ test "opening /pane/new makes a pane and removing one closes it" { var expected: [16]u8 = undefined; const want = try std.fmt.bufPrint(&expected, "{d}\n", .{serial}); for (0..2) |_| { - const answer = call(p, .{ .tag = 3, .op = .read, .node = @intFromEnum(TopFile.new), .handle = made.reply.handle, .size = 64 }); + const answer = call(p, .{ .tag = 3, .op = .read, .node = @backingInt(TopFile.new), .handle = made.reply.handle, .size = 64 }); try testing.expectEqualStrings(want, answer.bytes); } @@ -1670,10 +1670,10 @@ test "opening /pane/new makes a pane and removing one closes it" { // A second open is a second pane, and releasing a clone fid leaves the // pane it made standing. - const second = call(p, .{ .tag = 4, .op = .open, .node = @intFromEnum(TopFile.new) }); + const second = call(p, .{ .tag = 4, .op = .open, .node = @backingInt(TopFile.new) }); try testing.expectEqual(Status.ok, second.reply.status); try testing.expect(second.reply.handle != made.reply.handle); - _ = call(p, .{ .tag = 5, .op = .release, .node = @intFromEnum(TopFile.new), .handle = made.reply.handle, .opened = true }); + _ = call(p, .{ .tag = 5, .op = .release, .node = @backingInt(TopFile.new), .handle = made.reply.handle, .opened = true }); try testing.expect(p.paneBySerial(serial) != null); try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content); @@ -1691,7 +1691,7 @@ test "opening /pane/new makes a pane and removing one closes it" { // 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.expectEqual(E.PERM, th.rmdir(p, @backingInt(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); @@ -1702,7 +1702,7 @@ test "every open that holds something is one record, named by its handle only on const p = try th.withTerm(testing.allocator); defer p.deinit(); const serial = serialOf(p); - const log = @intFromEnum(TopFile.log); + const log = @backingInt(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; @@ -1731,15 +1731,15 @@ test "directories walk to their parents" { defer p.deinit(); for ([_]struct { node: u64, parent: u64 }{ .{ .node = root, .parent = root }, - .{ .node = @intFromEnum(TopFile.pane), .parent = root }, - .{ .node = Node.of(serialOf(p), .dir), .parent = @intFromEnum(TopFile.pane) }, + .{ .node = @backingInt(TopFile.pane), .parent = root }, + .{ .node = Node.of(serialOf(p), .dir), .parent = @backingInt(TopFile.pane) }, .{ .node = fs.os_root, .parent = root }, }) |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); } - try testing.expectEqual(E.NOTDIR, look_up(p, @intFromEnum(TopFile.index), "..").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, @backingInt(TopFile.index), "..").errno()); try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serialOf(p), .body), "..").errno()); } @@ -1750,10 +1750,10 @@ test "editor paths resolve to the same nodes the wire serves" { var path: [64]u8 = undefined; 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.status), resolveSelf(p, "status").?); + try testing.expectEqual(@backingInt(TopFile.index), resolveSelf(p, "index").?); + try testing.expectEqual(@backingInt(TopFile.status), resolveSelf(p, "status").?); try testing.expect(resolveSelf(p, "new") == null); - try testing.expectEqual(@intFromEnum(TopFile.pane), resolveSelf(p, "pane").?); + try testing.expectEqual(@backingInt(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); @@ -1802,7 +1802,7 @@ test "random placements, refused or not, leave no pane under its tag and two row const action = r.uintLessThan(u8, 8); switch (action) { 0 => _ = th.wr(p, Node.of(at, .exec), "New\n"), - 1 => _ = call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(TopFile.new) }), + 1 => _ = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }), 2 => _ = th.wr(p, Node.of(at, .exec), "Newcol\n"), 3 => _ = th.wr(p, Node.of(at, .exec), "Edit =\n"), 4 => _ = th.wr(p, Node.of(at, .exec), "Tty\n"), @@ -1825,7 +1825,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e // Tall enough that the column holds every pane at its tag and two rows, // and wide enough that each tag, the session directory's +New, is one. p.update(.{ .resize = .{ .cols = 400, .rows = pardes.MAX_PANES * 4 } }); - const new = @intFromEnum(TopFile.new); + const new = @backingInt(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 space for a pane: {d} max", .{pardes.MAX_PANES}); @@ -1842,7 +1842,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e 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 look_node = @backingInt(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); @@ -1859,7 +1859,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e 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); + const exec = @backingInt(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 })); @@ -1877,7 +1877,7 @@ test "nothing a mount's close or a no-op truncate sends waits on the editor: a h 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(); - const exec = @intFromEnum(TopFile.exec); + const exec = @backingInt(TopFile.exec); const h = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 1 }).reply.handle; try testing.expect(h != 0); // Each piece fills its Twrite (a client's one write cut at msize). @@ -1908,12 +1908,12 @@ test "a refused open, create or remove says why in words and logs no err; a refu const serial = serialOf(p); // pane/new is read, never written: a write is refused, and is no // failure the log tells of. - const new = th.wr(p, @intFromEnum(TopFile.new), "x\n"); + const new = th.wr(p, @backingInt(TopFile.new), "x\n"); try testing.expectEqual(Status.err, new.reply.status); try testing.expectEqualStrings("permission denied", new.reply.ename); const made = call(p, .{ .tag = 2, .op = .open, .node = Node.of(serial, .body), .create = true }); try testing.expectEqualStrings("permission denied", made.reply.ename); - const gone = th.rmdir(p, @intFromEnum(TopFile.index)); + const gone = th.rmdir(p, @backingInt(TopFile.index)); try testing.expectEqual(Status.err, gone.reply.status); try testing.expect(gone.reply.ename.len > 0 and !std.ascii.isUpper(gone.reply.ename[0])); // An OTRUNC open's truncation of data after a failed addr: refused, no err. @@ -1963,7 +1963,7 @@ test "a write with no newline waits for its newline or the close, whatever its s 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(); - const exec = @intFromEnum(TopFile.exec); + const exec = @backingInt(TopFile.exec); const first = p.panes[0].?.serial; const mine = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 2 }).reply.handle; const theirs = call(p, .{ .tag = 2, .op = .open, .node = exec, .omode = 2 }).reply.handle; @@ -2015,7 +2015,7 @@ test "a rename of a pane's directory or file is refused as not permitted" { test "no placement leaves a pane shorter than its tag and two rows; a full column refuses the next" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const new = @intFromEnum(TopFile.new); + const new = @backingInt(TopFile.new); var made: usize = 1; const refused = while (made < pardes.MAX_PANES) : (made += 1) { const a = call(p, .{ .tag = 1, .op = .open, .node = new }); @@ -2080,7 +2080,7 @@ test "a pane made from pane/new goes last in its column, even when the last pane const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); for (0..3) |_| { - const made = call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(TopFile.new) }).reply.handle; + const made = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }).reply.handle; p.sync(); try testing.expectEqual(made, p.panes[p.col_panes[0][p.col_n[0] - 1]].?.serial); } diff --git a/src/normal.zig b/src/normal.zig index 93487e88..8de23d1c 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -168,6 +168,168 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m t.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) } +/// Search only the primary range, as Helix does. Select mode adds a new +/// match and makes it primary; normal mode replaces only the primary. +fn searchStep(p: *Pardes, t: *Text, text: []const u8, direction: modal.Normal.Direction, count: u32) void { + const name = if (p.register != 0) p.register else p.registers.last_search; + const pat = p.registers.value(name, 0) orelse return; + var re = SearchRegex.compile(p.scratch.allocator(), pat) catch { + p.setMessage(p.active, "invalid search pattern"); + return; + }; + var hay = text; + if (for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true) { + const lower = p.scratch.allocator().dupe(u8, text) catch return; + for (lower) |*c| c.* = std.ascii.toLower(c.*); + hay = lower; + } + for (0..count) |_| { + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = t.ranges(text, 0, &ranges); + const old = ranges[got.pri]; + const from = @min(old.anchor, old.head); + const to = @max(old.anchor, old.head); + var wrapped = false; + const found = (if (direction == .forward) blk: { + if (tryFind(&re, hay, to, hay.len)) |h| break :blk h; + wrapped = true; + break :blk tryFind(&re, hay, 0, hay.len); + } else blk: { + if (lastMatch(&re, hay, 0, from)) |h| break :blk h; + wrapped = true; + break :blk lastMatch(&re, hay, from, hay.len); + }) orelse { + p.setMessage(p.active, "no more matches"); + return; + }; + if (found.end == 0) return; + const next: modal.Selection = if (old.anchor > old.head) + .{ .anchor = found.end, .head = found.start } + else + .{ .anchor = found.start, .head = found.end }; + if (t.select and got.n < ranges.len) { + ranges[got.n] = next; + t.setRanges(text, ranges[0 .. got.n + 1], &.{}, got.n, true); + } else { + ranges[got.pri] = next; + t.setRanges(text, ranges[0..got.n], &.{}, got.pri, true); + } + if (wrapped) p.setMessage(p.active, "wrapped around document"); + } + t.show(); +} + +fn tryFind(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { + return re.find(hay, @min(from, hay.len), to); +} + +fn lastMatch(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { + var last: ?regexp.Regex.Match = null; + var at = from; + while (at <= to) { + const found = tryFind(re, hay, at, to) orelse break; + last = found; + at = if (found.end > found.start) found.end else modal.nextGrapheme(hay, found.end); + if (at <= found.start) break; + } + return last; +} + +pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) void { + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = t.ranges(text, 0, &ranges); + var pattern: std.ArrayList(u8) = .empty; + const arena = p.scratch.allocator(); + for (ranges[0..got.n], 0..) |r, i| { + const from = @min(r.anchor, r.head); + const to = @min(text.len, @max(r.anchor, r.head)); + if (i > 0) pattern.append(arena, '|') catch return; + if (boundary and modal.searchWordAt(text, from) and !modal.searchWordBefore(text, from)) pattern.appendSlice(arena, "\\b") catch return; + appendSearchLiteral(&pattern, arena, text[from..to]) catch return; + if (boundary and to < text.len and modal.searchWordBefore(text, to) and !modal.searchWordAt(text, to)) pattern.appendSlice(arena, "\\b") catch return; + } + const name = if (p.register != 0) p.register else '/'; + p.registers.put(p.gpa, name, pattern.items, 0, 1, true); + p.registers.last_search = name; +} + +// mvzr's word boundary is ASCII-only. Strip outer boundaries and check +// them against Unicode characters for search-selection patterns. +const SearchRegex = struct { + const Branch = struct { re: regexp.Regex, start_word: bool, end_word: bool }; + branches: []Branch, + + fn compile(arena: std.mem.Allocator, pattern: []const u8) !SearchRegex { + if (std.mem.indexOf(u8, pattern, "\\b") == null) { + const branches = try arena.alloc(Branch, 1); + branches[0] = try branch(pattern); + return .{ .branches = branches }; + } + var branches: std.ArrayList(Branch) = .empty; + var from: usize = 0; + var depth: usize = 0; + var escaped = false; + var in_class = false; + for (pattern, 0..) |c, i| { + if (escaped) { + escaped = false; + continue; + } + if (c == '\\') { + escaped = true; + continue; + } + if (c == '[') in_class = true else if (c == ']') in_class = false; + if (in_class) continue; + if (c == '(') depth += 1 else if (c == ')') depth -|= 1; + if (c == '|' and depth == 0) { + try branches.append(arena, try branch(pattern[from..i])); + from = i + 1; + } + } + try branches.append(arena, try branch(pattern[from..])); + for (branches.items) |*b| b.re.steps = regexp.Regex.budget / branches.items.len; + return .{ .branches = branches.items }; + } + + fn branch(pattern: []const u8) !Branch { + var pat = pattern; + const start = std.mem.startsWith(u8, pat, "\\b"); + if (start) pat = pat[2..]; + const end = std.mem.endsWith(u8, pat, "\\b") and !std.mem.endsWith(u8, pat, "\\\\b"); + if (end) pat = pat[0 .. pat.len - 2]; + return .{ .re = try regexp.Regex.compile(pat), .start_word = start, .end_word = end }; + } + + fn find(self: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { + var best: ?regexp.Regex.Match = null; + for (self.branches) |*b| { + var at = from; + while (at <= to) { + const found = (b.re.find(hay, at, to, to) catch break) orelse break; + if ((!b.start_word or modal.searchWordBefore(hay, found.start) != modal.searchWordAt(hay, found.start)) and + (!b.end_word or modal.searchWordBefore(hay, found.end) != modal.searchWordAt(hay, found.end))) + { + if (best == null or found.start < best.?.start) best = found; + break; + } + at = modal.nextGrapheme(hay, found.start); + if (at <= found.start) break; + } + } + return best; + } +}; + +pub fn appendSearchLiteral(out: *std.ArrayList(u8), arena: std.mem.Allocator, text: []const u8) !void { + for (text) |c| { + if (std.mem.indexOfScalar(u8, "\\^$.[]()|*+?{}", c) != null) try out.append(arena, '\\'); + if (c == '\n') try out.appendSlice(arena, "\\n") else try out.append(arena, c); + } +} + /// The file's parse, made on the first key that walks it after an edit and /// kept until the next: never made again for a key that changed nothing. pub fn fileTree(p: *Pardes, f: *panes.File.State) ?*anyopaque { @@ -743,14 +905,16 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .undo => return edit.doUndo(p, t), .redo => return edit.doRedo(p, t), }, - .lsp => |request| return p.lspRequest(p.active, switch (request) { - .definition => .definition, - .declaration => .declaration, - .type_definition => .type_definition, - .implementation => .implementation, - .references => .references, - .format => .format, - }, ""), + // Language shortcuts run the same builtins as tags and leader commands. + .lsp => |request| return switch (request) { + .definition => exec.runBuiltin(p, .Def, p.active, "", null), + .references => exec.runBuiltin(p, .Refs, p.active, "", null), + .callstack => exec.runBuiltin(p, .Callstack, p.active, "", null), + .declaration => p.lspRequest(p.active, .declaration, ""), + .type_definition => p.lspRequest(p.active, .type_definition, ""), + .implementation => p.lspRequest(p.active, .implementation, ""), + .format => p.lspRequest(p.active, .format, ""), + }, .adjust_number => |delta| return edit.normalAdjustNumber(p, t, delta), .leader => if (p.macro.replaying == 0) { p.leader_on = true; @@ -765,10 +929,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void }, .pipe_selection => |how| return p.startPrompt(pane, t, .{ .pipe = how }), .search => return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), - .search_step => |direction| return look.lookWalk( - p, - if (direction == .forward) @as(i32, 1) else -1, - ), + .search_step => |step| return searchStep(p, t, text, step.direction, step.count), + .search_selection => |boundary| return searchSelection(p, t, text, boundary), .node => |walk| return nodeSelect(p, pane, t, walk), .goto_word => return startJump(p, pane, t), .object_jump => |jump| return objectJump(p, pane, t, text, range, jump.object, jump.direction == .forward, jump.count), @@ -853,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..aba73d43 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; @@ -240,8 +240,8 @@ const Handler = struct { .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) }, + .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @backingInt(name) }, + .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @backingInt(name) }, .@"256_fg" => |i| s.fg = .{ .index = i }, .@"256_bg" => |i| s.bg = .{ .index = i }, .reset_fg => s.fg = .default, diff --git a/src/panes.zig b/src/panes.zig index 89362996..7ce85419 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -49,8 +49,6 @@ pub const Pane = struct { hi: usize, /// Not the sweep's last row: its highlight runs to the right edge. to_edge: bool = false, - prefix: [32]u8 = @splat(0), - prefix_len: u8 = 0, raw_terminal: bool = false, prompt_bytes: usize = 0, }; @@ -219,6 +217,7 @@ pub const Pane = struct { // Visible rows map to source lines and raw/display column origins. wrap_line: [limits.wrap_rows]i32 = undefined, wrap_col: [limits.wrap_rows]i32 = undefined, + wrap_pad: [limits.wrap_rows]u16 = @splat(0), wrap_n: u16 = 0, /// A row map also exists for sticky headers when soft wrapping is off. body_wrapped: bool = false, @@ -317,7 +316,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), @@ -493,15 +492,15 @@ pub const Pane = struct { return pane.surfRow(terminal.gridOffset(pane)); } - pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32 } { + pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32, pad: i32 = 0 } { if (pane.wrap_n > 0 and vr >= 0 and vr < @as(i32, pane.wrap_n)) - return .{ .line = pane.wrap_line[@intCast(vr)], .at = pane.wrap_col[@intCast(vr)] }; + return .{ .line = pane.wrap_line[@intCast(vr)], .at = pane.wrap_col[@intCast(vr)], .pad = pane.wrap_pad[@intCast(vr)] }; // unwrapped: rows ARE lines, and the byte column a row starts at is the // horizontal scroll (always 0 on a terminal, which never has one) return .{ .line = pane.scroll() + vr, .at = pane.hscroll }; } - pub fn wrapRow(pane: *Pane, line: i32, col: i32) struct { row: i32, at: i32 } { + pub fn wrapRow(pane: *Pane, line: i32, col: i32) struct { row: i32, at: i32, pad: i32 = 0 } { if (pane.wrap_n == 0) return .{ .row = line - pane.scroll(), .at = pane.hscroll }; var i: u16 = 0; while (i < pane.wrap_n) : (i += 1) { @@ -509,7 +508,7 @@ pub const Pane = struct { // the LAST row of a line owns every column past its start, so a // cursor parked on the trailing newline still has somewhere to draw if (i + 1 < pane.wrap_n and pane.wrap_line[i + 1] == line and col >= pane.wrap_col[i + 1]) continue; - return .{ .row = @intCast(i), .at = pane.wrap_col[i] }; + return .{ .row = @intCast(i), .at = pane.wrap_col[i], .pad = pane.wrap_pad[i] }; } return .{ .row = -1, .at = 0 }; } diff --git a/src/pardes.zig b/src/pardes.zig index 2a74e441..aaa9d177 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -220,7 +220,6 @@ pub const Turn = struct { 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; } @@ -294,7 +293,7 @@ pub const MAX_JUMPS = 64; pub const TOPBAR_H: u16 = 1; pub const COLBAR_H: u16 = 1; pub const BOX_H: u16 = 1; -pub const TAG_GAP: u16 = 1; +pub const TAG_GAP: u16 = 0; pub const TAG_TEXT_INSET: u16 = config.GUTTER + TAG_GAP; pub fn taglineBandOffset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { @@ -480,6 +479,7 @@ pub const Loc = struct { test { _ = @import("tagline.zig"); + _ = @import("hunks.zig"); _ = @import("builtins_json.zig"); _ = @import("exec.zig"); _ = @import("look.zig"); @@ -654,25 +654,25 @@ test "topbar hover highlights exactly the executable word" { defer frame.deinit(); _ = try p.render(frame.allocator()); - p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = 1, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = TAG_TEXT_INSET + 1, .row = 0 } }); _ = frame.reset(.retain_capacity); const hovered = try p.render(frame.allocator()); for (0.."Newcol".len) |col| { - const cell = hovered.at(@intCast(col), 0); + const cell = hovered.at(TAG_TEXT_INSET + @as(u16, @intCast(col)), 0); try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, cell.style.bg); try std.testing.expectEqual(Color{ .rgb = p.theme().sel_fg }, cell.style.fg); } - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, hovered.at(6, 0).style.bg); + try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, hovered.at(TAG_TEXT_INSET + 6, 0).style.bg); - p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = 6, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = TAG_TEXT_INSET + 6, .row = 0 } }); _ = frame.reset(.retain_capacity); const whitespace = try p.render(frame.allocator()); - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, whitespace.at(1, 0).style.bg); + try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, whitespace.at(TAG_TEXT_INSET + 1, 0).style.bg); p.update(.pointer_leave); _ = frame.reset(.retain_capacity); const left = try p.render(frame.allocator()); - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, left.at(1, 0).style.bg); + try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, left.at(TAG_TEXT_INSET + 1, 0).style.bg); } test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { @@ -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; @@ -864,7 +864,7 @@ test "TreeContext command and custom tag survive a workspace round trip" { p.gpa.free(pane.file.?.path); pane.file.?.path = path; if (!panes.File.supportsContext(pane)) return error.SkipZigTest; - try std.testing.expectEqualStrings(tagline.context_pane_tail, tagline.curTail(pane)); + try std.testing.expectEqualStrings(if (lsp.speaks("/test.zig")) tagline.lsp_context_pane_tail else 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); @@ -920,11 +920,11 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqualStrings("unchanged\n", file.file.?.content); } -test "Filter is ordered after Del and toggles only its terminal pane" { +test "Filter is ordered after Del and toggles only its terminal or +Pager pane" { const testing = std.testing; const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin; const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin; - try testing.expectEqual(@intFromEnum(del) + 1, @intFromEnum(filter)); + try testing.expectEqual(@backingInt(del) + 1, @backingInt(filter)); const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -954,6 +954,17 @@ test "Filter is ordered after Del and toggles only its terminal pane" { try testing.expect(p.executeBuiltinLine(0, "Filter")); try testing.expect(first.tty_filter); try testing.expect(!second.tty_filter); + + // A +Pager opens filtered, with Filter on its tag and no line numbers; + // a second is a pane of its own. + const pager_id = try panes.Output.openPager(p, 0, "/tmp"); + const pager_pane = p.panes[pager_id].?; + try testing.expect(pager_pane.tty_filter); + try testing.expectEqualStrings(tagline.pager_pane_tail, tagline.curTail(pager_pane)); + try testing.expectEqual(@as(u16, 0), panes.File.gutterWidth(pager_pane)); + try testing.expect(p.executeBuiltinLine(pager_id, "Filter")); + try testing.expect(!pager_pane.tty_filter); + try testing.expect(try panes.Output.openPager(p, 0, "/tmp") != pager_id); } test "compact tag commands stay beside their own prefix across layout changes" { @@ -1194,6 +1205,78 @@ test "Lspwhy after a Hover asks to explain that hover, in its file at its place, try std.testing.expect(seen); } +test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all run them" { + if (!lsp.supports.contains(.definition)) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 24, .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("const alpha = 1;\nconst beta = alpha;\n"); + // A .txt has no server: no Def, no Refs. + try std.testing.expect(std.mem.indexOf(u8, tagline.curTail(pane), "Def") == null); + const f = &pane.file.?; + p.gpa.free(f.path); + f.path = try p.gpa.dupe(u8, "/tmp/x.zig"); + try std.testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Def Refs Del")); + p.sync(); + while (p.nextEffect()) |_| {} + const Asked = struct { + fn one(q: *Pardes, kind: lsp.Kind) !u32 { + var at: ?u32 = null; + while (q.nextEffect()) |e| if (e == .lsp) { + try std.testing.expectEqual(kind, e.lsp.kind); + try std.testing.expectEqualStrings("", e.lsp.arg.slice()); + try std.testing.expect(at == null); + at = e.lsp.offset; + }; + q.lsp_wait = null; + return at orelse error.NothingAsked; + } + }; + // gd and gr: at the cursor, on `alpha`'s declaration. + pane.body.cur_row = 0; + pane.body.cur_col = 8; + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .definition)); + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'r' } }); + try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .references)); + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'c' } }); + try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .callstack)); + + const r = p.rects[0]; + const x0 = r.x + config.GUTTER + panes.File.gutterWidth(pane); + const use_y = p.bodyTop(pane, r) + 1; + // 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. + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x0 + 13, .row = use_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x0 + 17, .row = use_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x0 + 17, .row = use_y } }); + // B2 on the tag word, B1 clicked while it is held: the sweep is its + // argument, and it asks at the start of `alpha`, not at the cursor. + const wx = r.x + TAG_TEXT_INSET + @as(u16, @intCast(std.mem.indexOf(u8, tag, w.word).? + 1)); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } }); + try std.testing.expectEqual(@as(u32, 30), try Asked.one(p, w.kind)); + // Clicked bare, it asks at the cursor, where the sweep left it. + pane.body.cur_row = 0; + pane.body.cur_col = 2; + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } }); + try std.testing.expectEqual(@as(u32, 2), try Asked.one(p, w.kind)); + } + // A symbol the file does not hold is said, and nothing is asked. + exec.runBuiltin(p, .Def, 0, "", "gamma"); + try std.testing.expectError(error.NothingAsked, Asked.one(p, .definition)); + try std.testing.expectEqualStrings("Def: no gamma in this file", pane.msg[0..pane.msg_len]); +} + test "the Tutor pane is named +Tutor in the session's directory, never a bare path at the root" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -1267,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; @@ -1446,7 +1529,6 @@ test "unknown Exec from a document runs as a command pane in its directory, type try std.testing.expect(spawned); } - const FakeTtyQuery = struct { taken: [MAX_PANES]bool = @splat(false), asked: usize = 0, @@ -1926,11 +2008,10 @@ 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)); } - test "image dump restores source bytes renderer choices and exact custom tail" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); @@ -1983,7 +2064,6 @@ test "image dump restores source bytes renderer choices and exact custom tail" { try std.testing.expectEqualStrings(" Keep Del", redump.panes[0].tag_tail.?); } - test "a Look on a directory does not type ls into an occupied terminal" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 }); @@ -2892,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))}; @@ -2903,9 +2983,7 @@ fn chordName(comptime c: config.Chord) []const u8 { fn shortcutCount(comptime b: Builtin) comptime_int { var count = 0; - for (config.window_keys) |wk| if (wk.cmd == b) { - count += 2; - }; + if (b == .Window) count += 1; for (config.jump_keys) |jk| if (jk.cmd == b) { count += 1; }; @@ -2923,13 +3001,9 @@ fn shortcuts(comptime b: Builtin) []const u8 { @setEvalBranchQuota(20000); var parts: [shortcutCount(b)][]const u8 = undefined; var part: usize = 0; - for (config.window_keys) |wk| { - if (wk.cmd != b) continue; - // the prefix has one spelling and this is it - const pfx = chordName(config.window_prefix[0]) ++ " "; - parts[part] = pfx ++ chordName(wk.letter); - parts[part + 1] = pfx ++ chordName(wk.arrow); - part += 2; + if (b == .Window) { + parts[part] = chordName(config.window_prefix[0]); + part += 1; } for (config.jump_keys) |jk| { if (jk.cmd == b) { @@ -3010,11 +3084,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"; @@ -3033,8 +3107,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); } } @@ -3228,8 +3302,8 @@ test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { const pane = try p.setTestFile("\treturn x\n"); const f = &pane.file.?; f.highlights = try p.tree_sitter_gpa.alloc(u8, f.content.len); - @memset(f.highlights, @intFromEnum(syntax.Syn.none)); - @memset(f.highlights[1..7], @intFromEnum(syntax.Syn.keyword)); + @memset(f.highlights, @backingInt(syntax.Syn.none)); + @memset(f.highlights[1..7], @backingInt(syntax.Syn.keyword)); f.syntax_dirty = false; pane.body.cur_row = 0; pane.body.cur_col = 1; @@ -3295,9 +3369,9 @@ test "editable workspace and column tags are typed into and persist" { p.acknowledgePanelPresentation(&.{}); try std.testing.expectEqual(TOPBAR_H + COLBAR_H, p.rects[0].y); // a sweep over a header is its selection, the caret where it ended - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = 0, .row = 0 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 6, .row = 0 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 6, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = TAG_TEXT_INSET + 6, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET + 6, .row = 0 } }); try std.testing.expect(p.global_tag.vsel.active and p.global_tag.vsel.col == 0 and p.global_tag.cur_col == 6); p.update(.{ .key = .{ .cp = 'H', .text = " Help" } }); try std.testing.expect(std.mem.startsWith(u8, p.global_tag.own.?, "Newcol Help Joincol")); @@ -3641,7 +3715,7 @@ pub fn hit(key: Key, binding: []const config.Chord) bool { return false; } -pub const sel_slot = @intFromEnum(config.select_button); +pub const sel_slot = @backingInt(config.select_button); /// 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. @@ -4421,7 +4495,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, @@ -4470,6 +4544,9 @@ pub const Pardes = struct { cursor_view: struct { serial: u32 = 0, line: i64 = 0, origin: [2]f32 = .{ 0, 0 }, inside: bool = true } = .{}, /// The cursor glides from one pane to another: it may cross the grid. cursor_crossing: bool = false, + /// A click took focus to another pane and its button is still down: the + /// cursor waits where it was drawn for the release that places it. + cursor_held: bool = false, input_ns: u64 = 0, animate_theme_changes: bool = false, native_images: bool = false, @@ -4508,6 +4585,9 @@ pub const Pardes = struct { chord_hold: bool = false, /// The look just run found nothing (look.zig missed). look_missed: bool = false, + /// The look being run opens a .diff or .patch as text whatever DiffLook + /// says: Diff going back from a +Diff, Edit's B (it edits the file). + look_text: bool = false, look_hover_wait: ?look.LookHoverWait = null, /// The place a look-hover last found nothing to open: the pointer /// resting there does not ask again every frame (look.noteLookHover). @@ -4528,6 +4608,8 @@ pub const Pardes = struct { /// default one. register: u21 = 0, leader_on: bool = false, + /// Window mode's outlined pane (layout.windowKey); null outside it. + window_pick: ?usize = null, leader_keys: [4]u8 = undefined, leader_n: u8 = 0, /// The keyboard is on a header: the column tag `header_column` names, or @@ -4748,6 +4830,8 @@ pub const Pardes = struct { const named = try std.fs.path.join(gpa, &.{ dir, "+Pager" }); gpa.free(shown.file.?.path); shown.file.?.path = named; + shown.file.?.pager = true; + shown.tty_filter = true; shown.file.?.pager_diff = panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]); shown.file.?.pager_spans = page.spans; p.oneColumn(); @@ -4935,7 +5019,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); @@ -5955,7 +6039,7 @@ pub const Pardes = struct { // The one-failure rule is a write's: a refused open (its OTRUNC's // truncation, a setattr, too), create or remove is its Rerror alone, // no err, as is a write to pane/new, which is only ever read. - const ruled = req.op == .write and req.node != @intFromEnum(ctlfs.TopFile.new); + const ruled = req.op == .write and req.node != @backingInt(ctlfs.TopFile.new); if (reply.status == .err and ruled) 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 @@ -6284,12 +6368,26 @@ pub const Pardes = struct { } return; } + if (p.window_pick != null) return layout.windowKey(p, key); const pane = p.panes[p.active] orelse return; p.noteTyped(); + // In a raw terminal the two Escs swap unless ProgramEsc is on: Esc + // backs out, and Shift-Esc is the program's, sent as a plain Esc. + const raw_esc = key.cp == Key.escape and !key.ctrl and !key.alt and !p.settings.program_esc and + pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none and + tagline.focusedHeader(p) == null; + if (raw_esc and key.shift) { + p.leader_on = false; + p.ctrl_w_pending = false; + panes.terminal.followOutput(pane); + var plain = key; + plain.shift = false; + return panes.terminal.forwardKey(p, p.active, plain); + } // Shift-Esc backs out of whatever the pane is in -- a prompt, insert // mode, a pending count, a raw program -- to the previous pane, as // Esc does from normal mode. Nothing under it sees the key. - if (hit(key, config.back_out)) { + if (raw_esc or hit(key, config.back_out)) { p.leader_on = false; p.ctrl_w_pending = false; if (pane.prompt != .none) { @@ -6317,8 +6415,8 @@ 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); - // Bare Escape leaves only at a shell prompt (Shift-Esc, above, - // always). + // With ProgramEsc on, bare Escape leaves only at a shell prompt + // (Shift-Esc, above, always). 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 @@ -6346,12 +6444,16 @@ pub const Pardes = struct { } return; } - // insert mode owns Ctrl-w (delete word backward, helix); the focus - // prefix applies outside raw tty mode + // insert mode owns Ctrl-w (delete word backward, helix); outside raw + // tty mode it enters window mode, or on a header prefixes a move + // between the headers const t = header orelse if (pane.focus == .tag) &pane.tag else &pane.body; if (hit(key, config.window_prefix) and t.mode != .insert and (header != null or pane.prompt == .none)) { - p.ctrl_w_pending = true; - return; + if (header != null) { + p.ctrl_w_pending = true; + return; + } + return exec.runBuiltin(p, .Window, p.active, "", null); } // global window ops (any mode): Alt-n new terminal below, Alt-c move // the active terminal into a fresh column @@ -6674,7 +6776,8 @@ pub const Pardes = struct { pub const SavePath = Effect.Buf(effect_path_cap); - pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg: []const u8) void { + pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) 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 // file, place and argument -- from wherever it is run. @@ -6697,10 +6800,30 @@ 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"); } - const off = if (pane.file) |f| modal.offsetAt(f.content, .{ + var 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; + // Def or Refs given a symbol (a 2-1 chord's selection) asks at its + // occurrence nearest the cursor, which a sweep leaves at one end of + // what it selected; the server is asked at a place, never a name. + if ((kind == .definition or kind == .references) and arg.len > 0) { + const content = pane.file.?.content; + var nearest: ?usize = null; + var best: usize = 0; + var from: usize = 0; + while (std.mem.indexOfPos(u8, content, from, arg)) |at_hit| : (from = at_hit + 1) { + const d = if (at_hit > off) at_hit - off else off -| (at_hit + arg.len); + if (nearest != null and at_hit > off and d >= best) break; + if (nearest == null or d < best) { + nearest = at_hit; + best = d; + } + } + off = nearest orelse + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no {s} in this file", .{ lspWord(kind), arg }) catch "no such symbol in this file"); + arg = ""; + } // Lspwhy asks the last query again, narrated: its kind and argument, // at its place when asked from its pane. None yet: a definition. var explained: [160]u8 = undefined; @@ -6858,7 +6981,10 @@ pub const Pardes = struct { fn lspWord(kind: lsp.Kind) []const u8 { return switch (kind) { .hover => "Hover", + .definition => "Def", + .references => "Refs", .explain => "Lspwhy", + .callstack => "Callstack", .incoming_calls => "Callers", .outgoing_calls => "Callees", .document_symbols => "Symbols", @@ -6974,6 +7100,18 @@ pub const Pardes = struct { // (a multi-file Rename's preview, Lspinfo's +Lsp), made or filled // again, not the pane it was asked from. p.fs.lsp_result = if (p.next_serial != serial_before) p.next_serial else p.fs.refilled; + if (w.kind == .callstack) { + for (p.panes, 0..) |slot, result_id| if (slot) |result_pane| { + if (result_pane.serial != p.fs.lsp_result) continue; + if (p.next_serial != serial_before) { + const report_rows = std.mem.count(u8, result_pane.file.?.content, "\n"); + const wanted: u16 = @intCast(@min(p.screen_h, report_rows + result_pane.tag_rows)); + layout.givePaneRows(p, result_id, wanted, w.pane); + } + look.focusPaneLine(p, result_id, .{ .line = 1, .col = 1 }, .keep); + break; + }; + } if (w.kind == .rename) { var said_buf: [128]u8 = undefined; // Rows that only name a file the server left alone (lsp_client @@ -7517,7 +7655,6 @@ pub const Pardes = struct { return if (frames) |n| p.stepped_ns + n * animation.frame_ns else null; } - /// A render-time animation is moving (a pane's lift): it is sampled at /// each frame's own `now`, so while it moves the shell draws every loop /// and its present (vsync) paces it, at the display's rate. `nextWake` @@ -8319,7 +8456,7 @@ test "Esc back into a file leaves its view where it was" { try std.testing.expectEqual(@as(usize, @intCast(row)) -| @as(usize, dp.rows) / 2, dp.file.?.scroll); } -test "raw tty Escape only leaves at a shell prompt" { +test "raw tty Esc backs out and Shift-Esc is the program's Esc" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); @@ -8329,6 +8466,32 @@ test "raw tty Escape only leaves at a shell prompt" { var buf: [256]u8 = undefined; _ = drainWrites(p, &buf); + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + _ = drainWrites(p, &buf); + p.update(.{ .key = .{ .cp = Key.escape } }); // past typed text too + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("", drainWrites(p, &buf)); + try std.testing.expectEqual(Text.Mode.tty, pane.body.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, .shift = true } }); + try std.testing.expectEqual(shell, p.active); + try std.testing.expectEqualStrings("\x1b", drainWrites(p, &buf)); +} + +test "with ProgramEsc 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.settings.program_esc = true; + _ = exec.spawnTty(p, 0); + const shell = p.active; + const pane = p.panes[shell].?; + var buf: [256]u8 = undefined; + _ = drainWrites(p, &buf); + // Ordinary keys reach the child; Shift-Escape is the one unconditional way // out and sends it nothing. p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); @@ -8372,6 +8535,63 @@ test "Shift-Esc backs out to the previous pane in every mode, never into raw" { try std.testing.expect(p.active != 0); } +test "window mode moves an outline and focuses it on Enter, Esc or a label" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30 }); + defer p.deinit(); + _ = try p.setTestFile("left\n"); + _ = try p.newShell(1, ""); + try std.testing.expect(layout.splitColumn(p, 0, 1, false)); + p.newScratchBelow(1); + p.sync(); + const lower = for (p.panes, 0..) |slot, id| { + if (slot != null and id > 1) break id; + } else return error.TestExpectedScratch; + p.active = 0; + // Ctrl-w enters it; h/j/k/l move only the outline. + p.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + try std.testing.expectEqual(@as(?usize, 0), p.window_pick); + p.update(.{ .key = .{ .cp = 'l', .text = "l" } }); + try std.testing.expect(p.window_pick != null and p.window_pick.? != 0); + p.update(.{ .key = .{ .cp = 'j', .text = "j" } }); + try std.testing.expectEqual(@as(?usize, lower), p.window_pick); + try std.testing.expectEqual(@as(usize, 0), p.active); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(lower, p.active); + try std.testing.expect(p.window_pick == null); + // SPC w enters it too, and Esc also leaves it on the outlined pane. + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + p.update(.{ .key = .{ .cp = 'w', .text = "w" } }); + p.update(.{ .key = .{ .cp = 'h', .text = "h" } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(p.window_pick == null); + // Other keys change nothing. + p.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + p.update(.{ .key = .{ .cp = '!', .text = "!" } }); + try std.testing.expectEqual(@as(?usize, 0), p.window_pick); + p.update(.{ .key = .{ .cp = Key.escape } }); + // `:` focuses the outlined pane's tag. + p.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + p.update(.{ .key = .{ .cp = 'l', .text = "l" } }); + p.update(.{ .key = .{ .cp = ':', .text = ":" } }); + try std.testing.expect(p.active != 0 and p.panes[p.active].?.focus == .tag); + p.update(.{ .key = .{ .cp = Key.escape } }); + // A label goes straight there: the left column's pane is "a". + try std.testing.expectEqual(@as(?u8, 'a'), layout.windowLabel(p, 0)); + try std.testing.expect(p.executeBuiltinLine(p.active, "Window")); + p.update(.{ .key = .{ .cp = 'a', .text = "a" } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + // Painted: the outlined tag's band in the selection colour, each pane's + // letter in its tag's box. + try std.testing.expect(p.executeBuiltinLine(p.active, "Window")); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const shown = try p.render(arena.allocator()); + try std.testing.expectEqual(p.theme().sel_bg, shown.tag_layers[0].bg); + const box = shown.at(p.rects[0].x, p.tagTop(p.panes[0].?, p.rects[0])); + try std.testing.expectEqualStrings("a", box.text[0..box.len]); +} + 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" }); @@ -8390,7 +8610,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; @@ -8407,6 +8627,44 @@ test "the jump list never holds two entries in a row the same, when the one betw try std.testing.expectEqual(@as(u32, 150), p.jumps[1].line); } +test "Callstack always opens and focuses its own pane, reusing it for another symbol" { + if (!lsp.supports.contains(.callstack)) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("fn work() {}\n"); + const source = p.panes[0].?; + p.lspRequest(0, .callstack, ""); + const first = p.lsp_wait orelse return error.NoRequest; + p.lspResponse(first.id, "└──┬ /test.txt:1:4-7 work\n@callstack-match └─ /test.txt:1:4-7 fn work() {}\n"); + const report = p.panes[p.active].?; + try std.testing.expect(report != source); + try std.testing.expect(std.mem.endsWith(u8, report.file.?.path, "/+Callstack")); + try std.testing.expectEqual(@as(i32, 0), source.body.cur_row); + const stale_selection = std.mem.indexOfScalar(u8, report.file.?.content, '\n').? + 1; + report.body.setRange(report.file.?.content, 0, .{ .anchor = stale_selection, .head = stale_selection + 6 }, true); + layout.toggleCollapse(p, 0); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const surface = try p.render(frame.allocator()); + p.acknowledgePanelPresentation(&.{}); + const r = p.rects[p.active]; + const row = r.y + report.tag_rows; + const col = r.x + config.GUTTER + panes.File.gutterWidth(report) + 7; + try std.testing.expectEqual(.off, surface.at(col, row).style.ul); + p.update(.{ .mouse = .{ .button = .right, .kind = .press, .row = row, .col = col } }); + p.update(.{ .mouse = .{ .button = .right, .kind = .release, .row = row, .col = col } }); + try std.testing.expect(!source.collapsed); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(!report.body.vsel.active); + try std.testing.expectEqual(@as(usize, 0), report.body.nsel); + const serial = report.serial; + p.lspRequest(0, .callstack, ""); + const second = p.lsp_wait orelse return error.NoRequest; + p.lspResponse(second.id, "No callers reported\n"); + try std.testing.expectEqual(serial, p.panes[p.active].?.serial); + try std.testing.expectEqualStrings("No callers reported\n", p.panes[p.active].?.file.?.content); +} + test "Callers with one answer jumps to it and says where, in a msg" { if (!lsp.supports.contains(.incoming_calls)) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); @@ -8460,6 +8718,7 @@ test "hopping between two panes does not grow the jump stack" { p.update(.{ .key = .{ .cp = ' ' } }); p.update(.{ .key = .{ .cp = 'w' } }); p.update(.{ .key = .{ .cp = dir } }); + p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(want, p.active); } try std.testing.expectEqual(depth, p.njumps); @@ -8843,6 +9102,19 @@ test "board heap: every allocation failure during boot is a clean OutOfMemory" { ); } +test "a sweep pressed on the line numbers copies only the text" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha beta\ngamma delta\n"); + const numbers: i32 = panes.File.gutterWidth(pane); + const top: i32 = pane.tag_rows; + pane.sel[0] = .{ .state = .done, .c0 = 1, .c1 = numbers + 4, .r0 = top, .r1 = top + 1 }; + // Live, while the drag is held, and captured, once it is released. + try std.testing.expectEqualStrings("alpha beta\ngamma", try edit.selectionText(p, pane, pane.sel[0])); + try edit.capturePointerSelection(p, pane, 0); + try std.testing.expectEqualStrings("alpha beta\ngamma", try edit.selectionText(p, pane, pane.sel[0])); +} + test "jump history clears selections and lands at the recorded cursor" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); @@ -8898,7 +9170,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/pdf_view.zig b/src/pdf_view.zig index d5769ad3..2a89ef01 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -1843,7 +1843,7 @@ pub fn applyNormal( .leader => result.host = .leader, .command_line => result.host = .command_line, .search => result.host = .search, - .search_step => |direction| result.host = if (direction == .forward) + .search_step => |step| result.host = if (step.direction == .forward) .search_forward else .search_backward, @@ -2604,7 +2604,7 @@ pub fn pointerRelease( ) PointerRelease { if (comptime !enabled) return .{}; const state = &(pane.pdf orelse return .{}); - const slot = @intFromEnum(button); + const slot = @backingInt(button); const grid_selection = pane.sel[slot]; pane.sel[slot].state = .none; // native quads, not projected text cells @@ -2814,6 +2814,8 @@ pub fn draw( )); rail.thumb_y = @intCast(pos); rail.thumb_h = @intCast(@min(len, track_h -| pos)); + rail.thumb_at = @floatCast(state.document_scroll_y / @as(f64, @floatFromInt(total))); + rail.thumb_span = @as(f32, @floatFromInt(view.pixel_h)) / @as(f32, @floatFromInt(total)); s.fill(rail.rect.x, rail.rect.y, 1, rail.rect.h, .{ .bg = .{ .rgb = chrome.scroll_track } }); s.fill(rail.rect.x + 1, rail.rect.y, 1, rail.rect.h, .{ .bg = pane_bg }); s.fill(rail.rect.x, rail.rect.y + rail.thumb_y, 1, rail.thumb_h, .{ .bg = .{ .rgb = chrome.scroll_thumb } }); 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/surface.zig b/src/surface.zig index f7cc6010..e67cf21c 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -368,6 +368,11 @@ pub const Region = struct { /// regions once render has returned. thumb_y: u16 = 0, thumb_h: u16 = 0, + /// The same thumb unrounded, for a pixel shell: its top and its length + /// as fractions of the track (the length before any minimum, so one + /// row of the content is `thumb_span / rect.h`). Zero when unmeasured. + thumb_at: f32 = 0, + thumb_span: f32 = 0, /// A notice's index in its pane's `notices`. notice: u8 = 0, /// How far it stands off the page, 0 to 1: a pane's while it has the diff --git a/src/syntax.zig b/src/syntax.zig index b7406b04..1c09c9f3 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -214,7 +214,7 @@ fn ensure(spec: *Spec) !Selected { const capture_styles = spec.capture_styles[0..query.captureCount()]; for (capture_styles, 0..) |*style, id| { const name = query.captureNameForId(@intCast(id)) orelse ""; - style.* = @intFromEnum(synFor(name)); + style.* = @backingInt(synFor(name)); if (style.* == 0) query.disableCapture(name); } const parser = ts.Parser.create(); @@ -414,7 +414,6 @@ pub fn walkNodes(tree_ptr: *anyopaque, walk: NodeWalk, from: usize, to: usize, a return 1; } - /// helix's textobjects, which its `]f`, `mif` and kin select: the name a /// query's captures begin with (`function.around`, `test.inside`). pub const Object = @import("modal.zig").Normal.Object; @@ -854,7 +853,13 @@ pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: if (comptime @hasField(@TypeOf(row), "location_end")) { address_only = row.location_end > 0 and source_start == end; } - if (!address_only) { + // A row its producer coloured whole is coloured below: no + // fragment of it to parse. + var coloured = false; + if (comptime @hasField(@TypeOf(row), "colors")) { + coloured = row.colors.len > 0 and row.colors.len >= end - source_start; + } + if (!address_only and !coloured) { sources[source_count] = .{ .index = index, .start = source_start, .len = end - source_start }; source_count += 1; } @@ -934,13 +939,10 @@ pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: } fn codeAfterLocation(line: []const u8) ?struct { path: []const u8, at: usize, text: []const u8 } { - const token_end = std.mem.indexOfAny(u8, line, " \t") orelse return null; - if (token_end == 0) return null; - const token = line[0..token_end]; - const target = look.parsePathLine(token); - if (target.end != token.len) return null; + const trimmed = std.mem.trimStart(u8, line, " \t"); + const target = @import("locations.zig").parseRaw(trimmed); if (target.at.line == 0) return null; - const at = token_end + 1; + const at = line.len - trimmed.len + target.code_start; if (at >= line.len) return null; return .{ .path = target.path, .at = at, .text = line[at..] }; } @@ -963,11 +965,11 @@ test "syntax formatted locations color hidden context and preserve multiline sou const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); const body = std.mem.indexOf(u8, content, "comment body").?; - try std.testing.expectEqual(@intFromEnum(Syn.comment), styles[body]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[body - 1]); + try std.testing.expectEqual(@backingInt(Syn.comment), styles[body]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[body - 1]); const number = std.mem.indexOf(u8, content, "42").?; - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[number]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[0]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[number]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[0]); } test "syntax formatted locations separate alignment from Markdown indentation" { @@ -983,8 +985,8 @@ test "syntax formatted locations separate alignment from Markdown indentation" { }; const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]); - try std.testing.expectEqual(@intFromEnum(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]); + try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]); } fn inject(styles: []u8, source: []const u8, node: ts.Node, markdown: bool) void { const kind = node.kind(); @@ -1037,10 +1039,15 @@ fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node { /// A diff line's style byte carries whether the line was added or removed /// over its syntax style (the low bits), so the painter can tint its row -/// and mark its prefix. +/// and mark its prefix; Diff marks the words a changed line changed +/// (hunks.zig), drawn on a stronger tint. pub const diff_added: u8 = 0x80; pub const diff_removed: u8 = 0x40; -pub const syn_bits: u8 = 0x3f; +pub const diff_emph: u8 = 0x20; +/// A +Diff line added or removed whole, paired with no line it changed: +/// its row takes a faint tint, on its marker's byte. +pub const diff_whole: u8 = 0x10; +pub const syn_bits: u8 = 0x0f; /// A file section's hunks are parsed together, each side as one text, in /// pieces: a piece takes whole hunks until it holds `diff_piece_lines` @@ -1142,7 +1149,7 @@ pub fn highlightDiffRows(gpa: std.mem.Allocator, content: []const u8, start_raw: .meta, .old_path, .new_path => .comment, else => .none, }; - if (style != .none) window.fill(at, nl - at, @intFromEnum(style)); + if (style != .none) window.fill(at, nl - at, @backingInt(style)); } if (nl >= content.len) break; at = nl + 1; @@ -1185,10 +1192,10 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: anytype, bytes: []const u8, at for (kinds) |kind| { const line = lines.next() orelse break; const style: u8 = switch (kind) { - .added => @intFromEnum(Syn.string) | diff_added, - .removed => @intFromEnum(Syn.number) | diff_removed, - .no_newline => @intFromEnum(Syn.comment), - .hunk => @intFromEnum(Syn.keyword), + .added => @backingInt(Syn.string) | diff_added, + .removed => @backingInt(Syn.number) | diff_removed, + .no_newline => @backingInt(Syn.comment), + .hunk => @backingInt(Syn.keyword), else => 0, }; if (style != 0) window.fill(at + offset, line.len, style); @@ -1266,8 +1273,8 @@ fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []cons .removed => @memcpy(dst, old_colors[old_at..][0..code_len]), .added => @memcpy(dst, new_colors[new_at..][0..code_len]), .context => @memcpy(dst, if (context_new) new_colors[new_at..][0..code_len] else old_colors[old_at..][0..code_len]), - .no_newline => @memset(out[offset..][0..line.len], @intFromEnum(Syn.comment)), - .hunk => @memset(out[offset..][0..line.len], @intFromEnum(Syn.keyword)), + .no_newline => @memset(out[offset..][0..line.len], @backingInt(Syn.comment)), + .hunk => @memset(out[offset..][0..line.len], @backingInt(Syn.keyword)), else => {}, } if (kind == .context or kind == .removed) old_at += code_len + 1; @@ -1315,8 +1322,8 @@ test "syntax a results row is coloured by the file its location names" { try std.testing.expectEqual(content.len, styles.len); for (styles[0.."src/a.zig:1:1".len]) |b| try std.testing.expectEqual(@as(u8, 0), b); const zig_kw = std.mem.indexOf(u8, content, "struct").?; - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[zig_kw]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[zig_kw + 5]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[zig_kw]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[zig_kw + 5]); const prose = std.mem.indexOf(u8, content, "just some prose").?; for (styles[prose .. prose + 14]) |b| try std.testing.expectEqual(@as(u8, 0), b); const bare = std.mem.indexOf(u8, content, "src/c.zig").?; @@ -1344,6 +1351,11 @@ test "syntax codeAfterLocation takes whole-token locations and nothing else" { try std.testing.expect(codeAfterLocation("src/x.zig:7:2") == null); try std.testing.expect(codeAfterLocation("") == null); try std.testing.expect(codeAfterLocation(" leading space") == null); + const indented = " some directory/x.zig:7:2-9 return 42;"; + const nested = codeAfterLocation(indented) orelse return error.ShouldBeALocation; + try std.testing.expectEqualStrings("some directory/x.zig", nested.path); + try std.testing.expectEqualStrings(" return 42;", nested.text); + try std.testing.expectEqualStrings(nested.text, indented[nested.at..]); } test "syntax default full grammar set highlights Typst source" { @@ -1359,14 +1371,14 @@ test "syntax default full grammar set highlights Typst source" { const keyword_at = std.mem.indexOf(u8, source, "let").?; const number_at = std.mem.indexOf(u8, source, "42").?; const string_at = std.mem.indexOf(u8, source, "\"hello\"").?; - try std.testing.expectEqual(Syn.comment, @as(Syn, @enumFromInt(styles[comment_at]))); - try std.testing.expectEqual(Syn.keyword, @as(Syn, @enumFromInt(styles[keyword_at]))); - try std.testing.expectEqual(Syn.number, @as(Syn, @enumFromInt(styles[number_at]))); - try std.testing.expectEqual(Syn.string, @as(Syn, @enumFromInt(styles[string_at]))); + try std.testing.expectEqual(Syn.comment, @as(Syn, @fromBackingInt(@intCast(styles[comment_at])))); + try std.testing.expectEqual(Syn.keyword, @as(Syn, @fromBackingInt(@intCast(styles[keyword_at])))); + try std.testing.expectEqual(Syn.number, @as(Syn, @fromBackingInt(@intCast(styles[number_at])))); + try std.testing.expectEqual(Syn.string, @as(Syn, @fromBackingInt(@intCast(styles[string_at])))); const short_ext = try highlightFileRange(std.testing.allocator, "paper.typ", source, 0, source.len); defer std.testing.allocator.free(short_ext); - try std.testing.expectEqual(Syn.keyword, @as(Syn, @enumFromInt(short_ext[keyword_at]))); + try std.testing.expectEqual(Syn.keyword, @as(Syn, @fromBackingInt(@intCast(short_ext[keyword_at])))); } test "syntax Typst markup constructs paint and raw blocks inject their language" { @@ -1391,7 +1403,7 @@ test "syntax Typst markup constructs paint and raw blocks inject their language" const synAt = struct { fn f(s: []const u8, src: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(s[std.mem.indexOf(u8, src, needle).? + offset]); + return @fromBackingInt(@intCast(s[std.mem.indexOf(u8, src, needle).? + offset])); } }.f; try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "= Heading", 0)); @@ -1431,7 +1443,7 @@ test "syntax markdown highlights markup, injects inline spans and fenced code bl const synAt = struct { fn f(s: []const u8, src: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(s[std.mem.indexOf(u8, src, needle).? + offset]); + return @fromBackingInt(@intCast(s[std.mem.indexOf(u8, src, needle).? + offset])); } }.f; try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "Title", 0)); @@ -1459,8 +1471,8 @@ test "syntax inline fast path agrees with full Markdown query" { const actual = try std.testing.allocator.alloc(u8, source.len); defer std.testing.allocator.free(actual); for ([_]Syn{ .none, .keyword }) |background| { - @memset(expected, @intFromEnum(background)); - @memset(actual, @intFromEnum(background)); + @memset(expected, @backingInt(background)); + @memset(actual, @backingInt(background)); runQuery(expected, sel, tree, 0); inject(actual, source, tree.rootNode(), true); if (!std.mem.eql(u8, expected, actual)) std.debug.print("inline mismatch: {s}\n", .{source}); @@ -1499,9 +1511,9 @@ test "syntax plain Markdown keeps block styles without starting the inline parse const source = "# Heading\n\nPlain prose.\n\n indented code\n"; const styles = try highlightFileRange(std.testing.allocator, "a.md", source, 0, source.len); defer std.testing.allocator.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[2]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[std.mem.indexOf(u8, source, "Plain").?]); - try std.testing.expectEqual(@intFromEnum(Syn.string), styles[std.mem.indexOf(u8, source, "indented").?]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[2]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[std.mem.indexOf(u8, source, "Plain").?]); + try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, source, "indented").?]); for (specs) |spec| { if (std.mem.eql(u8, spec.name, "markdown_inline")) try std.testing.expect(spec.selected == null); } @@ -1532,7 +1544,7 @@ test "syntax highlightDiff colors unified diff lines by prefix" { } fn diffSynAt(styles: []const u8, text: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits); + return @fromBackingInt(@intCast(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits)); } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { @@ -1703,7 +1715,7 @@ test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { const at = std.mem.indexOf(u8, content, "+const v1000 ").?; const window = try highlightDiff(gpa, content, at, at + 200); defer gpa.free(window); - try std.testing.expectEqual(Syn.number, @as(Syn, @enumFromInt(window["+const v1000 = ".len] & syn_bits))); + try std.testing.expectEqual(Syn.number, @as(Syn, @fromBackingInt(@intCast(window["+const v1000 = ".len] & syn_bits)))); var cached: usize = 0; for (diff_pieces) |slot| if (slot) |piece| { cached += 1; @@ -1725,6 +1737,7 @@ test "syntax result fragments preserve source indentation and inline markup" { defer stop(); const fixtures = [_]struct { path: []const u8, source: []const u8 }{ .{ .path = "a.zig", .source = " const number = 42; // note" }, + .{ .path = " nested path/a.zig", .source = " return call(42, \"hello\"); // note" }, .{ .path = "a.md", .source = "# Heading *slant*" }, .{ .path = "a.md", .source = "**bold** and `code`" }, .{ .path = "a.md", .source = " # this is indented code" }, @@ -1767,7 +1780,7 @@ test "syntax query filtering preserves upstream colors" { reference.query = raw_query; reference.capture_styles = try std.testing.allocator.alloc(u8, raw_query.captureCount()); defer std.testing.allocator.free(reference.capture_styles); - for (reference.capture_styles, 0..) |*style, id| style.* = @intFromEnum(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); + for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed; defer tree.destroy(); var expected: [source.len]u8 = @splat(0); @@ -1793,8 +1806,8 @@ test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { defer std.testing.allocator.free(styles); for ([_][]const u8{ "fn", "if" }) |keyword| { const at = std.mem.indexOf(u8, code, keyword).?; - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[at]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[at + 1]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[at]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[at + 1]); } } @@ -1810,8 +1823,8 @@ test "syntax allocator switching clears default-runtime caches" { const restored = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len); defer std.testing.allocator.free(restored); defer stop(); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), restored[0]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), restored[1]); + try std.testing.expectEqual(@backingInt(Syn.keyword), restored[0]); + try std.testing.expectEqual(@backingInt(Syn.keyword), restored[1]); } test "syntax location context snapshots retain omitted multiline comment scope" { @@ -1835,8 +1848,8 @@ test "syntax location context snapshots retain omitted multiline comment scope" const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); for (styles[rows[0].code_start..][0..code.len]) |style| - try std.testing.expectEqual(@intFromEnum(Syn.comment), style); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[0]); + try std.testing.expectEqual(@backingInt(Syn.comment), style); + try std.testing.expectEqual(@backingInt(Syn.none), styles[0]); } test "syntax declaration locations clear snapshots without muting ordinary context" { @@ -1846,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, @@ -1862,7 +1875,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); for (styles[3..][0..header.len]) |style| try std.testing.expectEqual(@as(u8, 0), style); - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[std.mem.indexOf(u8, content, "42").?]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[std.mem.indexOf(u8, content, "42").?]); } test "syntax stacked addresses do not split multiline source groups" { @@ -1882,11 +1895,11 @@ test "syntax stacked addresses do not split multiline source groups" { }; const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.comment), styles[std.mem.indexOf(u8, content, "42").?]); - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[std.mem.indexOf(u8, content, "7;").?]); + try std.testing.expectEqual(@backingInt(Syn.comment), styles[std.mem.indexOf(u8, content, "42").?]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[std.mem.indexOf(u8, content, "7;").?]); for ([_][]const u8{ "a.c:1:1", "a.c:2:1", "a.c:3:1" }) |label| { const at = std.mem.indexOf(u8, content, label).?; - for (styles[at..][0..label.len]) |style| try std.testing.expectEqual(@intFromEnum(Syn.none), style); + for (styles[at..][0..label.len]) |style| try std.testing.expectEqual(@backingInt(Syn.none), style); } } @@ -1950,4 +1963,3 @@ test "syntax source analysis preserves declarations and injected colors" { try std.testing.expectEqual(@as(usize, 0), unsupported.declarations.len); try std.testing.expectEqual(@as(usize, 0), unsupported.colors.len); } - diff --git a/src/tagline.zig b/src/tagline.zig index d13f3c5f..b6601d61 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -19,8 +19,19 @@ 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"; +fn withFileCommands(comptime tail: []const u8, comptime words: []const u8) []const u8 { + std.debug.assert(std.mem.endsWith(u8, tail, " Del")); + return tail[0 .. tail.len - " Del".len] ++ " " ++ words ++ " Del"; +} +pub const context_pane_tail = withFileCommands(file_pane_tail, "TreeContext"); +pub const locations_pane_tail = withFileCommands(file_pane_tail, "LocationsConfig"); +/// Language commands precede the final Del, like other file-pane commands. +pub const lsp_pane_tail = withFileCommands(file_pane_tail, config.lsp_pane_builtins_str); +pub const lsp_context_pane_tail = withFileCommands(context_pane_tail, config.lsp_pane_builtins_str); +pub const pager_pane_tail = " " ++ config.pager_pane_builtins_str; +pub const diff_pane_tail = " " ++ config.diff_pane_builtins_str; +pub const pager_diff_pane_tail = " " ++ config.pager_diff_pane_builtins_str; +pub const diff_view_tail = withFileCommands(" " ++ config.diff_view_builtins_str, "LocationsConfig"); 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; @@ -69,7 +80,7 @@ pub fn revealHeader(p: *Pardes) void { if (cur < p.header_top) p.header_top = cur; if (rows > 0 and cur >= p.header_top + rows) p.header_top = cur + 1 - rows; const line = modal.lineSlice(text, cur); - const width = p.tagCapacity(if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else p.screen_w); + const width = p.tagCapacity(if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else p.screen_w -| TAG_TEXT_INSET); 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); @@ -164,10 +175,15 @@ 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.file) |file| if (file.listing != null) return dir_pane_tail; - if (pane.file) |file| if (file.output) |out| + 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; + if (pane.file) |file| if (file.output) |out| { + if (std.meta.eql(out.from, panes.Output.Origin{ .cmd = .Diff })) return diff_view_tail; 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; + }; + const speaks = if (pane.file) |file| file.output == null and file.mini == null and pardes.lsp.speaks(file.path) else false; + if (panes.File.supportsContext(pane)) return if (speaks) lsp_context_pane_tail else context_pane_tail; + if (pane.file != null) return if (speaks) lsp_pane_tail else file_pane_tail; if (pane.command != null) return command_pane_tail; if (pane.isTerminal()) return if (pane.shell_tail_len > 0) pane.shell_tail[0..pane.shell_tail_len] else terminal_pane_tail; return pane_tail; @@ -468,4 +484,3 @@ test "a pane tag wraps a long line onto rows, and offsets map both ways" { try std.testing.expectEqual(@as(usize, 10), shown.toReal(11)); // the 'e' of Del try std.testing.expectEqual(@as(usize, 11), shown.fromReal(10)); } - diff --git a/src/terminal.zig b/src/terminal.zig index 3bb1fbda..33ad22e6 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 @@ -1330,7 +1347,7 @@ pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { 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; + const selected = pane.rawPointerText(pane.sel[@backingInt(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); @@ -2041,7 +2058,7 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16 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); + filtered_storage = FilteredColors.init(p, &pane.terminal.?.vt); break :blk &filtered_storage; } else null; // DECSCNM, read once: the filtered palette folds it in itself, the raw @@ -2192,7 +2209,9 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor return cs; } -const FilteredColors = struct { +/// A program's colours mapped to the theme (Filter): a terminal's cells, or +/// a +Pager's spans (`vt` null, the program's palette xterm's own). +pub const FilteredColors = if (enabled) struct { source: GColor.Palette, target: *const GColor.Palette, theme_bg: GColor.RGB, @@ -2212,16 +2231,18 @@ const FilteredColors = struct { cache_key: [256]u8 = undefined, cache_valid: [256]bool = @splat(false), - fn init(p: *Pardes, pane: *const Pane) FilteredColors { + pub fn init(p: *Pardes, vt: ?*const ghostty_vt.Terminal) FilteredColors { var source = GColor.default; - for (&source, 0..) |*rgb, i| - rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + if (vt) |t| { + for (&source, 0..) |*rgb, i| + rgb.* = t.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)) { + var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null; + var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null; + if (vt != null and vt.?.modes.get(.reverse_colors)) { std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); } @@ -2280,6 +2301,18 @@ const FilteredColors = struct { return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); } + /// A +Pager span's colour (pager.zig), as `fg` and `bg` map a cell's. + pub fn spanColor(self: *FilteredColors, color: pardes.Color, is_bg: bool) pardes.Color { + return switch (color) { + .default => color, + .index => |idx| if (is_bg) self.bg_for_palette[idx] else self.fg_for_palette[idx], + .rgb => |rgb| blk: { + const keyed = self.keyedRgb(asGhostRgb(rgb)); + break :blk asPardesColor(if (is_bg) keyed else self.legible(keyed)); + }, + }; + } + 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; @@ -2317,7 +2350,7 @@ const FilteredColors = struct { self.cache_valid[slot] = true; return best; } -}; +} else struct {}; const channel_luminance: [256]f64 = blk: { @setEvalBranchQuota(20000); @@ -2570,7 +2603,7 @@ test "terminal Filter maps the default roles before it maps anything else" { // 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); + const stage_one = FilteredColors.init(p, &pane.terminal.?.vt); // `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(); @@ -2584,7 +2617,7 @@ test "terminal Filter maps the default roles before it maps anything else" { p.settings.theme = 0; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, pane); + var moved = FilteredColors.init(p, &pane.terminal.?.vt); 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 }))); } @@ -2609,7 +2642,7 @@ test "terminal Filter refuses a foreground that would collapse onto the page" { for (0..9) |t| { p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); + var fc = FilteredColors.init(p, &pane.terminal.?.vt); const page = asPardesColor(fc.default_bg); const rescued = asPardesColor(fc.fallback_fg); _ = frame.reset(.retain_capacity); @@ -2661,7 +2694,7 @@ test "terminal Filter holds every projected foreground off the page" { for (0..9) |t| { p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); + var fc = FilteredColors.init(p, &pane.terminal.?.vt); var refused: usize = 0; for (fc.target, 0..) |projected, key| { const ink = fc.legible(projected); @@ -2797,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); @@ -2952,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..4cd1bc9a 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 { @@ -1737,7 +1737,7 @@ const Shell = struct { }; for (&s.ptys, 0..) |*slot, id| if (slot.*) |pt| { var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(pt.pid, &lbuf)) |cwd| s.core.setCwd(id, cwd); + if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(id, cwd); }; if (s.caps_pending and s.vx.queries_done.load(.unordered)) { @@ -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/src/tutor.txt b/src/tutor.txt index 0f3e3359..083a5028 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -30,8 +30,8 @@ Esc again. 3. Press Alt-n: a terminal opens, in NORMAL mode, and pardes types ls at its first prompt. Press Ctrl-b: its box shows $ (RAW), and - keys go to the shell. At its empty prompt, Esc brings you back - here; the terminal stays $. + keys go to the shell. Esc brings you back here; the terminal stays + $. Shift-Esc sends the shell an Esc. -> Guide: Modes @@ -84,7 +84,8 @@ shows its output, and the keyboard stays here. 2. `Exec` `New` in this column's tag: a scratch opens and takes the keyboard. - 3. Ctrl-w h, j, k, l move the keyboard between panes; Ctrl-o and + 3. Ctrl-w shows a letter on every pane: h, j, k, l move the outline + and Enter goes there, or press a pane's letter. Ctrl-o and Ctrl-i walk back and forward through where you have been. Ctrl-i needs the kitty keyboard protocol or the GUI; elsewhere it is Tab, so use SPC j i (and SPC j o), or the mouse's side buttons. @@ -101,8 +102,7 @@ 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. n moves into it and walks its rows; Enter on a row goes - to that line here. + keys and the cursor goes to the first. n and N select search matches. -> Guide: Look @@ -261,7 +261,8 @@ typed | filter every selection through the shell / case-insensitive SUBSTRING search, one hit a line; the regex lives on s and S - n / N the next/previous text `Look` would open, as above + n / N next/previous search match (Helix); v adds matches + SPC j n/p `LookNext`/`LookPrev`: select locations; Enter opens Ctrl-c comment or uncomment the lines VIEWPORT @@ -287,7 +288,7 @@ typed SPC d `Del` SPC q `Exit` SPC f s `Save` SPC f f `Find` SPC f n `New` SPC y yank to the clipboard SPC p paste from it - SPC w h focus left (and j, k, l) + SPC w window mode: h/j/k/l, Enter SPC j j `Last` SPC j o / SPC j i back / forward SPC s a `Attach` SPC s D `Detach` SPC t ... the toggles SPC l ... the language @@ -332,7 +333,7 @@ typed 2-1 `Exec` the middle word with the left selection keyboard: Enter = `Look`, Tab = `Exec` - PANES Ctrl-w h/j/k/l focus a neighbour (NORMAL mode) + PANES Ctrl-w h/j/k/l pick a pane, Enter (NORMAL mode) Ctrl-o / Ctrl-i jump history back / forward (SPC j o / SPC j i where Ctrl-i is Tab) Alt-n new terminal Alt-c pane into a new column @@ -347,7 +348,7 @@ typed SPC is the leader (SPC ? is `Help`) vs HELIX selection is LINE-first (x), v for characters; / is a - substring search; n/N walk what `Look` would open. + substring search; n/N repeat it in the current text. 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/src/web.zig b/src/web.zig index fed2ba5a..f89aa7e9 100644 --- a/src/web.zig +++ b/src/web.zig @@ -258,18 +258,20 @@ fn mouseWithHit(button_arg: u32, kind_arg: u32, col_arg: u32, row_arg: u32, mods 3 => .drag, else => return, }; - s.core.update(.{ .mouse = .{ - .body_hit = hit, - .tag_hit = tag_hit, - .button = button, - .kind = kind, - .col = @intCast(@min(col_arg, std.math.maxInt(u16))), - .row = @intCast(@min(row_arg, std.math.maxInt(u16))), - .ctrl = mods & 1 != 0, - // Alt-click is B2 and Cmd/Super-click B3 (mouse.emulateButton). - .alt = mods & 2 != 0, - .super = mods & 8 != 0, - } }); + s.core.update(.{ + .mouse = .{ + .body_hit = hit, + .tag_hit = tag_hit, + .button = button, + .kind = kind, + .col = @intCast(@min(col_arg, std.math.maxInt(u16))), + .row = @intCast(@min(row_arg, std.math.maxInt(u16))), + .ctrl = mods & 1 != 0, + // Alt-click is B2 and Cmd/Super-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, + }, + }); } export fn pardes_touch_scroll(delta: f32) void { @@ -347,7 +349,7 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { if (layer.rows == 0) return 0; return switch (field) { 0 => layer.cols, - 1 => @intFromEnum(layer.kind), + 1 => @backingInt(layer.kind), 2 => layer.id, 3 => layer.serial, 4 => layer.viewport.x, @@ -421,7 +423,7 @@ export fn pardes_row_metrics(body_w: u16, body_h: u16, tagline_w: u16, tagline_h export fn pardes_pointer_shape() u32 { const s = &(state orelse return 0); - return @intFromEnum(s.core.surface.pointer_shape); + return @backingInt(s.core.surface.pointer_shape); } export fn pardes_cursor_y() i32 { @@ -557,6 +559,6 @@ fn encodeAttrs(style: pardes.CellStyle) u16 { attrs |= @as(u16, @intFromBool(style.invisible)) << 5; attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; attrs |= @as(u16, @intFromBool(style.font_role == .tagline)) * attr_tagline; - attrs |= @as(u16, @intFromEnum(style.ul)) << 8; + attrs |= @as(u16, @backingInt(style.ul)) << 8; return attrs; } |
