From b1fb4242c0ab52767df1b8e155edcf2692f37873 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 23 Nov 2026 18:00:35 -0300 Subject: scroll: a view's top is a line and a row within that line's own wrapped rows, and a scroll moves it by rows (P62, round 3, on the layer's new model where the `Changes` layer's lines are lines of the buffer): a wheel's notch, the glide, PageDown/PageUp, zj/zk, Ctrl-d/u, zt/zz/zb and the margin (`scroll_off` now ROWS) go a row at a time through a line wrapped over many rows and through a long description line of the layer, where the base jumped all of a wrapped line's rows at once (the user, 2026-11-23: "the scroll view jumps around near deleted lines on the diff view"; one-row deleted lines were cured by the layer's second step, a wrapped one was not): TESTS FIRST: core/jj.zig "a view scrolls by rows through a line wrapped over 12 rows and a change's description wrapped over several (a line of the layer): ..." (a notch is one row down the whole text and back, the notches the text's rows exactly; PageDown/PageUp a page of rows; zj/zk one; a held j and k keep the cursor's row `scroll_off` rows inside the body) failing on the base at notch 21 (line 20's 12 rows crossed at once), and "a client wheels its session's view a row a notch into a change's description wrapped over several rows ..., agreeing at every notch; a client joined over that view loads its row"; kept from round 1: core/replica.zig's join over a view scrolled into a wrapped line (with a rollback and a dump) and the explorer of a view's rows (30 seeds), dev/gui's glide a row a notch; THE CHANGE, taken from pardes-row-scroll (`xrxmqlnw`) and -2 (`xxzmwnvq`) without their ghost-row "blocks" (a block is now just a line's own rows): `File.State.scroll_row` and `views.PaneView.scroll_row` in the generic walk (digested, dumped, copied; a dump of 34 loads at its lines' first rows), the wire 35; core/File.zig `Top`, `rowIn`/`rowWalked` (a line's rows as fillBody wraps them, `guideOf` shared), `rowOf`, `lineRows`, `top`/`setTop`, `walkRows`/`walkKnown`, `rowsTo`, `rowsOf` (off the map where it holds the line), `mapFresh`, `scrollRows`, `shownRows` (the geometry laid out first), `show` (a cursor's or a result's row inside the band, the line's rows whole when they fit), `textRowLine`, fillBody's skip to the top's row walked once a geometry (`Pane.top_skip`, derived), the geometry's key with `scroll_row` and stored as what the map was made from; the one-row fact `State.widest` (`Widest`, an upper bound kept by the index's own vector passes `countLines`/`fillLines`) so a view whose lines are each one row walks nothing (`oneRow`: line arithmetic, checked against the walk in Debug); `fitEnd` a vector of printable ASCII at a time; the callers in rows: panes.zig `scrollBy(tab, delta)` and `ensureCursorVisible` (a file's through `File.show`), the wheel and the rail and the edge scroll (mouse.zig), Ctrl-d/u (normal.zig `halfPageMove`), zt/zz/zb, Ctrl-f/b and PgUp/PgDn (Text.zig `scrollViewMove`), Look's reveal and centring, Places' `goTo`/`restore`, Query's `showCurrent`/`caretTo`, the frames' `Region.row` and the glide (dev/glide.zig, the window's `topOf`); test/perf.zig's checks by (line, row) and its seek at a line's first row; Debug in the workspace: core-test 963/1129 (166 skipped), shell-test 1172/1175 (3 skipped) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wire.zig | 5 +- core/Core.zig | 6 +- core/File.zig | 503 ++++++++++++++++++++++++++++++++++++++++++++++---- core/Output.zig | 1 + core/Places.zig | 11 +- core/Query.zig | 40 ++-- core/Text.zig | 11 +- core/draw.zig | 3 +- core/jj.zig | 173 +++++++++++++++++ core/look.zig | 18 +- core/mouse.zig | 14 +- core/ninep/events.zig | 4 +- core/normal.zig | 52 +++++- core/panes.zig | 62 ++----- core/replica.zig | 154 ++++++++++++++++ core/rollback.zig | 3 +- core/root.zig | 4 +- core/surface.zig | 4 +- core/views.zig | 17 +- dev/glide.zig | 43 +++-- dev/gui/gui.zig | 60 ++++-- test/daemon.py | 2 +- test/kitty.zig | 2 +- test/panes.zig | 28 +-- test/perf.zig | 14 +- test/terminal.zig | 2 +- 26 files changed, 1030 insertions(+), 206 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index ea5998e6..f558cb9a 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,9 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 35: a view's top is a line and a row of that line's wrapped rows: a +/// file's `scroll_row` (and its share's in each view) in the dump and the +/// digest; a dump without it loads at its lines' first rows; /// 34: the `Changes` layer's lines are the pane's buffer's while it is /// shown: a file pane's `read_only` places and `layer` in the dump and the /// digest, its buffer dumped whole while it has them (a clean file's text @@ -73,7 +76,7 @@ const build_info = @import("build_info"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 34; +pub const version: u16 = 35; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Core.zig b/core/Core.zig index 4c8aa2eb..1894247d 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -3871,11 +3871,11 @@ test "raw terminal cursor follows its active row only while that row is visible" try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x); try std.testing.expectEqual(body_y + 2, live.y); - pane.scrollBy(-1); + pane.scrollBy(p.settings.tab, -1); const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, scrolled.x); try std.testing.expectEqual(live.y + 1, scrolled.y); - pane.scrollBy(-@as(i32, pane.rows)); + pane.scrollBy(p.settings.tab, -@as(i32, pane.rows)); try std.testing.expect((try p.render(frame.allocator())).cursor == null); pane.followOutput(); const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; @@ -3929,7 +3929,7 @@ test "tty output follows only from the bottom" { try std.testing.expect(bottom > 0); // Scrolled back, the reader stays put however much the shell prints. - sp.scrollBy(-10); + sp.scrollBy(p.settings.tab, -10); p.sync(); const parked = sp.termTop(); try std.testing.expect(parked < bottom); diff --git a/core/File.zig b/core/File.zig index b2df6c0f..86861792 100644 --- a/core/File.zig +++ b/core/File.zig @@ -98,7 +98,7 @@ pub const State = struct { /// from the text whenever it is wanted. // Syntax caches must not load through the dump loader's core allocator. pub const replica = .{ - .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" }, + .derived = .{ "cap", "line_starts", "line_cap", "widest", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" }, // Big texts, dumped and sent by their hash (core/walk.zig). The // text is written in place by `replace`, but never while a join // sends it (memory.zig `pin`): then an edit puts a new buffer in @@ -160,11 +160,18 @@ pub const State = struct { /// A directory pane's entries (Dir.zig), its output `.dir`. listing: ?panes.Dir.State = null, mini: ?Mini.State = null, + /// The view's top: the line its first row is of, and that row of the + /// line's wrapped rows (`Top`): each view's own (views.zig), digested, + /// dumped. scroll: usize = 0, + scroll_row: u32 = 0, /// `line_starts[i]` is line i's byte offset. Empty means not built yet. line_starts: []usize = &.{}, /// The room `line_starts` has, as `cap` is `content`'s. line_cap: usize = 0, + /// The widest any line is, found with the index and kept with it + /// (`Widest`): what tells a view whose rows are its lines (`oneRow`). + widest: Widest = .{}, /// One tree_sitter_gpa-owned syntax.Syn byte per highlighted source byte. highlights: []u8 = &.{}, location_rows: []locations.Row = &.{}, @@ -605,6 +612,16 @@ pub fn renderedLineDisplayCol(tab: u16, pane: *const Pane, row: i32, line_text: pub fn fitEnd(tab: u16, text: []const u8, start: usize, width: usize) usize { var end = start; var used: usize = 0; + // A vector of printable ASCII at a time, a cell a byte, while the width + // is past it and the byte after it is ASCII too: what the loop below + // takes a byte at a time (it leaves the ASCII byte a non-ASCII one + // follows to the grapheme walk). Every row walk is this loop. + while (used + lanes < width and end + lanes < text.len and text[end + lanes] < 0x80) { + const v: Lanes = text[end..][0..lanes].*; + if (@reduce(.Or, v -% @as(Lanes, @splat(0x20)) >= @as(Lanes, @splat(0x5f)))) break; + used += lanes; + end += lanes; + } while (used < width and end < text.len) { const b = text[end]; if (b < 0x20 or b >= 0x7f) break; @@ -629,20 +646,91 @@ pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { if (f.line_starts.len > 0) return f.line_starts; // Exact allocation: deinitPane frees `line_starts` itself, so the stored // slice must span the complete allocation rather than spare capacity. - const starts = try gpa.alloc(usize, lineCount(f.content)); + const found = countLines(f.content); + const starts = try gpa.alloc(usize, found.newlines + 1); starts[0] = 0; - var i: usize = 1; - var off: usize = 0; - while (std.mem.indexOfScalarPos(u8, f.content, off, '\n')) |nl| { - off = nl + 1; - starts[i] = off; - i += 1; - } + f.widest = .{ .bytes = fillLines(f.content, 0, starts[1..]), .tabbed = found.tabbed }; f.line_starts = starts; f.line_cap = 0; return starts; } +/// The widest a text's lines are, at most: the most bytes between two +/// newlines, and whether a tab is among them. A tab is `tab` cells, any +/// other byte at most one (graphemeDisplayWidth), so a line is never +/// wider than its bytes, times the tab width where a tab may be. Made +/// with the line index and kept by its edits, only ever made wider: an +/// edit taking the widest line away leaves it so (`oneRow` then walks, +/// and finds the same rows). +pub const Widest = struct { + bytes: usize = 0, + tabbed: bool = false, + + fn cells(w: Widest, tab: u16) usize { + return if (w.tabbed) w.bytes *| @max(tab, 1) else w.bytes; + } +}; + +const lanes = std.simd.suggestVectorLength(u8) orelse 16; +const Lanes = @Vector(lanes, u8); + +/// The newlines in `bytes` and whether a tab is among them: a lane's own +/// sum a vector, added up every 255 (std.mem.count's popcount of a mask is +/// a dozen instructions a vector on a baseline x86-64). +fn countLines(bytes: []const u8) struct { newlines: usize, tabbed: bool } { + const one: Lanes = @splat(1); + const zero: Lanes = @splat(0); + var newlines: usize = 0; + var tabs = zero; + var i: usize = 0; + while (bytes.len - i >= lanes) { + var sums = zero; + for (0..@min((bytes.len - i) / lanes, 255)) |_| { + const v: Lanes = bytes[i..][0..lanes].*; + sums += @select(u8, v == @as(Lanes, @splat('\n')), one, zero); + tabs |= @select(u8, v == @as(Lanes, @splat('\t')), one, zero); + i += lanes; + } + newlines += @reduce(.Add, @as(@Vector(lanes, u16), sums)); + } + var tabbed = @reduce(.Or, tabs) != 0; + for (bytes[i..]) |b| { + newlines += @intFromBool(b == '\n'); + tabbed = tabbed or b == '\t'; + } + return .{ .newlines = newlines, .tabbed = tabbed }; +} + +/// The start after each newline of `bytes` (its byte `off` past it) into +/// `out`, a vector at a time, a newline's place off its mask (a search for +/// each cost a short line ~57 instructions); and the most bytes of `bytes` +/// between two newlines or an end. +fn fillLines(bytes: []const u8, off: usize, out: []usize) usize { + const Mask = @Int(.unsigned, lanes); + var n: usize = 0; + var from: usize = 0; + var widest: usize = 0; + var i: usize = 0; + while (i + lanes <= bytes.len) : (i += lanes) { + const v: Lanes = bytes[i..][0..lanes].*; + var nl: Mask = @bitCast(v == @as(Lanes, @splat('\n'))); + while (nl != 0) : (nl &= nl - 1) { + const at = i + @ctz(nl); + widest = @max(widest, at - from); + from = at + 1; + out[n] = off + from; + n += 1; + } + } + for (bytes[i..], i..) |b, at| if (b == '\n') { + widest = @max(widest, at - from); + from = at + 1; + out[n] = off + from; + n += 1; + }; + return @max(widest, bytes.len - from); +} + /// The whole buffer of a text's bytes, its room past them included. fn textRoom(f: *const State) []u8 { return f.content.ptr[0..@max(f.cap, f.content.len)]; @@ -668,7 +756,10 @@ pub const Span = struct { head: usize, tail: usize }; fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes: []const u8) void { const starts = f.line_starts; const room = indexRoom(f); - const n = starts.len - (std.sort.upperBound(usize, starts, off + len, ascending) - std.sort.upperBound(usize, starts, off, ascending)) + std.mem.count(u8, bytes, "\n"); + const first = std.sort.upperBound(usize, starts, off, ascending); + const found = countLines(bytes); + const added = found.newlines; + const n = starts.len - (std.sort.upperBound(usize, starts, off + len, ascending) - first) + added; var out = room; if (n > room.len) { out = gpa.alloc(usize, n + @max(n / 8, 512)) catch { @@ -679,10 +770,17 @@ fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes: }; @memcpy(out[0..starts.len], starts); } else pardes.rollback.Epoch.wrote(gpa, usize, room, starts.len, n, off, f.content[off..][0..len], bytes.len); - shiftStarts(out, starts.len, n, off, len, bytes); + const inside = shiftStarts(out, starts.len, n, off, len, bytes); if (out.ptr != room.ptr) pardes.memory.freeRaw(gpa, room); f.line_starts = out[0..n]; f.line_cap = out.len; + // The widest: what the edit put in, and the two lines it joined at + // its ends (the line `off` is on, the one its last newline starts). + const total = f.content.len - len + bytes.len; + const ends = [2]usize{ first - 1, first - 1 + added }; + var widest = @max(f.widest.bytes, inside); + for (ends) |l| widest = @max(widest, (if (l + 1 < n) f.line_starts[l + 1] - 1 else total) - f.line_starts[l]); + f.widest = .{ .bytes = widest, .tabbed = f.widest.tabbed or found.tabbed }; } /// The first `len` of `room`, a line index, through the edit that puts @@ -692,7 +790,8 @@ fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes: /// only the moving is a pass over the index, and only from the edit on. The /// edit turned round (`cut` its length in, `bytes` what it took out) gives /// the index before it back: a rollback's (core/rollback.zig `unwrite`). -pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, bytes: []const u8) void { +/// The most bytes of `bytes` between two newlines or an end (fillLines). +pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, bytes: []const u8) usize { const starts = room[0..len]; const kept = std.sort.upperBound(usize, starts, off, ascending); const moved = len - std.sort.upperBound(usize, starts, off + cut, ascending); @@ -709,13 +808,7 @@ pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, } else for (0..moved) |k| { room[to + k] = room[from + k] - cut + bytes.len; } - var i = kept; - var at: usize = 0; - while (std.mem.indexOfScalarPos(u8, bytes, at, '\n')) |nl| { - at = nl + 1; - room[i] = off + at; - i += 1; - } + return fillLines(bytes, off, room[kept..]); } /// line count, O(1) once the index is warm @@ -982,9 +1075,9 @@ pub fn relayer(p: *Pardes, f: *State, new: []u8, spans: []ReadOnly, layer: u32) // selection's anchor and ranges in the live view, a cursor and a top // line in the others. const Place = struct { row: *i32, col: *i32, at: usize }; - const Top = struct { line: *usize, at: usize }; + const Kept = struct { line: *usize, at: usize }; var places: std.ArrayList(Place) = .empty; - var tops: std.ArrayList(Top) = .empty; + var tops: std.ArrayList(Kept) = .empty; const At = struct { fn of(q: *Pardes, g: *State, row: i32, col: i32) usize { const r: usize = @intCast(@max(0, row)); @@ -1031,7 +1124,7 @@ pub fn relayer(p: *Pardes, f: *State, new: []u8, spans: []ReadOnly, layer: u32) place.row.* = @intCast(pos.row); place.col.* = @intCast(pos.col); } - for (tops.items) |top| top.line.* = positionIn(p.gpa, f, bufferOffset(f, top.at, false)).row; + for (tops.items) |kept| kept.line.* = positionIn(p.gpa, f, bufferOffset(f, kept.at, false)).row; return true; } @@ -1222,6 +1315,7 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who tf.cap = f.cap; tf.line_starts = f.line_starts; tf.line_cap = f.line_cap; + tf.widest = f.widest; if (!told and tf.context.revision == f.revision -% 1) tf.context.revision = f.revision; // Its copy of the read-only lines, moved as this one's were (the // layer's own edit sets them after, jj.showLayer). @@ -1409,6 +1503,7 @@ pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane { .cap = f.cap, .line_starts = f.line_starts, .line_cap = f.line_cap, + .widest = f.widest, .history = f.history, .revision = f.revision, .saved_revision = f.saved_revision, @@ -1419,6 +1514,7 @@ pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane { .on_disk = f.on_disk, .mtime = f.mtime, .scroll = f.scroll, + .scroll_row = f.scroll_row, .tree_context = f.tree_context, .twin = f.twin, }; @@ -1650,11 +1746,309 @@ fn pageEnd(tab: u16, pane: *Pane) usize { } fn setPageScroll(pane: *Pane, line: usize) void { + setTop(pane, .{ .line = @min(line, nlines(pane.gpa, &pane.file.?) -| 1) }); +} + +/// A view's top: the line its first row is of (`State.scroll`) and that +/// row of the line's rows as wrapped (`State.scroll_row`; one row +/// unwrapped). A scroll moves it by rows through the lines. +pub const Top = struct { line: usize, row: u32 = 0 }; + +/// The row of line `line` that shows its byte `col` (a line's last row +/// every byte past its start, as wrapRow has it), as fillBody wraps it. +pub fn rowOf(tab: u16, pane: *const Pane, line: usize, col: usize) u32 { + return rowIn(tab, pane, line, col).row; +} + +/// The rows line `line` takes in `pane`'s view. +pub fn lineRows(tab: u16, pane: *const Pane, line: usize) u32 { + return rowIn(tab, pane, line, std.math.maxInt(usize)).rows; +} + +/// Whether every line of `pane`'s view is one row: none wider than a row +/// (the text's widest, kept with its index), so its rows are its lines and +/// the walks below are line arithmetic, nothing read. +fn oneRow(tab: u16, pane: *const Pane) bool { + const width = wrapWidth(pane, pane.view.wrap); const f = &pane.file.?; - const to = @min(line, nlines(pane.gpa, f) -| 1); - if (to == f.scroll) return; - f.scroll = to; - f.syntax_dirty = true; + return width == 0 or (f.line_starts.len > 0 and f.widest.cells(tab) <= width); +} + +const RowIn = struct { row: u32, rows: u32 }; + +/// rowOf's row and lineRows' rows, in one walk of the line: the one walk +/// of a line's rows every map from rows to lines asks, beside the +/// geometry's own map of the body (the same `fitEnd` at the same width). +fn rowIn(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn { + if (pane.file != null and oneRow(tab, pane)) { + if (builtin.mode == .debug) std.debug.assert(rowWalked(tab, pane, line, col).rows == 1); + return .{ .row = 0, .rows = 1 }; + } + return rowWalked(tab, pane, line, col); +} + +fn rowWalked(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn { + const f = if (pane.file) |*file| file else return .{ .row = 0, .rows = 1 }; + const width = wrapWidth(pane, pane.view.wrap); + if (width == 0) return .{ .row = 0, .rows = 1 }; + const text = sourceLine(pane, @intCast(line)); + // No more bytes than a row has cells and no tab is one row: a tab is + // `tab` cells, any other byte at most one (Widest); no grapheme walked + // (the lines a page or a margin crosses, nearly all of a source's). + if (text.len <= width and std.mem.indexOfScalar(u8, text, '\t') == null) { + if (builtin.mode == .debug) std.debug.assert(fitEnd(tab, text, 0, width) >= text.len); + return .{ .row = 0, .rows = 1 }; + } + var guide: [1024]u8 = undefined; + var at: usize = 0; + var row: u32 = 0; + var found: ?u32 = null; + while (true) { + const end = fitEnd(tab, text, at, width - displayWidth(tab, guideOf(f, text, at, width, &guide))); + if (found == null and col < end) found = row; + if (end >= text.len or end <= at) return .{ .row = found orelse row, .rows = row + 1 }; + at = end; + row += 1; + } +} + +/// Where `pane`'s view starts: a row past its line's last (the text +/// rewrapped, an edit, the layer's lines come or gone) is read as its +/// last, as the geometry's walk found it (no walk of the line a frame). +pub fn top(tab: u16, pane: *Pane) Top { + const f = &pane.file.?; + if (f.scroll_row == 0) return .{ .line = f.scroll }; + geometry(tab, pane); + return .{ .line = f.scroll, .row = pane.top_skip.row }; +} + +pub fn setTop(pane: *Pane, to: Top) void { + const f = &pane.file.?; + if (to.line != f.scroll) f.syntax_dirty = true; + f.scroll = to.line; + f.scroll_row = to.row; +} + +/// The place `n` rows below `from` (above it, `n` negative) through the +/// lines' rows, held at the text's first row and at its last line's last; +/// and the rows it moved. +pub fn walkRows(tab: u16, pane: *Pane, from: Top, n: i64) Walked { + return walkKnown(tab, pane, from, n, null); +} + +/// A line's rows its caller has walked already (show's, the cursor's +/// line): a walk reads them, not the line again. +const Known = struct { line: usize, rows: u32 }; + +const Walked = struct { to: Top, moved: i64 }; + +fn walkKnown(tab: u16, pane: *Pane, from: Top, n: i64, known: ?Known) Walked { + const last = nlines(pane.gpa, &pane.file.?) -| 1; + if (!oneRow(tab, pane)) return walkedRows(tab, pane, from, n, last, known); + const to = if (n < 0) from.line -| @abs(n) else if (from.line >= last) from.line else @min(from.line +| @abs(n), last); + const w: Walked = .{ .to = .{ .line = to }, .moved = @as(i64, @intCast(to)) - @as(i64, @intCast(from.line)) }; + if (builtin.mode == .debug) std.debug.assert(std.meta.eql(w, walkedRows(tab, pane, from, n, last, known))); + return w; +} + +fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Known) Walked { + const map = mapFresh(pane); + var t = from; + var rows = rowsOf(tab, pane, map, known, t.line); + t.row = @min(t.row, rows - 1); + var left = n; + while (left > 0) { + const room = rows - 1 - t.row; + if (left <= room) { + t.row += @intCast(left); + left = 0; + } else if (t.line >= last) { + left -= room; + t.row = rows - 1; + break; + } else { + left -= room + 1; + t.line += 1; + t.row = 0; + rows = rowsOf(tab, pane, map, known, t.line); + } + } + while (left < 0) { + if (-left <= t.row) { + t.row -= @intCast(-left); + left = 0; + } else if (t.line == 0) { + left += t.row; + t.row = 0; + break; + } else { + left += t.row + 1; + t.line -= 1; + rows = rowsOf(tab, pane, map, known, t.line); + t.row = rows - 1; + } + } + return .{ .to = t, .moved = n - left }; +} + +/// The rows from `from` down to line `line`'s first row (up to it, +/// negative), or null when it is more than `bound` rows away. +pub fn rowsTo(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 { + if (!oneRow(tab, pane)) return rowsWalked(tab, pane, from, line, bound); + const d = @as(i64, @intCast(line)) - @as(i64, @intCast(from.line)) - from.row; + const to: ?i64 = if ((line > from.line and d > bound) or (line < from.line and -d > bound)) null else d; + if (builtin.mode == .debug) std.debug.assert(std.meta.eql(to, rowsWalked(tab, pane, from, line, bound))); + return to; +} + +fn rowsWalked(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 { + const map = mapFresh(pane); + var d: i64 = -@as(i64, from.row); + var l = from.line; + while (l < line) : (l += 1) { + d += rowsOf(tab, pane, map, null, l); + if (d > bound) return null; + } + while (l > line) { + l -= 1; + d -= rowsOf(tab, pane, map, null, l); + if (-d > bound) return null; + } + return d; +} + +/// Whether `pane`'s map (the geometry) is of the view as it is now: only +/// then may a walk read a line's rows off it (derived state, made by +/// whoever asked first). +fn mapFresh(pane: *const Pane) bool { + return pane.wrap_n > 0 and pane.geometry_key == geometryKey(pane, &pane.file.?); +} + +/// The rows line `line` takes: counted off the map when the map is fresh +/// and holds all of them in the body (no line walked: a page, a cursor +/// past the body's edge), else walked (lineRows). +fn rowsOf(tab: u16, pane: *const Pane, map: bool, known: ?Known, line: usize) u32 { + if (known) |k| if (k.line == line) return k.rows; + if (map and pane.wrap_n > pane.context_rows and line >= pane.wrap_line[pane.context_rows] and line <= pane.wrap_line[pane.wrap_n - 1]) { + const f = &pane.file.?; + var rows: u32 = 0; + var i: usize = pane.context_rows; + while (i < pane.wrap_n) : (i += 1) { + if (pane.wrap_line[i] == line) { + // Rows of it above the top are not in the map. + if (rows == 0 and i == pane.context_rows and line == f.scroll and pane.top_skip.row > 0) break; + rows += 1; + } else if (rows > 0) return rows; + } + } + return lineRows(tab, pane, line); +} + +/// `pane`'s view moved `delta` rows (a wheel's notch is one): the rows it +/// moved. +pub fn scrollRows(tab: u16, pane: *Pane, delta: i64) i64 { + geometry(tab, pane); + const t = top(tab, pane); + // Down to a row the body shows: the map has it, its line and its row in + // that line, no line walked (a notch, a page). + const i = @as(i64, pane.context_rows) + delta; + if (delta > 0 and pane.wrap_n > 0 and i < shownRows(tab, pane) + @as(i64, pane.context_rows)) { + const k: usize = @intCast(i); + const line: usize = @intCast(pane.wrap_line[k]); + if (line < nlines(pane.gpa, &pane.file.?)) { + var row: u32 = if (line == t.line) t.row else 0; + for (pane.wrap_line[pane.context_rows..k]) |l| row += @intFromBool(l == pane.wrap_line[k]); + setTop(pane, .{ .line = line, .row = row }); + return delta; + } + } + const w = walkRows(tab, pane, t, delta); + setTop(pane, w.to); + return w.moved; +} + +/// The rows of `pane`'s body under its context rows, of its geometry as +/// the view is now (made again first if stale: a key's step reads it +/// before any draw, and only the state it is made of may decide it). +pub fn shownRows(tab: u16, pane: *Pane) u16 { + geometry(tab, pane); + const visible = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n; + return @max(1, if (pane.wrap_n == 0) pane.rows else visible -| pane.context_rows); +} + +/// The view moved when line `line_at`'s row that shows its byte `col` is +/// out of the body's margins (`margin_rows` rows, helix's scrolloff, at +/// most half of it): by the rows that show the line's rows whole inside +/// them, or that row where the line is taller than they leave. A cursor's +/// (Pane.ensureCursorVisible's, for a file) or a result's. +pub fn show(tab: u16, pane: *Pane, line_at: i32, col: i32, margin_rows: i64) void { + const f = &pane.file.?; + geometry(tab, pane); + const t = top(tab, pane); + // The line held at the top (a sticky context row): as it is. + if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == t.line) { + for (pane.wrap_line[0..pane.context_rows]) |row| if (row == line_at) return; + } + const body: i64 = shownRows(tab, pane); + const margin: i64 = @min(margin_rows, @divTrunc(body - 1, 2)); + // The row in the body (the map's, made just now), or none: the line is + // above the top, or below the map. Inside the band the view stays, and + // no line is walked (a key's step, nearly always). + const mapped: i64 = pane.wrapRow(tab, line_at, col).row - @as(i64, pane.context_rows); + const row: ?i64 = if (mapped >= 0 and mapped < @max(pane.wrap_n, pane.rows) -| pane.context_rows) mapped else null; + if (row) |r| if (r >= margin and r <= body - 1 - margin) return; + const line: usize = @intCast(@max(0, line_at)); + const at = rowIn(tab, pane, line, @intCast(@max(0, col))); + const known: Known = .{ .line = line, .rows = at.rows }; + if (pane.follow_edges != 0 and (row == null or row.? < 0 or row.? >= body)) pane.follow_crossed = true; + const whole = at.rows <= body - 2 * margin; + if (if (row) |r| r < margin else line <= t.line) { + if (pane.follow_edges & 1 != 0) return; + setTop(pane, walkKnown(tab, pane, .{ .line = line, .row = if (whole) 0 else at.row }, -margin, known).to); + } else if (if (row) |r| r > body - 1 - margin else true) { + if (pane.follow_edges & 2 != 0) return; + // The margin only reveals text: a pane its whole text fits in + // never scrolls for it; a longer one keeps helix's clamp at the + // text's last line. + var past = walkKnown(tab, pane, .{ .line = line, .row = if (whole) at.rows - 1 else at.row }, margin, known).to; + if (t.line == 0 and t.row == 0 and pane.textFits()) { + const stop = @max(line, nlines(pane.gpa, f) -| 1 -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))); + if (past.line > stop) past = .{ .line = stop, .row = lineRows(tab, pane, stop) - 1 }; + } + setTop(pane, walkKnown(tab, pane, past, -(body - 1), known).to); + } +} + +/// The line whose first row (no wrapped line's later row) is nearest body +/// row `from` inside the body's band (`margin` rows in from each edge, at +/// most half of it, under its context rows): the first at or below it +/// going `.down`, else the last above it; `.up` the other way round. Where +/// a view key leaves a cursor (Text.scrollViewMove, normal.halfPageMove); +/// null when the band has none (inside a line taller than the body): the +/// cursor stays. +pub fn textRowLine(tab: u16, pane: *Pane, from: i64, margin: i64, way: enum { down, up }) ?i32 { + geometry(tab, pane); + const lines: i32 = @intCast(nlines(pane.gpa, &pane.file.?)); + const held: i64 = pane.context_rows; + const shown: i64 = shownRows(tab, pane); + const m = @min(margin, @divTrunc(shown - 1, 2)); + const lo = held + m; + const hi = held + shown - 1 - m; + for ([2]i64{ if (way == .down) 1 else -1, if (way == .down) -1 else 1 }) |step| { + var vr = std.math.clamp(held + from, lo, hi); + while (vr >= lo and vr <= hi) : (vr += step) { + const w = pane.wrapAt(tab, @intCast(vr)); + if ((w.at == 0 or !pane.body_wrapped) and w.line < lines) return w.line; + } + } + return null; +} + +/// A call stack's row after its line's first starts with its tree's guide +/// (locations.treeContinuation), in `buffer`; any other row with none. +fn guideOf(f: *const State, text: []const u8, at: usize, width: usize, buffer: *[1024]u8) []const u8 { + if (at == 0 or width <= 1 or f.output == null or !std.meta.eql(f.output.?.from, Output.Origin{ .query = .callstack })) return ""; + return locations.treeContinuation(text, buffer, width - 1); } /// `pane` out of its Follow chain (Unfollow, or a chain down to it): a @@ -2131,12 +2525,12 @@ fn prepareContextRows(pane: *Pane, file: *State) void { if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return; const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row // The declarations are the file's lines; the rows, the buffer's. - const top = fileRow(file, file.scroll); + const top_line = fileRow(file, file.scroll); for (file.context.declarations) |declaration| { - if (declaration.start_line >= top) break; - if (declaration.end_line < top) continue; + if (declaration.start_line >= top_line) break; + if (declaration.end_line < top_line) continue; var line = declaration.start_line; - while (line <= declaration.header_end_line and line < top) : (line += 1) { + while (line <= declaration.header_end_line and line < top_line) : (line += 1) { if (pane.context_rows >= capacity) return; const row = bufferRow(file, line); if (pane.context_rows > 0 and row <= pane.wrap_line[pane.context_rows - 1]) continue; @@ -2186,6 +2580,11 @@ pub fn geometry(tab: u16, pane: *Pane) void { const key = geometryKey(pane, f); if (pane.geometry_key == key) return; pane.geometry_key = key; + // The key of what the map was made from: the walk brings the text's + // index and tables up to it (`line_starts`, `tables.revision`, in the + // key), and with the key from before, a step's second ask made it all + // again. + defer pane.geometry_key = geometryKey(pane, f); pane.body_rows = 0; pane.body_visible_rows = 0; pane.context_row_limit = null; @@ -2228,7 +2627,7 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 { if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0, f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len, pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h, - pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat), + pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat), f.scroll_row, }; // One hash of them laid out as words: every reader of the map asks for // this key, a hundred times a frame. @@ -2256,6 +2655,20 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State var body_line: usize = f.scroll; var body_at: usize = 0; var written: usize = 0; + var guide_buffer: [1024]u8 = undefined; + // The top line from the view's row in it (`top`): the rows above + // skipped, never past its last; walked once a geometry (the map's + // pass), its text's pass a frame starting where that walk ended. + if (record_wrap) { + var skipped: u32 = 0; + while (skipped < f.scroll_row and width > 0 and body_line < total) : (skipped += 1) { + const text = sourceLine(pane, @intCast(body_line)); + const end = fitEnd(tab, text, body_at, width - displayWidth(tab, guideOf(f, text, body_at, width, &guide_buffer))); + if (end >= text.len or end <= body_at) break; + body_at = end; + } + pane.top_skip = .{ .row = skipped, .at = body_at }; + } else body_at = pane.top_skip.at; for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| { if (i > 0) { if (dst) |out| out[written] = '\n'; @@ -2265,12 +2678,7 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State 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 guide = guideOf(f, text, at, width, &guide_buffer); const pad = displayWidth(tab, guide); // Headers use one screen row per source row, preserving signatures // without allowing a long ancestor to consume the whole viewport. @@ -2709,6 +3117,11 @@ test "the ASCII run in fitEnd survives an exhaustive byte sweep" { } test "the ASCII run in fitEnd cuts where the grapheme walk would" { + const run = struct { + fn of(comptime c: u8, comptime n: usize) [n]u8 { + return @splat(c); + } + }.of; const reference = struct { fn fitEnd(text: []const u8, start: usize, width: usize) usize { var end = start; @@ -2739,6 +3152,12 @@ test "the ASCII run in fitEnd cuts where the grapheme walk would" { // an ASCII byte followed by a continuation byte is NOT its own cluster "e\u{0301}x", "\u{1f1e6}\u{1f1e7}ok", + // runs longer than a vector (the vector loop), each ending at a + // non-ASCII byte, a combining mark, a tab, or the text's end + &(run('x', 40) ++ "\u{00e9}".* ++ run('y', 40)), + &(run('a', 32) ++ "\u{0301}".* ++ run('b', 17)), + &(run('c', 47) ++ "\t".* ++ run('d', 20)), + &run('z', 100), }; for (cases) |text| { var width: usize = 0; @@ -2769,7 +3188,7 @@ test "a line index shifted in place equals a rebuilt one, and the edit turned ro const del = r.uintAtMost(usize, @min(12, text.items.len - at)); var ins: [12]u8 = undefined; const ins_len = r.uintAtMost(usize, 12); - for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)]; + for (ins[0..ins_len]) |*c| c.* = "ab\n\t"[r.uintLessThan(usize, 4)]; const before = try gpa.dupe(usize, f.line_starts); defer gpa.free(before); const cut = try gpa.dupe(u8, text.items[at..][0..del]); @@ -2781,12 +3200,18 @@ test "a line index shifted in place equals a rebuilt one, and the edit turned ro const want = try lineIndex(gpa, &fresh); defer gpa.free(want); try std.testing.expectEqualSlices(usize, want, f.line_starts); + // The kept widest is never less than the text's, made anew exact. + var widest: usize = 0; + var lines = std.mem.splitScalar(u8, text.items, '\n'); + while (lines.next()) |line| widest = @max(widest, line.len); + try std.testing.expectEqual(Widest{ .bytes = widest, .tabbed = std.mem.indexOfScalar(u8, text.items, '\t') != null }, fresh.widest); + try std.testing.expect(f.widest.bytes >= widest and (f.widest.tabbed or !fresh.widest.tabbed)); // Every tenth turned round in a copy, as a rollback takes it back. if (round % 10 == 0) { const room = try gpa.alloc(usize, indexRoom(&f).len); defer gpa.free(room); @memcpy(room[0..f.line_starts.len], f.line_starts); - shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut); + _ = shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut); try std.testing.expectEqualSlices(usize, before, room[0..before.len]); } } diff --git a/core/Output.zig b/core/Output.zig index a1e5865e..380fadb1 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -1041,6 +1041,7 @@ pub fn openErrors(p: *Pardes, id: usize, content: []u8) !void { pub fn resetBody(p: *Pardes, pane: *Pane) void { const v = p.view(); pane.file.?.scroll = 0; + pane.file.?.scroll_row = 0; pane.body.cur_row = 0; pane.body.cur_col = 0; pane.body.cur_pinned = true; diff --git a/core/Places.zig b/core/Places.zig index 1c24e992..6c3ac9ab 100644 --- a/core/Places.zig +++ b/core/Places.zig @@ -561,9 +561,12 @@ pub fn goTo(set: *Places, tab: u16, pane: *Pane, i: usize, add: bool) void { } set.current = i; set.gen +%= 1; - const off = pane.scroll(); - if (t.cur_row < off or t.cur_row >= off + @as(i32, pane.rows)) - pane.scrollBy(t.cur_row - off - @divTrunc(@as(i32, pane.rows), 2)); + // Off the view, its row half the body's rows down (as zz). + const line: usize = @intCast(@max(0, t.cur_row)); + const row = panes.File.rowOf(tab, pane, line, @intCast(@max(0, t.cur_col))); + const body: i64 = panes.File.shownRows(tab, pane); + const on = if (panes.File.rowsTo(tab, pane, panes.File.top(tab, pane), line, @intCast(body))) |d| d + row else -1; + if (on < 0 or on >= body) panes.File.setTop(pane, panes.File.walkRows(tab, pane, .{ .line = line, .row = row }, -@divTrunc(body, 2)).to); t.show(tab); } @@ -634,7 +637,7 @@ pub fn restore(set: *Places, tab: u16, pane: *Pane) void { r.head = @min(r.head, f.content.len); } pane.body.setRanges(tab, f.content, set.snap, &.{}, set.snap_pri, set.snap_expl); - f.scroll = set.snap_scroll; + panes.File.setTop(pane, .{ .line = set.snap_scroll }); f.syntax_dirty = true; pane.hscroll = set.snap_hscroll; } diff --git a/core/Query.zig b/core/Query.zig index 228cdd0e..92a3d9f2 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -344,7 +344,7 @@ pub fn toLineOne(p: *Pardes, id: usize) void { t.cur_pinned = true; rp.query.?.seen_row = 0; edit.enterInsert(p.editor(), t, .line_end, 1) catch |err| return p.reportError(.at(id), "query", err); - showCurrent(rp); + showCurrent(p.settings.tab, rp); } /// The rows' state for a new question: nothing found yet. @@ -456,7 +456,7 @@ fn makeAllRows(p: *Pardes, id: usize) !void { // The current one: the first hit row, until a step moves it. if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); countCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); } /// The names the query matches, best first, `Names.max_rows` of them: each @@ -528,7 +528,7 @@ fn makeNameRows(p: *Pardes, id: usize) !void { // The best is current until a step or a click moves it. q.current = if (shown > 0) 0 else null; countCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); if (q.current == null) blankPreview(p, id) else showTarget(p, id); } @@ -1151,7 +1151,7 @@ fn showPlacesCurrent(p: *Pardes, id: usize) void { }; // Stepped out of the window the live rows are: made again around it. if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64); - showCurrent(rp); + showCurrent(p.settings.tab, rp); } fn firstHit(q: *const Query) ?usize { @@ -1226,7 +1226,7 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { q.more = p.stream.busyFor(rp.serial); q.current = current orelse firstHit(q); countGrepCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); if (q.current == null) blankPreview(p, id) else if (!shown) showTarget(p, id); } @@ -1317,7 +1317,7 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v if (t.mode == .insert) edit.exitInsert(p.editor(), t); t.vsel.active = false; t.nsel = 0; - caretTo(rp, q.current orelse 0); + caretTo(p.settings.tab, rp, q.current orelse 0); showTarget(p, qid); } @@ -1438,7 +1438,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { } } countCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); } // ---- the current row ---- @@ -1447,7 +1447,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { /// elsewhere, line 1 kept when it can be. Its mark is `paint`'s, drawn /// from `current`: no selection, so no click, sweep or chord clears it and /// no B2 or B3 borrows it. -fn showCurrent(rp: *Pane) void { +fn showCurrent(tab: u16, rp: *Pane) void { const q = rp.query orelse return; if (rp.body.cur_row != 0 and rp.focus == .body) return; const c = q.current orelse return; @@ -1455,24 +1455,19 @@ fn showCurrent(rp: *Pane) void { // Typed into, line 1 stays in view whatever the current row: what you // type is never scrolled away (the live rows start just before the // current one, so it sits under line 1). Frozen, the row is scrolled to. - if (!q.frozen) { - if (rp.scroll() != 0) rp.scrollBy(-rp.scroll()); - return; - } - const off = rp.scroll(); - const shown = off + @as(i32, rp.rows) - 1; - if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); + if (rp.file == null) return; + if (!q.frozen) return panes.File.setTop(rp, .{ .line = 0 }); + panes.File.show(tab, rp, r, 0, 0); } /// The caret on item `i`'s row, the row in view. -fn caretTo(rp: *Pane, i: usize) void { +fn caretTo(tab: u16, rp: *Pane, i: usize) void { const r: i32 = @intCast(i + 1); rp.body.cur_row = r; rp.body.cur_col = 0; rp.body.cur_pinned = true; rp.query.?.seen_row = r; - const off = rp.scroll(); - if (r >= off + @as(i32, rp.rows)) rp.scrollBy(r - off - @as(i32, rp.rows) + 1) else if (r < off) rp.scrollBy(r - off); + if (rp.file != null) panes.File.show(tab, rp, r, 0, 0); } /// The first of pane `tp`'s places on line `line` (1-based), if any. @@ -1503,7 +1498,7 @@ fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q); } else countCurrent(q); } else countCurrent(q) else countCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); if (show) showTarget(p, id); } @@ -1562,6 +1557,7 @@ fn blankPreview(p: *Pardes, qid: usize) void { File.setContent(p, f, empty); f.saved_revision = f.revision; f.scroll = 0; + f.scroll_row = 0; } /// Where the current row points, shown with the keyboard left where it is: @@ -1679,6 +1675,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void File.setContent(p, f, bytes); f.saved_revision = f.revision; f.scroll = 0; + f.scroll_row = 0; f.syntax_dirty = true; pane.hscroll = 0; // another file: its own places, found below @@ -1688,6 +1685,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void look.clearNavigationSelection(p, pane); if (at.line == 0 or at.line > File.nlines(p.gpa, f)) { f.scroll = 0; + f.scroll_row = 0; f.syntax_dirty = true; pane.body.cur_row = 0; pane.body.cur_col = 0; @@ -1907,7 +1905,7 @@ pub fn cancel(p: *Pardes, id: usize) void { q.frozen = true; rp.body.cur_row = 0; rp.body.cur_col = 0; - showCurrent(rp); + showCurrent(p.settings.tab, rp); // Its places again, as Enter left them. if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| { const owner = p.panes[oid].?; @@ -1973,7 +1971,7 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { // The caret on the rows goes to the current row, as j and k // would have taken it there. if (t.cur_row != 0) if (q.current) |c| { - caretTo(rp, c); + caretTo(p.settings.tab, rp, c); }; return true; } diff --git a/core/Text.zig b/core/Text.zig index 54d69a74..ba544bff 100644 --- a/core/Text.zig +++ b/core/Text.zig @@ -339,10 +339,19 @@ pub fn scrollViewMove(t: *Text, tab: u16, text: []const u8, range: modal.Selecti if (t.what != .body) return; const w = t.pane() orelse return; const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2)); - w.scrollBy(delta); + w.scrollBy(tab, delta); const top = w.scroll(); const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); const cur = modal.selectionCursor(text, range); + // A file's rows are not its lines: a line's first row at the margin, + // none (inside a line taller than the body) leaving the cursor be. + if (w.file != null) { + const snap = File.textRowLine(tab, w, if (delta > 0) margin else File.shownRows(tab, w) - 1 - margin, margin, if (delta > 0) .down else .up) orelse return; + const head = File.textLineStart(t, text, @intCast(snap)); + if (if (delta > 0) head <= cur else head >= cur) return; + const anchor = if (t.select) range.anchor else head; + return setRange(t, tab, text, 0, .{ .anchor = anchor, .head = head }, false); + } if (delta > 0) { const snap: i32 = @max(0, @min(top + margin, last_row)); const head = File.textLineStart(t, text, @intCast(snap)); diff --git a/core/draw.zig b/core/draw.zig index 5263f7bf..ff76aa75 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -111,7 +111,8 @@ pub fn place(p: *Pardes, s: *Surface) void { // path, a generated text's revision with it (rows rewritten as its // view moved are another text's); none for a terminal or a picture. const doc: u64 = if (pane.file) |f| std.hash.Wyhash.hash(if (f.output != null) f.revision else 0, f.path) else 0; - s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .doc = doc, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); + const row: u32 = if (pane.file != null) panes.File.top(p.settings.tab, pane).row else 0; + s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .row = row, .doc = doc, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } }; // A kind's rail is its paint's (drawPane); every other pane's is // here. diff --git a/core/jj.zig b/core/jj.zig index 176ead49..c1d07662 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -3306,6 +3306,179 @@ test "a description is whole, its title and its author never cut: in a pane narr } } +/// 60 numbered lines, line 20 of 130 numbered words (12 rows or more at +/// 60 columns), and a change to line 40 whose title wraps over several +/// rows: the rows a view scrolls through, the layer's description among +/// them. +const Tall = struct { + const title = "a title long enough to wrap: the description of this change says what it does and why at some length, " ++ + "and then says it again in other words, and once more, so that no pane of sixty columns holds it in fewer than four rows " ++ + "beside its author and its age"; + + fn repo(gpa: std.mem.Allocator) !?Repo { + var base: std.ArrayList(u8) = .empty; + defer base.deinit(gpa); + var changed: std.ArrayList(u8) = .empty; + defer changed.deinit(gpa); + for (0..60) |i| { + const from = base.items.len; + if (i == 20) { + for (0..130) |w| try base.print(gpa, "t{d:0>3} ", .{w}); + try base.append(gpa, '\n'); + } else try base.print(gpa, "line {d:0>2}\n", .{i}); + try changed.appendSlice(gpa, if (i == 40) "line 40 changed\n" else base.items[from..]); + } + return Repo.with(gpa, &.{ .{ base.items, "base" }, .{ changed.items, title } }, null); + } + + /// The buffer's line the description is. + fn description(f: *const File.State) !usize { + for (f.layer.lines) |l| if (std.mem.indexOf(u8, f.content[l.at..][0..l.len], title[0..20]) != null) + return std.mem.count(u8, f.content[0..l.at], "\n"); + return error.NoDescription; + } + + /// The rows of the text above line `line`'s row that shows its byte + /// `col`, in `pane`'s view. + fn rowsAbove(tab: u16, pane: *Pane, line: usize, col: usize) usize { + var n: usize = File.rowOf(tab, pane, line, col); + for (0..line) |l| n += File.lineRows(tab, pane, l); + return n; + } +}; + +test "a view scrolls by rows through a line wrapped over 12 rows and a change's description wrapped over several (a line of the layer): a wheel's notch is one row down the whole text and back, PageDown and PageUp a page of rows, zj and zk one; a held j and k keep the cursor's row three rows inside the body" { + const gpa = testing.allocator; + var repo = try Tall.repo(gpa) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false }); + defer p.deinit(); + const tab = p.settings.tab; + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + p.update(.{ .command = "Changes @-" }); + p.sync(); + const f = &pane.file.?; + try testing.expect(File.lineRows(tab, pane, 20) >= 12); + try testing.expect(File.lineRows(tab, pane, try Tall.description(f)) >= 4); + var total: usize = 0; + for (0..File.nlines(gpa, f)) |l| total += File.lineRows(tab, pane, l); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const shot = struct { + fn of(q: *Pardes, w: *Pane, a: std.mem.Allocator) ![]const []const u8 { + return Ghosts.rows(q, w, a, try a.alloc([]const u8, 256)); + } + }.of; + const rect = p.view().rects[id]; + const at = .{ .col = rect.x + 10, .row = p.bodyTop(pane, rect) + 5 }; + const notch = struct { + fn of(down: bool, x: u16, y: u16) pardes.Event { + return .{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, .col = x, .row = y } }; + } + }.of; + // Every row of the text at the body's top in turn, a notch each: the + // body's rows one up. + var was = try shot(p, pane, arena.allocator()); + const kept = was.len - 1; + var all: std.ArrayList([]const u8) = .empty; + try all.append(arena.allocator(), was[0]); + while (true) { + p.update(notch(true, at.col, at.row)); + const now = try shot(p, pane, arena.allocator()); + if (std.mem.eql(u8, now[0], was[0])) break; + for (now[0 .. kept - 1], was[1..kept]) |n, w| try testing.expectEqualStrings(w, n); + try all.append(arena.allocator(), now[0]); + was = now; + } + try testing.expectEqual(total, all.items.len); + // And back up, a row a notch. + var back = all.items.len - 1; + while (back > 0) : (back -= 1) { + p.update(notch(false, at.col, at.row)); + const now = try shot(p, pane, arena.allocator()); + try testing.expectEqualStrings(all.items[back - 1], now[0]); + for (now[1..kept], was[0 .. kept - 1]) |n, w| try testing.expectEqualStrings(w, n); + was = now; + } + const indexOf = struct { + fn in(rows: []const []const u8, row: []const u8) usize { + for (rows, 0..) |r, i| if (std.mem.eql(u8, r, row)) return i; + return rows.len; + } + }.in; + // PageDown and PageUp: a page of rows each, the text's last row at the + // top the furthest. + var top: usize = 0; + while (top < all.items.len - 1) { + p.update(.{ .key = .{ .cp = pardes.Key.page_down } }); + top = @min(top + pane.rows, all.items.len - 1); + try testing.expectEqual(top, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0])); + } + while (top > 0) { + p.update(.{ .key = .{ .cp = pardes.Key.page_up } }); + top -|= pane.rows; + try testing.expectEqual(top, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0])); + } + // zj and zk: a row each, through line 20's rows and the description's. + for (0..all.items.len - 1) |n| { + for ("zj") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); + try testing.expectEqual(n + 1, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0])); + } + for (0..all.items.len - 1) |n| { + for ("zk") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); + try testing.expectEqual(all.items.len - 2 - n, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0])); + } + // A held j from the first line to the last and a held k back: the + // cursor's row three rows (`scroll_off`) inside the body's edges, or + // as far as the text before or after it goes. + p.update(.{ .command = "Look a.zig:1" }); + const body = File.shownRows(tab, pane); + for ("jk") |cp| for (0..total) |_| { + p.update(.{ .key = .{ .cp = cp, .text = &[_]u8{cp} } }); + const t = File.top(tab, pane); + const cur = Tall.rowsAbove(tab, pane, @intCast(pane.body.cur_row), @intCast(pane.body.cur_col)); + const on = cur - Tall.rowsAbove(tab, pane, t.line, 0) - t.row; + try testing.expect(on >= @min(pardes.config.scroll_off, cur)); + try testing.expect(on <= body - 1 - @min(pardes.config.scroll_off, total - 1 - cur)); + }; +} + +test "a client wheels its session's view a row a notch into a change's description wrapped over several rows (a line of the layer), agreeing with the session at every notch; a client joined over that view loads its row" { + var repo = try Tall.repo(testing.allocator) orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + const R = pardes.replica; + const a = try R.Authority.init(testing.allocator, .{ .cols = 60, .rows = 24 }, .{}); + defer a.deinit(); + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); + defer r.deinit(); + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) })); + r.confirm(try a.local(.{ .command = "Changes @-" })); + r.settle(); + const id = a.core.view().active; + const af = &a.core.panes[id].?.file.?; + const desc = try Tall.description(af); + const rect = a.core.view().rects[id]; + const notch: pardes.Event = .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } }; + var n: usize = 0; + while (af.scroll != desc or af.scroll_row != 2) : (n += 1) { + if (n > 300) return error.NeverThere; + const m = try testing.allocator.dupe(u8, try r.input(notch)); + defer testing.allocator.free(m); + r.confirm(try a.take(m)); + r.settle(); + try testing.expect(r.diverged == null); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); + const rf = &r.core().panes[id].?.file.?; + try testing.expectEqual(af.scroll, rf.scroll); + try testing.expectEqual(af.scroll_row, rf.scroll_row); + } + try R.loadsAsSession(a, 2); +} + test "at one place a change's ghost rows come before its description: a line it changed and the next it took away, then its description" { const gpa = testing.allocator; const fn_text = "fn f() void {\n a();\n b();\n c();\n d();\n}\n"; diff --git a/core/look.zig b/core/look.zig index b240b6e2..f60b90f5 100644 --- a/core/look.zig +++ b/core/look.zig @@ -423,9 +423,7 @@ pub fn jumpResult(p: *Pardes, id: usize, row: usize) bool { rp.body.nsel = 0; rp.body.cur_row = r; rp.body.cur_pinned = true; - const off = rp.scroll(); - const last = off + @as(i32, rp.rows) - 1; - if (r < off) rp.scrollBy(r - off) else if (r > last) rp.scrollBy(r - last); + if (rp.file != null) panes.File.show(p.settings.tab, rp, r, 0, 0); var realbuf: [4096]u8 = undefined; const span = if (tr.commands) wholeRowSpan(ln) @@ -744,14 +742,9 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at_in: Spot, landing: enum { center, }; if (pane.file) |*f| { if (at.line > panes.File.nlines(p.gpa, f)) return; - if (landing == .center) { - // center, clamp at top; a text that fits is shown whole - const next = if (pane.textFits()) 0 else (at.line - 1) -| pane.rows / 2; - if (next != f.scroll) { - f.scroll = next; - f.syntax_dirty = true; - } - } + // centred (its first row of text half the body's rows down, as + // zz), clamped at the top; a text that fits is shown whole + if (landing == .center) panes.File.setTop(pane, if (pane.textFits()) .{ .line = 0 } else panes.File.walkRows(p.settings.tab, pane, .{ .line = at.line - 1, .row = panes.File.rowOf(p.settings.tab, pane, at.line - 1, 0) }, -@as(i64, pane.rows / 2)).to); } pane.body.cur_row = @intCast(at.line - 1); pane.body.cur_col = if (at.col > 0) @intCast(at.col - 1) else 0; @@ -2195,6 +2188,7 @@ test "Look on a diff: headers and a hunk line's prefix are the whole line, hover // Back to the diff, scrolled to its top again. p.view().active = 0; pane.file.?.scroll = 0; + pane.file.?.scroll_row = 0; p.sync(); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); @@ -2268,6 +2262,7 @@ test "a click, a 9P whole-line look and an empty event write-back take one expan for (points) |at| { p.view().active = 0; pane.file.?.scroll = 0; + pane.file.?.scroll_row = 0; pane.body.cur_row = 0; p.sync(); _ = frame.reset(.retain_capacity); @@ -2344,6 +2339,7 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5 pane.body.cur_col = case.col; pane.body.cur_pinned = true; pane.file.?.scroll = 0; + pane.file.?.scroll_row = 0; p.sync(); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); diff --git a/core/mouse.zig b/core/mouse.zig index 2d731acf..14700995 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -702,7 +702,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { const id = hovered orelse return; const pane = p.panes[id].?; if (!programWheel(p, id, m, mcol, mrow)) - pane.scrollBy(if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows); + pane.scrollBy(p.settings.tab, if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows); }, .wheel_left, .wheel_right => { if (m.kind != .press) return; @@ -779,7 +779,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { return pane.places.goTo(p.settings.tab, pane, i, false); }; // gutter scrollbar: a left click scrolls UP to that row - pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); + pane.scrollBy(p.settings.tab, -(@as(i32, mrow) - @as(i32, body_y))); } else { const on_tag = mrow >= tag_y and mrow < tag_y + pane.tag_rows; if (on_tag and mcol < r.x + TAG_TEXT_INSET) return; @@ -847,7 +847,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { if (mcol < r.x + config.GUTTER and !on_tag) { const local = @as(i32, mrow) - @as(i32, body_y); if (m.button == config.look_button) v.active = id; - pane.scrollBy(if (m.button == config.look_button) local else -local); + pane.scrollBy(p.settings.tab, if (m.button == config.look_button) local else -local); } else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, v.pointer_tag_hit)) |pointed| { if (m.button == config.look_button) v.active = id; pane.clearPointerSelection(@backingInt(m.button)); @@ -1150,11 +1150,15 @@ pub fn edgeScroll(p: *Pardes) void { const sl = &pane.sel[sel_slot]; if (s.anchor == null) s.anchor = sweepPoint(p, pane, sl.r0, sl.c0) orelse return; const before = pane.scroll(); - pane.scrollBy(s.edge); + // A file's view moves by rows (File.Top), a terminal's rows are lines. + const moved: i64 = if (pane.file != null) panes.File.scrollRows(p.settings.tab, pane, s.edge) else blk: { + pane.scrollBy(p.settings.tab, s.edge); + break :blk pane.scroll() - before; + }; // The start's row follows its text while it is on the screen, and // stays on the body's edge row once it is off (the anchor keeps it). const top: i32 = pane.tag_rows; - sl.r0 = std.math.clamp(sl.r0 - (pane.scroll() - before), top, top + @as(i32, pane.rows) - 1); + sl.r0 = std.math.clamp(sl.r0 - @as(i32, @intCast(moved)), top, top + @as(i32, pane.rows) - 1); } /// The text position under a body cell of the sweep's space. diff --git a/core/ninep/events.zig b/core/ninep/events.zig index f1e17324..e18b5d96 100644 --- a/core/ninep/events.zig +++ b/core/ninep/events.zig @@ -1406,14 +1406,14 @@ test "a click in the body reports the offsets of the word it takes, so the recor }) |c| for ([_]pardes.Mouse.Button{ config.look_button, config.exec_button }, [_][]const u8{ c.look, c.exec }) |button, want| { // The pointer rests on the word first, as a hand's does, and // the hover preview comes up under it. - p.panes[id].?.scrollBy(c.scroll); + p.panes[id].?.scrollBy(p.settings.tab, c.scroll); _ = try p.render(frame.allocator()); p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = c.x, .row = c.y } }); for (0..200) |_| p.update(.tick); p.update(.{ .mouse = .{ .button = button, .kind = .press, .col = c.x, .row = c.y } }); p.update(.{ .mouse = .{ .button = button, .kind = .release, .col = c.x, .row = c.y } }); try testing.expectEqualStrings(want, call(p, .{ .tag = 2, .op = .read, .node = event, .handle = h, .size = 256 }).bytes); - p.panes[id].?.scrollBy(-c.scroll); + p.panes[id].?.scrollBy(p.settings.tab, -c.scroll); }; // A click on nothing expands to nothing, and acme then says // nothing (look.c:37, exec.c:141). diff --git a/core/normal.zig b/core/normal.zig index 89fd72f6..61f8f26b 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -946,14 +946,31 @@ fn verticalMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, do t.sticky_col = @intCast(goal); } -/// Ctrl-d/u: scroll half a page AND move the cursor by the same rows +/// Ctrl-d/u: the view half the body's rows on, and the cursor where it +/// stood on the screen (inside the margins): on the line whose first row is +/// now there, the next one the way it went past a wrapped line's later +/// row, and the rows the view could not move (the text's end) further. +/// None in the body (inside a line taller than it): it stays, off the +/// view, and the view where it went. A terminal's rows are its lines: both +/// move by them. fn halfPageMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, down: bool) void { // a view to move through is a body's; a tag or an answer is all shown if (t.what != .body) return; const w = t.pane() orelse return; const half: i32 = @max(1, @divTrunc(@as(i32, w.rows), 2)); - w.scrollBy(if (down) half else -half); - verticalMove(tab, t, text, range, down, @intCast(half), 0); + if (w.file == null) { + w.scrollBy(tab, if (down) half else -half); + return verticalMove(tab, t, text, range, down, @intCast(half), 0); + } + const body: i64 = File.shownRows(tab, w); + const margin = @min(config.scroll_off, @divTrunc(body - 1, 2)); + const from = File.top(tab, w); + const line: usize = @intCast(@max(0, t.cur_row)); + const on: i64 = if (File.rowsTo(tab, w, from, line, @intCast(body))) |d| d + File.rowOf(tab, w, line, @intCast(@max(0, t.cur_col))) else if (line < from.line) 0 else body - 1; + const moved = File.scrollRows(tab, w, if (down) half else -half); + const to = File.textRowLine(tab, w, on + (if (down) half else -half) - moved, margin, if (down) .down else .up) orelse return; + if (to == t.cur_row) return; + verticalMove(tab, t, text, range, to > t.cur_row, @abs(to - t.cur_row), 0); } /// gt/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window) @@ -1235,13 +1252,28 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! // helix align_view: the cursor's row goes `above` rows down the // view, the middle of an odd one and the upper middle of an even one .view_top, .view_center, .view_bottom => if (t.what == .body) { - const above: i32 = switch (a.role) { - .view_top => 0, - .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2), - else => @as(i32, pane.rows) - 1, - }; - pane.scrollBy(t.cur_row - (pane.scroll() + above)); - pane.ensureCursorVisible(p.settings.tab); + // In rows: zt shows the cursor's line from its first row, a + // line taller than the body from the cursor's. + const tab = p.settings.tab; + if (pane.file == null) { + const above: i32 = switch (a.role) { + .view_top => 0, + .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2), + else => @as(i32, pane.rows) - 1, + }; + pane.scrollBy(tab, t.cur_row - (pane.scroll() + above)); + } else { + const body: i64 = File.shownRows(tab, pane); + const line: usize = @intCast(@max(0, t.cur_row)); + const row = File.rowOf(tab, pane, line, @intCast(@max(0, t.cur_col))); + const at: File.Top = .{ .line = line, .row = if (a.role == .view_top and row < body) 0 else row }; + File.setTop(pane, File.walkRows(tab, pane, at, switch (a.role) { + .view_top => 0, + .view_center => -@divTrunc(body - 1, 2), + else => -(body - 1), + }).to); + } + pane.ensureCursorVisible(tab); }, // helix align_view_middle: the cursor's column to the middle of an // unwrapped view diff --git a/core/panes.zig b/core/panes.zig index 02ee805f..b238992a 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -31,7 +31,7 @@ pub const Pane = struct { /// it (views.zig). (The 9P server's part of `fs` says so in its type.) pub const replica = .{ .local = .{ "pv", "pv_known" }, - .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan" }, + .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "top_skip", "notices", "pan" }, .len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, // A picture's memory is its own allocator's (a dump loaded makes // it there). @@ -309,6 +309,10 @@ pub const Pane = struct { wrap_n: u16 = 0, /// A row map also exists for sticky headers when soft wrapping is off. body_wrapped: bool = false, + /// Where the geometry's walk found the view's top inside its line's + /// rows (File.Top): the row it is and the bytes of the line before it; + /// a frame's text starts there with no walk again. + top_skip: struct { row: u32 = 0, at: usize = 0 } = .{}, context_rows: u16 = 0, body_rows: u16 = 0, body_visible_rows: u16 = 0, @@ -636,15 +640,11 @@ pub const Pane = struct { return .{ .row = -1, .at = 0 }; } - pub fn scrollBy(pane: *Pane, delta: i32) void { - if (pane.file) |*f| { - const max: i64 = @intCast(File.nlines(pane.gpa, f) -| 1); - const n = std.math.clamp(@as(i64, @intCast(f.scroll)) + delta, 0, max); - const next: usize = @intCast(n); - if (next != f.scroll) { - f.scroll = next; - f.syntax_dirty = true; - } + /// The view moved `delta` rows: a file's through its lines' wrapped + /// rows (File.Top), a terminal's through its history. + pub fn scrollBy(pane: *Pane, tab: u16, delta: i32) void { + if (pane.file != null) { + _ = File.scrollRows(tab, pane, delta); } else if (pane.addon == null) { // the vt scrolls in SHELL rows; convert through the edit buffer. // The alternate screen has no history (ghostty's scrolls none): @@ -669,42 +669,14 @@ pub const Pane = struct { pub fn ensureCursorVisible(pane: *Pane, tab: u16) void { File.geometry(tab, pane); - const off = pane.scroll(); - var in_context = false; - // The map is the view's as it is now (File.geometry): an ancestor is - // pinned only in the view it was found for. - if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == off) { - for (pane.wrap_line[0..pane.context_rows]) |row| { - if (row == pane.body.cur_row) { - in_context = true; - break; - } - } - } - // Scrolloff is measured in the ordinary body, excluding sticky rows. - var margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2)); - var last = off + @as(i32, pane.rows) - 1; - const visible_rows = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n; - if (pane.context_rows < visible_rows) { - const lines_shown = pane.wrap_line[visible_rows - 1] - pane.wrap_line[pane.context_rows]; - last = off + lines_shown; - margin = @min(margin, @divTrunc(@max(0, lines_shown), 2)); - } - if (!in_context) { - if (pane.follow_edges != 0 and (pane.body.cur_row < off or pane.body.cur_row > last)) pane.follow_crossed = true; + if (pane.file != null) File.show(tab, pane, pane.body.cur_row, pane.body.cur_col, config.scroll_off) else { + // A terminal's rows are its lines. + const off = pane.scroll(); + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2)); + const last = off + @as(i32, pane.rows) - 1; if (pane.body.cur_row < off + margin) { - if (pane.follow_edges & 1 == 0) pane.scrollBy(pane.body.cur_row - margin - off); - } else if (pane.body.cur_row > last - margin and pane.follow_edges & 2 == 0) { - var to = pane.body.cur_row + margin; - if (pane.file) |*f| { - // The margin only reveals text: a pane its whole text - // fits in never scrolls for it. A longer one keeps - // helix's clamp at the buffer's last line. - const lines: i32 = @intCast(File.nlines(pane.gpa, f)); - to = @min(to, if (off == 0 and pane.textFits()) @max(pane.body.cur_row, lines - 1 - @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) else lines - 1); - } - pane.scrollBy(@max(0, to - last)); - } + pane.scrollBy(tab, pane.body.cur_row - margin - off); + } else if (pane.body.cur_row > last - margin) pane.scrollBy(tab, pane.body.cur_row + margin - last); } if (pane.file) |f| { if (pane.body_wrapped) return; diff --git a/core/replica.zig b/core/replica.zig index 57dd4eed..f62cd629 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -4491,6 +4491,160 @@ test "bytes: a client's wheel over a terminal is its own view's: applied at once try std.testing.expect(placeIn(b.r.core(), b.r.view, id).? < back); } +test "a view's top is a line and a row of its block: a client's wheel into a line wrapped over rows moves it a row a notch, the session agrees through a rollback, and a dump keeps the row" { + const gpa = std.testing.allocator; + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + // Line 3 is 60 words: four rows at this width. + for (0..40) |i| if (i == 3) { + for (0..60) |w| try text.print(gpa, "w{d:0>3} ", .{w}); + try text.append(gpa, '\n'); + } else try text.print(gpa, "line {d}\n", .{i}); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); + defer a.deinit(); + const was = Stepping.begin(&a.t, null); + _ = try a.core.setTestFile(text.items); + was.end(); + _ = try a.unit(0, 0); + const id = a.core.view().active; + // A client joined from the session's dump: the text is in it. + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + const rect = a.core.view().rects[id]; + const notch: pardes.Event = .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } }; + // Three notches to line 3's first row, two into its block. + for (0..5) |_| { + const m = try gpa.dupe(u8, try r.input(notch)); + defer gpa.free(m); + r.confirm(try a.take(m)); + r.settle(); + try agrees(a, r); + } + for ([_]*Pardes{ a.core, r.core() }) |core| { + try std.testing.expectEqual(@as(usize, 3), core.panes[id].?.file.?.scroll); + try std.testing.expectEqual(@as(u32, 2), core.panes[id].?.file.?.scroll_row); + } + // A notch of the client's on top of the session's own key (one that + // leaves the view be): the copy put back, the notch applied over it. + const again = try gpa.dupe(u8, try r.input(notch)); + defer gpa.free(again); + r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } })); + r.settle(); + r.confirm(try a.take(again)); + r.settle(); + try agrees(a, r); + try std.testing.expectEqual(@as(u32, 3), r.core().panes[id].?.file.?.scroll_row); + // A client joining over the view scrolled into the block has the row. + const late = try joinedNow(a, 2, 0); + defer late.deinit(); + try agrees(a, late); + try std.testing.expectEqual(@as(u32, 3), late.core().panes[id].?.file.?.scroll_row); + // The client's view keys, each after the session drew (its geometry + // made for the frame; the client's is not): what a key reads of the + // body's rows is made of the state alone (the soak's divergence at a + // Ctrl-b, before File.shownRows laid the geometry out first). + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + for ([_]pardes.Key{ .{ .cp = 'b', .ctrl = true }, .{ .cp = 'f', .ctrl = true }, .{ .cp = 'd', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'e', .ctrl = true } }) |k| { + for (0..3) |_| { + { + const drew = Stepping.begin(&a.t, null); + defer drew.end(); + _ = try a.core.render(arena.allocator()); + } + const m = try gpa.dupe(u8, try r.input(.{ .key = k })); + defer gpa.free(m); + r.confirm(try a.take(m)); + r.settle(); + try agrees(a, r); + } + } + // A session's dump keeps the row. + const bytes = try pardes.dump.dumpBytes(a.core); + defer gpa.free(bytes); + const loaded = try pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, bytes, null); + defer loaded.deinit(); + try std.testing.expectEqual(walk.digest(Pardes, a.core), walk.digest(Pardes, loaded)); + try std.testing.expectEqual(a.core.panes[id].?.file.?.scroll_row, loaded.panes[id].?.file.?.scroll_row); +} + +test "a text's views under random orders of the session's and a client's keys, wheels and draws, keys of the session's between a client's and its confirm (rollbacks): every side agrees (an explorer of a view's rows)" { + const gpa = std.testing.allocator; + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + // Lines of one row and of several (wrapped at 80 columns). + for (0..120) |i| if (i % 7 == 3) { + for (0..20 + i % 40) |w| try text.print(gpa, "w{d:0>3} ", .{w}); + try text.append(gpa, '\n'); + } else try text.print(gpa, "line {d}\n", .{i}); + const keys = [_]pardes.Key{ + .{ .cp = 'j', .text = "j" }, .{ .cp = 'k', .text = "k" }, + .{ .cp = 'w', .text = "w" }, .{ .cp = 'b', .text = "b" }, + .{ .cp = 'b', .ctrl = true }, .{ .cp = 'f', .ctrl = true }, + .{ .cp = 'd', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, + .{ .cp = 'G', .text = "G" }, .{ .cp = 'z', .text = "z" }, + .{ .cp = 't', .text = "t" }, .{ .cp = 'i', .text = "i" }, + .{ .cp = 'x', .text = "x" }, .{ .cp = pardes.Key.escape }, + .{ .cp = '/', .text = "/" }, .{ .cp = pardes.Key.enter }, + }; + for (0..view_orders) |seed| { + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); + defer a.deinit(); + const was = Stepping.begin(&a.t, null); + _ = try a.core.setTestFile(text.items); + was.end(); + _ = try a.unit(0, 0); + const id = a.core.view().active; + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + const opened = try a.openView(1); + r.view = opened.view; + r.confirm(opened.unit); + r.settle(); + try agrees(a, r); + var prng: std.Random.DefaultPrng = .init(seed); + const rand = prng.random(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + for (0..150) |_| { + const rect = a.core.views[r.view].?.rects[id]; + const at = .{ .col = rect.x + 10, .row = rect.y + rect.h / 2 }; + const ev: pardes.Event = switch (rand.uintLessThan(u8, 10)) { + 0 => .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = at.col, .row = at.row } }, + 1 => .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = at.col, .row = at.row } }, + else => .{ .key = keys[rand.uintLessThan(usize, keys.len)] }, + }; + if (rand.boolean()) { + const drew = Stepping.begin(&a.t, null); + defer drew.end(); + _ = arena.reset(.retain_capacity); + _ = try a.core.render(arena.allocator()); + } + if (rand.uintLessThan(u8, 4) == 0) _ = r.draw(.{ .ctx = null, .f = null }); + if (rand.uintLessThan(u8, 3) == 0) { + // The session's own key, then nothing of the client's. + r.confirm(try a.local(.{ .key = keys[rand.uintLessThan(usize, keys.len)] })); + r.settle(); + } else { + const m = try gpa.dupe(u8, try r.input(ev)); + defer gpa.free(m); + // Sometimes the session's own key first: the client's + // applied at once is rolled back and replayed. + if (rand.uintLessThan(u8, 3) == 0) { + r.confirm(try a.local(.{ .key = keys[rand.uintLessThan(usize, keys.len)] })); + r.settle(); + } + r.confirm(try a.take(m)); + r.settle(); + } + agrees(a, r) catch |err| { + std.debug.print("seed {d}: diverged\n", .{seed}); + return err; + }; + } + } +} + /// Seeds of the explorer below a run of the suite takes; 3,000 were run /// once (reports/pardes-term-join-10.md). const view_orders = 30; diff --git a/core/rollback.zig b/core/rollback.zig index 61fb7b89..2702594c 100644 --- a/core/rollback.zig +++ b/core/rollback.zig @@ -249,7 +249,8 @@ pub const Epoch = struct { const cut = e.taken.items[w.at..][0..w.cut]; if (w.index) { const room = @as([*]usize, @ptrFromInt(w.addr))[0..w.room]; - pardes.panes.File.shiftStarts(room, w.len, w.was, w.off, w.ins, cut); + // The text's widest is the copy's, put back with it. + _ = pardes.panes.File.shiftStarts(room, w.len, w.was, w.off, w.ins, cut); } else { const room = @as([*]u8, @ptrFromInt(w.addr))[0..w.room]; const tail = w.len - w.off - w.ins; diff --git a/core/root.zig b/core/root.zig index 773c7588..7056935d 100644 --- a/core/root.zig +++ b/core/root.zig @@ -751,10 +751,10 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, .{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" }, - .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state; a tab change resets the key" }, + .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len top_skip", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state; a tab change resets the key" }, .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, - .{ "File.zig", "cap line_starts line_cap", "the text's line index, of its bytes" }, + .{ "File.zig", "cap line_starts line_cap widest", "the text's line index, of its bytes, and the widest line it found (an upper bound: which walk answers, never what)" }, .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest; what a step asks a worker to paint is never decided by them, Stream.paintRows)" }, .{ "File.zig", "allocator", "ContextCache's: what its declarations were made with, the parse's or a load's (a machine's handle, no state)" }, .{ "File.zig", "declarations", "ContextCache's: the text's at its revision (dumped, digested), parsed again from the text at a load" }, diff --git a/core/surface.zig b/core/surface.zig index 5b381958..98696721 100644 --- a/core/surface.zig +++ b/core/surface.zig @@ -130,9 +130,11 @@ pub const Region = struct { /// A notice's index in its pane's `notices`. notice: u8 = 0, /// A body's view: the first line it shows (a file's scroll, a - /// terminal's grid offset), and the text it shows (`draw.place`'s doc: + /// terminal's grid offset) and which of that line's wrapped rows its + /// first row is (File.Top), and the text it shows (`draw.place`'s doc: /// 0 for a terminal or a picture), which a frontend's glide follows. line: i32 = 0, + row: u32 = 0, doc: u64 = 0, /// A body drawn as a strip of pictures (a PDF): how far down the strip /// it shows, in pixels. Its placements are laid at the whole pixel; a diff --git a/core/views.zig b/core/views.zig index f414eb6c..4f2d5744 100644 --- a/core/views.zig +++ b/core/views.zig @@ -63,9 +63,11 @@ pub const PaneView = struct { follow_scroll: usize = 0, scrolled_to: ?usize = null, body: Part(Text, &body_fields) = .{}, - /// A document's scroll and size; a terminal's size is its pty's, which - /// every view shows (sized by its last typist, `Pardes.sync`). + /// A document's scroll (its top: File.Top) and size; a terminal's size + /// is its pty's, which every view shows (sized by its last typist, + /// `Pardes.sync`). scroll: usize = 0, + scroll_row: u32 = 0, cols: u16 = 1, rows: u16 = 1, @@ -252,7 +254,10 @@ fn extract(pane: *const Pane) PaneView { var v: PaneView = .{ .cols = pane.cols, .rows = pane.rows }; copy(&pane_fields, &v, pane); copy(&body_fields, &v.body, &pane.body); - if (pane.file) |f| v.scroll = f.scroll; + if (pane.file) |f| { + v.scroll = f.scroll; + v.scroll_row = f.scroll_row; + } return v; } @@ -269,6 +274,7 @@ fn apply(pane: *Pane, v: *const PaneView) void { // brought back inside it. const lines = File.nlines(pane.gpa, f); f.scroll = @min(v.scroll, lines -| 1); + f.scroll_row = v.scroll_row; if (pane.body.cur_row >= lines) { pane.body.vsel.active = false; pane.body.nsel = 0; @@ -552,7 +558,10 @@ pub fn within(p: *Pardes, k: u8, ctx: anytype, comptime f: fn (@TypeOf(ctx), *Pa pane.cols = pv.cols; pane.rows = pv.rows; } - if (pane.file) |*file| file.scroll = pv.scroll; + if (pane.file) |*file| { + file.scroll = pv.scroll; + file.scroll_row = pv.scroll_row; + } pv.body.sels = &.{}; pv.body.nsel = 0; }; diff --git a/dev/glide.zig b/dev/glide.zig index 62e44bb7..9d622b3d 100644 --- a/dev/glide.zig +++ b/dev/glide.zig @@ -2,8 +2,9 @@ //! scroll, on its own clock, from the frames it draws alone. Whatever //! scrolls a text (a wheel's lines, Ctrl-d, a page, G, n, a Look) scrolls //! the core at once, so every key and click acts on where the text is; the -//! frontend sees a body's first line move between two frames (Region.line) -//! and its picture follows there, critically damped (text never passes its +//! frontend sees a body's top move between two frames (Region.line, and +//! Region.row: a row inside a wrapped line, File.Top) and its picture +//! follows there, critically damped (text never passes its //! mark), every distance on the same law. The GUI draws it at the pixel; //! the tty at whole rows (tui.zig's glideRows). Nothing here reaches back //! into the core. @@ -60,9 +61,9 @@ pub const Glide = struct { caret_row: ?u16 = null, caret_rides: bool = false, /// Each body as the last frame showed it, by its pane: its serial, - /// first line, text and place, so a view that moved since is found - /// whatever moved it. - seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i32 = 0, doc: u64 = 0, rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 } } = @splat(.{}), + /// top (a line and a row of it), text and place, so a view that + /// moved since is found whatever moved it. + seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i32 = 0, row: u32 = 0, doc: u64 = 0, rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 } } = @splat(.{}), /// Each body's rows held at its top while it scrolls (a source's /// sticky context rows, TreeContext), its frontend's to say: they do /// not move, so a move is measured, and the rows that left are kept, @@ -121,7 +122,9 @@ pub const Glide = struct { /// The frame about to be drawn, at `now_ns` on the frontend's clock: /// the glide moves on to now, and a body whose first line moved since /// the last frame (the same text in the same place) is measured against - /// that frame and kicks it. A terminal's view glides only under the + /// that frame and kicks it: a move of lines guessed at as many rows (as + /// unwrapped), one inside a line's wrapped rows known in rows. A + /// terminal's view glides only under the /// wheel (`wheeled`: its output scrolls it at every line, and that is no /// glide); not one the frontend moves by the pixel (`direct`). One glide /// at a time: the focused body's, else the one that moved most. @@ -139,24 +142,26 @@ pub const Glide = struct { } var pick: ?pardes.Region = null; var delta: i64 = 0; + var lines: i64 = 0; var shown: [pardes.MAX_PANES]bool = @splat(false); for (surface.regionList()) |region| { if (region.kind != .body or region.owner >= glide.seen.len) continue; const id: usize = region.owner; shown[id] = true; const was = glide.seen[id]; - glide.seen[id] = .{ .serial = region.serial, .line = region.line, .doc = region.doc, .rect = region.rect }; - if (was.serial != region.serial or was.doc != region.doc or was.line == region.line) continue; + glide.seen[id] = .{ .serial = region.serial, .line = region.line, .row = region.row, .doc = region.doc, .rect = region.rect }; + if (was.serial != region.serial or was.doc != region.doc or (was.line == region.line and was.row == region.row)) continue; // The last frame drew this body where it is now: a pane that // moved or was resized in the same step has no picture to glide // from. if (!std.meta.eql(was.rect, region.rect)) continue; if (region.doc == 0 and wheeled != id) continue; if (direct == id) continue; - const moved = @as(i64, region.line) - was.line; + const moved = if (region.line != was.line) @as(i64, region.line) - was.line else @as(i64, region.row) - was.row; if (pick) |best| if (best.active or (!region.active and @abs(moved) <= @abs(delta))) continue; pick = region; delta = moved; + lines = @as(i64, region.line) - was.line; } for (&glide.seen, shown) |*seen, here| if (!here) { seen.* = .{}; @@ -179,8 +184,8 @@ pub const Glide = struct { if (glide.before.len < n) return glide.stop(); for (0..r.h) |row| @memcpy(glide.before[row * w ..][0..w], glide.last[(@as(usize, r.y) + row) * glide.last_cols + r.x ..][0..w]); glide.dir = @intCast(std.math.sign(delta)); - glide.pending_lines += @floatFromInt(@abs(delta)); - glide.measure(gpa, surface); + glide.pending_lines += @floatFromInt(@abs(lines)); + glide.measure(gpa, surface, @floatFromInt(@abs(delta))); } /// This frame's cells and caret, for the next frame's measure. @@ -202,8 +207,9 @@ pub const Glide = struct { } /// Finds how far the pane's body rows moved, `dir` rows at a time, by - /// the rows of `surface` against `before`; keeps the rows that left. - fn measure(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { + /// the rows of `surface` against `before` (`guess` rows tried first); + /// keeps the rows that left. + fn measure(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface, guess_rows: f32) void { const w = glide.bw(); const x0 = glide.rect.x + config.GUTTER; if (w == 0 or glide.body_h == 0 or x0 + w > surface.cols or glide.body_y + glide.body_h > surface.rows or glide.before.len < @as(usize, w) * glide.body_h) return glide.stop(); @@ -218,9 +224,10 @@ pub const Glide = struct { }; // The least shift under which the rows agree, but for a few: the // cursor's line and its number's weight move with the scroll. The - // lines the core moved are tried first: unwrapped, they are the - // rows, and one pass over the body settles it (the search over - // every shift was 6 ms of the first frame of a page in Debug). + // rows guessed are tried first: the lines the core moved, which are + // the rows unwrapped, or the rows inside a wrapped line; one pass over the + // body settles it (the search over every shift was 6 ms of the + // first frame of a page in Debug). const agrees = struct { fn at(gl: *const Glide, surf: *const pardes.Surface, x: u16, width: u16, height: u16, kk: u16) bool { if (kk == 0 or kk + 3 > height) return false; @@ -239,7 +246,7 @@ pub const Glide = struct { return true; } }; - const guess: u16 = @intFromFloat(@min(glide.pending_lines, @as(f32, @floatFromInt(h)))); + const guess: u16 = @intFromFloat(@min(guess_rows, @as(f32, @floatFromInt(h)))); // A body's lines or more: every row moved off, none in common. var shift: u16 = if (guess >= h) 0 else if (agrees.at(glide, surface, x0, w, h, guess)) guess else found: for (1..h) |k| { if (agrees.at(glide, surface, x0, w, h, @intCast(k))) break :found @intCast(k); @@ -252,7 +259,7 @@ pub const Glide = struct { // None in common: a body's move from the last frame's body, if the // lines moved are that many (rows that merely changed, a small // scroll the rows cannot show, land at once). - if (shift == 0 and glide.pending_lines + 3 < @as(f32, @floatFromInt(h))) return glide.stop(); + if (shift == 0 and guess_rows + 3 < @as(f32, @floatFromInt(h))) return glide.stop(); const far = shift == 0; if (far) shift = h; glide.caret_rides = !far and if (glide.caret_row) |old| if (surface.cursor) |c| diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 2756f69b..0f1fe0e6 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -1773,10 +1773,9 @@ const Input = struct { /// Pane `id`'s first row shown, after the inputs posted: the session's /// own window asks (a wheel's rows stop where the pane does); a replica /// client's speculation may wait on the session, so it never asks. - fn scrollOf(in: *const Input, id: usize) ?i32 { + fn scrollOf(in: *const Input, id: usize) ?[2]i64 { if (in.client != null) return null; - const pane = in.core.panes[id] orelse return null; - return pane.scroll(); + return topOf(in.core.panes[id] orelse return null); } fn close(in: *Input) void { @@ -3301,6 +3300,12 @@ fn notchOf(raw_y: f32, integer_y: i32) ?i32 { const Glide = pardes.glide.Glide; +/// Where a pane's view starts, to tell a wheel's row moved it: its line, +/// and a file's row of that line's wrapped rows (File.Top). +fn topOf(pane: *pardes.Pane) [2]i64 { + return .{ pane.scroll(), if (pane.file) |f| f.scroll_row else 0 }; +} + /// Feeds a wheel's notches to the core, and keeps what moved the view for /// the frame's glide (Glide.frame). fn stepGlide(g: *Gui, core: *pardes.Pardes) void { @@ -3322,10 +3327,10 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes) void { while (left != 0) { const down = left > 0; left += if (down) -1 else 1; - const was = pane.scroll(); + const was = topOf(pane); // Shift: 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 } }); - if (pane.scroll() == was) break; + if (std.mem.eql(i64, &topOf(pane), &was)) break; wheeled = id; } if (wheeled != null) core.needs_frame = true; @@ -3541,7 +3546,7 @@ fn scrollRows(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { }, }); // A replica client's rows may wait on the session: it never asks. - if (was != null and in.scrollOf(id) == was) { + if (was != null and std.mem.eql(i64, &in.scrollOf(id).?, &was.?)) { resetScroll(g); return false; } @@ -6544,16 +6549,19 @@ test "a wheel over codex in a terminal reaches its pty as the mouse reports it a try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); } -test "a notch scrolls the core at once and the picture glides after it, a wrapped line's rows at a time" { +test "a notch scrolls the core at once and the picture glides after it, a row a notch: a wrapped line's rows one by one" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - // Lines of two rows each at this width, numbered so no two rows match. + // Lines of two rows each at this width, numbered so no two rows match; + // line 3 of 80 numbered words, five rows or more. var text: std.ArrayList(u8) = .empty; defer text.deinit(gpa); for (0..60) |i| { try text.print(gpa, "{d:0>4} ", .{i}); - try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); + if (i == 3) { + for (0..80) |w| try text.print(gpa, "w{d:0>3} ", .{w}); + } else try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); try text.append(gpa, '\n'); } _ = try core.setTestFile(text.items); @@ -6570,26 +6578,42 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe g.scroll_col = r.x + 10; g.scroll_row = r.y + r.h - 2; const body_y = core.bodyTop(core.panes[core.view().active].?, r); - const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y + 1) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); + const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); defer gpa.free(row_before); // The window has drawn the view once (Glide.frame finds a view that moved). g.now_ns = now; glideFrame(&g, gpa, s); - // One notch down: the core is a line on at once. + // One notch down: the core is a row on at once, line 0's second. g.scroll_notch = 1; - const scrolled = core.panes[core.view().active].?.scroll(); + const f = &core.panes[core.view().active].?.file.?; stepGlide(&g, core); - try std.testing.expectEqual(scrolled + 1, core.panes[core.view().active].?.scroll()); + try std.testing.expectEqual(@as(usize, 0), f.scroll); + try std.testing.expectEqual(@as(u32, 1), f.scroll_row); _ = arena.reset(.retain_capacity); s = try core.render(arena.allocator()); glideFrame(&g, gpa, s); // The window's own motion: it draws its frames while it moves. try std.testing.expect(frontendMoving(&g)); - // Its two rows: the picture two rows behind, the rows that left kept, - // nearest first. - try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); - try std.testing.expectEqual(@as(u16, 2), g.glide.nabove); + // Its row: the picture a row behind, the row that left kept. + try std.testing.expectApproxEqAbs(@as(f32, -1), g.glide.follow.offset, 1e-4); + try std.testing.expectEqual(@as(u16, 1), g.glide.nabove); try std.testing.expect(pardes.glide.sameRow(g.glide.above[0 .. r.w - config.GUTTER], row_before)); + // Notch by notch to line 5, through line 3's rows: a row more + // behind each, never a line's rows at once. + var lag = g.glide.follow.offset; + var notches: usize = 1; + while (f.scroll < 5) : (notches += 1) { + g.scroll_notch = 1; + stepGlide(&g, core); + _ = arena.reset(.retain_capacity); + s = try core.render(arena.allocator()); + glideFrame(&g, gpa, s); + try std.testing.expectApproxEqAbs(lag - 1, g.glide.follow.offset, 1e-4); + lag = g.glide.follow.offset; + } + const line3: usize = pardes.panes.File.lineRows(core.settings.tab, core.panes[core.view().active].?, 3); + try std.testing.expect(line3 >= 5); + try std.testing.expectEqual(2 + 2 + 2 + line3 + 2, notches); // Frame by frame it comes back, never past, and settles. var frames: usize = 0; while (g.glide.moving()) : (frames += 1) { @@ -7746,7 +7770,7 @@ test "a body tells its first line" { const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); - pane.scrollBy(8); + pane.scrollBy(core.settings.tab, 8); core.sync(); const s = try core.render(core.scratch.allocator()); const body = for (s.regionList()) |region| { diff --git a/test/daemon.py b/test/daemon.py index 90977ef4..cfdac2ec 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -328,7 +328,7 @@ class Replica: """A replica's connection (abi/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 34 + WIRE = 35 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/kitty.zig b/test/kitty.zig index 0bd849c2..37e64949 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -1224,7 +1224,7 @@ test "kitty: scrolled back by pardes, an image shows on its row; scrolled forwar r.feed(0, &nl); try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(20)).len); // Back to the top of the history: the marker row is the body's first. - pane.scrollBy(-1000); + pane.scrollBy(pardes.config.tab_width, -1000); const o = r.origin(0); const drawn = try r.placesOf(20); try std.testing.expectEqual(@as(usize, 1), drawn.len); diff --git a/test/panes.zig b/test/panes.zig index bd39beba..eea4b36d 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -157,7 +157,7 @@ const BodyHitTests = struct { p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([60][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(10); + pane.scrollBy(pardes.config.tab_width, 10); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); p.sync(); @@ -205,7 +205,7 @@ const LineNumberLookTests = struct { p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([60][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(30); + pane.scrollBy(pardes.config.tab_width, 30); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); p.sync(); @@ -219,7 +219,7 @@ const LineNumberLookTests = struct { const rows = [_]u16{ 1, pane.context_rows + 3 }; for (rows) |row| { // Each Look recentres the view; come back under the headers. - pane.scrollBy(30 - pane.scroll()); + pane.scrollBy(pardes.config.tab_width, 30 - pane.scroll()); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); const expected = pane.wrapAt(config.tab_width, row).line; @@ -262,7 +262,7 @@ const TreeContextTests = struct { const pane = try setZigFile(p, "const Box = struct {\n\n // omitted member comment\n\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(10); + pane.scrollBy(pardes.config.tab_width, 10); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); p.sync(); @@ -278,7 +278,7 @@ const TreeContextTests = struct { // A one-pixel separator remains inside its existing header row. try std.testing.expectEqual(row, layer.bodyHit(x, y, 10, 20, 8, 10).?.row); } - pane.scrollBy(-5); + pane.scrollBy(pardes.config.tab_width, -5); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 2), layer.context_rows); try std.testing.expect(layer.hasContextBorderAfter(0)); @@ -317,7 +317,7 @@ const TreeContextTests = struct { const pane = try setZigFile(p, source); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); - pane.scrollBy(7); + pane.scrollBy(pardes.config.tab_width, 7); p.sync(); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 0), pane.context_rows); @@ -348,7 +348,7 @@ const TreeContextTests = struct { p.update(.{ .key = .{ .cp = Key.escape } }); var previous: u16 = pane.context_rows; while (pane.scroll() > 0) { - pane.scrollBy(-1); + pane.scrollBy(pardes.config.tab_width, -1); _ = try p.render(frame.allocator()); try std.testing.expect(pane.context_rows <= previous); previous = pane.context_rows; @@ -357,7 +357,7 @@ const TreeContextTests = struct { try std.testing.expectEqual(@as(u16, 0), pane.context_rows); try std.testing.expectEqual(@as(i32, 0), pane.wrapRow(config.tab_width, 0, pane.body.cur_col).row); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(7); + pane.scrollBy(pardes.config.tab_width, 7); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 0), pane.context_rows); } @@ -370,7 +370,7 @@ const TreeContextTests = struct { p.sync(); p.settings.wrap = false; try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(8); + pane.scrollBy(pardes.config.tab_width, 8); pane.hscroll = 4; var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); @@ -409,7 +409,9 @@ const TreeContextTests = struct { p.sync(); p.settings.wrap = true; try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(2); + // The view's top on line 2 (a scroll's rows would stop in line 0's + // three: File.Top). + panes.File.setTop(pane, .{ .line = 2 }); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); p.sync(); @@ -994,7 +996,7 @@ test "terminal output keeps following new rows after scrollback eviction" { for (0..3) |phase| { if (phase > 0) { pane.body.mode = .normal; - pane.scrollBy(-30); + pane.scrollBy(pardes.config.tab_width, -30); try std.testing.expect(pane.termTop() < pages.scrollbar().total - pane.rows); pardes.keys.enterTty(p, 0); } @@ -2032,7 +2034,7 @@ const OutputTests = struct { try std.testing.expectEqual(next, panes.Output.nextResult(restored_file.content, restored_file.location_rows, path, .{ .line = 2, .col = 5 })); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); - result.scrollBy(-1000); + result.scrollBy(pardes.config.tab_width, -1000); layout.compute(p); const surface = try p.render(frame.allocator()); const rect = p.view().rects[pane.search_pane.?]; @@ -2690,7 +2692,7 @@ const TerminalTests = struct { p.update(.{ .output = .{ .pane = .at(0), .bytes = bytes } }); } p.shell_rows.stale = true; - pane.scrollBy(-20); + pane.scrollBy(pardes.config.tab_width, -20); // ONE buffer line standing in for SIX shell rows: everything below slides // UP five, so the last rows of the body resolve past the viewport's bottom diff --git a/test/perf.zig b/test/perf.zig index 8622e31b..f36d64ac 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -631,7 +631,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u for (0..warmup + reps) |n| { if (op != .deep_selection) seek(pane, fx, n); _ = try frame(core); // settle the view at the new spot, untimed - const before = .{ .row = pane.body.cur_row, .col = pane.body.cur_col, .scroll = pane.scroll(), .len = pane.file.?.content.len }; + const before = .{ .row = pane.body.cur_row, .col = pane.body.cur_col, .scroll = pane.scroll(), .scroll_row = pane.file.?.scroll_row, .len = pane.file.?.content.len }; const rect = core.view().rects[id]; const wheel_col = rect.x + pardes.config.GUTTER; const wheel_row = rect.y + pardes.BOX_H; @@ -658,9 +658,11 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u return error.RenderChangedDocument, .key_down => if (pane.body.cur_row != before.row + 1) return error.DownDidNotMove, .key_right => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) return error.RightDidNotMove, - .page_down => if (pane.scroll() <= before.scroll and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) + // A view moves by rows (File.Top): inside a wrapped line's + // block its line stays and its row goes on. + .page_down => if (!past(pane, before.scroll, before.scroll_row) and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) return error.PageDidNotScroll, - .wheel => if (pane.scroll() <= before.scroll and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) + .wheel => if (!past(pane, before.scroll, before.scroll_row) and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) return error.WheelDidNotScroll, .edit_char, .edit_twin => { if (pane.file.?.content.len != before.len + 1 or pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) @@ -1884,6 +1886,7 @@ fn seek(pane: *pardes.Pane, fx: Fixture, n: usize) void { const span = @max(1, fx.lines * 8 / 10); const row = fx.lines / 10 + (n *% 7919) % span; f.scroll = @min(row, fx.lines -| 1); + f.scroll_row = 0; f.syntax_dirty = true; pane.body.cur_row = @intCast(f.scroll); pane.body.cur_col = if (fx.cols > 200) @intCast(fx.cols * 3 / 4) else 0; @@ -2401,3 +2404,8 @@ fn readFileAlloc(path: []const u8) ![]u8 { } return buf; } + +/// Whether `pane`'s view's top is past (`line`, `row`). +fn past(pane: *pardes.Pane, line: i32, row: u32) bool { + return pane.scroll() > line or (pane.scroll() == line and pane.file.?.scroll_row > row); +} diff --git a/test/terminal.zig b/test/terminal.zig index 03bcd294..2873c278 100644 --- a/test/terminal.zig +++ b/test/terminal.zig @@ -107,7 +107,7 @@ test "document construction allocates only the pane and has inert terminal defau try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); try std.testing.expectEqual(Term.Modes{}, modes(pane.terminal)); try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal)); - pane.scrollBy(100); + pane.scrollBy(pardes.config.tab_width, 100); pane.followOutput(); pane.resizeGrid(undefined, 80, 24); // no terminal: the core is never read try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); -- cgit v1.3 From cdab9ba0f0fdb433217f6b408ef81357176fa965 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 23 Nov 2026 18:20:56 -0300 Subject: perf: a long wrapped line's row walks cut to the rows the view needs, each row's end found without a grapheme step, the top's byte handed to the geometry by the step that found it, the geometry's key hashed once a step (P62 round 3, item 2): perfops against tree6 from 11 of 121 over (item 1's tree: body-appends on longline +18.2%, client-key-down on longline +1.44%) to 10 (deep-sel's eight, the view drawing the selection deep in its 2 MB line; body-appends on longline's SETUP +0.66%, derived; client-key-down on longline +0.44%; terminal on all +0.12%, below the base's own ruled +0.14%), body-appends on longline per-op -7.4%, every key, wheel, page and edit cell at or under tree6; each cut found by Intel PT by symbol (`.scratch/sketch/reorg/pardes-row-scroll-3/pt-*.txt`): `fitEnd` ended every full row with a grapheme step to learn the next byte did not fit (~118 instructions a row): a full row before a printable ASCII byte that no non-ASCII byte follows now ends there, and the rest of a row of printable ASCII past the vector loop is one masked vector (both checked by the exhaustive fitEnd tests); `show` walks the cursor's line once and no further than it needs (`Bound`: `margin` rows past the cursor's and `body - 2 margin + 1` in all, its rows a lower bound then, which its walks never pass), keeping the first bytes of its last rows in a ring on the stack, and where the view lands in that line hands that byte to the geometry (`Pane.top_skip` gains the `key` of the geometry it is for: fillBody walks to the top's row only for a key no step found it for); a wheel's notch down off the map hands the map's byte the same way; `show` and `scrollRows` hash the geometry's key once (`topNow`, `shownNow`; ensureCursorVisible's extra `geometry` call gone) and a walk asks whether the map is fresh only when it reads a line off it; `rowsOf` walks a line with the walk's width (`rowWalked`), not through `rowIn`'s one-row check again; Debug in the workspace: core-test 963/1129 (166 skipped) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/File.zig | 113 ++++++++++++++++++++++++++++++++++++++++++--------------- core/panes.zig | 10 ++--- 2 files changed, 88 insertions(+), 35 deletions(-) diff --git a/core/File.zig b/core/File.zig index 86861792..b2439b29 100644 --- a/core/File.zig +++ b/core/File.zig @@ -622,6 +622,14 @@ pub fn fitEnd(tab: u16, text: []const u8, start: usize, width: usize) usize { used += lanes; end += lanes; } + // The rest of a row of printable ASCII in one vector more: its bytes and + // the two after them printable ASCII, the row ends where the width does + // (what the loops below find a byte at a time). + if (used < width and width - used + 2 <= lanes and end + lanes <= text.len) { + const v: Lanes = text[end..][0..lanes].*; + const bad: @Int(.unsigned, lanes) = @bitCast(v -% @as(Lanes, @splat(0x20)) >= @as(Lanes, @splat(0x5f))); + if (@ctz(bad) >= width - used + 2) return end + (width - used); + } while (used < width and end < text.len) { const b = text[end]; if (b < 0x20 or b >= 0x7f) break; @@ -629,6 +637,10 @@ pub fn fitEnd(tab: u16, text: []const u8, start: usize, width: usize) usize { used += 1; end += 1; } + // A full row before a printable ASCII byte no non-ASCII byte follows (a + // grapheme of its own, a cell wide): the row ends there, nothing walked + // (every wrapped row ends so, and the walk cost a row a hundred more). + if (used == width and end > start and end < text.len and text[end] -% 0x20 < 0x5f and (end + 1 == text.len or text[end + 1] < 0x80)) return end; while (end < text.len) { const next_end = modal.nextGrapheme(text, end); const next_used = used +| graphemeDisplayWidth(tab, text[end..next_end]); @@ -1768,8 +1780,7 @@ pub fn lineRows(tab: u16, pane: *const Pane, line: usize) u32 { /// Whether every line of `pane`'s view is one row: none wider than a row /// (the text's widest, kept with its index), so its rows are its lines and /// the walks below are line arithmetic, nothing read. -fn oneRow(tab: u16, pane: *const Pane) bool { - const width = wrapWidth(pane, pane.view.wrap); +fn oneRow(tab: u16, pane: *const Pane, width: usize) bool { const f = &pane.file.?; return width == 0 or (f.line_starts.len > 0 and f.widest.cells(tab) <= width); } @@ -1780,16 +1791,24 @@ const RowIn = struct { row: u32, rows: u32 }; /// of a line's rows every map from rows to lines asks, beside the /// geometry's own map of the body (the same `fitEnd` at the same width). fn rowIn(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn { - if (pane.file != null and oneRow(tab, pane)) { - if (builtin.mode == .debug) std.debug.assert(rowWalked(tab, pane, line, col).rows == 1); + const width = wrapWidth(pane, pane.view.wrap); + if (pane.file != null and oneRow(tab, pane, width)) { + if (builtin.mode == .debug) std.debug.assert(rowWalked(tab, pane, width, line, col, .{}, &.{}).rows == 1); return .{ .row = 0, .rows = 1 }; } - return rowWalked(tab, pane, line, col); + return rowWalked(tab, pane, width, line, col, .{}, &.{}); } -fn rowWalked(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn { +/// How far a walk of a line's rows goes once the row showing its byte is +/// found: `after` rows past it and `least` in all, its rows a lower bound +/// then (what `show` needs of a long line); else to its end. +const Bound = struct { after: u32 = std.math.maxInt(u32), least: u32 = 0 }; + +/// rowIn's walk at `width`, as far as `bound`; `starts`, when it has room, +/// keeps the first byte of each row walked after the first, the last +/// `starts.len` of them (row `r` at `r % starts.len`; its caller's row 0). +fn rowWalked(tab: u16, pane: *const Pane, width: usize, line: usize, col: usize, bound: Bound, starts: []usize) RowIn { const f = if (pane.file) |*file| file else return .{ .row = 0, .rows = 1 }; - const width = wrapWidth(pane, pane.view.wrap); if (width == 0) return .{ .row = 0, .rows = 1 }; const text = sourceLine(pane, @intCast(line)); // No more bytes than a row has cells and no tab is one row: a tab is @@ -1807,8 +1826,10 @@ fn rowWalked(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn { const end = fitEnd(tab, text, at, width - displayWidth(tab, guideOf(f, text, at, width, &guide))); if (found == null and col < end) found = row; if (end >= text.len or end <= at) return .{ .row = found orelse row, .rows = row + 1 }; + if (found) |r| if (row >= r +| bound.after and row + 1 >= bound.least) return .{ .row = r, .rows = row + 1 }; at = end; row += 1; + if (starts.len > 0) starts[row % starts.len] = at; } } @@ -1816,10 +1837,15 @@ fn rowWalked(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn { /// rewrapped, an edit, the layer's lines come or gone) is read as its /// last, as the geometry's walk found it (no walk of the line a frame). pub fn top(tab: u16, pane: *Pane) Top { + if (pane.file.?.scroll_row > 0) geometry(tab, pane); + return topNow(pane); +} + +/// `top` off a geometry made already (a step that made it reads its key +/// once: each hash of it costs a long line's step a hundredth more). +fn topNow(pane: *const Pane) Top { const f = &pane.file.?; - if (f.scroll_row == 0) return .{ .line = f.scroll }; - geometry(tab, pane); - return .{ .line = f.scroll, .row = pane.top_skip.row }; + return .{ .line = f.scroll, .row = if (f.scroll_row == 0) 0 else pane.top_skip.row }; } pub fn setTop(pane: *Pane, to: Top) void { @@ -1844,7 +1870,7 @@ const Walked = struct { to: Top, moved: i64 }; fn walkKnown(tab: u16, pane: *Pane, from: Top, n: i64, known: ?Known) Walked { const last = nlines(pane.gpa, &pane.file.?) -| 1; - if (!oneRow(tab, pane)) return walkedRows(tab, pane, from, n, last, known); + if (!oneRow(tab, pane, wrapWidth(pane, pane.view.wrap))) return walkedRows(tab, pane, from, n, last, known); const to = if (n < 0) from.line -| @abs(n) else if (from.line >= last) from.line else @min(from.line +| @abs(n), last); const w: Walked = .{ .to = .{ .line = to }, .moved = @as(i64, @intCast(to)) - @as(i64, @intCast(from.line)) }; if (builtin.mode == .debug) std.debug.assert(std.meta.eql(w, walkedRows(tab, pane, from, n, last, known))); @@ -1852,9 +1878,10 @@ fn walkKnown(tab: u16, pane: *Pane, from: Top, n: i64, known: ?Known) Walked { } fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Known) Walked { - const map = mapFresh(pane); + var map: ?bool = null; + const width = wrapWidth(pane, pane.view.wrap); var t = from; - var rows = rowsOf(tab, pane, map, known, t.line); + var rows = rowsOf(tab, pane, width, &map, known, t.line); t.row = @min(t.row, rows - 1); var left = n; while (left > 0) { @@ -1870,7 +1897,7 @@ fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Kno left -= room + 1; t.line += 1; t.row = 0; - rows = rowsOf(tab, pane, map, known, t.line); + rows = rowsOf(tab, pane, width, &map, known, t.line); } } while (left < 0) { @@ -1884,7 +1911,7 @@ fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Kno } else { left += t.row + 1; t.line -= 1; - rows = rowsOf(tab, pane, map, known, t.line); + rows = rowsOf(tab, pane, width, &map, known, t.line); t.row = rows - 1; } } @@ -1894,7 +1921,7 @@ fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Kno /// The rows from `from` down to line `line`'s first row (up to it, /// negative), or null when it is more than `bound` rows away. pub fn rowsTo(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 { - if (!oneRow(tab, pane)) return rowsWalked(tab, pane, from, line, bound); + if (!oneRow(tab, pane, wrapWidth(pane, pane.view.wrap))) return rowsWalked(tab, pane, from, line, bound); const d = @as(i64, @intCast(line)) - @as(i64, @intCast(from.line)) - from.row; const to: ?i64 = if ((line > from.line and d > bound) or (line < from.line and -d > bound)) null else d; if (builtin.mode == .debug) std.debug.assert(std.meta.eql(to, rowsWalked(tab, pane, from, line, bound))); @@ -1902,16 +1929,17 @@ pub fn rowsTo(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ? } fn rowsWalked(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 { - const map = mapFresh(pane); + var map: ?bool = null; + const width = wrapWidth(pane, pane.view.wrap); var d: i64 = -@as(i64, from.row); var l = from.line; while (l < line) : (l += 1) { - d += rowsOf(tab, pane, map, null, l); + d += rowsOf(tab, pane, width, &map, null, l); if (d > bound) return null; } while (l > line) { l -= 1; - d -= rowsOf(tab, pane, map, null, l); + d -= rowsOf(tab, pane, width, &map, null, l); if (-d > bound) return null; } return d; @@ -1926,10 +1954,17 @@ fn mapFresh(pane: *const Pane) bool { /// The rows line `line` takes: counted off the map when the map is fresh /// and holds all of them in the body (no line walked: a page, a cursor -/// past the body's edge), else walked (lineRows). -fn rowsOf(tab: u16, pane: *const Pane, map: bool, known: ?Known, line: usize) u32 { +/// past the body's edge), else walked (a walk's: no line is one row). Its +/// walk's `map`: whether the map is fresh, asked the first time a line in +/// it is. +fn rowsOf(tab: u16, pane: *const Pane, width: usize, map: *?bool, known: ?Known, line: usize) u32 { if (known) |k| if (k.line == line) return k.rows; - if (map and pane.wrap_n > pane.context_rows and line >= pane.wrap_line[pane.context_rows] and line <= pane.wrap_line[pane.wrap_n - 1]) { + if (pane.wrap_n > pane.context_rows and line >= pane.wrap_line[pane.context_rows] and line <= pane.wrap_line[pane.wrap_n - 1] and + (map.* orelse fresh: { + map.* = mapFresh(pane); + break :fresh map.*.?; + })) + { const f = &pane.file.?; var rows: u32 = 0; var i: usize = pane.context_rows; @@ -1941,24 +1976,26 @@ fn rowsOf(tab: u16, pane: *const Pane, map: bool, known: ?Known, line: usize) u3 } else if (rows > 0) return rows; } } - return lineRows(tab, pane, line); + return rowWalked(tab, pane, width, line, std.math.maxInt(usize), .{}, &.{}).rows; } /// `pane`'s view moved `delta` rows (a wheel's notch is one): the rows it /// moved. pub fn scrollRows(tab: u16, pane: *Pane, delta: i64) i64 { geometry(tab, pane); - const t = top(tab, pane); + const t = topNow(pane); // Down to a row the body shows: the map has it, its line and its row in // that line, no line walked (a notch, a page). const i = @as(i64, pane.context_rows) + delta; - if (delta > 0 and pane.wrap_n > 0 and i < shownRows(tab, pane) + @as(i64, pane.context_rows)) { + if (delta > 0 and pane.wrap_n > 0 and i < shownNow(pane) + @as(i64, pane.context_rows)) { const k: usize = @intCast(i); const line: usize = @intCast(pane.wrap_line[k]); if (line < nlines(pane.gpa, &pane.file.?)) { var row: u32 = if (line == t.line) t.row else 0; for (pane.wrap_line[pane.context_rows..k]) |l| row += @intFromBool(l == pane.wrap_line[k]); setTop(pane, .{ .line = line, .row = row }); + // Its first byte is the map's: the geometry starts there. + if (pane.body_wrapped) pane.top_skip = .{ .key = geometryKey(pane, &pane.file.?), .row = row, .at = @intCast(pane.wrap_col[k]) }; return delta; } } @@ -1972,6 +2009,10 @@ pub fn scrollRows(tab: u16, pane: *Pane, delta: i64) i64 { /// before any draw, and only the state it is made of may decide it). pub fn shownRows(tab: u16, pane: *Pane) u16 { geometry(tab, pane); + return shownNow(pane); +} + +fn shownNow(pane: *const Pane) u16 { const visible = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n; return @max(1, if (pane.wrap_n == 0) pane.rows else visible -| pane.context_rows); } @@ -1984,12 +2025,12 @@ pub fn shownRows(tab: u16, pane: *Pane) u16 { pub fn show(tab: u16, pane: *Pane, line_at: i32, col: i32, margin_rows: i64) void { const f = &pane.file.?; geometry(tab, pane); - const t = top(tab, pane); + const t = topNow(pane); // The line held at the top (a sticky context row): as it is. if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == t.line) { for (pane.wrap_line[0..pane.context_rows]) |row| if (row == line_at) return; } - const body: i64 = shownRows(tab, pane); + const body: i64 = shownNow(pane); const margin: i64 = @min(margin_rows, @divTrunc(body - 1, 2)); // The row in the body (the map's, made just now), or none: the line is // above the top, or below the map. Inside the band the view stays, and @@ -1998,8 +2039,18 @@ pub fn show(tab: u16, pane: *Pane, line_at: i32, col: i32, margin_rows: i64) voi const row: ?i64 = if (mapped >= 0 and mapped < @max(pane.wrap_n, pane.rows) -| pane.context_rows) mapped else null; if (row) |r| if (r >= margin and r <= body - 1 - margin) return; const line: usize = @intCast(@max(0, line_at)); - const at = rowIn(tab, pane, line, @intCast(@max(0, col))); + // The line walked once and no further than the view needs (`Bound`: a + // long line's rows past the band are not), the first bytes of its last + // rows kept: where the view lands in it, its geometry starts there. + const width = wrapWidth(pane, pane.view.wrap); + var ring: [limits.wrap_rows]usize = undefined; + ring[0] = 0; + const starts = ring[0..@intCast(@min(body, ring.len))]; + const at = if (oneRow(tab, pane, width)) RowIn{ .row = 0, .rows = 1 } else rowWalked(tab, pane, width, line, @intCast(@max(0, col)), .{ .after = @intCast(margin), .least = @intCast(body - 2 * margin + 1) }, starts); const known: Known = .{ .line = line, .rows = at.rows }; + defer if (f.scroll == line and f.scroll_row < at.rows and at.rows - 1 - f.scroll_row < starts.len) { + pane.top_skip = .{ .key = geometryKey(pane, f), .row = f.scroll_row, .at = starts[f.scroll_row % starts.len] }; + }; if (pane.follow_edges != 0 and (row == null or row.? < 0 or row.? >= body)) pane.follow_crossed = true; const whole = at.rows <= body - 2 * margin; if (if (row) |r| r < margin else line <= t.line) { @@ -2659,7 +2710,9 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State // The top line from the view's row in it (`top`): the rows above // skipped, never past its last; walked once a geometry (the map's // pass), its text's pass a frame starting where that walk ended. - if (record_wrap) { + // A top whose byte a step already found (`show`, a scroll off the map) + // is not walked again. + if (record_wrap and pane.top_skip.key != pane.geometry_key) { var skipped: u32 = 0; while (skipped < f.scroll_row and width > 0 and body_line < total) : (skipped += 1) { const text = sourceLine(pane, @intCast(body_line)); @@ -2667,7 +2720,7 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State if (end >= text.len or end <= body_at) break; body_at = end; } - pane.top_skip = .{ .row = skipped, .at = body_at }; + pane.top_skip = .{ .key = pane.geometry_key, .row = skipped, .at = body_at }; } else body_at = pane.top_skip.at; for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| { if (i > 0) { diff --git a/core/panes.zig b/core/panes.zig index b238992a..08d91df5 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -309,10 +309,11 @@ pub const Pane = struct { wrap_n: u16 = 0, /// A row map also exists for sticky headers when soft wrapping is off. body_wrapped: bool = false, - /// Where the geometry's walk found the view's top inside its line's - /// rows (File.Top): the row it is and the bytes of the line before it; - /// a frame's text starts there with no walk again. - top_skip: struct { row: u32 = 0, at: usize = 0 } = .{}, + /// Where the view's top is inside its line's rows (File.Top) for the + /// geometry of `key`: the row it is and the bytes of the line before + /// it, found by the geometry's walk or by the step that put the top + /// there; a frame's text starts there with no walk again. + top_skip: struct { key: u64 = 0, row: u32 = 0, at: usize = 0 } = .{}, context_rows: u16 = 0, body_rows: u16 = 0, body_visible_rows: u16 = 0, @@ -668,7 +669,6 @@ pub const Pane = struct { } pub fn ensureCursorVisible(pane: *Pane, tab: u16) void { - File.geometry(tab, pane); if (pane.file != null) File.show(tab, pane, pane.body.cur_row, pane.body.cur_col, config.scroll_off) else { // A terminal's rows are its lines. const off = pane.scroll(); -- cgit v1.3 From defafb5ccce2ae30d3e16cc8fb57fb73485e03f4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 23 Nov 2026 18:26:46 -0300 Subject: scroll: what still moved by lines now counts rows where a wrapped line made it wrong (P62 round 3, item 3): gt/gb land on the row `scroll_off` rows in from the body's top or its last row of text, a wrapped line's later row as any, the cursor on the first byte that row shows (helix's goto_window), where they went `scroll_off` LINES down from the top line (inside a wrapped line: a line far below, the view moved); gw labels the words of the bytes the body shows (`File.shownBytes`: its first row's first to its last row's last), none on a wrapped line's rows above the view's top (a word the first row starts inside of begins above it: its label would not show), where it labelled the words of `rows` lines from the top line's start; a new pane goes below the rows a pane's text takes (layout.zig `blankRows`: the rows from the view's top to the text's end, `File.rowsTo`, a wrapped line's each), where a pane of a few long lines counted a row a line and had the new pane laid over its text; a Look opening a file in a pane of its own puts its line half the body's rows down, a wrapped line's rows above it counted (look.zig, `walkRows`), where it went half the body's LINES up; TESTS FIRST, each failing on item 1's tree (`qwssppvo`) and passing here: core/normal.zig "gt and gb go to the row scroll_off rows in from the body's top and from its bottom, ..." (the view moved, row 4 to 5), "gw labels the words the body shows and no others: ..." (a label above the top), core/layout.zig "a new pane goes below the rows a pane's text takes, ..." (the pane kept fewer rows than its text), core/look.zig "a Look that opens a file in a pane of its own puts its line half the body's rows down, ..." (24 rows above it, not 17); STILL LINES, each right there: Places' first range (its search pieces are whole lines, so a match is never cut at a piece's edge, and `scroll + rows + 1` lines hold every row shown, each line at least one), the frames' `view` (a statistic's label: no decision reads it), the rail's thumb (rows would wrap the whole text at each width), the syntax window (the rows shown lie inside the lines `scroll .. scroll + rows`) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/File.zig | 17 ++++++++++ core/layout.zig | 35 +++++++++++++++++--- core/look.zig | 37 +++++++++++++++++++-- core/normal.zig | 101 +++++++++++++++++++++++++++++++++++++++++++++++++++++--- 4 files changed, 179 insertions(+), 11 deletions(-) diff --git a/core/File.zig b/core/File.zig index b2439b29..8b7adae3 100644 --- a/core/File.zig +++ b/core/File.zig @@ -2095,6 +2095,23 @@ pub fn textRowLine(tab: u16, pane: *Pane, from: i64, margin: i64, way: enum { do return null; } +pub const Bytes = struct { start: usize, end: usize }; + +/// The bytes of the text `pane`'s body shows: its first row's first to its +/// last row's last (whole lines unwrapped, as each row is one). +pub fn shownBytes(tab: u16, pane: *Pane) Bytes { + const f = &pane.file.?; + const shown = shownRows(tab, pane); + if (!pane.body_wrapped) return .{ .start = lineStart(pane.gpa, f, f.scroll), .end = lineStart(pane.gpa, f, f.scroll + shown) }; + const first = pane.context_rows; + const last = first + shown - 1; + const start = lineStart(pane.gpa, f, @intCast(pane.wrap_line[first])) + @as(usize, @intCast(pane.wrap_col[first])); + const line: usize = @intCast(pane.wrap_line[last]); + if (line >= nlines(pane.gpa, f)) return .{ .start = start, .end = f.content.len }; + const text = sourceLine(pane, @intCast(line)); + return .{ .start = start, .end = lineStart(pane.gpa, f, line) + fitEnd(tab, text, @intCast(pane.wrap_col[last]), wrapWidth(pane, pane.view.wrap) -| pane.wrap_pad[last]) }; +} + /// A call stack's row after its line's first starts with its tree's guide /// (locations.treeContinuation), in `buffer`; any other row with none. fn guideOf(f: *const State, text: []const u8, at: usize, width: usize, buffer: *[1024]u8) []const u8 { diff --git a/core/layout.zig b/core/layout.zig index 4c7d6afb..7fa57ee9 100644 --- a/core/layout.zig +++ b/core/layout.zig @@ -845,10 +845,14 @@ fn bodyRows(p: *const Pardes, id: usize) u16 { fn blankRows(p: *const Pardes, id: usize) u16 { const pane = p.panes[id].?; const rows = bodyRows(p, id); - const used: usize = if (pane.file) |*f| - // The empty line after a final newline shows nothing. - (panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) -| f.scroll - else if (pane.isTerminal()) + const used: usize = if (pane.file) |*f| used: { + // The rows from the view's top to the text's end, a wrapped line's + // each; the empty line after a final newline shows nothing. + const end = panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n")); + const top = panes.File.top(p.settings.tab, pane); + if (end <= top.line) break :used 0; + break :used @intCast(panes.File.rowsTo(p.settings.tab, pane, top, end, rows) orelse rows); + } else if (pane.isTerminal()) @as(usize, panes.Term.grid(pane.terminal).cursor_y) + 1 else rows; @@ -2158,3 +2162,26 @@ test "tiny screens keep pane space before adding a column tag" { try std.testing.expectEqual(TOPBAR_H, p.view().rects[0].y); _ = try p.render(p.scratch.allocator()); } + +test "a new pane goes below the rows a pane's text takes, a wrapped line's each counted: a pane whose few lines fill its rows keeps them all" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "b.txt", .data = "other\n" }); + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(io, &buf)]; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 40 }); + defer p.deinit(); + p.settings.wrap = true; + // Two lines of 400 bytes: seven rows each at this width. + const long = &@as([400]u8, @splat('a')); + const pane = try p.setTestFile(long ++ "\n" ++ long ++ "\n"); + const a = p.view().active; + const used = panes.File.lineRows(p.settings.tab, pane, 0) + panes.File.lineRows(p.settings.tab, pane, 1); + try std.testing.expect(used >= 12); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/b.txt", .{dir}) }); + try std.testing.expect(p.view().active != a); + try std.testing.expect(p.view().rects[a].h -| pane.tag_rows >= used); +} diff --git a/core/look.zig b/core/look.zig index f60b90f5..eee808cb 100644 --- a/core/look.zig +++ b/core/look.zig @@ -1605,11 +1605,13 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // miss of its line too. if (p.fs.failures != failures) return; layout.compute(p); - nt.file.?.scroll -|= @max(1, v.rects[free].h -| BOX_H) / 2; + // Its line half the body's rows down, a wrapped line's + // rows above it counted. + const centered = panes.File.walkRows(p.settings.tab, nt, .{ .line = nt.file.?.scroll }, -@as(i64, @max(1, v.rects[free].h -| BOX_H) / 2)).to; + panes.File.setTop(nt, centered); if (target.at.end_line != 0) { - const centered = nt.file.?.scroll; selectSpan(p, nt, target.at); - nt.file.?.scroll = centered; + panes.File.setTop(nt, centered); } opened = free; } @@ -1840,6 +1842,35 @@ test "lookableLineSpan prefers the longest run, so a blank inside a path is one ); } +test "a Look that opens a file in a pane of its own puts its line half the body's rows down, a wrapped line's rows above it counted" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + // Line 10 of 600 bytes, eleven rows or more in a pane 60 wide. + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..60) |i| if (i == 10) { + try text.appendNTimes(gpa, 'a', 600); + try text.append(gpa, '\n'); + } else try text.print(gpa, "line {d:0>2}\n", .{i}); + try tmp.dir.writeFile(io, .{ .sub_path = "c.txt", .data = text.items }); + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(io, &buf)]; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 40 }); + defer p.deinit(); + p.settings.wrap = true; + _ = try p.setTestFile("x\n"); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/c.txt:14", .{dir}) }); + const id = p.view().active; + const pane = p.panes[id].?; + try std.testing.expect(panes.File.lineRows(p.settings.tab, pane, 10) >= 11); + try std.testing.expectEqual(@as(i32, 13), pane.body.cur_row); + const half: i64 = @max(1, p.view().rects[id].h -| BOX_H) / 2; + try std.testing.expectEqual(half, panes.File.rowsTo(p.settings.tab, pane, panes.File.top(p.settings.tab, pane), 13, 100).?); +} + test "a miss names a long path by its start and its end, its middle given up to …" { var cut: [miss_path_cap + "…".len]u8 = undefined; const long = "/home/someone/" ++ std.mem.asBytes(&@as([80][5]u8, @splat("deep/".*))) ++ "the-file.zig"; diff --git a/core/normal.zig b/core/normal.zig index 61f8f26b..fe0c729a 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -339,11 +339,22 @@ fn startJump(p: *Pardes, pane: *Pane, t: *Text) edit.Error!void { const text = try edit.flatSurface(p.editor(), t); const cursor = modal.selectionCursor(text, t.primaryRange(text, 0)); const top: usize = @intCast(@max(0, pane.scroll())); - const start = @min(modal.lineStartOffset(text, top), text.len); - const end = @min(modal.lineStartOffset(text, top + pane.rows), text.len); + // A file's words the body shows, its rows' bytes; a terminal's rows + // are its lines. + const shown = if (pane.file != null) File.shownBytes(p.settings.tab, pane) else File.Bytes{ .start = modal.lineStartOffset(text, top), .end = modal.lineStartOffset(text, top + pane.rows) }; + const start = @min(shown.start, text.len); + const end = @min(shown.end, text.len); const letters = config.jump_label_alphabet.len; try pane.jump.resize(p.gpa, letters * letters); - pane.jump.shrinkRetainingCapacity(modal.jumpWords(text, cursor, start, end, pane.jump.items)); + const n = modal.jumpWords(text, cursor, start, end, pane.jump.items); + // A word the body's first row starts inside of (a wrapped line's row + // cut mid-word) begins above it: no label it would not show. + var kept: usize = 0; + for (pane.jump.items[0..n]) |r| if (@min(r.anchor, r.head) >= start) { + pane.jump.items[kept] = r; + kept += 1; + }; + pane.jump.shrinkRetainingCapacity(kept); pane.jump_first = null; } @@ -978,11 +989,28 @@ fn gotoWindow(tab: u16, t: *Text, text: []const u8, range: modal.Selection, whic // a view to move through is a body's; a tag or an answer is all shown if (t.what != .body) return; const w = t.pane() orelse return; + const n: i32 = @intCast(cnt - 1); + if (w.file != null) { + // In rows, as helix's goto_window: the row `margin + n` in from the + // body's top or its last row of text, inside the margins, the + // cursor on the first byte it shows (a wrapped line's later row). + const held: i32 = w.context_rows; + const shown: i32 = File.shownRows(tab, w); + const lines = File.textLineCount(t, text); + var last: i32 = shown - 1; + while (last > 0 and w.wrapAt(tab, held + last).line >= lines) last -= 1; + const margin: i32 = @min(config.scroll_off, @divTrunc(shown - 1, 2)); + const vr = std.math.clamp(@min(@max(switch (which) { + .top => margin + n, + .bottom => last - (margin + n), + }, margin), last - margin), 0, last); + const at = w.wrapAt(tab, held + vr); + return pointMove(tab, t, text, range, File.textLineStart(t, text, @intCast(at.line)) + if (w.body_wrapped) @as(usize, @intCast(at.at)) else 0); + } const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2)); const top = w.scroll(); const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); const last_vis: i32 = @min(@as(i32, w.rows) - 1, last_row - top); - const n: i32 = @intCast(cnt - 1); var vline: i32 = switch (which) { .top => top + margin + n, .bottom => top + last_vis - (margin + n), @@ -1461,6 +1489,71 @@ test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); } +/// 10 short lines, line 10 of 200 numbered words (17 rows or more at 60 +/// columns), 40 short lines after it; the view's top four rows into line +/// 10, the cursor on a row the body shows. +fn wrappedView(p: *Pardes) !*Pane { + p.settings.wrap = true; + var text: std.ArrayList(u8) = .empty; + defer text.deinit(p.gpa); + for (0..51) |i| if (i == 10) { + for (0..200) |w| try text.print(p.gpa, "w{d:0>3} ", .{w}); + try text.append(p.gpa, '\n'); + } else try text.print(p.gpa, "line {d:0>2}\n", .{i}); + const pane = try p.setTestFile(text.items); + File.setTop(pane, .{ .line = 10, .row = 4 }); + p.sync(); + const at = pane.wrapAt(p.settings.tab, pane.context_rows + 6); + pane.body.cur_row = at.line; + pane.body.cur_col = at.at; + return pane; +} + +test "gt and gb go to the row scroll_off rows in from the body's top and from its bottom, a wrapped line's later row as any, the cursor on its first byte; the view stays" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24 }); + defer p.deinit(); + const tab = p.settings.tab; + const pane = try wrappedView(p); + const top = File.top(tab, pane); + try std.testing.expectEqual(@as(u32, 4), top.row); + for ("tb") |k| { + p.update(.{ .key = .{ .cp = 'g', .text = "g" } }); + p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); + try std.testing.expectEqual(top, File.top(tab, pane)); + const row: i32 = if (k == 't') config.scroll_off else File.shownRows(tab, pane) - 1 - config.scroll_off; + const want = pane.wrapAt(tab, pane.context_rows + row); + try std.testing.expectEqual(want.line, pane.body.cur_row); + try std.testing.expectEqual(want.at, pane.body.cur_col); + } +} + +test "gw labels the words the body shows and no others: none on a wrapped line's rows above the view's top" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24 }); + defer p.deinit(); + const tab = p.settings.tab; + const pane = try wrappedView(p); + p.update(.{ .key = .{ .cp = 'g', .text = "g" } }); + p.update(.{ .key = .{ .cp = 'w', .text = "w" } }); + try std.testing.expect(pane.jump.items.len > 20); + const f = &pane.file.?; + const shown = File.shownRows(tab, pane); + // Rows with a label: the body's first and its last among them. + var labelled: [2]bool = .{ false, false }; + for (pane.jump.items) |r| { + const at = @min(r.anchor, r.head); + const line = std.mem.count(u8, f.content[0..at], "\n"); + const col = at - File.lineStart(p.gpa, f, line); + // The row that shows its first byte is in the body, at or after + // that row's start (no row above the top). + const row = pane.wrapRow(tab, @intCast(line), @intCast(col)); + try std.testing.expect(row.row >= pane.context_rows and row.row < pane.context_rows + shown); + try std.testing.expect(col >= row.at); + if (row.row == pane.context_rows) labelled[0] = true; + if (row.row == pane.context_rows + shown - 1) labelled[1] = true; + } + try std.testing.expectEqual([2]bool{ true, true }, labelled); +} + test "flat text movement and selection replay need no scratch rows" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); -- cgit v1.3 From 59b6ac1bae9cb6720252e1c3e1cc9d4f3a8ab3b1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 01:02:27 -0300 Subject: tests: two process cases read the view in rows (P62 round 3): the gate's process-test on the tip failed two cases the base passes, both the behaviour this line changes: "tty boot: builtins" waited after `/^ +Look ` Enter for Look's row AND Exec's row on the screen; the jump puts Look's row `scroll_off` ROWS above the body's bottom (round 2's ruling: the margin counts rows) and Look's documentation wraps, so Exec's row is under the body (the base's margin of three LINES showed it): the case now waits for Look's row and the first words of its documentation (its point unchanged: the search lands on Look, `n` executes nothing); its `tutor-from-index` snapshot and "tty boot: leader"'s `tutor` snapshot have the new pane one row lower, below the +Help pane's last text row (a wrapped line there counted two rows by item 3's `blankRows`; the base laid the new pane over that row): test/snapshots/builtins.golden and leader.golden updated a case at a time (`-- --update builtins`, `-- --update leader`) and read: their rows' texts the same but the shift, the Help pane's line 15 shown again in leader's, the Tutor's last row gone in each; process-test 0 of 146 failed (2 skipped), Debug Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/process/tty_boot.zig | 7 ++-- test/snapshots/builtins.golden | 71 ++++++++++++++++++++------------------- test/snapshots/leader.golden | 75 +++++++++++++++++++++--------------------- 3 files changed, 77 insertions(+), 76 deletions(-) diff --git a/test/process/tty_boot.zig b/test/process/tty_boot.zig index 6373de84..01b35a24 100644 --- a/test/process/tty_boot.zig +++ b/test/process/tty_boot.zig @@ -130,14 +130,17 @@ fn builtins(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.key("/"); try t.send("^ +Look "); try t.key("enter"); + // Look's row and its documentation under it (the margin below the row + // a search lands on is `scroll_off` rows, and Look's documentation + // wraps: Exec's row is under the body). try t.wait(10000, "Look enter, right-click"); - try t.wait(10000, "Exec tab, middle-click"); + try t.wait(10000, "Look at its argument as B3 does"); try t.stable(700, 15000); // n moves through look-able text; it must not execute command names. try t.key("space j n space j n space j n"); try t.wait(10000, "Look enter, right-click"); - try t.wait(10000, "Exec tab, middle-click"); + try t.wait(10000, "Look at its argument as B3 does"); try t.key("space c ?"); try t.wait(10000, "under SPC c"); try t.wait(10000, "Joincol"); diff --git a/test/snapshots/builtins.golden b/test/snapshots/builtins.golden index 6d5739ef..e9786c8a 100644 --- a/test/snapshots/builtins.golden +++ b/test/snapshots/builtins.golden @@ -55,40 +55,39 @@ |28: |29: |30: -== snap tutor-from-index grid=120x67 cursor=7,36 +== snap tutor-from-index grid=120x67 cursor=7,37 |10: 1 pardes builtins under SPC h Tutor -|25: +Search 1/1 Save Undock Del -|26: /^ +Look -|27: @p2:220:1 Look enter, right-click -|35: /tmp/pardes-snap/builtins/cwd/+Tutor Save Term Collapse Follow Del -|36: 1 -|37: 2 PARDES TUTOR -|38: 3 -|39: 4 This pane is +Tutor, a copy: edit it freely; there is no need to -|40: 5 Save it (a bare Save asks for a path to write a copy to). -|41: 6 `Del` in its tag closes it; once you have edited it, `Del` refuses -|42: 7 once and the second `Del` discards. `Tutor` or SPC h t opens a -|43: 8 fresh copy. -|44: 9 -|45: 10 The guide (docs/typ/guide.typ) explains; this is the hands-on part. -|46: 11 Each lesson is a few things to do, then names its guide section. -|47: 12 Words in backticks, like `Save`, are builtins. -|48: 13 `Exec` (B2) runs the builtin a word names, or else runs it as a -|49: 14 shell line; `Look` (B3) opens what the text names, or else finds -|50: 15 it. Type a builtin in any tag and `Exec` it. Lines starting with -|51: 16 "| " are tags. -|52: 17 -|53: 18 Press j until you reach part 1. -|54: 19 -|55: 20 -|56: 21 ================================================================= -|57: 22 = PART 1 — MODES = -|58: 23 ================================================================= -|59: 24 -|60: 25 1. The box left of this pane's tag is blank, so you are in -|61: 26 NORMAL mode. Press i: it shows ^ (INSERT). Type a word, then -|62: 27 Esc: blank again. -|63: 28 2. Press Esc once more, in NORMAL: the keyboard goes back to the -|64: 29 pane you were in before (not what helix does). Come back with -|65: 30 Esc again. -|66: 31 3. Press Alt-n: a terminal opens, in NORMAL mode, and pardes types +|26: +Search 1/1 Save Undock Del +|27: /^ +Look +|28: @p2:220:1 Look enter, right-click +|36: /tmp/pardes-snap/builtins/cwd/+Tutor Save Term Collapse Follow Del +|37: 1 +|38: 2 PARDES TUTOR +|39: 3 +|40: 4 This pane is +Tutor, a copy: edit it freely; there is no need to +|41: 5 Save it (a bare Save asks for a path to write a copy to). +|42: 6 `Del` in its tag closes it; once you have edited it, `Del` refuses +|43: 7 once and the second `Del` discards. `Tutor` or SPC h t opens a +|44: 8 fresh copy. +|45: 9 +|46: 10 The guide (docs/typ/guide.typ) explains; this is the hands-on part. +|47: 11 Each lesson is a few things to do, then names its guide section. +|48: 12 Words in backticks, like `Save`, are builtins. +|49: 13 `Exec` (B2) runs the builtin a word names, or else runs it as a +|50: 14 shell line; `Look` (B3) opens what the text names, or else finds +|51: 15 it. Type a builtin in any tag and `Exec` it. Lines starting with +|52: 16 "| " are tags. +|53: 17 +|54: 18 Press j until you reach part 1. +|55: 19 +|56: 20 +|57: 21 ================================================================= +|58: 22 = PART 1 — MODES = +|59: 23 ================================================================= +|60: 24 +|61: 25 1. The box left of this pane's tag is blank, so you are in +|62: 26 NORMAL mode. Press i: it shows ^ (INSERT). Type a word, then +|63: 27 Esc: blank again. +|64: 28 2. Press Esc once more, in NORMAL: the keyboard goes back to the +|65: 29 pane you were in before (not what helix does). Come back with +|66: 30 Esc again. diff --git a/test/snapshots/leader.golden b/test/snapshots/leader.golden index 1bd0bb41..9f523992 100644 --- a/test/snapshots/leader.golden +++ b/test/snapshots/leader.golden @@ -27,28 +27,27 @@ |20: 14 Open the tutor, a document to work through. |21: 15 |22: ~ -== snap tutor grid=100x41 cursor=7,22 +== snap tutor grid=100x41 cursor=7,23 |6: 1 pardes builtins under SPC h Tutor -|21: /tmp/pardes-snap/leader/cwd/+Tutor Save Term Collapse Follow Del -|22: 1 -|23: 2 PARDES TUTOR -|24: 3 -|25: 4 This pane is +Tutor, a copy: edit it freely; there is no need to -|26: 5 Save it (a bare Save asks for a path to write a copy to). -|27: 6 `Del` in its tag closes it; once you have edited it, `Del` refuses -|28: 7 once and the second `Del` discards. `Tutor` or SPC h t opens a -|29: 8 fresh copy. -|30: 9 -|31: 10 The guide (docs/typ/guide.typ) explains; this is the hands-on part. -|32: 11 Each lesson is a few things to do, then names its guide section. -|33: 12 Words in backticks, like `Save`, are builtins. -|34: 13 `Exec` (B2) runs the builtin a word names, or else runs it as a -|35: 14 shell line; `Look` (B3) opens what the text names, or else finds -|36: 15 it. Type a builtin in any tag and `Exec` it. Lines starting with -|37: 16 "| " are tags. -|38: 17 -|39: 18 Press j until you reach part 1. -|40: 19 +|22: /tmp/pardes-snap/leader/cwd/+Tutor Save Term Collapse Follow Del +|23: 1 +|24: 2 PARDES TUTOR +|25: 3 +|26: 4 This pane is +Tutor, a copy: edit it freely; there is no need to +|27: 5 Save it (a bare Save asks for a path to write a copy to). +|28: 6 `Del` in its tag closes it; once you have edited it, `Del` refuses +|29: 7 once and the second `Del` discards. `Tutor` or SPC h t opens a +|30: 8 fresh copy. +|31: 9 +|32: 10 The guide (docs/typ/guide.typ) explains; this is the hands-on part. +|33: 11 Each lesson is a few things to do, then names its guide section. +|34: 12 Words in backticks, like `Save`, are builtins. +|35: 13 `Exec` (B2) runs the builtin a word names, or else runs it as a +|36: 14 shell line; `Look` (B3) opens what the text names, or else finds +|37: 15 it. Type a builtin in any tag and `Exec` it. Lines starting with +|38: 16 "| " are tags. +|39: 17 +|40: 18 Press j until you reach part 1. == snap deleted grid=100x41 cursor=7,3 |5: |6: @@ -69,23 +68,23 @@ |21: |22: |23: -|24: -|25: /tmp/pardes-snap/leader/cwd/+Help Save Term Collapse Follow Del -|26: 1 pardes builtins under SPC h -|27: 2 -|28: 3 SPC h b Build -|29: 4 Show this build in a +Build: its version, compiler, optimize mode, target and dependencies. -|30: 5 A stamped build's (a release, or the ~/.local install) commit, jj change and build time too,↩ -|31: its platform, its grammars, and whether the addons are compiled in. -|32: 6 -|33: 7 SPC h c Changelog topbar -|34: 8 Show this build's version and what changed to reach it, in a +Changelog. -|35: 9 -|36: 10 SPC h m Messages -|37: 11 Show the messages said so far in a +Messages. -|38: 12 -|39: 13 SPC h t Tutor topbar -|40: 14 Open the tutor, a document to work through. +|24: /tmp/pardes-snap/leader/cwd/+Help Save Term Collapse Follow Del +|25: 1 pardes builtins under SPC h +|26: 2 +|27: 3 SPC h b Build +|28: 4 Show this build in a +Build: its version, compiler, optimize mode, target and dependencies. +|29: 5 A stamped build's (a release, or the ~/.local install) commit, jj change and build time too,↩ +|30: its platform, its grammars, and whether the addons are compiled in. +|31: 6 +|32: 7 SPC h c Changelog topbar +|33: 8 Show this build's version and what changed to reach it, in a +Changelog. +|34: 9 +|35: 10 SPC h m Messages +|36: 11 Show the messages said so far in a +Messages. +|37: 12 +|38: 13 SPC h t Tutor topbar +|39: 14 Open the tutor, a document to work through. +|40: 15 == snap help-column grid=100x41 cursor=7,6 |5: /tmp/pardes-snap/leader/cwd/+Help Save Term Collapse Follow Del |6: 1 pardes builtins under SPC c -- cgit v1.3 From f0f2a5125fd4b034ebcd424afd4a55c3185191ab Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 02:44:13 -0300 Subject: layout: a view's geometry (`rects`, `col_x`, `col_w`) is the layout pass's, never dumped: every load lays each open view out again (dump.zig `afterLoad`: `layout.compute` per open view, as a resize lays it out), and `cols` is held to `ncol` (`View.replica.len`): RUN FIRST on pardes-merge67 (core/fuzz.zig's dump fuzz, the restore road's seed 589): an image's pane 0 rect read back as 534 rows on a 24-row screen (`View.rects`, dumped as it was), drawn: draw.zig:448 `clearRect`, then surface.zig:322's `at` asserted; walk.zig `pastHeld` passes over a pair whose buffer is derived; TEST FIRST: dump.zig "a view's geometry is laid out again at a load, never read: a pane's rect past its screen in a dump is the layout's after it" (merge67: expected 22, found 534); not whole alone: the dump's layout moved, and the fuzz's seeds then reach the indexes the next change holds (`live` past the views, a file's top past its text) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 8 +++++++- core/dump.zig | 28 ++++++++++++++++++++++++++++ core/walk.zig | 2 ++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/core/Core.zig b/core/Core.zig index 1894247d..ff0a84ac 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -87,7 +87,13 @@ const Pardes = @This(); /// One client's view of the session (views.zig): its screen and layout, /// its focus, its pointer and gestures, its jumps, its key prefixes. pub const View = struct { - pub const replica = .{ .len = .{ .{ "leader_keys", "leader_n" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } } }; + /// Its geometry (`rects`, `col_x`, `col_w`) is the layout pass's over + /// its columns and screen: never dumped, laid out again at a load + /// (dump.afterLoad), as a resize lays it out. + pub const replica = .{ + .len = .{ .{ "leader_keys", "leader_n" }, .{ "cols", "ncol" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } }, + .derived = .{ "rects", "col_x", "col_w" }, + }; /// A view's slot in `Pardes.views`, as it crosses the core's edge: an /// entry's argument or answer, the wire's welcome. A type of its own, /// so a pane's slot (`Pane.Id`) is not taken for it; the core's own diff --git a/core/dump.zig b/core/dump.zig index deb18dba..10d36350 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -143,6 +143,14 @@ pub fn dumpExit(p: *Pardes) !void { /// view showed in a dump made before the layer's lines were the buffer's /// (wire 31 and older: a view's bit, no lines), its lines in it (jj.loaded). fn afterLoad(p: *Pardes) void { + // Each view laid out again over its columns and its screen, as a resize + // lays it out: its geometry is derived, never read (View.replica). + const live = p.live; + for (p.views, 0..) |slot, k| if (slot != null) { + p.live = @intCast(k); + layout.compute(p); + }; + p.live = live; for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| { const text = pardes.panes.File.fileText(f, p.scratch.allocator()) catch continue; f.context.reload(p.tree_sitter_gpa, f.path, text, f.revision); @@ -1024,6 +1032,26 @@ test "a dump keeps the session's settings, and a restore applies them" { try std.testing.expect(!restored.settings.wrap); } +test "a view's geometry is laid out again at a load, never read: a pane's rect past its screen in a dump is the layout's after it" { + // The fuzz's restore road, seed 589: an image whose pane 0 said 534 + // rows on a 24-row screen, drawn: surface.zig's `at` asserted. + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const want = p.view().rects[0]; + p.view().rects[0].h = 534; + p.view().col_w[0] = 900; + const dumped = try dumpBytes(p); + defer gpa.free(dumped); + p.view().rects[0] = want; + const q = try load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, dumped, null); + defer q.deinit(); + try std.testing.expectEqual(want, q.view().rects[0]); + try std.testing.expectEqual(@as(u16, 80), q.view().col_w[0]); + _ = q.frame_arena.reset(.retain_capacity); + _ = try q.render(q.frame_arena.allocator()); +} + test "a session with every column it may hold dumps and restores them all" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 1200, .rows = 24 }); diff --git a/core/walk.zig b/core/walk.zig index 5e91490c..f6a9c088 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -249,6 +249,8 @@ const Past = struct { name: []const u8, says: usize, holds: usize }; /// its own. fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past { inline for (0..comptime pairs(T)) |i| { + // A buffer no dump carries (derived) is made again, not read. + if (comptime excluded(T, T.replica.len[i][0])) continue; const buffer = @field(v, T.replica.len[i][0]); const holds = if (comptime @typeInfo(@TypeOf(buffer)) == .array) (if (held) |h| @min(h[i], buffer.len) else buffer.len) else buffer.len; const says = lengthIn(v, T.replica.len[i][1]); -- cgit v1.3 From 2645734806155dac927967289b0f11683eb3a1d0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 02:56:05 -0300 Subject: walk: a loaded index is held to what it names, and a place to its thing, by a declaration beside the field, read by the comptime walk and checked where `pastHeld` is (the end of a struct's fields in all three decoders: a tape's `decode`, a byte dump's `Loader.fields`, an image's `Get.fields`, through `holdTo`): `replica.index` says what a field names (a field's slots, a predicate's things, or, with a third word, the things of the struct holding it, held where ITS fields end over every value of the type it holds (`heldIn`, `visit`); a fourth word: a span counted from it), and one that names none is REFUSED, the field named, in the words `fromDump` and a Restore say (`Core.live says 9, which names none of Core.openViews: refused`); `replica.place` gives a field's last place (or its first and last) and one past it is that place (the session is there, its view a line off); `replica.left_out` is what a load that left a thing out (another build's pane) does to what named it before the indexes are held (`Pardes.dropMissing`, now every view's); a field that names a slot by its type (`Pane.Id`, `View.Id`) with no declaration is a compile error (`checkSlots`). RUN FIRST, each the dump fuzz with every loaded core drawn at its size, 40x12 and 200x60 and given keys and a wheel notch (core/fuzz.zig `use`), each a panic or an allocation past the fuzz's cap on the tree before: join seed 1761, `Pardes.multi_count` read as 2^30 sized a yank's register array at 17 GB (`d`, Registers.put): a step's own, now not dumped, with `multi_*`, `exec_depth`, `exec_column` (root.zig `kept_out`); join 3682, `File.State.scroll` past its text: `@intCast` into `wrap_line` (File.zig fillBody): clamped to its last line (`lastLine`; a slim dump's file, read again at its revival, to its saved bytes' lines), `scroll_row` to the top line's bytes; join 77, `Messages.head` past its ring (logMessage): clamped (`head`, `len`); restore 1211, `View.screen_h` 0, drawn (draw.zig paintHeaders: surface.zig `at`), and join 24086/28218 a screen sizing a 111 GB frame: a view's screen side is a grid a frontend sizes or the dump is refused: a cell at least (a zero refused, not clamped, as abi/wire.zig `getCols` refuses one), at most 4096 (`View.max_grid`: past any display's; the wire's 512x128 is a client's, and a session's own frontend is wider: a replica test's view is 500 rows); join 14189, `Pane.tag_lead` past i32 (Core.sync): held to the room its prefix is made in (`Pane.prefix_room`); join 18926, an undo's `Journal.done` past its steps (Text.zig `mark`): clamped, `Step.first..n` a span of the journal's entries (refused past them), and join 35489 `Journal.bytes` overflowing (`record`): held to what its entries hold. And a bitset a load made is freed with the rest when the load fails or what held it is let go (`Bits`, on `customs`): the 40,000-seed run's leak (16 KB, `Loader.value` `.bitset`), reached once a refusal came after one was read. Declared beside them, by the brief and by reading: `Pardes.live` (an open view), `theme_file_pane`; `View.active` (a pane there, or any slot in a window with none), `window_pick`, `kind_grab`, `kind_hover`; `Column.panes` (panes there, held as far as `n` now says: a `len` pair, so a digest and a dump take that far); `Pane.sized_by`, `prompt_view`, `search_pane`; `Jump.cur` (place), `Jump.Loc.pane`; the language server's awaited `pane`. TESTS (each site was a failing run first, above): walk.zig "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image; a place past its thing's last is that last", "a thing another build's dump left out takes what named it with it (`left_out`), before the indexes are held"; dump.zig "a dump whose index names no view or pane there is refused, the field named; a top past its text is its last line; a key's replay is not dumped" Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 56 ++++++- core/File.zig | 20 +++ core/Jump.zig | 9 +- core/Messages.zig | 12 ++ core/Text.zig | 16 ++ core/dump.zig | 91 +++++++++-- core/lsp/Ask.zig | 2 + core/panes.zig | 10 ++ core/root.zig | 2 + core/walk.zig | 445 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 10 files changed, 625 insertions(+), 38 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index ff0a84ac..b2f96886 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -93,6 +93,10 @@ pub const View = struct { pub const replica = .{ .len = .{ .{ "leader_keys", "leader_n" }, .{ "cols", "ncol" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } }, .derived = .{ "rects", "col_x", "col_w" }, + // What its keyboard is on: a pane there; window mode's outline and + // a kind's press and hover, slots; its screen, a grid a frontend + // sizes (walk.zig `.index`). + .index = .{ .{ "active", Pardes, "focusPanes" }, .{ "window_pick", Pardes, "panes" }, .{ "kind_grab", Pardes, "panes" }, .{ "kind_hover", Pardes, "panes" }, .{ "screen_w", "grids" }, .{ "screen_h", "grids" } }, }; /// A view's slot in `Pardes.views`, as it crosses the core's edge: an /// entry's argument or answer, the wire's welcome. A type of its own, @@ -208,6 +212,15 @@ pub const View = struct { pastes: u32 = 0, links: u32 = 0, link: pardes.Effect.Buf(256) = .{}, + + /// A side of a grid a frontend sizes: a cell at least (a zero is + /// refused, not clamped, as the wire refuses one: abi/wire.zig + /// `getCols`), past no display's (a frame is as many cells as it + /// holds, Surface.cells: a damaged image's asked 111 GB). + pub fn grids(_: *const View, n: usize) bool { + return n >= 1 and n <= max_grid; + } + pub const max_grid = 4096; }; gpa: std.mem.Allocator, @@ -481,6 +494,11 @@ pub const replica = .{ "in_head", "in_len", // The views no frontend here draws (views.zig). "undrawn", + // A step's own, set and put back within it (a key's replay across + // the ranges, normal.replaySels; a word's run, exec.zig): as + // `init` makes them between any two steps. + "multi_first", "multi_stop", "multi_index", + "multi_count", "exec_depth", "exec_column", // How this process was started, and the last dump it made for // its host to write: a session loaded elsewhere has its own. "opts", "dump_out", "dump_export", @@ -493,8 +511,38 @@ pub const replica = .{ // server's own part of `fs` says so in fs.Namespace.) .authority = .{ "host", "store", "recent", "db", "fallback" }, .len = .{ .{ "look_src", "n_look_src" }, .{ "session_dir", "session_dir_len" }, .{ "session_home", "session_home_len" }, .{ "session_shell", "session_shell_len" } }, + // The live view is an open one; a ThemeFile's pane a slot (walk.zig + // `.index`). + .index = .{ .{ "live", "openViews" }, .{ "theme_file_pane", "panes" } }, + // A pane another build's dump could not give: out of every layout. + .left_out = "dropMissing", }; +/// What an index into the session names (walk.zig `.index`): an open view. +pub fn openViews(p: *const Pardes, k: usize) bool { + return k < Views.max and p.views[k] != null; +} + +/// A pane there. +pub fn openPanes(p: *const Pardes, id: usize) bool { + return id < MAX_PANES and p.panes[id] != null; +} + +/// What a view's keyboard may be on: a pane there, or any slot in a window +/// with none (the last column's Delcol leaves one, layout.zig `delColumn`). +pub fn focusPanes(p: *const Pardes, id: usize) bool { + if (id >= MAX_PANES) return false; + if (p.panes[id] != null) return true; + return for (p.panes) |slot| { + if (slot != null) break false; + } else true; +} + +/// The panes a view's columns list that are not there (another build's +/// dump left them out: walk.zig `left_out`) taken out of them, and its +/// keyboard on one that is. +pub const dropMissing = pardes.dump.dropMissing; + /// The message row's entry points, called from everywhere as /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. pub const setStatus = Messages.setStatus; @@ -1929,7 +1977,7 @@ pub fn sync(p: *Pardes) void { // had any; a folded pane shows its first line only. Its prefix // is made once, on the stack: this runs on every event, and not // every event may take from the scratch arena. - var wrap_room: [32 * 1024]u8 = undefined; + var wrap_room: [Pane.prefix_room]u8 = undefined; var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room); const wa = wrap_fba.allocator(); const prefix: ?[]const u8 = tagline.prefixIn(p, wa, pane) catch null; @@ -2223,9 +2271,9 @@ pub const PendingWrite = struct { bytes: []u8, off: usize = 0 }; /// place on screen (`col_x`, `col_w`) is worked out each sync, as a pane's /// rect is. pub const Column = struct { - // Zeroed, not undefined: a digest takes the whole of it, a release - // build's heap leaves its unused slots whatever was there before, and - // two replicas must agree on them (core/replica.zig). + /// Its panes, as far as `n` says (what a digest, a dump and a copy take), + /// each a pane there (walk.zig `.index`). + pub const replica = .{ .len = .{.{ "panes", "n" }}, .index = .{.{ "panes", Pardes, "openPanes" }} }; panes: [MAX_PANES]usize = @splat(0), n: usize = 0, weight: u64 = column_weight_unit, diff --git a/core/File.zig b/core/File.zig index 8b7adae3..8e464d61 100644 --- a/core/File.zig +++ b/core/File.zig @@ -108,8 +108,28 @@ pub const State = struct { // none of their bytes, and takes back what a speculation wrote // (core/rollback.zig `Epoch.wrote`). .journal = .{ "content", "line_starts" }, + // Where the view's top is, held to its text (walk.zig `.place`). + .place = .{ .{ "scroll", "lastLine" }, .{ "scroll_row", "lastRow" } }, }; + /// The last line a view's top may be at: its text's. A clean file a + /// slim dump left the text of (dump.zig `Slim`, read from its file + /// again when it is revived) has a line a byte of what it saved at most, + /// in the rows a view counts (`Pane.wrap_line`). + pub fn lastLine(f: *const State) usize { + if (f.content.len == 0) if (f.saved_len) |n| return @min(n, std.math.maxInt(i32)); + return modal.lineCount(f.content) -| 1; + } + + /// The last row of the top's line its top may be at: a row holds a byte + /// of it at least (its rows as wrapped are the view's, made after). + pub fn lastRow(f: *const State) usize { + if (f.content.len == 0) return 0; + const at = modal.lineStartOffset(f.content, f.scroll); + const end = std.mem.indexOfScalarPos(u8, f.content, at, '\n') orelse f.content.len; + return end - at; + } + path: []u8, content: []u8, /// The bytes `content`'s buffer has room for (0: as many as it holds): diff --git a/core/Jump.zig b/core/Jump.zig index ccdb8fdc..a83b6ab4 100644 --- a/core/Jump.zig +++ b/core/Jump.zig @@ -27,12 +27,19 @@ cur: usize = 0, /// (a query answered: Ctrl-o goes back to where it was asked). force: bool = false, -pub const replica = .{ .len = .{.{ "list", "n" }} }; +/// `cur` held to the places there are (walk.zig `.place`). +pub const replica = .{ .len = .{.{ "list", "n" }}, .place = .{.{ "cur", "lastCur" }} }; + +pub fn lastCur(j: *const Jump) usize { + return j.n -| 1; +} const Mouse = pardes.Mouse; const recent_path_cap = limits.host_path_cap; pub const Loc = struct { + /// Its pane's slot (walk.zig `.index`), that pane while `serial` says. + pub const replica = .{ .index = .{.{ "pane", Pardes, "panes" }} }; pane: u16, /// 0 once its pane has closed: a file's entry stays, reopened by a /// jump to it from `path_hash`'s recent entry. diff --git a/core/Messages.zig b/core/Messages.zig index 18b10ff8..040b8d2c 100644 --- a/core/Messages.zig +++ b/core/Messages.zig @@ -19,6 +19,10 @@ const Pardes = pardes.Pardes; const Messages = @This(); +/// Where its ring's next line goes and how many it holds, held to the ring +/// where a dump is read back (walk.zig `.place`). +pub const replica = .{ .place = .{ .{ "head", "lastSlot" }, .{ "len", "size" } } }; + /// The message-row log: a fixed ring, never allocated, never grown. See /// `logMessage` and the `Messages` builtin. log: [limits.message_log]LoggedMessage = @splat(.{}), @@ -26,6 +30,14 @@ log: [limits.message_log]LoggedMessage = @splat(.{}), head: usize = 0, len: usize = 0, +pub fn lastSlot(m: *const Messages) usize { + return m.log.len - 1; +} + +pub fn size(m: *const Messages) usize { + return m.log.len; +} + pub const LoggedMessage = struct { pub const cap = 256; pub const replica = .{ .len = .{.{ "text", "len" }} }; diff --git a/core/Text.zig b/core/Text.zig index ba544bff..37feb081 100644 --- a/core/Text.zig +++ b/core/Text.zig @@ -426,6 +426,8 @@ pub const Place = struct { /// (`entries[first..][0..n]`), and the places at its edges: an undo goes /// back to `before`, a redo to `after`, where it was undone from. pub const Step = struct { + /// Its entries are the journal's (walk.zig `.index`, a span). + pub const replica = .{ .index = .{.{ "first", Journal, "entries", "n" }} }; first: usize, n: usize = 0, before: Place, @@ -438,12 +440,26 @@ pub const Step = struct { /// limits.undo_max steps and limits.undo_bytes of what they hold, the /// oldest step dropped first and the newest kept whatever its size. pub const Journal = struct { + /// `done` held to its steps, `bytes` to what its entries hold (walk.zig + /// `.place`). + pub const replica = .{ .place = .{ .{ "done", "stepCount" }, .{ "bytes", "entryBytes" } } }; steps: std.ArrayList(Step) = .empty, done: usize = 0, entries: std.ArrayList(Entry) = .empty, /// What the entries hold: the bytes they took out, and their own size. bytes: usize = 0, + pub fn stepCount(j: *const Journal) usize { + return j.steps.items.len; + } + + /// What `bytes` says, its one place: what the entries hold. + pub fn entryBytes(j: *const Journal) [2]usize { + var n: usize = 0; + for (j.entries.items) |e| n +|= held(e); + return .{ n, n }; + } + pub fn deinit(j: *Journal, gpa: std.mem.Allocator) void { for (j.entries.items) |e| free(gpa, e); j.entries.deinit(gpa); diff --git a/core/dump.zig b/core/dump.zig index 10d36350..9dcc076e 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -563,21 +563,25 @@ fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void { pane.terminal = try pardes.Term.open(&p.outside, pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows)); } -/// The panes a column lists that are not there (another build's dump left -/// them out) taken out of it, and the keyboard on one that is. -fn dropMissing(p: *Pardes) void { - const v = p.view(); - for (0..p.view().ncol) |c| { - var n: usize = 0; - for (v.cols[c].panes[0..p.view().cols[c].n]) |id| if (id < MAX_PANES and p.panes[id] != null) { - v.cols[c].panes[n] = id; - n += 1; - }; - v.cols[c].n = n; - } - if (v.active >= MAX_PANES or p.panes[v.active] == null) v.active = for (p.panes, 0..) |slot, i| { - if (slot != null) break i; - } else 0; +/// The panes each view's columns list that are not there (another build's +/// dump left them out) taken out of them, and its keyboard on one that is: +/// at the load's end, and where the core's fields end (walk.zig +/// `left_out`), before what names a pane is held to one there. Every view: +/// the live one may not be one yet then. (Their lengths are held already.) +pub fn dropMissing(p: *Pardes) void { + for (&p.views) |*slot| if (slot.*) |*v| { + for (v.cols[0..v.ncol]) |*col| { + var n: usize = 0; + for (col.panes[0..col.n]) |id| if (id < MAX_PANES and p.panes[id] != null) { + col.panes[n] = id; + n += 1; + }; + col.n = n; + } + if (v.active >= MAX_PANES or p.panes[v.active] == null) v.active = for (p.panes, 0..) |s, i| { + if (s != null) break i; + } else 0; + }; } /// The replacement core for a Restore of the dump at `from`, whose log says @@ -1052,6 +1056,63 @@ test "a view's geometry is laid out again at a load, never read: a pane's rect p _ = try q.render(q.frame_arena.allocator()); } +test "a dump whose index names no view or pane there is refused, the field named; a top past its text is its last line; a key's replay is not dumped" { + // The fuzz's join road (core/fuzz.zig): `live` read past the views + // (views.zig `bit`), a file's top past its text (File.zig fillBody's + // `wrap_line`), and `multi_count` sizing a yank's register at 17 GB. + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\n"); + const id = p.view().active; + const Refused = struct { + fn by(q: *Pardes, why: []const u8) !void { + inline for (.{ byteDump, dumpBytes }) |dumpOf| { + const bytes = try dumpOf(q); + defer q.gpa.free(bytes); + var notes: std.ArrayList(u8) = .empty; + defer notes.deinit(q.gpa); + try std.testing.expectError(error.BadDump, load(q.gpa, q.opts, bytes, ¬es)); + std.testing.expect(std.mem.indexOf(u8, notes.items, why) != null) catch |err| { + std.debug.print("refused, but not by {s}: {s}\n", .{ why, notes.items }); + return err; + }; + } + } + }; + // No view open to write the shares of (the live one's are its panes'). + p.live = 9; + p.views_open = 0; + try Refused.by(p, "live says 9"); + p.live = 0; + p.views_open = 1; + p.view().active = 9; + try Refused.by(p, ".active says 9"); + p.view().active = id; + const col = &p.view().cols[0].panes[0]; + col.* = 9; + try Refused.by(p, "Column.panes says 9"); + col.* = id; + pane.sized_by = 7; + try Refused.by(p, "Pane.sized_by says 7"); + pane.sized_by = 0; + // Where a thing is, past its end: its last place, the session there. + pane.file.?.scroll = 1 << 40; + p.multi_count = 1 << 30; + inline for (.{ byteDump, dumpBytes }) |dumpOf| { + const bytes = try dumpOf(p); + defer gpa.free(bytes); + const q = try load(gpa, p.opts, bytes, null); + defer q.deinit(); + try std.testing.expectEqual(@as(usize, 2), q.panes[id].?.file.?.scroll); + try std.testing.expectEqual(@as(usize, 1), q.multi_count); + _ = q.frame_arena.reset(.retain_capacity); + _ = try q.render(q.frame_arena.allocator()); + } + pane.file.?.scroll = 0; + p.multi_count = 1; +} + test "a session with every column it may hold dumps and restores them all" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 1200, .rows = 24 }); diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig index 4d57f21e..29d36f0a 100644 --- a/core/lsp/Ask.zig +++ b/core/lsp/Ask.zig @@ -27,6 +27,8 @@ seq: u32 = 0, last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } = null, /// The query whose answer is awaited. wait: ?struct { + /// Its pane's slot (walk.zig `.index`), that pane while `serial` says. + pub const replica = .{ .index = .{.{ "pane", pardes.Pardes, "panes" }} }; id: u32, kind: lsp.Kind, pane: Pane.Id, diff --git a/core/panes.zig b/core/panes.zig index 08d91df5..62814227 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -36,7 +36,17 @@ pub const Pane = struct { // A picture's memory is its own allocator's (a dump loaded makes // it there). .alloc = .{ .{ "addon", "image" }, .{ "pdf", "image" }, .{ "terminal", "terminal" } }, + // Slots of the session's (walk.zig `.index`): a view's, a pane's, + // each looked at before it is used (one gone since is no error). + .index = .{ .{ "sized_by", Pardes, "views" }, .{ "prompt_view", Pardes, "views" }, .{ "search_pane", Pardes, "panes" } }, + // The tag's prefix as it was placed: one its room holds. + .place = .{.{ "tag_lead", "leadRoom" }}, }; + /// The room a tag's computed prefix is made in, each step (Pardes.sync). + pub const prefix_room = 32 * 1024; + pub fn leadRoom(_: *const Pane) usize { + return prefix_room; + } /// A pane's slot in `Pardes.panes`, as it crosses the core's edge: an /// entry's argument or answer, an event's, an effect's, a host call's. /// A type of its own, so a view's slot (`View.Id`) is not taken for diff --git a/core/root.zig b/core/root.zig index 7056935d..3128f37b 100644 --- a/core/root.zig +++ b/core/root.zig @@ -748,6 +748,8 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; the terminal's own digest covers its active area, not its history (Term.zig `calls`)" }, .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" }, .{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" }, + .{ "Core.zig", "multi_first multi_stop multi_index multi_count exec_depth exec_column", "a step's own: set by a key's replay across the ranges (normal.replaySels) and a word's run (exec.zig), each put back before the step ends; between steps what `init` makes, so a load takes them as it makes them (a dump's said 2^30 ranges once: a yank sized its register by it)" }, + .{ "Core.zig", "rects col_x col_w", "a view's geometry: the layout pass's (layout.compute) over its columns and screen, at every sync and resize, and at a load (dump.afterLoad); never read before it" }, .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, .{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" }, diff --git a/core/walk.zig b/core/walk.zig index f6a9c088..25e4bdc3 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -259,14 +259,255 @@ fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past return null; } -/// Every name an annotation gives is a field: a rename cannot quietly put -/// a field back in the digest. +// ---- an index read back is held to what it names ---- +// +// A field that NAMES one of the things a session holds (a view by its slot, +// a pane by its) says what, beside it, as a length says its buffer; a field +// that says WHERE in a thing it is (a scroll, a row), the thing's last place: +// +// pub const replica = .{ +// // One of the slots field `views` has (as many as it holds), or one +// // a predicate of the struct says is there (`fn (*const T, usize) +// // bool`); a third word, one of the things of the struct named +// // second that holds this one (held where ITS fields end, every +// // value of this type it holds); a fourth, the field counting a +// // span of them from it (all within the field named third). +// .index = .{ .{ "sized_by", Pardes, "views" }, .{ "live", "openViews" }, .{ "first", Journal, "entries", "n" } }, +// // Its last place, a function of the struct (`fn (*const T) usize`), +// // or its first and last (`[2]usize`). +// .place = .{ .{ "scroll", "lastLine" } }, +// // What a load that left one of its things out (another build's +// // pane) does to what names it (`fn (*T) void`), before its indexes +// // are held. +// .left_out = "dropMissing", +// }; +// +// A value read back (a tape, a dump, an image: bytes from another process or +// the disk) is held to them where its fields end, beside its lengths +// (`pastHeld`), every declaration of every type at once: an index that names +// none is REFUSED, its field named (the dump is not the session: the view, +// the pane it names is not there); a place past its thing's last is that +// LAST (the session is there, its view a line off). A field that names a +// slot by its type (`Pane.Id`, `View.Id`) and says nothing is a compile +// error (`checkSlots`); a bare integer that does is found by reading, as +// the lengths' were, until it is typed as its slot. + +fn declared(comptime T: type, comptime kind: []const u8) usize { + return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), kind)) @field(T.replica, kind).len else 0; +} + +/// An index read back that names none of what it says it indexes. +const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8 }; + +/// What an index field says, as a number: an integer, an optional one's (null +/// names nothing), a slot's enum's (`Pane.Id`). +fn number(comptime F: type, v: F) ?usize { + return switch (@typeInfo(F)) { + .int => std.math.cast(usize, v) orelse std.math.maxInt(usize), + .optional => |o| if (v) |x| number(o.child, x) else null, + .@"enum" => |e| number(e.tag_type, @backingInt(v)), + else => @compileError("walk: an `index` names a thing by a number, not " ++ @typeName(F)), + }; +} + +/// How many of field `name`'s elements `v` holds: as far as its length says. +fn heldOf(comptime T: type, v: *const T, comptime name: []const u8) usize { + const all = &@field(v, name); + if (comptime isList(@TypeOf(all.*))) return all.items.len; + return if (comptime lengthOf(T, name)) |len| @min(lengthIn(v, len), all.len) else all.len; +} + +/// Whether `h` has the thing `i` names by `what`: a field of it (one of its +/// slots), or a predicate of it. +fn hasThing(comptime H: type, h: *const H, comptime what: []const u8, i: usize) bool { + if (comptime @hasField(H, what)) { + return i < heldOf(H, h, what); + } else return @field(H, what)(h, i); +} + +/// The first number field `name` of `u` says (each of an array as far as its +/// length says) that names no thing of `h`'s by `what`. +fn firstUnnamed(comptime U: type, u: *const U, comptime name: []const u8, comptime H: type, h: *const H, comptime what: []const u8) ?usize { + const F = @FieldType(U, name); + if (comptime @typeInfo(F) == .array) { + for (@field(u, name)[0..heldOf(U, u, name)]) |e| if (number(@typeInfo(F).array.child, e)) |i| if (!hasThing(H, h, what, i)) return i; + return null; + } + const i = number(F, @field(u, name)) orelse return null; + return if (hasThing(H, h, what, i)) null else i; +} + +/// `at` held to `[first, last]`: a place past its thing's last is that last. +fn clampTo(comptime F: type, at: *F, first: usize, last: usize) void { + switch (@typeInfo(F)) { + .int => if (at.* > last) { + at.* = @intCast(last); + } else if (at.* < first) { + at.* = @intCast(first); + }, + .optional => |o| if (at.*) |*x| clampTo(o.child, x, first, last), + else => @compileError("walk: a `place` is a number, not " ++ @typeName(F)), + } +} + +/// The types `T`'s value holds whose indexes name `T`'s things (a third word +/// `T`): held where `T`'s fields end. +fn heldIn(comptime T: type) []const type { + comptime { + if (!@hasDecl(T, "replica")) return &.{}; + var out: []const type = &.{}; + for (graph(&.{T})) |U| if (@typeInfo(U) == .@"struct") for (0..declared(U, "index")) |k| { + const d = U.replica.index[k]; + if (d.len >= 3) if (d[1] == T) { + out = out ++ .{U}; + break; + }; + }; + return out; + } +} + +/// Whether a value of `X` can hold a `U`, as a dump walks it. +fn reaches(comptime X: type, comptime U: type) bool { + comptime { + @setEvalBranchQuota(100_000_000); + return switch (kindOf(Canon(X))) { + .@"struct", .optional, .one, .slice, .array, .@"union" => for (graph(&.{Canon(X)})) |Y| { + if (Y == U) break true; + } else false, + else => false, + }; + } +} + +/// `v`'s places held to their things' last, then the first of its indexes, +/// and of every value it holds whose indexes name its things, that names +/// none (see above). +fn heldIndexes(comptime T: type, v: *T) ?Unnamed { + inline for (0..comptime declared(T, "place")) |k| { + const d = T.replica.place[k]; + const held = @field(T, d[1])(v); + const span: [2]usize = if (@TypeOf(held) == usize) .{ 0, held } else held; + clampTo(@FieldType(T, d[0]), &@field(v, d[0]), span[0], span[1]); + } + inline for (0..comptime declared(T, "index")) |k| { + const d = T.replica.index[k]; + if (comptime d.len == 2) if (firstUnnamed(T, v, d[0], T, v, d[1])) |i| + return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1] }; + } + inline for (comptime heldIn(T)) |U| if (visit(T, v, U, T, v, 0)) |bad| return bad; + return null; +} + +/// Every `U` that `x` holds (its fields as a dump walks them, as far as each +/// length says; optionals, arrays, slices, lists, unions and pointers +/// followed), its indexes into `h`'s things held; the first that names none. +/// A value nested past `max_depth` (a pointer that is its own holder: a +/// damaged dump's) is refused too. +fn visit(comptime X: type, x: *const X, comptime U: type, comptime H: type, h: *const H, depth: u16) ?Unnamed { + if (comptime !reaches(X, U)) return null; + if (depth == max_depth) return .{ .holder = @typeName(X), .name = "", .says = depth, .of = "a depth a session's values nest to" }; + if (X == U) inline for (0..comptime declared(U, "index")) |k| { + const d = U.replica.index[k]; + if (comptime d.len >= 3) if (comptime d[1] == H) { + const of = @typeName(H) ++ "." ++ d[2]; + if (comptime d.len == 3) { + if (firstUnnamed(U, x, d[0], H, h, d[2])) |i| return .{ .holder = @typeName(U), .name = d[0], .says = i, .of = of }; + } else { + // A span: as many as its count says from it, all there (an + // empty one may stand at their end). + const end = @as(usize, @field(x, d[0])) +| @field(x, d[3]); + if (end > heldOf(H, h, d[2])) return .{ .holder = @typeName(U), .name = d[0], .says = @field(x, d[0]), .of = of }; + } + }; + }; + switch (@typeInfo(X)) { + .optional => |o| if (x.*) |*c| return visit(o.child, c, U, H, h, depth + 1), + .array => |a| for (x) |*e| if (visit(a.child, e, U, H, h, depth + 1)) |bad| return bad, + .pointer => |p| switch (p.size) { + .one => return visit(p.child, x.*, U, H, h, depth + 1), + .slice => for (x.*) |*e| if (visit(p.child, e, U, H, h, depth + 1)) |bad| return bad, + else => {}, + }, + .@"struct" => { + if (comptime isAtomic(X)) return visit(@FieldType(X, "raw"), &x.raw, U, H, h, depth + 1); + if (comptime isList(X)) return visit(@FieldType(X, "items"), &x.items, U, H, h, depth + 1); + inline for (comptime dumpFields(X)) |name| { + const F = @FieldType(X, name); + if (comptime reaches(F, U)) { + if (comptime lengthOf(X, name) != null) { + for (@field(x, name)[0..heldOf(X, x, name)]) |*e| if (visit(Element(F), e, U, H, h, depth + 1)) |bad| return bad; + } else if (visit(F, &@field(x, name), U, H, h, depth + 1)) |bad| return bad; + } + } + }, + .@"union" => switch (x.*) { + inline else => |*payload| return visit(@TypeOf(payload.*), payload, U, H, h, depth + 1), + }, + else => {}, + } + return null; +} + +/// `out`'s lengths held to what their buffers hold as read (`pastHeld`), and +/// its indexes to what they name (`heldIndexes`), where a reader (`Loader`, +/// `Get`) has read its fields: the dump refused, the field named. One that +/// left a thing out since `dropped` (another build's pane) first has `T`'s +/// `left_out` take out what names it. +fn holdTo(l: anytype, comptime T: type, out: *T, held: *const [pairs(T)]usize, dropped: usize) error{BadDump}!void { + if (pastHeld(T, out, held)) |past| { + l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds }); + return error.BadDump; + } + if (comptime @hasDecl(T, "replica")) if (comptime @hasField(@TypeOf(T.replica), "left_out")) if (l.dropped != dropped) @field(T, T.replica.left_out)(out); + if (heldIndexes(T, out)) |bad| { + l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of }); + return error.BadDump; + } +} + +/// A slot's type (`Pane.Id`, `View.Id`: an enum that is `at` a slot and +/// gives its `index`), bare, optional or in an array. +fn isSlot(comptime F: type) bool { + return switch (@typeInfo(F)) { + .optional => |o| isSlot(o.child), + .array => |a| isSlot(a.child), + .@"enum" => @hasDecl(F, "at") and @hasDecl(F, "index"), + else => false, + }; +} + +/// A field a dump carries that names a slot by its type says what it +/// indexes (`.index`): a compile error otherwise, so that one added later +/// is held where it is read back. +fn checkSlots(comptime T: type) void { + for (dumpFields(T)) |name| if (isSlot(@FieldType(T, name))) { + for (0..declared(T, "index")) |k| { + if (std.mem.eql(u8, T.replica.index[k][0], name)) break; + } else @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " names a slot: say what it indexes (`replica.index`)"); + }; +} + +/// Every name an annotation gives is a field (and what an index or a place +/// says it is held to, a field or a function): a rename cannot quietly put a +/// field back in the digest, nor take one out of its rule. fn checkAnnotations(comptime T: type) void { if (!@hasDecl(T, "replica")) return; inline for (@typeInfo(@TypeOf(T.replica)).@"struct".field_names) |kind| { + if (comptime std.mem.eql(u8, kind, "left_out")) { + if (!@hasDecl(T, T.replica.left_out)) @compileError("walk: " ++ @typeName(T) ++ " has no " ++ T.replica.left_out ++ " for what a load left out"); + continue; + } inline for (@field(T.replica, kind)) |entry| { - const name = if (comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc")) entry[0] else entry; + const pair = comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc") or std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place"); + const name = if (pair) entry[0] else entry; if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name); + if (comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place")) { + const H = if (entry.len >= 3) entry[1] else T; + const what = if (entry.len >= 3) entry[2] else entry[1]; + if (entry.len == 4) if (!@hasField(T, entry[3])) @compileError("walk: " ++ @typeName(T) ++ " counts its span by no field " ++ entry[3]); + if (!@hasField(H, what) and !@hasDecl(H, what)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is held to " ++ what ++ ", which " ++ @typeName(H) ++ " has not"); + } } } } @@ -634,7 +875,7 @@ pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T { try decodeError(F, r, &@field(out, name)); } else @field(out, name) = try decode(F, r, a); } - if (pastHeld(T, &out, null) != null) return error.BadTape; + if (pastHeld(T, &out, null) != null or heldIndexes(T, &out) != null) return error.BadTape; return out; }, .@"union" => |u| { @@ -818,7 +1059,10 @@ fn collect(comptime T: type, comptime list: []const type) []const type { comptime { for (list) |U| if (U == T) return list; var out: []const type = list ++ .{T}; - if (kindOf(T) == .@"struct") checkAnnotations(T); + if (kindOf(T) == .@"struct") { + checkAnnotations(T); + checkSlots(T); + } for (children(T)) |C| out = collect(C, out); return out; } @@ -1205,6 +1449,8 @@ pub const Loader = struct { filled: usize = 0, /// How deep `skip` is in the dump's own types. depth: u16 = 0, + /// How many things (a session's panes) it left out (`holdTo`). + dropped: usize = 0, pub fn init(gpa: std.mem.Allocator, bytes: []const u8, table: []const u8) DecodeError!Self { var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) }; @@ -1550,6 +1796,10 @@ pub const Loader = struct { .bitset => { const bits = try l.bitCount(); out.* = try .initEmpty(l.gpa, bits); + l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| { + out.deinit(l.gpa); + return err; + }; const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize))); }, @@ -1618,6 +1868,7 @@ pub const Loader = struct { if (droppable) { l.letGo(before); out[i] = null; + l.dropped += 1; l.note("{s}[{d}] left out", .{ l.field, i }); } else failed = true; }; @@ -1630,6 +1881,7 @@ pub const Loader = struct { const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed"; const outer = l.field; defer l.field = outer; + const dropped = l.dropped; // How far each array a length cuts was read: none yet (one read in // place holds what it held). var held: [pairs(T)]usize = @splat(if (existing) std.math.maxInt(usize) else 0); @@ -1640,7 +1892,7 @@ pub const Loader = struct { try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing); if (comptime pairAt(T, field)) |i| held[i] = l.filled; } - return l.heldTo(T, out, &held); + return holdTo(l, T, out, &held, dropped); } var found: std.StaticBitSet(@max(1, names.len)) = .empty; var failed = false; @@ -1684,15 +1936,7 @@ pub const Loader = struct { } }; if (failed) return error.Incompatible; - return l.heldTo(T, out, &held); - } - - /// `out`'s lengths held to what their buffers hold as read (`pastHeld`): - /// the dump refused, the length named. - fn heldTo(l: *Self, comptime T: type, out: *const T, held: *const [pairs(T)]usize) DecodeError!void { - const past = pastHeld(T, out, held) orelse return; - l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds }); - return error.BadDump; + return holdTo(l, T, out, &held, dropped); } fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void { @@ -1779,6 +2023,16 @@ pub const Loader = struct { } }; +/// A bitset a load made, freed as a `dumpRead`'s value is (`customs`) when +/// the load fails or what held it is let go: its words are no `made` slice. +fn Bits(comptime T: type) type { + return struct { + fn free(b: *T, gpa: std.mem.Allocator) void { + b.deinit(gpa); + } + }; +} + /// `out` as a new `T` is before a load reads its fields: each field's /// default, an allocator `gpa`. fn freshOf(comptime T: type, out: *T, gpa: std.mem.Allocator) void { @@ -2069,6 +2323,8 @@ pub const Get = struct { allocs: Allocators = .{}, /// How many elements the last array read holds (`pastHeld`). filled: usize = 0, + /// How many things (a session's panes) it left out (`holdTo`). + dropped: usize = 0, const Cursor = Mem.Cursor(.read_only); pub const Error = error{ BadDump, Incompatible, OutOfMemory }; @@ -2330,6 +2586,10 @@ pub const Get = struct { const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); if (got.value.len != 8 + words * @sizeOf(usize)) return error.BadDump; out.* = try .initEmpty(l.gpa, bits); + l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| { + out.deinit(l.gpa); + return err; + }; if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), got.value[8..]); }, } @@ -2510,6 +2770,7 @@ pub const Get = struct { if (droppable) { l.letGo(before); out[i] = null; + l.dropped += 1; l.note("{s}[{d}] left out", .{ l.field, i }); } else failed = true; }; @@ -2521,6 +2782,7 @@ pub const Get = struct { const names = comptime dumpFields(T); const outer = l.field; defer l.field = outer; + const dropped = l.dropped; const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible; var found: std.StaticBitSet(@max(1, names.len)) = .empty; var failed = false; @@ -2572,9 +2834,7 @@ pub const Get = struct { }; }; if (failed) return error.Incompatible; - const past = pastHeld(T, out, &held) orelse return; - l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds }); - return error.BadDump; + return holdTo(l, T, out, &held, dropped); } fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void { @@ -2886,6 +3146,155 @@ test "a length past what its buffer holds is refused where it is read back (a ta try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?)); } +test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image; a place past its thing's last is that last" { + const S = struct { + const Self = @This(); + const Inner = struct { + at: u8 = 0, + list: [3]u8 = @splat(0), + n: u8 = 0, + // Indexes into the struct holding it, held where its fields end. + pub const replica = .{ .len = .{.{ "list", "n" }}, .index = .{ .{ "at", Self, "there" }, .{ "list", Self, "there" } } }; + }; + things: [4]?u8 = @splat(null), + live: u8 = 0, + slot: ?u16 = null, + scroll: u32 = 0, + inner: [2]?*Inner = @splat(null), + pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }} }; + pub fn there(s: *const Self, i: usize) bool { + return i < s.things.len and s.things[i] != null; + } + pub fn last(_: *const Self) usize { + return 9; + } + }; + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var inner: S.Inner = .{ .at = 2, .list = .{ 0, 2, 1 }, .n = 2 }; + const good: S = .{ .things = .{ 1, null, 3, null }, .live = 2, .slot = 3, .scroll = 50, .inner = .{ &inner, null } }; + // Each a value no session has: the field it names. + const Bad = struct { []const u8, S }; + var bad_at: S.Inner = .{ .at = 1 }; + var bad_list: S.Inner = .{ .list = .{ 0, 3, 0 }, .n = 2 }; + const bad = [_]Bad{ + .{ "S.live says 1", blk: { + var v = good; + v.live = 1; + break :blk v; + } }, + .{ "S.slot says 4", blk: { + var v = good; + v.slot = 4; + break :blk v; + } }, + .{ "Inner.at says 1", blk: { + var v = good; + v.inner[1] = &bad_at; + break :blk v; + } }, + .{ "Inner.list says 3", blk: { + var v = good; + v.inner[1] = &bad_list; + break :blk v; + } }, + }; + var notes: std.ArrayList(u8) = .empty; + + // A dump. + const bytes = try save(S, gpa, &good); + defer gpa.free(bytes); + const back = try load(S, a, bytes, null); + try std.testing.expectEqual(@as(u32, 9), back.scroll); + try std.testing.expectEqual(@as(?u16, 3), back.slot); + for (bad) |b| { + const dumped = try save(S, gpa, &b[1]); + defer gpa.free(dumped); + notes.clearRetainingCapacity(); + try std.testing.expectError(error.BadDump, load(S, a, dumped, ¬es)); + try std.testing.expect(std.mem.indexOf(u8, notes.items, b[0]) != null); + } + + // A tape. + var buf: [256]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try encode(S, &good, &w); + for (bad) |b| try encode(S, &b[1], &w); + var r: Reader = .{ .bytes = w.buffered() }; + try std.testing.expectEqual(@as(u32, 9), (try decode(S, &r, a)).scroll); + for (bad) |_| try std.testing.expectError(error.BadTape, decode(S, &r, a)); + + // An image. + var image: std.Io.Writer.Allocating = .init(gpa); + defer image.deinit(); + var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 }); + var put: Put = .{ .gpa = gpa }; + defer put.deinit(); + try db.runContext(struct { + put: *Put, + good: *const S, + bad: []const Bad, + pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void { + const map = try Mem.HashMap(.read_write).init(cursor.*); + try ctx.put.member(map, "good", S, ctx.good); + inline for (0..4) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]); + } + }{ .put = &put, .good = &good, .bad = &bad }); + var get: Get = .init(a); + defer get.deinit(); + const root = db.rootCursor().readOnly(); + try std.testing.expectEqual(@as(u32, 9), (try get.get(S, (try Get.member(root, "good")).?)).scroll); + inline for (0..4) |i| { + get.notes.clearRetainingCapacity(); + try std.testing.expectError(error.BadDump, get.get(S, (try Get.member(root, std.fmt.comptimePrint("bad{d}", .{i}))).?)); + try std.testing.expect(std.mem.indexOf(u8, get.notes.items, bad[i][0]) != null); + } +} + +test "a thing another build's dump left out takes what named it with it (`left_out`), before the indexes are held" { + const Old = struct { + const Thing = struct { n: u32 = 0 }; + things: [2]?*Thing = @splat(null), + at: ?u8 = null, + }; + // A thing whose `n` changed kind, no default: it is left out. + const New = struct { + const Self = @This(); + const Thing = struct { n: struct { a: u8 } }; + things: [2]?*Thing = @splat(null), + at: ?u8 = null, + pub const replica = .{ .index = .{.{ "at", "there" }}, .left_out = "forget" }; + pub fn there(s: *const Self, i: usize) bool { + return i < s.things.len and s.things[i] != null; + } + pub fn forget(s: *Self) void { + if (s.at) |i| if (!s.there(i)) { + s.at = null; + }; + } + }; + const Unforgiving = struct { + const Self = @This(); + things: [2]?*New.Thing = @splat(null), + at: ?u8 = null, + pub const replica = .{ .index = .{.{ "at", "there" }} }; + pub fn there(s: *const Self, i: usize) bool { + return i < s.things.len and s.things[i] != null; + } + }; + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var one: Old.Thing = .{ .n = 1 }; + const bytes = try save(Old, gpa, &.{ .things = .{ &one, null }, .at = 0 }); + defer gpa.free(bytes); + const new = try load(New, arena.allocator(), bytes, null); + try std.testing.expect(new.things[0] == null and new.at == null); + try std.testing.expectError(error.BadDump, load(Unforgiving, arena.allocator(), bytes, null)); +} + test "a bitset's count read back is held to the bytes left, read or passed over, in a dump and an image: never a size that overflows" { const gpa = std.testing.allocator; const B = struct { bits: std.DynamicBitSetUnmanaged = .{}, after: []const u8 = "" }; -- cgit v1.3 From da985ae98180c2394ccdf48cf8bdf5bd85873c2f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 02:56:05 -0300 Subject: fuzz: a loaded core is used as its user would, on both roads: drawn at its own size, at 40x12 and at 200x60 (a resize each), then given keys (`j w x d u`, PageDown, PageUp, `k`, Escape) and a wheel notch each way, and drawn again (core/fuzz.zig `use`): a load that draws and then dies at a key is the same fault as one that dies drawing; the join road's byte dump is digested first, as a join's is; in the suite 2048 join seeds and 1024 image seeds (Debug: about 2.5 ms and 5 ms a seed); the image road past seed 1779 reaches xitdb's own reader (a slot's tag past its kinds: a `switch` on it), a dependency's, for build/patches.zig; what this fuzz reached is held by the change before (each seed in its description) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/fuzz.zig | 53 +++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/core/fuzz.zig b/core/fuzz.zig index 4f291d64..616636ab 100644 --- a/core/fuzz.zig +++ b/core/fuzz.zig @@ -713,9 +713,42 @@ fn damage(r: Random, b: []u8, n: usize) usize { /// What is done with a dump once it loads: a join's is digested (the /// session's digest decides before anything draws it: replica.fromDump), -/// a Restore's or an Upgrade's image is drawn. +/// a Restore's or an Upgrade's image is not; then each is used (`use`). const Road = enum { join, restore }; +/// A core loaded used as its user would: drawn at the size it says, then +/// smaller and larger (a resize each), then given keys and a wheel notch each +/// way and drawn again. A load that draws and then dies at a key is the same +/// fault as one that dies drawing. +fn use(q: *Pardes) void { + const K = pardes.Key; + const steps = [_]pardes.Event{ + .{ .resize = .{ .cols = 40, .rows = 12 } }, + .{ .resize = .{ .cols = 200, .rows = 60 } }, + .{ .key = .{ .cp = 'j' } }, + .{ .key = .{ .cp = 'w' } }, + .{ .key = .{ .cp = 'x' } }, + .{ .key = .{ .cp = 'd' } }, + .{ .key = .{ .cp = 'u' } }, + .{ .key = .{ .cp = K.page_down } }, + .{ .key = .{ .cp = K.page_up } }, + .{ .key = .{ .cp = 'k' } }, + .{ .key = .{ .cp = K.escape } }, + .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = 100, .row = 30 } }, + .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = 100, .row = 30 } }, + }; + for (0..steps.len + 1) |at| { + if (at < 3 or at == steps.len) { + q.sync(); + _ = q.frame_arena.reset(.retain_capacity); + _ = q.render(q.frame_arena.allocator()) catch {}; + } + if (at == steps.len) return; + q.update(steps[at]); + while (q.nextEffect()) |_| {} + } +} + fn loadSeed(whole: []const u8, road: Road, seed: u64) !void { var prng: Random.DefaultPrng = .init(seed); const r = prng.random(); @@ -733,14 +766,9 @@ fn loadSeed(whole: []const u8, road: Road, seed: u64) !void { var notes: std.ArrayList(u8) = .empty; defer notes.deinit(gpa); if (pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, b[0..n], ¬es)) |q| { - switch (road) { - .join => _ = pardes.tape.digestOf(q), - .restore => { - _ = q.frame_arena.reset(.retain_capacity); - _ = q.render(q.frame_arena.allocator()) catch {}; - }, - } - q.deinit(); + defer q.deinit(); + if (road == .join) _ = pardes.tape.digestOf(q); + use(q); } else |err| if (seed == 0) return err; try testing.expectEqual(@as(usize, 0), cap.refused); } @@ -754,9 +782,10 @@ test "a dump and an image cut, flipped and grown: refused or loaded, never a pan defer gpa.free(bytes); const image = try pardes.dump.dumpBytes(p); defer gpa.free(image); - // Seconds a road. The image's past 1024 seeds reach xitdb's own reader - // (a slot's tag past its kinds: a `switch` on it), a dependency's. - for ([_][]const u8{ bytes, image }, [_]Road{ .join, .restore }, [_]u64{ 4096, 1024 }) |whole, road, n| { + // Seconds a road, each core used (`use`). The image's past 1779 seeds + // reach xitdb's own reader (a slot's tag past its kinds: a `switch` on + // it), a dependency's. + for ([_][]const u8{ bytes, image }, [_]Road{ .join, .restore }, [_]u64{ 2048, 1024 }) |whole, road, n| { try loadSeed(whole, road, 0); for (1..n + 1) |seed| try loadSeed(whole, road, seed); } -- cgit v1.3 From 4e28df7f8e02ceec66a9d62ca75f8ec006e26d7c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 05:28:45 -0300 Subject: layout: a view's geometry is read back as its session holds it, never laid out again at a load, and held to its screen (walk.zig `.within`): a dump whose rect or column is off its screen is REFUSED, the field named: RUN FIRST (the soak, `replicas -- --clients 5`, Debug): `rpplxwst` ALONE diverged 124 at rtt 30 (225 clients parted at their first unit after a join, `addon pdf: its state after view is not the session's (it breaks PA_PLAIN)` and `the tape's answer to addon is short`; then 532 keys into the pdf's pane stopped at `a key into a kind's pane`, the kind distrusted; the witness's replay past a divergence panicked, `integer overflow` in Core.advanceInner), `pardes-merge67` 0 at 30, 80 and 207 ms; THE CAUSE: a join opens its client a view (views.zig `open`: the live one's screen and columns, NO rects: laid out at that view's first input), and rpplxwst's load (dump.zig `afterLoad`) laid every view out again, so the client had rects for its own view the session had not, told its plain kinds a view the session never told them (Kind.zig `step`, `viewOf`), and parted at the session's next step; a join's dump is the session: THE FIX: `rects`, `col_x`, `col_w` back in the digest, the dump and the copy as merge67 had them, `afterLoad`'s relayout gone (and walk.zig `pastHeld`'s pass over a derived buffer with it), and where a value read back may be is declared beside the field: `replica.within` (a predicate of the struct by the entry's place in the field, as far as its length says), checked with the indexes (`heldIndexes`) in all three decoders (a tape's `decode`, a byte dump's and an image's `holdTo`): `View.rects` on its screen (`onScreen`: x + w <= screen_w, y + h <= screen_h, as the layout pass puts every one, and a view not laid out yet has empty ones), a column's edge with its width (`columnOnScreen`, declared on `col_w`), refused in words (`Core.View.rects[0] is not within Core.View.onScreen: refused`), never clamped (a clamped rect is a state no session had); `cols` stays held to `ncol` (a column past `ncol` is a dropped one's, which the index rule would read); TESTS FIRST: replica.zig "a client joins with its session's geometry as the session holds it ..." (a plain kind keeping the rows its view was told; on pardes-load-index: `expected 0, found 5`, the joined view's rect, and without that line `the tape's answer to addon is short (tape byte 241, in tick)`), dump.zig "a view's geometry is read back as the session holds it, never laid out again; a rect or a column off its screen is refused, the field named" (the fuzz's restore seed 589: a pane 534 rows tall on a 24-row screen; a column 900 wide; a column's edge at 900), walk.zig's index test gains an entry not where it may be (`S.edges[1] is not within`, a tape, a dump and an image) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 23 ++++++++++++++++++---- core/dump.zig | 59 ++++++++++++++++++++++++++++++++++---------------------- core/replica.zig | 39 +++++++++++++++++++++++++++++++++++++ core/walk.zig | 55 +++++++++++++++++++++++++++++++++++++--------------- 4 files changed, 133 insertions(+), 43 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index b2f96886..6c981adf 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -87,16 +87,18 @@ const Pardes = @This(); /// One client's view of the session (views.zig): its screen and layout, /// its focus, its pointer and gestures, its jumps, its key prefixes. pub const View = struct { - /// Its geometry (`rects`, `col_x`, `col_w`) is the layout pass's over - /// its columns and screen: never dumped, laid out again at a load - /// (dump.afterLoad), as a resize lays it out. pub const replica = .{ .len = .{ .{ "leader_keys", "leader_n" }, .{ "cols", "ncol" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } }, - .derived = .{ "rects", "col_x", "col_w" }, // What its keyboard is on: a pane there; window mode's outline and // a kind's press and hover, slots; its screen, a grid a frontend // sizes (walk.zig `.index`). .index = .{ .{ "active", Pardes, "focusPanes" }, .{ "window_pick", Pardes, "panes" }, .{ "kind_grab", Pardes, "panes" }, .{ "kind_hover", Pardes, "panes" }, .{ "screen_w", "grids" }, .{ "screen_h", "grids" } }, + // Its geometry, read back as the session holds it (a view opened + // and not laid out yet has none, on a join's client too, whose + // kinds are told its views as the session's are): on its screen, + // a pane's rect and a column's `col_x` with its width (walk.zig + // `.within`). + .within = .{ .{ "rects", "onScreen" }, .{ "col_w", "columnOnScreen" } }, }; /// A view's slot in `Pardes.views`, as it crosses the core's edge: an /// entry's argument or answer, the wire's welcome. A type of its own, @@ -221,6 +223,19 @@ pub const View = struct { return n >= 1 and n <= max_grid; } pub const max_grid = 4096; + + /// Pane slot `id`'s rect on the screen, where the layout pass puts + /// every one (a frame is the screen's cells: one past it, drawn, is a + /// cell outside the frame). + pub fn onScreen(v: *const View, id: usize) bool { + const r = v.rects[id]; + return @as(u32, r.x) + r.w <= v.screen_w and @as(u32, r.y) + r.h <= v.screen_h; + } + + /// Column `c` on the screen: its left edge and its width. + pub fn columnOnScreen(v: *const View, c: usize) bool { + return @as(u32, v.col_x[c]) + v.col_w[c] <= v.screen_w; + } }; gpa: std.mem.Allocator, diff --git a/core/dump.zig b/core/dump.zig index 9dcc076e..b4561ae2 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -143,14 +143,6 @@ pub fn dumpExit(p: *Pardes) !void { /// view showed in a dump made before the layer's lines were the buffer's /// (wire 31 and older: a view's bit, no lines), its lines in it (jj.loaded). fn afterLoad(p: *Pardes) void { - // Each view laid out again over its columns and its screen, as a resize - // lays it out: its geometry is derived, never read (View.replica). - const live = p.live; - for (p.views, 0..) |slot, k| if (slot != null) { - p.live = @intCast(k); - layout.compute(p); - }; - p.live = live; for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| { const text = pardes.panes.File.fileText(f, p.scratch.allocator()) catch continue; f.context.reload(p.tree_sitter_gpa, f.path, text, f.revision); @@ -1036,24 +1028,45 @@ test "a dump keeps the session's settings, and a restore applies them" { try std.testing.expect(!restored.settings.wrap); } -test "a view's geometry is laid out again at a load, never read: a pane's rect past its screen in a dump is the layout's after it" { - // The fuzz's restore road, seed 589: an image whose pane 0 said 534 - // rows on a 24-row screen, drawn: surface.zig's `at` asserted. +test "a view's geometry is read back as the session holds it, never laid out again; a rect or a column off its screen is refused, the field named" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); - const want = p.view().rects[0]; - p.view().rects[0].h = 534; - p.view().col_w[0] = 900; - const dumped = try dumpBytes(p); - defer gpa.free(dumped); - p.view().rects[0] = want; - const q = try load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, dumped, null); - defer q.deinit(); - try std.testing.expectEqual(want, q.view().rects[0]); - try std.testing.expectEqual(@as(u16, 80), q.view().col_w[0]); - _ = q.frame_arena.reset(.retain_capacity); - _ = try q.render(q.frame_arena.allocator()); + // Not what the layout pass would make of its columns (a view opened + // and not laid out yet has no rects at all): as the session has it. + p.view().rects[0].h -= 1; + const held = p.view().rects[0]; + inline for (.{ byteDump, dumpBytes }) |dumpOf| { + const bytes = try dumpOf(p); + defer gpa.free(bytes); + const q = try load(gpa, p.opts, bytes, null); + defer q.deinit(); + try std.testing.expectEqual(held, q.view().rects[0]); + } + // The fuzz's restore road, seed 589: an image whose pane 0 said 534 + // rows on a 24-row screen, drawn: surface.zig's `at` asserted. + const Off = struct { at: *u16, to: u16, why: []const u8 }; + for ([_]Off{ + .{ .at = &p.view().rects[0].h, .to = 534, .why = "View.rects[0] is not within" }, + .{ .at = &p.view().col_w[0], .to = 900, .why = "View.col_w[0] is not within" }, + // A column's edge is held with its width. + .{ .at = &p.view().col_x[0], .to = 900, .why = "View.col_w[0] is not within" }, + }) |off| { + const was = off.at.*; + off.at.* = off.to; + defer off.at.* = was; + inline for (.{ byteDump, dumpBytes }) |dumpOf| { + const bytes = try dumpOf(p); + defer gpa.free(bytes); + var notes: std.ArrayList(u8) = .empty; + defer notes.deinit(gpa); + try std.testing.expectError(error.BadDump, load(gpa, p.opts, bytes, ¬es)); + std.testing.expect(std.mem.indexOf(u8, notes.items, off.why) != null) catch |err| { + std.debug.print("refused, but not by {s}: {s}\n", .{ off.why, notes.items }); + return err; + }; + } + } } test "a dump whose index names no view or pane there is refused, the field named; a top past its text is its last line; a key's replay is not dumped" { diff --git a/core/replica.zig b/core/replica.zig index 46320fea..4126972a 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6615,6 +6615,45 @@ test "a kind's place moved in a step of another view's: a replica's key that rea try agrees(a, r); } +/// Placed, plain (PA_PLAIN): a client runs it, and its state is the rows +/// its last view was told. +const Viewed = struct { + const pa = pardes.Kind.c; + const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Viewed", .opens = 1, .doc = "the rows its view was told" })}; + const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ + .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "viewed".* ++ @as([10]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), + .open = Placed.open, + .paint = Placed.paint, + .view = Placed.view, + }); +}; + +test "a client joins with its session's geometry as the session holds it: the view opened for it, not laid out yet, is not laid out in the client either, and a plain kind is told the same views on both" { + // The soak's (test/replicas.zig): a client parted at its first unit + // after its join, `addon pdf: its state after view is not the + // session's`: it had laid every view out at its load, its own new one + // too, which the session lays out at that view's first input. + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); + defer a.deinit(); + var words: [64]pardes.Kind.LoadedWord = undefined; + const viewed = pardes.Kind.loadedOf(&Viewed.ops, "/x/viewed.so", @splat(7), &words); + _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &viewed } }); + _ = try a.local(.{ .command = "Viewed" }); + const kid = a.core.view().active; + const joined = (try a.join(1, null)).?; + defer gpa.free(joined.dump); + const r = try Replica.initDump(gpa, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer r.deinit(); + try std.testing.expect(r.loaded(joined.digest)); + try runsHere(r, kid, &Viewed.ops); + try std.testing.expectEqual(a.core.views[joined.view].?.rects[kid], r.core().views[joined.view].?.rects[kid]); + // The session's own step tells the kind each view whose facts changed. + r.confirm(try a.local(.tick)); + r.settle(); + try agrees(a, r); +} + /// A kind whose every key asks a job, for the job tokens' test. const Jobber = struct { const pa = pardes.Kind.c; diff --git a/core/walk.zig b/core/walk.zig index 25e4bdc3..51b0a384 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -249,8 +249,6 @@ const Past = struct { name: []const u8, says: usize, holds: usize }; /// its own. fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past { inline for (0..comptime pairs(T)) |i| { - // A buffer no dump carries (derived) is made again, not read. - if (comptime excluded(T, T.replica.len[i][0])) continue; const buffer = @field(v, T.replica.len[i][0]); const holds = if (comptime @typeInfo(@TypeOf(buffer)) == .array) (if (held) |h| @min(h[i], buffer.len) else buffer.len) else buffer.len; const says = lengthIn(v, T.replica.len[i][1]); @@ -276,6 +274,10 @@ fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past // // Its last place, a function of the struct (`fn (*const T) usize`), // // or its first and last (`[2]usize`). // .place = .{ .{ "scroll", "lastLine" } }, +// // Where each of its entries (as far as its length says) may be, +// // a predicate of the struct by the entry's place in the field +// // (`fn (*const T, usize) bool`): a view's rects on its screen. +// .within = .{ .{ "rects", "onScreen" } }, // // What a load that left one of its things out (another build's // // pane) does to what names it (`fn (*T) void`), before its indexes // // are held. @@ -286,18 +288,20 @@ fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past // the disk) is held to them where its fields end, beside its lengths // (`pastHeld`), every declaration of every type at once: an index that names // none is REFUSED, its field named (the dump is not the session: the view, -// the pane it names is not there); a place past its thing's last is that -// LAST (the session is there, its view a line off). A field that names a -// slot by its type (`Pane.Id`, `View.Id`) and says nothing is a compile -// error (`checkSlots`); a bare integer that does is found by reading, as -// the lengths' were, until it is typed as its slot. +// the pane it names is not there), and so is an entry that is not where it +// may be (no session's: a rect past its screen); a place past its thing's +// last is that LAST (the session is there, its view a line off). A field +// that names a slot by its type (`Pane.Id`, `View.Id`) and says nothing is +// a compile error (`checkSlots`); a bare integer that does is found by +// reading, as the lengths' were, until it is typed as its slot. fn declared(comptime T: type, comptime kind: []const u8) usize { return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), kind)) @field(T.replica, kind).len else 0; } -/// An index read back that names none of what it says it indexes. -const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8 }; +/// An index read back that names none of what it says it indexes, or +/// (`within`) the entry `says` of a field that is not where it may be. +const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8, within: bool = false }; /// What an index field says, as a number: an integer, an optional one's (null /// names nothing), a slot's enum's (`Pane.Id`). @@ -395,6 +399,11 @@ fn heldIndexes(comptime T: type, v: *T) ?Unnamed { if (comptime d.len == 2) if (firstUnnamed(T, v, d[0], T, v, d[1])) |i| return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1] }; } + inline for (0..comptime declared(T, "within")) |k| { + const d = T.replica.within[k]; + for (0..heldOf(T, v, d[0])) |i| if (!@field(T, d[1])(v, i)) + return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1], .within = true }; + } inline for (comptime heldIn(T)) |U| if (visit(T, v, U, T, v, 0)) |bad| return bad; return null; } @@ -461,7 +470,10 @@ fn holdTo(l: anytype, comptime T: type, out: *T, held: *const [pairs(T)]usize, d } if (comptime @hasDecl(T, "replica")) if (comptime @hasField(@TypeOf(T.replica), "left_out")) if (l.dropped != dropped) @field(T, T.replica.left_out)(out); if (heldIndexes(T, out)) |bad| { - l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of }); + if (bad.within) + l.note("{s}.{s}[{d}] is not within {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of }) + else + l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of }); return error.BadDump; } } @@ -499,10 +511,11 @@ fn checkAnnotations(comptime T: type) void { continue; } inline for (@field(T.replica, kind)) |entry| { - const pair = comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc") or std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place"); + const held = comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place") or std.mem.eql(u8, kind, "within"); + const pair = comptime held or std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc"); const name = if (pair) entry[0] else entry; if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name); - if (comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place")) { + if (held) { const H = if (entry.len >= 3) entry[1] else T; const what = if (entry.len >= 3) entry[2] else entry[1]; if (entry.len == 4) if (!@hasField(T, entry[3])) @compileError("walk: " ++ @typeName(T) ++ " counts its span by no field " ++ entry[3]); @@ -3146,7 +3159,7 @@ test "a length past what its buffer holds is refused where it is read back (a ta try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?)); } -test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image; a place past its thing's last is that last" { +test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image, and so is an entry not where it may be; a place past its thing's last is that last" { const S = struct { const Self = @This(); const Inner = struct { @@ -3161,10 +3174,14 @@ test "an index read back that names none of its things is refused, its field nam slot: ?u16 = null, scroll: u32 = 0, inner: [2]?*Inner = @splat(null), - pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }} }; + edges: [2]u8 = @splat(0), + pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }}, .within = .{.{ "edges", "inside" }} }; pub fn there(s: *const Self, i: usize) bool { return i < s.things.len and s.things[i] != null; } + pub fn inside(s: *const Self, i: usize) bool { + return s.edges[i] < 8; + } pub fn last(_: *const Self) usize { return 9; } @@ -3200,7 +3217,13 @@ test "an index read back that names none of its things is refused, its field nam v.inner[1] = &bad_list; break :blk v; } }, + .{ "S.edges[1] is not within", blk: { + var v = good; + v.edges = .{ 7, 8 }; + break :blk v; + } }, }; + const n_bad = bad.len; var notes: std.ArrayList(u8) = .empty; // A dump. @@ -3239,14 +3262,14 @@ test "an index read back that names none of its things is refused, its field nam pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void { const map = try Mem.HashMap(.read_write).init(cursor.*); try ctx.put.member(map, "good", S, ctx.good); - inline for (0..4) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]); + inline for (0..n_bad) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]); } }{ .put = &put, .good = &good, .bad = &bad }); var get: Get = .init(a); defer get.deinit(); const root = db.rootCursor().readOnly(); try std.testing.expectEqual(@as(u32, 9), (try get.get(S, (try Get.member(root, "good")).?)).scroll); - inline for (0..4) |i| { + inline for (0..n_bad) |i| { get.notes.clearRetainingCapacity(); try std.testing.expectError(error.BadDump, get.get(S, (try Get.member(root, std.fmt.comptimePrint("bad{d}", .{i}))).?)); try std.testing.expect(std.mem.indexOf(u8, get.notes.items, bad[i][0]) != null); -- cgit v1.3 From 9ebe0ab174b25d488dfbf20a9b9d9827fc564b6c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 05:49:28 -0300 Subject: replica: `may_wait` lists the two stops the soaks saw that no row held, each a read of what only the session has: `a key into a kind's pane` (a key to a kind this client does not run, no library for it here or not PA_PLAIN: its state the session's, as "a replica with no code for a kind whose state is not plain ... its keys go to the authority" has it; on `.addon`, which the walk does not stand in, as the kinds' other rows) and `jj` (jj run in the session's tree: `At `, a file at a revision; a Look at a change id, its patch; `Diff a..b`: what the session's repository holds, its disk, as `resolve` and `read_file` are); the walk walks `At @-` (walk_samples), which stops at `jj` on a file's pane and a directory's, so the row is held to a stop it names (the shell-test walk's stale check passes with it, 12/12); WHERE EACH WAS SEEN: the first only after a divergence (the geometry fault, the change before: a client that found the pdf break PA_PLAIN distrusts it and joins again without its code, then every key into its pane stops there: 532 in rpplxwst's soak), none in a soak with the fix; the second on main's soaks (pair-14, link-3, merge65's release soak: a client's Enter, `\r`, stopped at `jj`), whose path to a jj site is not named here (Enter on a word that reads as a change id, in a scratch and in a file, stopped nowhere in a probe) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core/replica.zig b/core/replica.zig index 4126972a..182d25c2 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -7365,12 +7365,16 @@ const may_wait = [_]Wait{ .{ .what = "DumpThemes", .on = .any, .stop = "the authority's own state", .why = "the theme files written" }, // A +Preview's text is read from the session's disk. .{ .what = "Search *", .on = .any, .stop = "preview", .why = "a +Preview's file, from the session's disk" }, + // jj run in the session's tree (jj.zig `show`, `diffChange`, + // `diffPair`): what its repository holds, the session's disk. + .{ .what = "At *", .on = .any, .stop = "jj", .why = "a file at a revision, asked of the session's repository" }, // A kind's own state on the session (a PDF's document): asking it. .{ .what = "*", .on = .addon, .stop = "a kind's search", .why = "a search in a kind's pane: its own state, the session's" }, .{ .what = "*", .on = .addon, .stop = "a kind's address", .why = "a place in a kind's pane (`Look doc.pdf:3`): its own state" }, .{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" }, .{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" }, .{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" }, + .{ .what = "*", .on = .addon, .stop = "a key into a kind's pane", .why = "a key to a kind this client does not run (no library for it here, or not PA_PLAIN): its state the session's" }, } ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{ // A window's view's words, which a terminal's build has too: a window // client of its session runs them. @@ -7426,7 +7430,7 @@ const walk_samples = [_]struct { []const u8, []const u8 }{ .{ "Msg", "hi" }, .{ "ThemeFile", "t.zon" }, .{ "Edit", "s/a/b/" }, .{ "Mini", "x" }, .{ "Find", "x" }, .{ "Grep", "x" }, .{ "Rename", "x" }, .{ "WsSymbols", "x" }, .{ "Theme", "acme" }, .{ "Font", "Mono 12" }, .{ "TaglineSize", "100" }, .{ "WindowOpacity", "100" }, - .{ "MessageLinger", "1000" }, .{ "InactiveDim", "0" }, .{ "GripWidth", "100" }, + .{ "MessageLinger", "1000" }, .{ "InactiveDim", "0" }, .{ "GripWidth", "100" }, .{ "At", "@-" }, }; fn keyName(buf: []u8, k: pardes.Key) []const u8 { -- cgit v1.3 From c90db8c04787d923bbef500eb78c68fd65715cf0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 05:55:02 -0300 Subject: walk, views, Core: what the 40,000-seed dump fuzz reached once a view's geometry is in the dump again (its seeds land elsewhere; and the dump holds its tree's path, so each tree's seeds damage bytes of their own), each a run first: (1) THE WORKSPACE'S RUN (my gate's fuzz40k, the join road): `views.undumped` took `bit(d.k)` of a view's shares whose `k` was past any view (`integer does not fit in destination type` at views.zig `bit`), and `Shares.k` declared an index (`slots`) did NOT hold it: the `[]Shares` was a REFERENCE (walk.zig `Loader.ref`) to bytes made for another type, read as shares without being decoded (no-panic-1's open item, "references read back as another type", reached): every allocation a load makes records what it holds (`Made.of`, `typeWord` of its element), and a reference read back is to a value of its own type or the dump is refused (`Loader.ref`, `Get.again`, at a pointer's and a slice's, in both readers: a damaged one had one type's bytes read as another's, pointers and alignment and all; the writers share a reference between values of one type only, so no session's dump is refused); the skips' placeholders hold no type, so a reference to one is refused; `Shares.k` stays declared (a slot read back is held); (3) THE WORKSPACE'S RUN with (1) (my gate h2's fuzz40k): leaked 1 allocation, 7 bytes, a byte dump's theme (dump.zig `loadKnowing`: `l.get([]const u8)` failed after its slice was made, and the load's `defer` cut its books back to before the mounts, dropping the half-made slice unfreed: a leak at every such damaged join dump or Restore): a root read that fails lets go of what it had made (`Loader.get`, `Get.get`: `mark`/`letGo`, merge65's mechanism), so no caller's books hold half of a value; (2) MY SECOND TREE'S RUN (the join road): `Pardes.resize_count` read back as the most a usize holds, `+= 1` at the next resize (`integer overflow`, Core.zig `updateInner`, the fuzz's `use` resizing to 40x12): a count that only grows saturates (`+|=`); the fuzz with them: 40000 join and 1779 image seeds green in my second tree three times (212 seeds refused by `.within` each: 211 a pane's rect off its screen, 1 a column; 210 on the join road, 2 on the image's); in the workspace 40000 join seeds green with no leak (206 refused by `.within`), the image road green to seed 1366: seed 1367 there reaches xitdb's own reader (`switch on corrupt value`, xitdb lib.zig `readBytesObjectAlloc`, from Db.zig `Read.open` in dump.check: the last agent's seed 1780 in another tree, a dependency's, not here) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 2 +- core/views.zig | 6 ++++++ core/walk.zig | 55 ++++++++++++++++++++++++++++++++++--------------------- 3 files changed, 41 insertions(+), 22 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index 6c981adf..835eb86c 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1753,7 +1753,7 @@ fn updateInner(p: *Pardes, ev: Event) void { v.cell_pixels.w = @max(1, sz.cell_pixels.w); v.cell_pixels.h = @max(1, sz.cell_pixels.h); layout.compute(p); - p.resize_count += 1; + p.resize_count +|= 1; }, .output => |o| { const pane = p.panes[o.pane.index()] orelse return; diff --git a/core/views.zig b/core/views.zig index 4f2d5744..4c020981 100644 --- a/core/views.zig +++ b/core/views.zig @@ -82,6 +82,12 @@ pub const Shares = struct { k: u8, panes: []const Share = &.{}, + /// Its view, a slot (walk.zig `.index`). + pub const replica = .{ .index = .{.{ "k", "slots" }} }; + pub fn slots(_: *const Shares, k: usize) bool { + return k < max; + } + pub const Share = struct { id: u16, pv: PaneView }; }; diff --git a/core/walk.zig b/core/walk.zig index 51b0a384..7a77fdb6 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -1398,8 +1398,11 @@ fn countOf(n: u64) DecodeError!usize { } /// An allocation a load made: what a reference to it finds, and what a -/// failed load frees. -const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false }; +/// failed load frees. `of`: what it holds (`typeWord` of its element); a +/// reference read back is to a value of its own type, or the dump is +/// refused (a damaged one would have one type's bytes read as another's, +/// pointers and all). +const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false, of: u64 = 0 }; /// How far a reader had made things before a value: what that value made /// is everything after it (`letGo`). @@ -1509,8 +1512,8 @@ pub const Loader = struct { } } - fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment) DecodeError!usize { - try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa }); + fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment, of: u64) DecodeError!usize { + try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa, .of = of }); return l.shared.items.len - 1; } @@ -1609,6 +1612,11 @@ pub const Loader = struct { /// The next root, made: what it points at is `gpa`'s. pub fn get(l: *Self, comptime T: type) DecodeError!T { + // A root that fails lets go of what it had made: its caller's books + // (a load's, cut back past what it frees itself) never hold half + // of a value. + const at = l.mark(); + errdefer l.letGo(at); var out: T = undefined; try l.fresh(T, &out); try l.value(T, try l.root(), &out); @@ -1750,12 +1758,12 @@ pub const Loader = struct { }, .one => { const C = @typeInfo(T).pointer.child; - if (try l.ref()) |again| { + if (try l.ref(C)) |again| { out.* = @ptrCast(@alignCast(again.ptr)); return; } const one = try l.gpa.create(C); - const at = l.made(std.mem.asBytes(one), .of(C)) catch |err| { + const at = l.made(std.mem.asBytes(one), .of(C), typeWord(C)) catch |err| { l.gpa.destroy(one); return err; }; @@ -1821,22 +1829,23 @@ pub const Loader = struct { /// A reference to a pointer or slice made before, or null for a /// new one (its length then read). - fn ref(l: *Self) DecodeError!?[]u8 { + fn ref(l: *Self, comptime E: type) DecodeError!?[]u8 { const n = try l.scalar(u32); if (n == 0) return null; if (n > l.shared.items.len) return error.BadDump; const got = l.shared.items[n - 1]; if (got.dead) return error.Incompatible; + if (got.of != typeWord(E)) return error.BadDump; return got.bytes; } fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E { - if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))]; + if (try l.ref(E)) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))]; const n = try l.count(); if (n == 0) return &.{}; if (n > l.bytes.len - l.at) return error.EndOfDump; const many = try l.gpa.alloc(E, n); - const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| { + const at = l.made(std.mem.sliceAsBytes(many), .of(E), typeWord(E)) catch |err| { l.gpa.free(many); return err; }; @@ -1994,14 +2003,14 @@ pub const Loader = struct { .float => _ = try l.take(s.bits / 8), .optional => if ((try l.take(1))[0] != 0) try l.skip(s.child), .one => if (try l.scalar(u32) == 0) { - _ = try l.made(&.{}, .@"1"); + _ = try l.made(&.{}, .@"1", 0); l.shared.items[l.shared.items.len - 1].dead = true; try l.skip(s.child); }, .slice => if (try l.scalar(u32) == 0) { const n = try l.scalar(u64); if (n > 0) { - _ = try l.made(&.{}, .@"1"); + _ = try l.made(&.{}, .@"1", 0); l.shared.items[l.shared.items.len - 1].dead = true; } try l.skipMany(s.child, n); @@ -2390,6 +2399,9 @@ pub const Get = struct { /// The value at `c`, made: what it points at is `gpa`'s. pub fn get(l: *Get, comptime T: type, c: Cursor) Error!T { + // As `Loader.get`: a value that fails leaves nothing made. + const at = l.mark(); + errdefer l.letGo(at); var out: T = undefined; try l.fresh(T, &out); try l.value(T, c, &out); @@ -2441,8 +2453,8 @@ pub const Get = struct { /// An allocation made for the value at `slot`, kept: what a value met /// again is, and what `rollback` frees. - fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot) Error!usize { - try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa }); + fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot, of: u64) Error!usize { + try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa, .of = of }); const at = l.made.items.len - 1; // Not kept after all: the caller frees it. if (placed(slot)) l.memo.put(l.own, slotWord(slot), at) catch |err| { @@ -2453,13 +2465,14 @@ pub const Get = struct { } /// The value made before for the same place, when there was one. - fn again(l: *Get, slot: xitdb.Slot) Error!?[]u8 { + fn again(l: *Get, slot: xitdb.Slot, comptime E: type) Error!?[]u8 { if (!placed(slot)) return null; const at = l.memo.get(slotWord(slot)) orelse return null; // Made, then let go of by the reader's caller (a dump's mounts). if (at >= l.made.items.len) return null; const m = l.made.items[at]; if (m.dead) return error.Incompatible; + if (m.of != typeWord(E)) return error.BadDump; return m.bytes; } @@ -2539,12 +2552,12 @@ pub const Get = struct { }, .one => { const C = @typeInfo(T).pointer.child; - if (try l.again(slot)) |bytes| { + if (try l.again(slot, C)) |bytes| { out.* = @ptrCast(@alignCast(bytes.ptr)); return; } const one = try l.gpa.create(C); - const at = l.keep(std.mem.asBytes(one), .of(C), slot) catch |err| { + const at = l.keep(std.mem.asBytes(one), .of(C), slot, typeWord(C)) catch |err| { l.gpa.destroy(one); return err; }; @@ -2674,7 +2687,7 @@ pub const Get = struct { /// A slice of `E` at `c`: numbers' bytes, a blob's text by its hash, or /// a list; one met again is the same. fn slice(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot) Error![]E { - if (try l.again(slot)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))]; + if (try l.again(slot, E)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))]; if (comptime numbers(E)) { switch (slot.tag) { .bytes, .short_bytes => {}, @@ -2692,7 +2705,7 @@ pub const Get = struct { l.gpa.free(got.bytes); return &.{}; } - _ = l.keep(got.bytes, .@"1", slot) catch |err| { + _ = l.keep(got.bytes, .@"1", slot, typeWord(u8)) catch |err| { l.gpa.free(got.bytes); return err; }; @@ -2704,7 +2717,7 @@ pub const Get = struct { const n = got.bytes.len / width; if (n == 0) return &.{}; const many = try l.gpa.alloc(E, n); - const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| { + const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot, typeWord(E)) catch |err| { l.gpa.free(many); return err; }; @@ -2721,7 +2734,7 @@ pub const Get = struct { // sizes nothing. if (n > (c.db.core.length() catch return error.BadDump) / (@bitSizeOf(xitdb.Slot) / 8)) return error.BadDump; const many = try l.gpa.alloc(E, n); - const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| { + const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot, typeWord(E)) catch |err| { l.gpa.free(many); return err; }; @@ -2742,7 +2755,7 @@ pub const Get = struct { const at = (texts.getCursor(std.mem.readInt(u256, got.value[0..32], .big)) catch return error.BadDump) orelse return error.BadDump; const text = at.readBytesAlloc(l.gpa, most(at)) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump; const bytes: []u8 = @constCast(text); - _ = l.keep(bytes, .@"1", slot) catch |err| { + _ = l.keep(bytes, .@"1", slot, typeWord(u8)) catch |err| { l.gpa.free(bytes); return err; }; -- cgit v1.3 From e332c4c300bd39ba9b2da797391e37ddebda5319 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 06:03:39 -0300 Subject: soak: a join's dump that loads as another session says the fields it differs by, as a client's join says them (replica.fromDump's words: `loadDiffers` made pub): the coordinator's merge67b release soak had 'seed 3 rtt 207 ms: client 3's dump loaded as another session' and no field (1 in 12 seed-runs), not reproduced yet Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 2 +- test/replicas.zig | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/core/replica.zig b/core/replica.zig index 182d25c2..48cb1838 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -3100,7 +3100,7 @@ fn loadAgain(gpa: Allocator, j: *Joined, have: ?*Have, why: []u8, session: []con /// The fields a replica loaded from the join's dump `bytes` has other than /// the session as it dumped them (the digest a field at a time the dump /// ends with: dump.joinParts), named in `out`. -fn loadDiffers(r: *Replica, bytes: []const u8, out: []u8) []const u8 { +pub fn loadDiffers(r: *Replica, bytes: []const u8, out: []u8) []const u8 { const want = pardes.dump.joinParts(r.gpa, bytes) orelse return "(the dump names no field) "; defer r.gpa.free(want); var arena: std.heap.ArenaAllocator = .init(r.gpa); diff --git a/test/replicas.zig b/test/replicas.zig index 3aa9263e..cd0a3459 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -1986,7 +1986,9 @@ const Soak = struct { rp.echo.now = m.at * 1000; if (!rp.loaded(cl.digest)) { s.totals.unequal += 1; - std.debug.print("seed {d} rtt {d} ms: client {d}'s dump loaded as another session\n", .{ s.r.seed, s.r.rtt_ms, m.who }); + // The fields it differs by, as a client's join says them (replica.fromDump). + var named: [400]u8 = undefined; + std.debug.print("seed {d} rtt {d} ms: client {d}'s dump loaded as another session: {s}differs\n", .{ s.r.seed, s.r.rtt_ms, m.who, replica.loadDiffers(rp, m.bytes, &named) }); } cl.live = m.gen; var j: replica.Joined = .{ .fd = cl.cfd, .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} }; -- cgit v1.3 From 552400589c0514e8e3f9a9f96b23d2224302e1a7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 14:38:59 -0300 Subject: tui: a terminal's resize says a terminal's row metrics (terminalSize: .row_metrics = .{}, one cell for its tag and its body), so a terminal client's view, opened from a window's (views.open gives a new view the live one's `sized` facts, row metrics among them, and a resize with none keeps them, Core.zig 1681), wraps its tags at its own width: the user's "in some of them contents got cut" (2026-11-24), the hunt's cause 4: a 100-column terminal client of a window's session wrapped the PDF's tag at 120 characters in a 98-cell row (the window's tagline glyphs a fifth narrower than its body: layout.tagCapacity), its first row cut and its second begun past what was cut, the middle of a long tag never shown (the hunt's screens: 124 characters, the second row " Del"); TEST FIRST: tui.zig "a terminal client's view, opened from a window's, wraps a tag at its own width" (two views, 140 and 100 columns, a file's pane with a 40-word tag): before, w22 to w27 missing; after, every word shown; the PDF's text cut at a narrower client's right edge is the PDF's text layer drawn line by line, unwrapped (pdf.zig paint), the same in a terminal session of that width alone; nothing on the wire changes shape (the field was there, null) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/tui/tui.zig | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index e2cdd2fa..91b25b7a 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -442,6 +442,11 @@ fn terminalSize(cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) @FieldType(par .w = @intCast(terminalCellPixels(pixel_w, cols, 8)), .h = @intCast(terminalCellPixels(pixel_h, rows, 16)), }, + // A terminal's tag and body are one cell: its own row metrics, said, + // never those of the view its client's was opened from (a window's + // tagline is narrower than its body: a tag wrapped at a fifth more + // than its row held, the middle of a long tag never shown). + .row_metrics = .{}, }; } @@ -3289,3 +3294,46 @@ test "the tty draws a glide at whole rows: once a flick or a spin slows, its ste try std.testing.expectEqual(row, (shown.cursor orelse return error.NoCursor).y); } } +test "a terminal client's view, opened from a window's, wraps a tag at its own width: a terminal's resize says a terminal's row metrics" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 140, .rows = 45 }); + defer core.deinit(); + // The session's window: its tag line's glyphs narrower than its body's, + // so a tag row holds more of them than it has cells. + core.update(.{ .resize = .{ .cols = 140, .rows = 45, .cell_pixels = .{ .w = 16, .h = 33 }, .row_metrics = .{ .body_w = 16, .body_h = 33, .tagline_w = 13, .tagline_h = 26 } } }); + const pane = try core.setTestFile("text\n"); + var words: [40][3]u8 = undefined; + var tag: std.ArrayList(u8) = .empty; + defer tag.deinit(gpa); + for (&words, 0..) |*w, i| { + w.* = .{ 'w', '0' + @as(u8, @intCast(i / 10)), '0' + @as(u8, @intCast(i % 10)) }; + try tag.appendSlice(gpa, " "); + try tag.appendSlice(gpa, w); + } + if (pane.tag.own) |own| gpa.free(own); + pane.tag.own = try gpa.dupe(u8, tag.items); + // A terminal's client joins: its view opened from the window's, then + // sized by its terminal, as the client's first inputs do. + const k = core.openView().?; + core.toView(k); + core.update(.{ .resize = terminalSize(100, 30, 0, 0) }); + core.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try core.render(arena.allocator()); + var shown: std.ArrayList(u8) = .empty; + defer shown.deinit(gpa); + for (s.regionList()) |region| { + if (region.kind != .tag) continue; + for (region.rect.y..region.rect.y + region.rect.h) |y| { + for (s.cells[y * s.cols ..][region.rect.x..][0..region.rect.w]) |cell| try shown.appendSlice(gpa, if (cell.len == 0) " " else cell.grapheme()); + try shown.append(gpa, '\n'); + } + } + // Each of its words shows: wrapped at its rows' width, none lost + // between a row cut short and the next. + for (&words) |*w| if (std.mem.indexOf(u8, shown.items, w) == null) { + std.debug.print("{s} is not shown in the tag:\n{s}\n", .{ w, shown.items }); + return error.TestUnexpectedResult; + }; +} -- cgit v1.3 From 8d0b21544824051873950ddcae1d4aab027a01fc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 14:06:54 -0300 Subject: tests: a view's top read off a geometry it is not the view of (row scroll round 4, fault 1, TESTS FIRST, each failing on the base ynxykzrt): the release soak's panic (run 18 of 24, a client's drawOne: `index out of bounds: index 41, len 38` at core/File.zig fillBody `text[from..end]`) is a view drawn after ANOTHER VIEW's step moved the top: the step's `show` hands its next geometry the top's byte (`Pane.top_skip`, keyed for the geometry after the move) while the map stays the one made before it; a view that was where the first was (a client's view opened as a copy of the live one, the same size) has that map's key, so `geometry` returns early and the text pass takes `top_skip.at`, a byte of the OTHER view's top line, with no look at its key: views.zig "a view drawn after another view's step moved the top into a long wrapped line, the two alike before it: ..." panics on the base `index out of bounds: index 1584, len 5` (a probe run first, throwaway, every top_skip read checked against the walk: made by `show`, line 10 row 22, read for line 0); a STEP takes the same stale row (`topNow`): views.zig "a view's step after another view's step moved the top, the two alike before it: it scrolls from its own top's row, as a core loaded from the session (none of its geometry) does" (PageDown in the second view: expected 12, found 14 on the base: a session that drew and a client that did not step apart); and the tab width is not in the geometry's key (a Tab zeroes `geometry_key` but not `top_skip`, whose key matches again: a row start of the old width trusted; in bounds, a wrong row; 180 such reads in one Debug soak with the probe): File.zig "a view scrolled by rows into a line of tabs, the tab width changed after a frame: its body drawn from the row the new width makes, as a core loaded from it draws it" fails on the base (rows from the 8-cell width's byte 27, the 2-cell width's is 74); and a second derived reader of the same kind, found by the table of every reader of a pane's geometry (normal.zig `gotoWindow` read `context_rows` before `shownRows` made the geometry): normal.zig "gt after a step that moved the view off the place its geometry was made for: ..." (two notches up off the held headers, then gt: expected 3, found 5 on the base: the session read the held rows of the place before the notch) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/File.zig | 28 ++++++++++++++++++ core/normal.zig | 32 ++++++++++++++++++++ core/views.zig | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+) diff --git a/core/File.zig b/core/File.zig index 8e464d61..163f40ff 100644 --- a/core/File.zig +++ b/core/File.zig @@ -3679,3 +3679,31 @@ test "Syntax off in a patch's pane takes the language's ink and leaves the patch if (pass == 1) try std.testing.expect(differ); } } + +test "a view scrolled by rows into a line of tabs, the tab width changed after a frame: its body drawn from the row the new width makes, as a core loaded from it draws it" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + try text.appendSlice(gpa, "head\n"); + for (0..40) |i| try text.print(gpa, "\tw{d}", .{i}); + try text.appendSlice(gpa, "\ntail\n"); + const pane = try p.setTestFile(text.items); + try std.testing.expect(p.executeBuiltinLine(0, "Tab 8")); + // The top on line 1's fourth row (at 8 cells a tab), drawn. + const f = &pane.file.?; + f.scroll = 1; + f.scroll_row = 3; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + _ = try p.render(arena.allocator()); + try std.testing.expect(p.executeBuiltinLine(0, "Tab 2")); + const drawn = try bodyText(p.settings.tab, arena.allocator(), pane, f); + const bytes = try pardes.dump.dumpBytes(p); + defer gpa.free(bytes); + const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, bytes, null); + defer loaded.deinit(); + const lp = loaded.panes[0].?; + try std.testing.expectEqualStrings(try bodyText(loaded.settings.tab, arena.allocator(), lp, &lp.file.?), drawn); +} diff --git a/core/normal.zig b/core/normal.zig index fe0c729a..5a9794ee 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -1527,6 +1527,38 @@ test "gt and gb go to the row scroll_off rows in from the body's top and from it } } +test "gt after a step that moved the view off the place its geometry was made for: the row scroll_off in from the body's top under the context rows the view has now, as a core loaded from the session goes" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .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" ++ (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 (!File.supportsContext(pane)) return error.SkipZigTest; + pane.file.?.tree_context = true; + // The view inside the function, its two headers held over the body, + // drawn. + File.setTop(pane, .{ .line = 3 }); + p.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + _ = try p.render(arena.allocator()); + try std.testing.expectEqual(@as(u16, 2), pane.context_rows); + // Two notches up: the top on the function's header, one header held + // (the geometry the second notch read was the one before it). + const rect = p.view().rects[0]; + for (0..2) |_| p.update(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } }); + try std.testing.expectEqual(@as(usize, 1), pane.file.?.scroll); + const bytes = try pardes.dump.dumpBytes(p); + defer gpa.free(bytes); + const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, bytes, null); + defer loaded.deinit(); + for ([_]*Pardes{ p, loaded }) |core| for ("gt") |k| core.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); + try std.testing.expectEqual(loaded.panes[0].?.body.cur_row, pane.body.cur_row); + try std.testing.expectEqual(@as(u16, 1), pane.context_rows); + try std.testing.expectEqual(pane.wrapAt(p.settings.tab, 1 + config.scroll_off).line, pane.body.cur_row); +} + test "gw labels the words the body shows and no others: none on a wrapped line's rows above the view's top" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24 }); defer p.deinit(); diff --git a/core/views.zig b/core/views.zig index 4c020981..5ad9b749 100644 --- a/core/views.zig +++ b/core/views.zig @@ -898,6 +898,96 @@ test "a view drawn while another is live keeps its own cursors" { try testing.expectEqual(@as(u16, 1), pane.body.nsel); } +test "a view drawn after another view's step moved the top into a long wrapped line, the two alike before it: drawn from its own top, line 0, not from the row the step found in the other's line" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + // A short first line, and line 10 wrapped over more rows than the body. + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + try text.appendSlice(gpa, "short\n"); + for (1..10) |i| try text.print(gpa, "line {d}\n", .{i}); + for (0..500) |w| try text.print(gpa, "w{d:0>4} ", .{w}); + try text.appendSlice(gpa, "\nlast\n"); + const pane = try p.setTestFile(text.items); + const k = p.openView().?; + // View 0's step puts the cursor at line 10's end: the top goes into + // that line's rows, a row far past line 0's five bytes. View k is + // where view 0 was: its top line 0, its size view 0's. + pane.body.cur_row = 10; + pane.body.cur_col = @intCast(pardes.panes.File.sourceLine(pane, 10).len - 1); + pane.body.cur_pinned = true; + pane.ensureCursorVisible(p.settings.tab); + p.sync(); + try testing.expectEqual(@as(usize, 10), pane.file.?.scroll); + try testing.expect(pane.file.?.scroll_row > 0); + const Seen = struct { + short: bool = false, + fn present(ctx: ?*anyopaque, s: *const pardes.Surface) bool { + const seen: *@This() = @ptrCast(@alignCast(ctx.?)); + var row: [512]u8 = undefined; + for (0..s.rows) |y| { + var n: usize = 0; + for (s.cells[y * s.cols ..][0..s.cols]) |c| { + if (n + c.len > row.len) break; + @memcpy(row[n..][0..c.len], c.text[0..c.len]); + n += c.len; + } + if (std.mem.indexOf(u8, row[0..n], "short") != null) seen.short = true; + } + return true; + } + }; + var seen: Seen = .{}; + _ = try drawOne(p, k.index(), .{ .ctx = &seen, .f = Seen.present }); + try testing.expect(seen.short); +} + +test "a view's step after another view's step moved the top, the two alike before it: it scrolls from its own top's row, as a core loaded from the session (none of its geometry) does" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + // Line 3 wrapped over several rows, line 10 over more than the body. + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..12) |i| switch (i) { + 3, 10 => { + for (0..@as(usize, if (i == 3) 60 else 500)) |w| try text.print(gpa, "w{d:0>4} ", .{w}); + try text.append(gpa, '\n'); + }, + else => try text.print(gpa, "line {d}\n", .{i}), + }; + const pane = try p.setTestFile(text.items); + const f = &pane.file.?; + // Both views' top on line 3's third row, the cursor on it. + pane.body.cur_row = 3; + pane.body.cur_col = 150; + f.scroll = 3; + f.scroll_row = 2; + p.sync(); + const k = p.openView().?; + // View 0's step: the cursor to line 10's end, the top into its rows. + pane.body.cur_row = 10; + pane.body.cur_col = @intCast(pardes.panes.File.sourceLine(pane, 10).len - 1); + pane.body.cur_pinned = true; + pane.ensureCursorVisible(p.settings.tab); + p.sync(); + try testing.expect(f.scroll == 10 and f.scroll_row > 2); + // The session as a client joining it loads it: no geometry made. + const bytes = try pardes.dump.dumpBytes(p); + defer gpa.free(bytes); + const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, bytes, null); + defer loaded.deinit(); + // View k's PageDown in each, from line 3's third row. + for ([_]*Pardes{ p, loaded }) |core| { + core.toView(k); + core.update(.{ .key = .{ .cp = pardes.Key.page_down } }); + } + const lf = &loaded.panes[0].?.file.?; + try testing.expectEqual(lf.scroll, f.scroll); + try testing.expectEqual(lf.scroll_row, f.scroll_row); +} + test "a view not live keeps its place in a text another view edits" { const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); -- cgit v1.3 From 249e0c92979012fc839ccd7b06643ee8ad5a735e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 14:42:48 -0300 Subject: rows: a view's top row is read off the geometry it is of, never another's (row scroll round 4, fault 1): `Pane.top_skip` (the top's row in its line and its first byte, a derived cache keyed by the geometry it is of) is read only through `File.topSkip`, the skip walk fillBody had, moved there: one keyed for another geometry is walked again, so the text pass, `topNow` (a step's top) and the map's pass all take the top of the view they draw or step: a step's `show` or `scrollRows` hands the NEXT geometry the byte it found (keyed so), and a view drawn or stepped in before that geometry is made (another view alike the first: a client's own view, drawn by `drawOne` after another client's unit moved the live one's top) took that byte for its own top line (the release soak's client panic, `index 41, len 38`); `geometry` stamps the top it found or took with the key it ends on (the walk brings tables and index up to it), so a text pass after a remade map reads it with no walk; `rowsOf` reads whether rows of the top line are above the top off the fresh map itself (its first body row starts past the line's first byte), not off the cache; the tab's width is in `geometryKey` (a Tab zeroed `geometry_key` and left `top_skip`, whose key then matched again: a row start of the old width trusted, a wrong row drawn and a step's top read wrong): the reset in exec.zig's Tab goes. The other readers of a pane's geometry, every one listed (the report's table): two read it on a step before making it: normal.zig `gotoWindow` read `context_rows` before `shownRows` made the geometry (gt/gb after a step that moved the top past its last geometry: the held rows of the place before; now read after it), and File.zig `rowTable` took its width from `body_wrapped` (the last geometry's) for j/k (`verticalMove`, which makes none): now from what that is made of, the view's `wrap`. The three tests of the change below pass (wip: gate to come) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/File.zig | 88 ++++++++++++++++++++++++++++++++++----------------------- core/exec.zig | 7 ++--- core/normal.zig | 2 +- core/panes.zig | 3 +- core/root.zig | 2 +- 5 files changed, 58 insertions(+), 44 deletions(-) diff --git a/core/File.zig b/core/File.zig index 163f40ff..1547756f 100644 --- a/core/File.zig +++ b/core/File.zig @@ -553,7 +553,7 @@ pub fn rowTable(pane: *const Pane, row: i32) ?*const Tables.Table { const f = if (pane.file) |*file| file else return null; if (row < 0 or f.tables.list.items.len == 0 or !f.tables.current(f)) return null; const table = f.tables.find(@intCast(row)) orelse return null; - const width = wrapWidth(pane, pane.body_wrapped); + const width = wrapWidth(pane, pane.view.wrap); if (width > 0 and table.width > width) return null; return table; } @@ -1858,14 +1858,38 @@ fn rowWalked(tab: u16, pane: *const Pane, width: usize, line: usize, col: usize, /// last, as the geometry's walk found it (no walk of the line a frame). pub fn top(tab: u16, pane: *Pane) Top { if (pane.file.?.scroll_row > 0) geometry(tab, pane); - return topNow(pane); + return topNow(tab, pane); } /// `top` off a geometry made already (a step that made it reads its key /// once: each hash of it costs a long line's step a hundredth more). -fn topNow(pane: *const Pane) Top { +fn topNow(tab: u16, pane: *Pane) Top { + const f = &pane.file.?; + return .{ .line = f.scroll, .row = if (f.scroll_row == 0) 0 else topSkip(tab, pane).row }; +} + +/// The top's row in its line (held at the line's last) and its first byte, +/// for the geometry made now: the one read of `Pane.top_skip`, a cache +/// keyed by the geometry it is of. A step that moves the top hands the +/// next geometry its byte (`show`, `scrollRows`), and a view drawn or +/// stepped in since leaves its own: one keyed for another geometry is +/// another view's top, or another place's, never this one's, and is +/// walked again here. +fn topSkip(tab: u16, pane: *Pane) @FieldType(Pane, "top_skip") { + if (pane.top_skip.key == pane.geometry_key) return pane.top_skip; const f = &pane.file.?; - return .{ .line = f.scroll, .row = if (f.scroll_row == 0) 0 else pane.top_skip.row }; + const width = wrapWidth(pane, pane.view.wrap); + const text = if (f.scroll < nlines(pane.gpa, f)) sourceLine(pane, @intCast(f.scroll)) else ""; + var guide: [1024]u8 = undefined; + var row: u32 = 0; + var at: usize = 0; + while (row < f.scroll_row and width > 0) : (row += 1) { + const end = fitEnd(tab, text, at, width - displayWidth(tab, guideOf(f, text, at, width, &guide))); + if (end >= text.len or end <= at) break; + at = end; + } + pane.top_skip = .{ .key = pane.geometry_key, .row = row, .at = at }; + return pane.top_skip; } pub fn setTop(pane: *Pane, to: Top) void { @@ -1968,8 +1992,8 @@ fn rowsWalked(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ? /// Whether `pane`'s map (the geometry) is of the view as it is now: only /// then may a walk read a line's rows off it (derived state, made by /// whoever asked first). -fn mapFresh(pane: *const Pane) bool { - return pane.wrap_n > 0 and pane.geometry_key == geometryKey(pane, &pane.file.?); +fn mapFresh(tab: u16, pane: *const Pane) bool { + return pane.wrap_n > 0 and pane.geometry_key == geometryKey(tab, pane, &pane.file.?); } /// The rows line `line` takes: counted off the map when the map is fresh @@ -1981,7 +2005,7 @@ fn rowsOf(tab: u16, pane: *const Pane, width: usize, map: *?bool, known: ?Known, if (known) |k| if (k.line == line) return k.rows; if (pane.wrap_n > pane.context_rows and line >= pane.wrap_line[pane.context_rows] and line <= pane.wrap_line[pane.wrap_n - 1] and (map.* orelse fresh: { - map.* = mapFresh(pane); + map.* = mapFresh(tab, pane); break :fresh map.*.?; })) { @@ -1990,8 +2014,9 @@ fn rowsOf(tab: u16, pane: *const Pane, width: usize, map: *?bool, known: ?Known, var i: usize = pane.context_rows; while (i < pane.wrap_n) : (i += 1) { if (pane.wrap_line[i] == line) { - // Rows of it above the top are not in the map. - if (rows == 0 and i == pane.context_rows and line == f.scroll and pane.top_skip.row > 0) break; + // Rows of it above the top are not in the map: its top row + // starts past its first byte. + if (rows == 0 and i == pane.context_rows and line == f.scroll and pane.wrap_col[i] > 0) break; rows += 1; } else if (rows > 0) return rows; } @@ -2003,7 +2028,7 @@ fn rowsOf(tab: u16, pane: *const Pane, width: usize, map: *?bool, known: ?Known, /// moved. pub fn scrollRows(tab: u16, pane: *Pane, delta: i64) i64 { geometry(tab, pane); - const t = topNow(pane); + const t = topNow(tab, pane); // Down to a row the body shows: the map has it, its line and its row in // that line, no line walked (a notch, a page). const i = @as(i64, pane.context_rows) + delta; @@ -2015,7 +2040,7 @@ pub fn scrollRows(tab: u16, pane: *Pane, delta: i64) i64 { for (pane.wrap_line[pane.context_rows..k]) |l| row += @intFromBool(l == pane.wrap_line[k]); setTop(pane, .{ .line = line, .row = row }); // Its first byte is the map's: the geometry starts there. - if (pane.body_wrapped) pane.top_skip = .{ .key = geometryKey(pane, &pane.file.?), .row = row, .at = @intCast(pane.wrap_col[k]) }; + if (pane.body_wrapped) pane.top_skip = .{ .key = geometryKey(tab, pane, &pane.file.?), .row = row, .at = @intCast(pane.wrap_col[k]) }; return delta; } } @@ -2045,7 +2070,7 @@ fn shownNow(pane: *const Pane) u16 { pub fn show(tab: u16, pane: *Pane, line_at: i32, col: i32, margin_rows: i64) void { const f = &pane.file.?; geometry(tab, pane); - const t = topNow(pane); + const t = topNow(tab, pane); // The line held at the top (a sticky context row): as it is. if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == t.line) { for (pane.wrap_line[0..pane.context_rows]) |row| if (row == line_at) return; @@ -2069,7 +2094,7 @@ pub fn show(tab: u16, pane: *Pane, line_at: i32, col: i32, margin_rows: i64) voi const at = if (oneRow(tab, pane, width)) RowIn{ .row = 0, .rows = 1 } else rowWalked(tab, pane, width, line, @intCast(@max(0, col)), .{ .after = @intCast(margin), .least = @intCast(body - 2 * margin + 1) }, starts); const known: Known = .{ .line = line, .rows = at.rows }; defer if (f.scroll == line and f.scroll_row < at.rows and at.rows - 1 - f.scroll_row < starts.len) { - pane.top_skip = .{ .key = geometryKey(pane, f), .row = f.scroll_row, .at = starts[f.scroll_row % starts.len] }; + pane.top_skip = .{ .key = geometryKey(tab, pane, f), .row = f.scroll_row, .at = starts[f.scroll_row % starts.len] }; }; if (pane.follow_edges != 0 and (row == null or row.? < 0 or row.? >= body)) pane.follow_crossed = true; const whole = at.rows <= body - 2 * margin; @@ -2665,14 +2690,18 @@ pub fn bodyText(tab: u16, arena: std.mem.Allocator, pane: *Pane, f: *State) ![]c /// which each step sets. pub fn geometry(tab: u16, pane: *Pane) void { const f = if (pane.file) |*file| file else return; - const key = geometryKey(pane, f); + const key = geometryKey(tab, pane, f); if (pane.geometry_key == key) return; pane.geometry_key = key; // The key of what the map was made from: the walk brings the text's // index and tables up to it (`line_starts`, `tables.revision`, in the // key), and with the key from before, a step's second ask made it all - // again. - defer pane.geometry_key = geometryKey(pane, f); + // again. The top's row it found or took is that key's too. + defer { + const made = geometryKey(tab, pane, f); + pane.top_skip.key = made; + pane.geometry_key = made; + } pane.body_rows = 0; pane.body_visible_rows = 0; pane.context_row_limit = null; @@ -2704,9 +2733,9 @@ fn mapRows(tab: u16, pane: *Pane, f: *State) usize { } /// Everything the geometry is made of, hashed: the text (its revision and -/// length), where it is scrolled, the pane's size, its tables, its context -/// declarations, the session's view. -fn geometryKey(pane: *const Pane, f: *const State) u64 { +/// length), where it is scrolled, the pane's size, the tab's width, its +/// tables, its context declarations, the session's view. +fn geometryKey(tab: u16, pane: *const Pane, f: *const State) u64 { const t = &f.tables; const facts = .{ f.revision, f.content.len, f.scroll, pane.hscroll, @@ -2715,7 +2744,7 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 { if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0, f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len, pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h, - pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat), f.scroll_row, + pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat), f.scroll_row, tab, }; // One hash of them laid out as words: every reader of the map asks for // this key, a hundred times a frame. @@ -2741,24 +2770,11 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State // row below asks whether it is that one. const end_slot: usize = if (total > 0 and endSlot(pane, total - 1)) total - 1 else std.math.maxInt(usize); var body_line: usize = f.scroll; - var body_at: usize = 0; + // The top line from the view's row in it (`top`): walked once a + // geometry (the map's pass), its text's pass a frame starting there. + var body_at: usize = topSkip(tab, pane).at; var written: usize = 0; var guide_buffer: [1024]u8 = undefined; - // The top line from the view's row in it (`top`): the rows above - // skipped, never past its last; walked once a geometry (the map's - // pass), its text's pass a frame starting where that walk ended. - // A top whose byte a step already found (`show`, a scroll off the map) - // is not walked again. - if (record_wrap and pane.top_skip.key != pane.geometry_key) { - var skipped: u32 = 0; - while (skipped < f.scroll_row and width > 0 and body_line < total) : (skipped += 1) { - const text = sourceLine(pane, @intCast(body_line)); - const end = fitEnd(tab, text, body_at, width - displayWidth(tab, guideOf(f, text, body_at, width, &guide_buffer))); - if (end >= text.len or end <= body_at) break; - body_at = end; - } - pane.top_skip = .{ .key = pane.geometry_key, .row = skipped, .at = body_at }; - } else body_at = pane.top_skip.at; for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| { if (i > 0) { if (dst) |out| out[written] = '\n'; diff --git a/core/exec.zig b/core/exec.zig index d1e1830f..2528805f 100644 --- a/core/exec.zig +++ b/core/exec.zig @@ -1057,11 +1057,8 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[ }, } if (setting.action == .tab) { - for (p.panes, 0..) |slot, id| { - p.surface.body_layers[id].rows = 0; - const pane = slot orelse continue; - pane.geometry_key = 0; - } + // The geometry's key holds the tab's width: made again where it is read. + for (&p.surface.body_layers) |*layer| layer.rows = 0; look.cancelLookHover(p); } if (setting.action == .tagline_size and p.settings.font.tagline_percent != previous_tagline_percent) diff --git a/core/normal.zig b/core/normal.zig index 5a9794ee..1f7ce1a7 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -994,8 +994,8 @@ fn gotoWindow(tab: u16, t: *Text, text: []const u8, range: modal.Selection, whic // In rows, as helix's goto_window: the row `margin + n` in from the // body's top or its last row of text, inside the margins, the // cursor on the first byte it shows (a wrapped line's later row). - const held: i32 = w.context_rows; const shown: i32 = File.shownRows(tab, w); + const held: i32 = w.context_rows; const lines = File.textLineCount(t, text); var last: i32 = shown - 1; while (last > 0 and w.wrapAt(tab, held + last).line >= lines) last -= 1; diff --git a/core/panes.zig b/core/panes.zig index 62814227..8939bd05 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -322,7 +322,8 @@ pub const Pane = struct { /// Where the view's top is inside its line's rows (File.Top) for the /// geometry of `key`: the row it is and the bytes of the line before /// it, found by the geometry's walk or by the step that put the top - /// there; a frame's text starts there with no walk again. + /// there; read only through File.topSkip, which walks one of another + /// key again (another view's top, a step's for the next geometry). top_skip: struct { key: u64 = 0, row: u32 = 0, at: usize = 0 } = .{}, context_rows: u16 = 0, body_rows: u16 = 0, diff --git a/core/root.zig b/core/root.zig index 3128f37b..63b77964 100644 --- a/core/root.zig +++ b/core/root.zig @@ -753,7 +753,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, .{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" }, - .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len top_skip", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state; a tab change resets the key" }, + .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len top_skip", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state (the tab's width too); top_skip, keyed by the geometry it is of, read only through File.topSkip, which walks one of another key again" }, .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, .{ "File.zig", "cap line_starts line_cap widest", "the text's line index, of its bytes, and the widest line it found (an upper bound: which walk answers, never what)" }, -- cgit v1.3 From 8688c01e9d3ce7524d37e2add652a6168c77880a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 14:50:56 -0300 Subject: load: a view's top row is read back as the session holds it, never held to its line's bytes (row scroll round 4, fault 2: 'client 3's dump loaded as another session', once in the merge67b release soak): `File.State.scroll_row` was a `.place` held at a load to `lastRow` (the top line's bytes), but no step holds it so: an edit leaves a view's row where it was while its top line shrinks or another line becomes its top (`ParkedPlaces`, a twin's, the live pane's own), and every reader takes a row past its line's as the line's last (`top`/`topSkip`, the walks' `@min(t.row, rows - 1)`), so the SESSION holds such a row and a join's load cut it: another digest. TEST FIRST, failing on uxxwxpvt (the fault 1 fix): views.zig "a view's top on a wrapped line's third row, the line taken out by another view and the next one empty: its top row past its line's, read as its last, and the session's dump loads as the session" (the session's row 2 on an empty line, read as row 0; the loaded core's digest another); the place and `lastRow` deleted (a row of any size is read as its line's last by every reader: `topSkip`'s walk ends at the line's end; the digest and the key take it as a number); fault 1's stale `top_skip.row` read by a step (`scrollRows`' map path: a row of another view's line plus the notch) was a second road to such a row Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/File.zig | 15 ++++----------- core/views.zig | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 11 deletions(-) diff --git a/core/File.zig b/core/File.zig index 1547756f..07dfa52d 100644 --- a/core/File.zig +++ b/core/File.zig @@ -108,8 +108,10 @@ pub const State = struct { // none of their bytes, and takes back what a speculation wrote // (core/rollback.zig `Epoch.wrote`). .journal = .{ "content", "line_starts" }, - // Where the view's top is, held to its text (walk.zig `.place`). - .place = .{ .{ "scroll", "lastLine" }, .{ "scroll_row", "lastRow" } }, + // Where the view's top is, held to its text (walk.zig `.place`); + // its row in that line is any (an edit leaves it past the line's + // rows, read as the last: `top`), as the session holds it. + .place = .{.{ "scroll", "lastLine" }}, }; /// The last line a view's top may be at: its text's. A clean file a @@ -121,15 +123,6 @@ pub const State = struct { return modal.lineCount(f.content) -| 1; } - /// The last row of the top's line its top may be at: a row holds a byte - /// of it at least (its rows as wrapped are the view's, made after). - pub fn lastRow(f: *const State) usize { - if (f.content.len == 0) return 0; - const at = modal.lineStartOffset(f.content, f.scroll); - const end = std.mem.indexOfScalarPos(u8, f.content, at, '\n') orelse f.content.len; - return end - at; - } - path: []u8, content: []u8, /// The bytes `content`'s buffer has room for (0: as many as it holds): diff --git a/core/views.zig b/core/views.zig index 5ad9b749..e5f2038e 100644 --- a/core/views.zig +++ b/core/views.zig @@ -988,6 +988,46 @@ test "a view's step after another view's step moved the top, the two alike befor try testing.expectEqual(lf.scroll_row, f.scroll_row); } +test "a view's top on a wrapped line's third row, the line taken out by another view and the next one empty: its top row past its line's, read as its last, and the session's dump loads as the session" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..30) |i| switch (i) { + 3 => { + for (0..60) |w| try text.print(gpa, "w{d:0>4} ", .{w}); + try text.append(gpa, '\n'); + }, + 4 => try text.append(gpa, '\n'), + else => try text.print(gpa, "line {d}\n", .{i}), + }; + const pane = try p.setTestFile(text.items); + const f = &pane.file.?; + // View k: its top on line 3's third row, its cursor well inside the body. + pane.body.cur_row = 10; + f.scroll = 3; + f.scroll_row = 2; + p.sync(); + const k = p.openView().?; + // View 0 takes line 3 out: view k's top line is the empty one after it. + cursorTo(p, pane, 3); + typeKeys(p, "xd"); + p.toView(k); + // A step of view k's own: its cursor inside the band, its top kept. + escape(p); + try testing.expectEqual(@as(usize, 3), f.scroll); + try testing.expectEqual(@as(usize, 0), pardes.panes.File.sourceLine(pane, 3).len); + try testing.expectEqual(@as(u32, 2), f.scroll_row); + try testing.expectEqual(pardes.panes.File.Top{ .line = 3, .row = 0 }, pardes.panes.File.top(p.settings.tab, pane)); + // A client joining loads the session's dump as the session. + const bytes = try pardes.dump.dumpBytes(p); + defer gpa.free(bytes); + const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, bytes, null); + defer loaded.deinit(); + try testing.expectEqual(pardes.walk.digest(Pardes, p), pardes.walk.digest(Pardes, loaded)); +} + test "a view not live keeps its place in a text another view edits" { const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); -- cgit v1.3 From 6fdf2bf2b1a90714ba998fa959db33089abb9f56 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 14:09:41 -0300 Subject: test/daemon.py --client-idle (FAILING on nvuylkxw, the multi-client line's flood: "a PDF in a window's session floods every client"): a session showing a PDF, one terminal client attached, nobody typing for 5 s, takes no more steps than the same session showing the text alone, plus 40 for the PDF's opening (its page drawn, its views told), in boundaries and in the client's units: a window's session on the test surface, a window's loop offscreen with no test mode (asleep until an event or its deadline, as a real window's is: `loop`), and a terminal's with its own terminal; on the base (Debug, load 4): the test surface 388 boundaries and 389 units against the text alone's 206 and 207, the window's loop 4871 and 4872 against 5 and 6 (the session's CPU 1070 ms in the 5 s, the client's 360), the terminal's 7 and 8 against 5 and 6 (passes); the bound's terms: on the test surface the window's loop polls its feed every 16 ms, a step and a unit each, which the text alone's count is; a window's own loop and a terminal's session step for nothing; pdf.so beside both binaries (`zig build install addons` into their prefix): one missing fails the test, never skips it Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/daemon.py | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/test/daemon.py b/test/daemon.py index 5603131d..97d7a2bb 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -55,6 +55,11 @@ private HOME and runtime directory: a client window showing a PDF resized 30 times in a second by the real compositor (driftwm), the caller's display: no SDL assertion, the last size taken, an input a size at most + python3 -B test/daemon.py --client-idle + a window's session (the test surface, and offscreen with no test + mode) and a terminal's, each with a PDF and a terminal client, + nobody typing: no more steps than the text alone (pdf.so in both + prefixes) """ import fcntl import json @@ -2278,6 +2283,112 @@ def client_motion(binary, gui_binary): shutil.rmtree(root, ignore_errors=True) +def idle_session(binary, gui_binary, surface, pdf, secs): + """One session (`surface`: a window's on the test surface; a window's + offscreen with no test mode, `loop`: the loop a real window runs, asleep + until an event or its deadline; or a terminal's with its own terminal), + a text and, with `pdf`, a PDF, one terminal client attached, nobody + typing for `secs`: the session's boundaries and the units the client + took over its whole life, and the CPU each spent in the idle seconds + (ticks of 10 ms).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='ci-', dir=os.environ.get('TMPDIR') or scratch)) + env = base_env() + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(60))) + stats = root / 'session.stats' + started, terms, windows = [], [], [] + try: + if surface == 'window': + win = Window(root, 'win', [gui_binary, '--9p=idle', str(notes)], dict(env, PARDES_DAEMON='on', PARDES_REPLICA_STATS=str(stats))) + windows.append(win) + started.append(win.pid) + elif surface == 'loop': + started.append(subprocess.Popen([gui_binary, '--9p=idle', str(notes)], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True, + env=dict(env, PARDES_DAEMON='on', PARDES_REPLICA_STATS=str(stats), SDL_VIDEO_DRIVER='offscreen')).pid) + else: + ts = Term(30, 100) + terms.append(ts) + started.append(ts.spawn([binary, '--tty', '--9p=idle', str(notes)], dict(env, PARDES_REPLICA_STATS=str(stats))).pid) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-idle.sock').exists, timeout=30) + nine = Client(root / 'pardes-9p-idle.sock') + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + started.append(session) + sock = root / 'pardes-replica.sock' + wait_for('the replica socket', sock.exists, timeout=30) + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + if pdf: + doc = root / 'design.pdf' + shutil.copy(Path(__file__).resolve().parent.parent / 'docs' / 'design.pdf', doc) + nine.write(f'/pane/{pane}/look', f'{doc}\n'.encode()) + wait_for('the PDF shown', lambda: any(row.split()[1] == b'pdf' for row in nine.read('/index').splitlines()), timeout=30) + tc = Term(24, 80) + terms.append(tc) + c = tc.spawn([binary, f'--attach={sock}:idle'], dict(env, PARDES_REPLICA_STATS=str(root / 'c.stats'))) + started.append(c.pid) + wait_for('the client\'s first frame', lambda: b'notes' in tc.text(), timeout=30) + # Its join and the frames after it over. + time.sleep(1.5) + cpu = (cpu_ticks(session), cpu_ticks(c.pid)) + time.sleep(secs) + cpu = (cpu_ticks(session) - cpu[0], cpu_ticks(c.pid) - cpu[1]) + c.send_signal(signal.SIGHUP) + c.wait(timeout=10) + line = checks(root / 'c.stats')[-1].split() + units = int(line[line.index('units') + 1]) + exit_session(nine, pane) + wait_for('the session ended', lambda: not alive(session), timeout=60) + nine.socket.close() + return int(session_stats(stats)[0]['boundaries']), units, cpu + finally: + for t in terms: + t.close() + for w in windows: + if w.p.poll() is None: + w.p.kill() + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + +def client_idle(binary, gui_binary, secs=5): + """An idle session sends nothing (2026-11-24: a PDF in a window's session + with a client attached stepped the session ~700 times a second, nobody + typing, each step a unit every client replayed): a session showing a + text and a PDF, one terminal client, nobody typing for `secs`, takes at + most the steps the same session with the text alone takes, plus the + PDF's own opening (its page drawn, its views told: `opening`). On the + test surface the window's loop polls its feed every 16 ms, a step and a + unit each (the text alone's count is that rate); a window's own loop + (`loop`: offscreen, no test mode) and a terminal's session step for + nothing. The PDF's addon (`/lib/pardes/addons/pdf.so`, `zig + build addons`) beside each binary.""" + for b in (binary, gui_binary): + lib = Path(b).resolve().parent.parent / 'lib' / 'pardes' / 'addons' / 'pdf.so' + assert lib.exists(), f'no {lib}: the PDF is this test\'s subject (zig build install addons into that prefix)' + opening = 40 + flooded = [] + for surface in ('window', 'loop', 'tty'): + text = idle_session(binary, gui_binary, surface, False, secs) + shown = idle_session(binary, gui_binary, surface, True, secs) + print(f'daemon: a {surface}\'s session idle {secs} s, a terminal client attached: ' + f'text alone {text[0]} boundaries, the client {text[1]} units, CPU {text[2][0] * 10}/{text[2][1] * 10} ms; ' + f'with a PDF {shown[0]} boundaries, {shown[1]} units, CPU {shown[2][0] * 10}/{shown[2][1] * 10} ms (session/client)') + if shown[0] > text[0] + opening or shown[1] > text[1] + opening: + flooded.append(f'{surface}: {shown[0]} boundaries and {shown[1]} units against the text alone\'s {text[0]} and {text[1]}') + assert not flooded, (f'a session showing a PDF, a client attached, nobody typing for {secs} s, steps with nothing to do, ' + f'a unit every client replays: {"; ".join(flooded)}') + + def client_resize_real(binary, gui_binary): """A client window resized by a real compositor (driftwm's `msg resize`, the configures a drag sends: 30 sizes in a second) while it shows a PDF: @@ -4493,6 +4604,8 @@ if __name__ == '__main__': client_motion(sys.argv[2], sys.argv[3]) elif sys.argv[1:2] == ['--client-resize-real']: client_resize_real(sys.argv[2], sys.argv[3]) + elif sys.argv[1:2] == ['--client-idle']: + client_idle(sys.argv[2], sys.argv[3]) elif sys.argv[1:2] == ['--ping']: ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50) elif sys.argv[1:2] == ['--pair-gui']: -- cgit v1.3 From 7db50fa75c7039cfeae00b6ba4d332258ea86a45 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 15:18:45 -0300 Subject: docs: loose-ends.md: what is known wrong, unfinished, or decided and not built, as of 2026-11-24 (the user: "those little bugs and things should be documented, but no need to do those now"): the faults known and not fixed (Restore on a release build, the database reader on a damaged image, the overflow of a client replaying after a divergence, a detached session's lost Upgrade words, the pointer state after an Upgrade, a client leaving across a wire number, a terminal client's column drag), what is decided and not built (an addon's panic closes only its pane: ruled today; back-pressure; the flush as a wait; more than four views; Help's wrap; a pane's rectangle inside its column), the prices accepted, the structural queue, and three test loose ends; an entry leaves the file in the change that settles it Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- docs/loose-ends.md | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 docs/loose-ends.md diff --git a/docs/loose-ends.md b/docs/loose-ends.md new file mode 100644 index 00000000..0fb2c984 --- /dev/null +++ b/docs/loose-ends.md @@ -0,0 +1,92 @@ +# Loose ends + +What is known to be wrong, unfinished or decided and not built, as of +2026-11-24, written down so that none of it has to be found twice. Nothing +here blocks daily use; each entry says where it was seen and what is known. +An entry leaves this file in the change that settles it. + +## Faults known, not fixed + +- **Restore on a release build fails one process test.** `process-test` + on ReleaseSafe, the root-ctl case "Restore asks once about unsaved text, + is answered before it cuts every connection": the request is answered + `Refused`. A request on a connection the Restore is cutting gets an error + in the 200 ms cut window (runtime/9p_io.zig `onServe`). Debug passes, + which is why every gate missed it until the release row was added. A fix + is written on the client-connection line (a connection being cut is hung + up, never answered with a refusal) and lands with that line. +- **A damaged session image can panic the database reader.** The dump + fuzz's image road reaches xitdb's own reader (`switch on corrupt value` + in `HashMap.init`, `readBytesObjectAlloc`, from core `Db.Read`) past its + fixed seeds. pardes's own decoders refuse a damaged dump naming the + field; this one is the dependency's. It wants an Edit in + build/patches.zig and a report beside the other dependency reports. +- **A client that replays after it diverged can overflow an integer.** + `Core.advanceInner` (`due - p.clock.stepped_ns`): seen only by the + soak's witness replaying a client that had already parted. A client that + diverges is dropped and joins again, so a user does not reach it today. +- **A detached session loses the words of an Upgrade that could not + load.** With no frontend of its own, "no build could load" is shown to + nobody; it should reach the log and the next client. +- **After an Upgrade a window says the pointer is inside.** `/status` + read "pointer in" in two windows right after their exec with the pointer + in neither (2026-11-24); one went back to "out" by itself. +- **A client left once across a build whose wire number differed.** Seen + once on the client-connection line, not reproduced. +- **In a terminal client a column's border did not drag** by B1 on the + second column's tag gutter (measured while testing several clients). + Whether a terminal has another handle for it was not looked at. + +## Decided, not built + +- **An addon's panic closes only its pane** (ruled 2026-11-24). Today an + addon's panic is pardes's panic: a crash record is written, the terminal + is put back, and the session ends. The ruling: the pane of the addon + that panicked is closed with its words in the log, the session goes on. +- **A client's send queue bounded by back-pressure.** The session writes + no more than a window W past what the client has read and queues the + rest; a client is cut to a fresh dump only when the queue also passes W. + Designed with a draft on the client-connection line; today a far client + under a flood is cut by the older lag rule, which works. +- **The 200 ms flush before a link is dropped** becomes a wait that each + writer's end wakes, and every other time bound gets one line saying why + real time is right there. Designed, not built. +- **More than four views a session.** A fifth view is refused (the + session's own and three clients, or four clients of a detached one). + What raising the limit costs (the per-view arrays, the digest, the dump, + the wire) is not measured. +- **Help wraps mid-word.** It waits on wrapping at word boundaries, which + no pane has yet. +- **A pane's rectangle inside its column, checked at a load.** A view's + rectangles off its screen are refused; this narrower check is not built + because a pane placed and not yet laid out has an empty rectangle inside + a step, and a dump is written inside a step. + +## Prices accepted (to turn if they are felt) + +- A view's scroll by rows: selecting deep into one 2 MB line costs about + 75% more a frame (it draws the rows the selection is on; the old view + did not show them). Every ordinary key, wheel, page and edit: no dearer. +- One terminal cell of the performance table is 0.14% to 0.16% over its + old count since the change layers; the baseline was recorded again. + +## The structural queue + +Three pieces of organization meant to make whole kinds of fault +impossible to write, each to start with a read-only survey and a plan: +a client's lifecycle as one state with codes on the wire and every time +bound named; what a field of the core costs (the digest, the dump and +the copy declared together); the test harness (the Python daemon tests +moved to the Zig runner, mode by mode). Three questions go with it: the +terminal boundary enforced by type or by a counted list; the codes' +names; whether the Python harness goes entirely. + +## Tests and gates + +- The gui `unit-test` step exits 1 with every test passing: its + performance check reports a baseline recorded by another harness. A + baseline recorded with the current one clears it. +- `test/daemon.py --upgrade --gui` assumes `wayland-0` when + `WAYLAND_DISPLAY` is unset; it should find the compositor's socket. +- `test/daemon.py --window-clients` skips its PDF case when the terminal + build's prefix holds no `pdf.so`. -- cgit v1.3 From 4ae132650106242a5130aad5230c4f429bf02b29 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 14:43:18 -0300 Subject: replica, gui, tui: the clock a session's pump reads after its wait is held only while a client's post waits for it (Peers.heldNow, which both shells' clocks call), so a wait that ran out always reads the clock and its step meets the deadline it waited for: a window's session showing a PDF with a client attached stepped ~700 times a second with nobody typing, each step a unit every client replayed (the multi-client line's "a PDF in a window's session floods every client"); RUN (an instrumented Debug build, the window's loop offscreen with no test mode, a terminal client; .scratch reorg/pardes-idle-flood/runs/probe): the client's view of the PDF (pane 1, view 1: 78x9, 8x16, glyphs) owed to the kind from its join on (Kind.wake: now, so nextWake a frame on), and 2247 of 2268 pumps 'mail_only true, mail false, wait ran out', the clock read after each the one held at the join (1.302 s while the real one ran to 2.93 s), so advance never reached the deadline, the view was never told, and the next wait was 1 ms: for ever; THE CAUSE: dev/gui/gui.zig guiNow held the clock after any wait whose `mail_only` was still set, and waitInput sets it at a wait's start and clears it only for an event that is not a replica's wake or a queue message: a wait that ran out (SDL_WaitEventTimeout false, waitDetached's too) took no post and still held the clock; a terminal's session never did (its wait ends in a .wake event, tui.zig apply clears it); THE FIX: Peers.heldNow (core/replica.zig): held only when the wait took nothing else (the shell's `mail_only`), a client is attached (`recording`), a post waits to be taken (`mail`, set by post, cleared at the boundary) and the clock has started; gui.zig guiNow and tui.zig clockNow call it (their own copies of the rule gone), so no shell's wait can hold the clock without a post; TEST FIRST: test/panes.zig "a PDF shown and a client's view its kind was not told: the session's next pump, its wait run out with nobody typing, tells it, and nothing is owed after; a client's post waiting holds the clock" (on the base's rule, the same function without `mail`: fails at panes.zig:4120, the view still owed after the pump); test/daemon.py --client-idle on this build: the window's loop 7 boundaries and 8 units with a PDF against the text alone's 5 and 6 (4871 and 4872 on the base), the test surface 223 against 207 (388 against 206), the terminal's 8 against 5; a user hit it: every window's session with a client attached and a deadline owed (a PDF's view, a message's linger, a Life's tick, a look's hover) stepped and sent a unit a millisecond until someone typed in the window Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 12 ++++++++ dev/gui/gui.zig | 7 ++--- dev/tui/tui.zig | 7 ++--- test/panes.zig | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 102 insertions(+), 8 deletions(-) diff --git a/core/replica.zig b/core/replica.zig index 829972c2..875a7828 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -1911,6 +1911,18 @@ pub const Peers = struct { return n; } + /// The time the session's pump reads after its wait, when that wait + /// took a client's post and nothing else (`only_mail`, the shell's word + /// for its wait): the core's clock as it stands, so the pump's unit + /// moves nothing a client's speculation stands on; null otherwise (the + /// shell's clock). Held only while a post waits (`mail`): a wait that + /// ran out took none, and the pump after it is the one its deadline + /// asked for (a window's wait that ran out was held, 2026-11-24: a + /// deadline never met, the session stepped a millisecond for ever). + pub fn heldNow(ps: *const Peers, core: *const Pardes, only_mail: bool) ?u64 { + return if (only_mail and ps.recording and ps.mail.load(.acquire) and core.clock.started) core.clock.now_ns else null; + } + pub fn post(ps: *Peers, note: Note) void { ps.lock.lockUncancelable(ps.io); if (note == .join and ps.upgrading.load(.monotonic)) { diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 9ea813fc..8fd8c24c 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -2457,9 +2457,8 @@ const Shell = struct { /// of their own with no window here; the session loop's /// (runtime/session.zig), a client's none. peers: *replica.Peers, - /// This wait took only a replica's post (its input, its join): the pump - /// after it reads no new time, so it moves nothing the replicas' - /// speculations stand on (tui.zig's `mail_only`). + /// This wait took nothing but a replica's post, if one (its input, its + /// join): the pump after one reads no new time (Peers.heldNow). mail_only: bool = false, waited: bool = false, /// With replica clients, a wait takes one person's input (tui.zig @@ -3167,7 +3166,7 @@ fn guiNow(ctx: ?*anyopaque) u64 { const s = shellOf(ctx); if (s.waited) { s.waited = false; - if (s.mail_only and s.peers.count() > 0 and s.core.clock.started) return s.core.clock.now_ns; + if (s.peers.heldNow(s.core, s.mail_only)) |held| return held; } return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); } diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index e2cdd2fa..312a0846 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -1240,9 +1240,8 @@ const Shell = struct { /// The session's replica clients (core/replica.zig), on sockets: the /// session loop's (runtime/session.zig); a client's, none. peers: *replica.Peers, - /// This wait took only a replica's post (its input, its join): the - /// pump after it reads no new time, so it moves nothing the replicas' - /// speculations stand on (a replica takes such a unit as is). + /// This wait took nothing but a replica's post, if one (its input, its + /// join): the pump after one reads no new time (Peers.heldNow). mail_only: bool = false, waited: bool = false, /// This wait's steps so far, and the input held for the next (`split`). @@ -1321,7 +1320,7 @@ const Shell = struct { const s = of(ctx); if (s.waited) { s.waited = false; - if (s.mail_only and s.peers.count() > 0 and s.core.clock.started) return s.core.clock.now_ns; + if (s.peers.heldNow(s.core, s.mail_only)) |held| return held; } return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); } diff --git a/test/panes.zig b/test/panes.zig index bd39beba..28a3b256 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -4047,6 +4047,90 @@ const PdfAddon = struct { } } + /// A session's loop with nobody typing: each wait runs out at its + /// deadline, and the clock read after it is the shells' (Peers.heldNow, + /// as gui.zig `guiNow` and tui.zig `clockNow` read it: a wait that took + /// nothing else, `only_mail`). + const Idle = struct { + now: u64 = std.time.ns_per_s, + waited: bool = false, + core: ?*Pardes = null, + peers: pardes.replica.Peers = .{ .gpa = std.testing.allocator, .io = std.testing.io }, + + const vtable: pardes.Host.VTable = .{ + .wait_input = wait, + .now = clock, + .watched = host_vtable.watched, + .job = host_vtable.job, + }; + + fn wait(ctx: ?*anyopaque, timeout_ms: u32) void { + const h: *Idle = @ptrCast(@alignCast(ctx.?)); + h.now += @as(u64, timeout_ms) * std.time.ns_per_ms; + h.waited = true; + } + + fn clock(ctx: ?*anyopaque) u64 { + const h: *Idle = @ptrCast(@alignCast(ctx.?)); + if (!h.waited) return h.now; + h.waited = false; + return h.peers.heldNow(h.core orelse return h.now, true) orelse h.now; + } + }; + + test "a PDF shown and a client's view its kind was not told: the session's next pump, its wait run out with nobody typing, tells it, and nothing is owed after; a client's post waiting holds the clock" { + // 2026-11-24: a window's session showing a PDF, a client attached, + // stepped ~700 times a second with nobody typing: the client's view + // owed to the kind (Kind.wake: now), a wait of a millisecond that + // ran out, and the clock after it held as if a client had posted + // (gui.zig guiNow: its wait's `mail_only` is cleared by an event, + // and one that ran out had none), so no step met the deadline. + if (!addons.has_pdf) return error.SkipZigTest; + const R = pardes.replica; + var idle: Idle = .{}; + defer idle.peers.deinit(); + const a = try R.Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .ctx = &idle, .vtable = &Idle.vtable }); + defer a.deinit(); + idle.core = a.core; + const Land = struct { + a: *R.Authority, + fn step(l: @This(), ev: pardes.Event) !void { + _ = try l.a.local(ev); + } + }; + const id = try opened(a, Land{ .a = a }); + const slot = a.core.panes[id].?.addon.?; + // A client attached (units go to it), its view sized by its input: + // a client's step tells no kind (17.2), so its view is owed. + idle.peers.recording = true; + const k = (try a.openView(2)).view; + const was = pardes.tape.on; + pardes.tape.on = &a.t; + const bytes = try pardes.dump.byteDump(a.core); + pardes.tape.resync(&a.t); + pardes.tape.on = was; + defer a.core.gpa.free(bytes); + const win = try R.Replica.initDump(std.testing.allocator, 2, k, bytes, .{ .cols = 80, .rows = 24 }); + defer win.deinit(); + _ = try a.take(try win.input(.{ .resize = .{ .cols = 80, .rows = 24 } })); + try std.testing.expect(pardes.Kind.viewOwed(a.core, slot, id)); + // ONE pump, nobody typing: its wait runs out at the wake, the step + // it asked for tells the view, and nothing is owed after. + a.pump(); + try std.testing.expect(!pardes.Kind.viewOwed(a.core, slot, id)); + try std.testing.expect((pardes.Kind.wake(a.core) orelse std.math.maxInt(u64)) > a.core.clock.now_ns); + // A client's post waiting (its input, its join): the pump before + // the boundary takes it reads the clock as it stands. + const at = a.core.clock.now_ns; + idle.now += std.time.ns_per_s; + idle.peers.mail.store(true, .release); + a.pump(); + try std.testing.expectEqual(at, a.core.clock.now_ns); + idle.peers.mail.store(false, .release); + a.pump(); + try std.testing.expectEqual(idle.now, a.core.clock.now_ns); + } + test "a PDF pane whose file changes on disk opens again from it at its page, its fit kept" { if (!addons.has_pdf) return error.SkipZigTest; const gpa = std.testing.allocator; -- cgit v1.3 From f0b23904f81d261b4f80544bf3c5cc7aafbf440b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 15:20:26 -0300 Subject: gui: imageScissor is the placement's cells again: item 3's change (nvuylkxw, installed as 654a1632400a) kept a throwaway line of its own experiment (every picture's clip widened by 100000 px, to make SDL's scissor assertion fire on the test surface), restored in the wrong tree (a copy from inside the sketchbook checkout, whose ../pardes is ws-gate's): held to the target by sketchbook's Cells.onTarget it asserted nothing, but a picture was no longer cut at its pane's right edge (a PDF page or an image wider than its pane drew over the panes to its right); no gate row has a picture past its pane's right edge (77/77 frames identical with it); TEST FIRST: gui.zig "a picture's scissor is its placement's cells, cut at its pane's edges" (expected 40, found 100040 on the installed line; passes now) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/gui/gui.zig | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 9ea813fc..aba74a94 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -3904,7 +3904,7 @@ fn imageScissor(g: *const Gui, place: pardes.Placement) c.SDL_Rect { return .{ .x = @intCast(@as(u32, place.dst.x) * g.cell_w), .y = @intCast(@as(u32, place.dst.y) * g.cell_h), - .w = @intCast(@as(u32, place.dst.w) * g.cell_w + 100000), // THROWAWAY: past any target + .w = @intCast(@as(u32, place.dst.w) * g.cell_w), .h = @intCast(@as(u32, place.dst.h) * g.cell_h), }; } @@ -7010,6 +7010,13 @@ test "a held key moves the view at the stream's own rate, never a bounce a line, for (70..90) |k| try std.testing.expectEqual(held.carets[70], held.carets[k]); } +test "a picture's scissor is its placement's cells, cut at its pane's edges" { + const g = testGui(10, 20, 6, 12); + var place: pardes.Placement = undefined; + place.dst = .{ .x = 2, .y = 3, .w = 4, .h = 5 }; + try std.testing.expectEqual(c.SDL_Rect{ .x = 20, .y = 60, .w = 40, .h = 100 }, imageScissor(&g, place)); +} + test "a scroll's shifted rows start under the context rows, and its scissor below their band" { var surface: pardes.Surface = .{}; var g = testGui(10, 20, 6, 12); -- cgit v1.3