summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--abi/wire.zig5
-rw-r--r--core/Core.zig6
-rw-r--r--core/File.zig573
-rw-r--r--core/Output.zig1
-rw-r--r--core/Places.zig11
-rw-r--r--core/Query.zig40
-rw-r--r--core/Text.zig11
-rw-r--r--core/draw.zig3
-rw-r--r--core/jj.zig173
-rw-r--r--core/layout.zig35
-rw-r--r--core/look.zig55
-rw-r--r--core/mouse.zig14
-rw-r--r--core/ninep/events.zig4
-rw-r--r--core/normal.zig153
-rw-r--r--core/panes.zig64
-rw-r--r--core/replica.zig154
-rw-r--r--core/rollback.zig3
-rw-r--r--core/root.zig4
-rw-r--r--core/surface.zig4
-rw-r--r--core/views.zig17
-rw-r--r--core/walk.zig.orig2618
-rw-r--r--dev/glide.zig43
-rw-r--r--dev/gui/gui.zig60
-rw-r--r--test/daemon.py2
-rw-r--r--test/kitty.zig2
-rw-r--r--test/panes.zig28
-rw-r--r--test/perf.zig14
-rw-r--r--test/process/tty_boot.zig7
-rw-r--r--test/snapshots/builtins.golden71
-rw-r--r--test/snapshots/leader.golden75
-rw-r--r--test/terminal.zig2
31 files changed, 1340 insertions, 2912 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..8b7adae3 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,24 @@ 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;
+ }
+ // 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;
@@ -612,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]);
@@ -629,20 +658,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 +768,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 +782,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 +802,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 +820,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 +1087,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 +1136,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 +1327,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 +1515,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 +1526,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 +1758,365 @@ 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, width: usize) bool {
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 {
+ 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, width, line, col, .{}, &.{});
+}
+
+/// 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 };
+ 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 };
+ 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;
+ }
+}
+
+/// 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 {
+ 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.?;
+ return .{ .line = f.scroll, .row = if (f.scroll_row == 0) 0 else 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, 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)));
+ return w;
+}
+
+fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Known) Walked {
+ var map: ?bool = null;
+ const width = wrapWidth(pane, pane.view.wrap);
+ var t = from;
+ var rows = rowsOf(tab, pane, width, &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, width, &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, width, &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, 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)));
+ return to;
+}
+
+fn rowsWalked(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 {
+ 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, width, &map, null, l);
+ if (d > bound) return null;
+ }
+ while (l > line) {
+ l -= 1;
+ d -= rowsOf(tab, pane, width, &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 (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 (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;
+ 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 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 = 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 < 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;
+ }
+ }
+ 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);
+ 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);
+}
+
+/// 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 = 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 = 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
+ // 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));
+ // 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) {
+ 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;
+}
+
+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 {
+ 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 +2593,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 +2648,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 +2695,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 +2723,22 @@ 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.
+ // 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';
@@ -2265,12 +2748,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 +3187,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 +3222,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 +3258,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 +3270,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 3023cc60..feebb6cd 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
@@ -533,7 +533,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);
}
@@ -1157,7 +1157,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 {
@@ -1233,7 +1233,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);
}
@@ -1326,7 +1326,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);
}
@@ -1448,7 +1448,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void {
}
}
countCurrent(q);
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
}
// ---- the current row ----
@@ -1457,7 +1457,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;
@@ -1465,24 +1465,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.
@@ -1513,7 +1508,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);
}
@@ -1572,6 +1567,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:
@@ -1689,6 +1685,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
@@ -1698,6 +1695,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;
@@ -1917,7 +1915,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].?;
@@ -1983,7 +1981,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/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 72bb42eb..ee6debf9 100644
--- a/core/look.zig
+++ b/core/look.zig
@@ -499,9 +499,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)
@@ -820,14 +818,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 = std.math.cast(i32, at.line - 1) orelse return;
pane.body.cur_col = columnOn(pane, pane.body.cur_row, at.col);
@@ -1697,11 +1690,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;
}
@@ -1932,6 +1927,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";
@@ -2313,6 +2337,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());
@@ -2386,6 +2411,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);
@@ -2462,6 +2488,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..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;
}
@@ -946,14 +957,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)
@@ -961,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),
@@ -1235,13 +1280,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
@@ -1429,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 });
diff --git a/core/panes.zig b/core/panes.zig
index 02ee805f..08d91df5 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,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 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,
@@ -636,15 +641,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):
@@ -668,43 +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 829972c2..46320fea 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -4534,6 +4534,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/core/walk.zig.orig b/core/walk.zig.orig
deleted file mode 100644
index d870052d..00000000
--- a/core/walk.zig.orig
+++ /dev/null
@@ -1,2618 +0,0 @@
-//! The reflective walk over the core's state: one comptime `@typeInfo` walk
-//! that hashes a session into a digest (the replay harness compares two),
-//! encodes values for the tape, and dumps a session for another build to
-//! load by name: into a xitdb database's maps (`Put`, `Get`: a Dump,
-//! Restore, -l, an Upgrade, a handover; Db.zig), or as bytes with a table
-//! of its types (`Dump`, `Load`: a closed pane, the join of phase 5, and
-//! for one release the `.dump` files before). The rollback copy is to walk
-//! the same way (docs/next-daemon.md).
-//!
-//! Values, never addresses: a pointer is followed to what it points at, a
-//! slice is its elements, an ArrayList its items, a hash map its entries in
-//! no order. A type the walk cannot see into (an opaque handle, a function,
-//! an untagged union, a many-pointer) is a compile error naming it, until
-//! the struct that holds it says what the field is:
-//!
-//! pub const replica = .{
-//! // This process's own: presentation, timing, the host's handles
-//! // and caches. A replica has its own and never compares them.
-//! .local = .{ "frames", "surface" },
-//! // Recomputed from the rest whenever it is wanted.
-//! .derived = .{ "wrap_line" },
-//! // Held by the session that performs effects alone.
-//! .authority = .{ "host" },
-//! // A field written only as far as another says: hashed that far.
-//! .len = .{ .{ "jumps", "njumps" } },
-//! // What a field holds is made with another allocator on a load.
-//! .alloc = .{ .{ "image", "image" } },
-//! // Immutable blobs: replaced whole, never written, freed raw
-//! // (memory.freeRaw). A digest hashes each once and
-//! // folds that word in; a replica's rollback copy pins them.
-//! .blob = .{ "content" },
-//! };
-//!
-//! None of the three kinds is in a digest or a dump. A type (a struct or a
-//! tagged union) with a `pub fn digest(*const T, *Hasher) void` of its own
-//! hashes itself; one with
-//! `dumpWrite`, `dumpRead` (and `dumpFree`) dumps itself as bytes.
-const std = @import("std");
-const xitdb = @import("xitdb");
-
-pub const Hasher = std.hash.Wyhash;
-const builtin = @import("builtin");
-
-/// Whether `T.name` holds blobs (`.blob`): a file's text, an undo entry's
-/// bytes, a register's text, a file's location rows.
-pub fn blob(comptime T: type, comptime name: []const u8) bool {
- @setEvalBranchQuota(100_000);
- if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "blob")) return false;
- inline for (T.replica.blob) |n| if (comptime std.mem.eql(u8, n, name)) return true;
- return false;
-}
-
-// ---- a blob in a digest: its length ----
-//
-// A digest walks the whole core at every unit a replica is sent (and every
-// unit a replica replays): a 100 MB file was hashed in full each time, then
-// once and kept as a word by its address while texts were never written in
-// place. A blob of `blob_min` bytes or more is digested as its length now,
-// never its bytes: a file's text says what it holds by its revision
-// (File.State.revision, in the digest), and the other blobs are replaced
-// whole, never written. A smaller one is hashed as any slice is.
-
-const blob_min = 4096;
-threadlocal var in_blob: bool = false;
-
-/// A blob as a digest takes it: its length.
-fn hashBlob(comptime E: type, items: []const E, h: *Hasher) void {
- // The list is the C heap's (a replica client's), which a build with no
- // libc has none of.
- if (comptime builtin.link_libc) if (blobs_out) |list| list.append(std.heap.c_allocator, std.mem.sliceAsBytes(items)) catch {};
- h.update(std.mem.asBytes(&items.len));
-}
-
-/// Where `blobs` notes every blob.
-threadlocal var blobs_out: ?*std.ArrayListUnmanaged([]const u8) = null;
-
-/// Every blob of `v` a digest takes as one (`blob_min` bytes and up), as
-/// its bytes, onto `out` (the C heap's): a replica client's, which knows
-/// its blobs by content (core/replica.zig `Have`).
-pub fn blobs(comptime T: type, v: *const T, out: *std.ArrayListUnmanaged([]const u8)) void {
- blobs_out = out;
- defer blobs_out = null;
- _ = digest(T, v);
-}
-
-pub fn digest(comptime T: type, v: *const T) u64 {
- var h = Hasher.init(0);
- hash(T, v, &h);
- return h.final();
-}
-
-/// A digest of each field `hash` would walk, in order (what a divergence
-/// is narrowed down by); `names` are theirs.
-pub fn fieldDigests(comptime T: type, v: *const T, out: []u64) []u64 {
- var n: usize = 0;
- const s = @typeInfo(T).@"struct";
- inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or comptime excluded(T, name)) continue;
- var h = Hasher.init(0);
- const was = in_blob;
- in_blob = comptime blob(T, name);
- defer in_blob = was;
- if (comptime lengthOf(T, name)) |len| {
- hashSlice(Element(F), @field(v, name)[0..lengthIn(v, len)], &h);
- } else hash(F, &@field(v, name), &h);
- out[n] = h.final();
- n += 1;
- }
- return out[0..n];
-}
-
-pub fn fieldNames(comptime T: type) []const []const u8 {
- comptime {
- var names: []const []const u8 = &.{};
- const s = @typeInfo(T).@"struct";
- for (s.field_names, s.field_attrs) |name, attr| {
- if (attr.@"comptime" or excluded(T, name)) continue;
- names = names ++ .{name};
- }
- return names;
- }
-}
-
-/// Types that are machinery, never state: an allocator, the Io, a lock.
-pub fn machinery(comptime T: type) bool {
- inline for (.{ std.mem.Allocator, std.Io, std.Io.Mutex, std.Io.Condition, std.Thread, std.heap.ArenaAllocator }) |M| if (T == M) return true;
- return false;
-}
-
-/// Bytes that are the value whole: no padding, no pointer.
-fn flat(comptime T: type) bool {
- return switch (@typeInfo(T)) {
- .int => @sizeOf(T) * 8 == @bitSizeOf(T),
- .bool => true,
- .@"enum" => |e| @sizeOf(T) * 8 == @bitSizeOf(e.tag_type),
- else => false,
- };
-}
-
-/// A field the walk cannot follow: a pointer to an opaque thing or a
-/// function, or a many-pointer, bare or optional (the struct holding it is
-/// named in the error, not the walk's depth).
-fn opaqueTo(comptime F: type) bool {
- return switch (@typeInfo(F)) {
- .optional => |o| opaqueTo(o.child),
- .pointer => |p| p.size == .many or p.size == .c or switch (@typeInfo(p.child)) {
- .@"opaque", .@"fn" => true,
- else => false,
- },
- else => false,
- };
-}
-
-fn excluded(comptime T: type, comptime name: []const u8) bool {
- @setEvalBranchQuota(100_000);
- if (!@hasDecl(T, "replica")) return false;
- inline for (.{ "local", "derived", "authority" }) |kind| {
- if (@hasField(@TypeOf(T.replica), kind)) inline for (@field(T.replica, kind)) |n| {
- if (comptime std.mem.eql(u8, n, name)) return true;
- };
- }
- return false;
-}
-
-/// What a `len`-cut field holds: a fixed array's, or a slice's room (a
-/// selection's ranges, made once and used `nsel` deep).
-fn Element(comptime F: type) type {
- return switch (@typeInfo(F)) {
- .array => |a| a.child,
- .pointer => |p| p.child,
- else => @compileError("walk: a `len` cuts an array or a slice, not " ++ @typeName(F)),
- };
-}
-
-pub fn lengthIn(v: anytype, comptime len: []const u8) usize {
- const n = @field(v, len);
- return if (@typeInfo(@TypeOf(n)) == .optional) (if (n) |k| k else 0) else n;
-}
-
-/// How far the field `len` names says its array is written (null: none).
-pub fn lengthOf(comptime T: type, comptime name: []const u8) ?[]const u8 {
- @setEvalBranchQuota(100_000);
- if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "len")) return null;
- inline for (T.replica.len) |pair| if (comptime std.mem.eql(u8, pair[0], name)) return pair[1];
- return null;
-}
-
-/// Every name an annotation gives is a field: a rename cannot quietly put
-/// a field back in the digest.
-fn checkAnnotations(comptime T: type) void {
- if (!@hasDecl(T, "replica")) return;
- inline for (@typeInfo(@TypeOf(T.replica)).@"struct".field_names) |kind| {
- 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;
- if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name);
- }
- }
-}
-
-pub fn hash(comptime T: type, v: *const T, h: *Hasher) void {
- switch (@typeInfo(T)) {
- .void, .null, .undefined => {},
- .bool => h.update(&.{@intFromBool(v.*)}),
- .int => hashInt(T, v.*, h),
- .float => h.update(std.mem.asBytes(v)),
- .@"enum" => hashEnum(T, v.*, h),
- .optional => |o| if (v.*) |*payload| {
- h.update(&.{1});
- hash(o.child, payload, h);
- } else h.update(&.{0}),
- .array => |a| if (comptime flatHash(a.child)) h.update(std.mem.sliceAsBytes(v)) else for (v) |*e| hash(a.child, e, h),
- .pointer => |p| switch (p.size) {
- .one => hash(p.child, v.*, h),
- .slice => hashSlice(p.child, v.*, h),
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => |s| {
- if (comptime machinery(T)) return;
- if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h);
- if (s.layout == .@"packed") return hashInt(s.backing_integer.?, @bitCast(v.*), h);
- if (comptime isList(T))
- return hashSlice(@typeInfo(@FieldType(T, "items")).pointer.child, v.items, h);
- // std.atomic.Value: what it holds.
- if (comptime isAtomic(T)) return hash(@FieldType(T, "raw"), &v.raw, h);
- // A worker's future is a handle of the host's, never state.
- if (comptime @hasField(T, "any_future")) return;
- // std.DynamicBitSetUnmanaged: its bits.
- if (comptime isBitset(T)) {
- h.update(std.mem.asBytes(&v.bit_length));
- return h.update(std.mem.sliceAsBytes(v.masks[0 .. (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize)]));
- }
- comptime checkAnnotations(T);
- inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or comptime excluded(T, name)) continue;
- if (comptime opaqueTo(F)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is " ++ @typeName(F) ++ ", which no walk sees into: say what it is (`replica`)");
- const was = in_blob;
- in_blob = comptime blob(T, name);
- defer in_blob = was;
- if (comptime lengthOf(T, name)) |len| {
- hashSlice(Element(F), @field(v, name)[0..lengthIn(v, len)], h);
- } else hash(F, &@field(v, name), h);
- }
- },
- .@"union" => |u| {
- if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T));
- if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h);
- const tag: u.tag_type.? = v.*;
- hash(u.tag_type.?, &tag, h);
- switch (v.*) {
- inline else => |*payload| hash(@TypeOf(payload.*), payload, h),
- }
- },
- .error_set => h.update(@errorName(v.*)),
- .error_union => |e| if (v.*) |*payload| {
- h.update(&.{1});
- hash(e.payload, payload, h);
- } else |err| {
- h.update(&.{0});
- h.update(@errorName(err));
- },
- else => @compileError("walk: cannot hash " ++ @typeName(T)),
- }
-}
-
-/// Bytes a digest takes whole: an enum's are its build's number, not it.
-fn flatHash(comptime T: type) bool {
- return flat(T) and @typeInfo(T) != .@"enum";
-}
-
-/// An enum by its name, as a dump reads it, not by its number: an enum
-/// made at compile time numbers its words as its build has them
-/// (`registry.Builtin` has fewer in a FreeBSD build than a Linux one, which
-/// has Tty9p), so a window client here of a session on the box loaded a
-/// +LocationsConfig to another digest. A name's word (its hash, fixed
-/// width, so that two names in a row are not one), looked up by number
-/// where the words are numbered 0 up; one numbered by hand, or a value no
-/// word has, by its number.
-fn hashEnum(comptime T: type, v: T, h: *Hasher) void {
- const e = @typeInfo(T).@"enum";
- const words: ?[e.field_names.len]u64 = comptime words: {
- @setEvalBranchQuota(100_000);
- var out: [e.field_names.len]u64 = undefined;
- for (e.field_names, e.field_values, 0..) |name, n, i| {
- if (n != i) break :words null;
- out[i] = std.hash.Wyhash.hash(0, name);
- }
- break :words out;
- };
- const n = @backingInt(v);
- if (words) |table| if (n >= 0 and n < table.len) return h.update(std.mem.asBytes(&table[@intCast(n)]));
- hashInt(e.tag_type, n, h);
-}
-
-/// An integer by its value: one narrower than its bytes (a u21, an i2) has
-/// bits in memory that are no part of it.
-fn hashInt(comptime I: type, n: I, h: *Hasher) void {
- const W = @Int(@typeInfo(I).int.signedness, @sizeOf(I) * 8);
- const wide: W = n;
- h.update(std.mem.asBytes(&wide));
-}
-
-fn hashSlice(comptime E: type, items: []const E, h: *Hasher) void {
- if (in_blob and items.len * @sizeOf(E) >= blob_min) return hashBlob(E, items, h);
- h.update(std.mem.asBytes(&items.len));
- if (comptime flatHash(E)) return h.update(std.mem.sliceAsBytes(items));
- for (items) |*e| hash(E, e, h);
-}
-
-/// The value as bytes, the same walk: what the tape carries (core/tape.zig),
-/// to a replica of another build too (a window of a terminal's session, a
-/// Linux client of a FreeBSD one). Native byte order, which every machine
-/// pardes runs on shares, and an error by its name: its number is its
-/// build's own (a Linux terminal's FileNotFound is a window's
-/// NoDefaultValue). What a field is laid out as (a std.Io.File.Stat's
-/// `nlink` is another width on FreeBSD) is the tape's shape, which
-/// wire.semantics hashes (`shape`).
-pub fn encode(comptime T: type, v: *const T, w: *std.Io.Writer) std.Io.Writer.Error!void {
- switch (@typeInfo(T)) {
- .void, .null, .undefined => {},
- .bool, .int, .float, .@"enum" => try w.writeAll(std.mem.asBytes(v)),
- .optional => |o| if (comptime machinery(o.child)) try w.writeByte(0) else if (v.*) |*payload| {
- try w.writeByte(1);
- try encode(o.child, payload, w);
- } else try w.writeByte(0),
- .array => |a| if (comptime flat(a.child)) try w.writeAll(std.mem.sliceAsBytes(v)) else for (v) |*e| try encode(a.child, e, w),
- .pointer => |p| switch (p.size) {
- .one => try encode(p.child, v.*, w),
- .slice => {
- try w.writeAll(std.mem.asBytes(&v.len));
- if (comptime flat(p.child)) try w.writeAll(std.mem.sliceAsBytes(v.*)) else for (v.*) |*e| try encode(p.child, e, w);
- },
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => |s| {
- if (comptime machinery(T)) return;
- if (s.layout == .@"packed") return w.writeAll(std.mem.asBytes(v));
- inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or comptime excluded(T, name)) continue;
- try encode(F, &@field(v, name), w);
- }
- },
- .@"union" => |u| {
- if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T));
- const tag: u.tag_type.? = v.*;
- try encode(u.tag_type.?, &tag, w);
- switch (v.*) {
- inline else => |*payload| try encode(@TypeOf(payload.*), payload, w),
- }
- },
- .error_set => try encodeError(T, v.*, w),
- .error_union => |e| if (v.*) |*payload| {
- try w.writeByte(1);
- try encode(e.payload, payload, w);
- } else |err| {
- try w.writeByte(0);
- try encodeError(e.error_set, err, w);
- },
- else => @compileError("walk: cannot encode " ++ @typeName(T)),
- }
-}
-
-/// What `encode` lays each of `types` out as, in words: each field, element
-/// and tag where it goes, an enum's names and numbers, an error as an
-/// error (it goes by its name). wire.semantics hashes the tape's: builds
-/// whose tapes differ in shape, as a FreeBSD std.Io.File.Stat differs from
-/// a Linux one, refuse each other's replicas in words, not read each other
-/// out of step.
-pub fn shape(comptime types: []const type) []const u8 {
- comptime {
- @setEvalBranchQuota(10_000_000);
- var out: []const u8 = "";
- for (types) |T| out = out ++ (shapeOf(T, 0) ++ "\n");
- return out;
- }
-}
-
-fn shapeOf(comptime T: type, comptime depth: u8) []const u8 {
- comptime {
- if (depth > 32) @compileError("walk: the tape's shape nests past 32 deep at " ++ @typeName(T) ++ ": a type that holds itself?");
- return switch (@typeInfo(T)) {
- .void, .null, .undefined => "v",
- .bool => "b",
- .int => |i| @tagName(i.signedness) ++ decimal(i.bits),
- .float => |f| "f" ++ decimal(f.bits),
- .@"enum" => |e| blk: {
- var out: []const u8 = shapeOf(e.tag_type, depth + 1) ++ "{";
- for (e.field_names, e.field_values) |n, v| out = out ++ (n ++ "=" ++ decimal(v) ++ ",");
- break :blk out ++ "}";
- },
- .optional => |o| if (machinery(o.child)) "0" else "?" ++ shapeOf(o.child, depth + 1),
- .array => |a| "[" ++ decimal(a.len) ++ "]" ++ shapeOf(a.child, depth + 1),
- .pointer => |p| switch (p.size) {
- .one => shapeOf(p.child, depth + 1),
- .slice => "[]" ++ shapeOf(p.child, depth + 1),
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => |s| blk: {
- if (machinery(T)) break :blk "";
- var out: []const u8 = if (s.layout == .@"packed") "p{" else "{";
- for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or excluded(T, name)) continue;
- out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ",");
- }
- break :blk out ++ "}";
- },
- .@"union" => |u| blk: {
- var out: []const u8 = shapeOf(u.tag_type.?, depth + 1) ++ "(";
- for (u.field_names, u.field_types) |name, F| out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ",");
- break :blk out ++ ")";
- },
- .error_set => "error",
- .error_union => |e| "!" ++ shapeOf(e.payload, depth + 1),
- else => @compileError("walk: cannot encode " ++ @typeName(T)),
- };
- }
-}
-
-/// `n` in decimal, as `{d}` writes it: memoized, where comptimePrint (an
-/// inline function) formats again at every call, 5e6 of the compiler's
-/// instructions each.
-fn decimal(comptime n: comptime_int) []const u8 {
- if (n < 0) return "-" ++ decimal(-n);
- if (n < 10) return &.{'0' + n};
- return decimal(n / 10) ++ &[_]u8{'0' + n % 10};
-}
-
-/// An error by its name. An `anyerror` must be one `decode` can read back
-/// (`errorNamed`): a Debug build stops at one that is not, as it is taped.
-fn encodeError(comptime E: type, err: E, w: *std.Io.Writer) std.Io.Writer.Error!void {
- if (comptime E == anyerror and builtin.mode == .debug) if (errorNamed(E, @errorName(err)) == null)
- std.debug.panic("walk: error.{s} is taped as an anyerror, which a replica reads back only as one of tape.Failure's: add the set it comes from", .{@errorName(err)});
- try writeName(w, @errorName(err));
-}
-
-/// The error of `E` called `name`. `anyerror` keeps no list of its names
-/// to look one up in: one is read back as one of tape.Failure's, what a
-/// host reports as failed (the tape's only anyerrors).
-fn errorNamed(comptime E: type, name: []const u8) ?E {
- const Named = if (E == anyerror) @import("tape.zig").Failure else E;
- inline for (@typeInfo(Named).error_set.error_names.?) |n| if (std.mem.eql(u8, name, n)) return @field(Named, n);
- return null;
-}
-
-pub const Reader = struct {
- bytes: []const u8,
- at: usize = 0,
-
- pub fn take(r: *Reader, n: usize) error{EndOfTape}![]const u8 {
- if (r.bytes.len - r.at < n) return error.EndOfTape;
- defer r.at += n;
- return r.bytes[r.at..][0..n];
- }
-
- fn scalar(r: *Reader, comptime T: type) error{EndOfTape}!T {
- return std.mem.bytesToValue(T, try r.take(@sizeOf(T)));
- }
-};
-
-/// What an error read back is when this build has none of that name (an
-/// OS's own, a newer build's): the tape is another build's, and diverges.
-const TapeError = error{ EndOfTape, OutOfMemory, NoSuchError };
-
-/// The inverse of `encode`; slices (and what a pointer points at) are made
-/// in `a`. A field `encode` left out is its default.
-pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T {
- switch (@typeInfo(T)) {
- .void, .null, .undefined => return {},
- .bool => return (try r.take(1))[0] != 0,
- .int, .float, .@"enum" => return r.scalar(T),
- .optional => |o| {
- if ((try r.take(1))[0] == 0) return null;
- if (comptime machinery(o.child)) unreachable;
- return try decode(o.child, r, a);
- },
- .array => |a_info| {
- var out: T = undefined;
- if (comptime flat(a_info.child)) {
- @memcpy(std.mem.sliceAsBytes(&out), try r.take(@sizeOf(T)));
- } else for (&out) |*e| {
- e.* = try decode(a_info.child, r, a);
- }
- return out;
- },
- .pointer => |p| switch (p.size) {
- .one => {
- const out = try a.create(p.child);
- out.* = try decode(p.child, r, a);
- return out;
- },
- .slice => {
- const n = try r.scalar(usize);
- const out = try a.alloc(p.child, n);
- if (comptime flat(p.child)) {
- @memcpy(std.mem.sliceAsBytes(out), try r.take(n * @sizeOf(p.child)));
- } else for (out) |*e| {
- e.* = try decode(p.child, r, a);
- }
- return out;
- },
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => |s| {
- if (s.layout == .@"packed") return r.scalar(T);
- var out: T = undefined;
- inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime") continue;
- if (comptime excluded(T, name)) {
- const default = attr.default_value_ptr orelse @compileError("walk: " ++ name ++ " has no default to decode to");
- @field(out, name) = @as(*const F, @ptrCast(@alignCast(default))).*;
- } else if (comptime @typeInfo(F) == .error_set) {
- // No `!anyerror` to return it through: read in place.
- try decodeError(F, r, &@field(out, name));
- } else @field(out, name) = try decode(F, r, a);
- }
- return out;
- },
- .@"union" => |u| {
- const tag = try decode(u.tag_type.?, r, a);
- inline for (u.field_names, u.field_types) |name, F| if (tag == @field(u.tag_type.?, name)) {
- return @unionInit(T, name, try decode(F, r, a));
- };
- unreachable;
- },
- .error_union => |e| {
- if ((try r.take(1))[0] != 0) return try decode(e.payload, r, a);
- // The value's error, not decode's own.
- var err: e.error_set = undefined;
- try decodeError(e.error_set, r, &err);
- return @as(T, err);
- },
- else => @compileError("walk: cannot decode " ++ @typeName(T)),
- }
-}
-
-/// An error by its name, as `encode` wrote it, into `out`: no error union
-/// holds an error set.
-fn decodeError(comptime E: type, r: *Reader, out: *E) TapeError!void {
- const len = try r.scalar(u16);
- out.* = errorNamed(E, try r.take(len)) orelse return error.NoSuchError;
-}
-
-// ---- the dump: the same walk, by name, for another build ----
-//
-// A dump (docs/next-daemon.md, phase 2) is `dump_magic`, then a table of
-// every type its roots' walk reaches -- each struct's and union's fields by
-// name, each enum's names, each number's width -- then each root's value,
-// laid out as `encode` lays it out but for three things: an enum or a
-// union's tag is its place among the table's names, a pointer or a slice met
-// again is a reference to the first (what two fields share is shared again),
-// and a type with a `dumpWrite` of its own is its bytes, counted.
-//
-// A build that is not the writer's matches by name: a field added since
-// takes its default, one removed is passed over, one whose kind changed
-// takes its default and says so (`Decoder.notes`). With no default to take,
-// the value it is part of is refused (`error.Incompatible`), and an element
-// of an array of optional pointers (a session's panes) is then left out,
-// nothing above it. A dump whose table is this build's own is read field
-// after field, no name asked.
-//
-// Native byte order: the machines pardes runs on are all little-endian.
-
-const dump_magic = "pardes-dump\x00\x02\n";
-
-const Kind = enum(u8) { skip, void, bool, int, float, @"enum", optional, one, slice, array, prefix, @"struct", @"union", err, error_union, custom, bitset };
-
-/// std's lists: their items, not the capacity behind them (nor, in a safe
-/// build, the lock that checks no pointer into them moves).
-pub fn isList(comptime T: type) bool {
- if (@typeInfo(T) != .@"struct" or !@hasField(T, "items") or !@hasField(T, "capacity")) return false;
- const n = @typeInfo(T).@"struct".field_names.len;
- return n == 2 or (n == 3 and @hasField(T, "pointer_stability"));
-}
-fn isAtomic(comptime T: type) bool {
- return @typeInfo(T) == .@"struct" and @hasField(T, "raw") and @typeInfo(T).@"struct".field_names.len == 1 and @hasDecl(T, "load");
-}
-fn isBitset(comptime T: type) bool {
- return @typeInfo(T) == .@"struct" and @hasField(T, "bit_length") and @hasField(T, "masks") and @typeInfo(T).@"struct".field_names.len == 2;
-}
-
-/// A field written only as far as its `len` says: a count, then that many.
-fn Prefix(comptime E: type) type {
- return struct {
- pub const element = E;
- };
-}
-
-/// What the dump walks `T` as: an atomic as what it holds, a list as its
-/// items.
-fn Canon(comptime T: type) type {
- if (comptime isAtomic(T)) return Canon(@FieldType(T, "raw"));
- if (comptime isList(T)) return []@typeInfo(@FieldType(T, "items")).pointer.child;
- return T;
-}
-
-fn kindOf(comptime T: type) Kind {
- return switch (@typeInfo(T)) {
- .void, .null, .undefined => .void,
- .bool => .bool,
- .int => .int,
- .float => .float,
- .@"enum" => .@"enum",
- .optional => .optional,
- .array => .array,
- .pointer => |p| switch (p.size) {
- .one => .one,
- .slice => .slice,
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => if (machinery(T) or @hasField(T, "any_future"))
- .skip
- else if (@hasDecl(T, "dumpWrite"))
- .custom
- else if (@hasDecl(T, "element") and T == Prefix(T.element))
- .prefix
- else if (isBitset(T))
- .bitset
- else
- .@"struct",
- .@"union" => |u| if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T)) else .@"union",
- else => @compileError("walk: cannot dump " ++ @typeName(T)),
- };
-}
-
-/// The fields of struct `T` a dump holds, in order.
-fn dumpFields(comptime T: type) []const [:0]const u8 {
- comptime {
- @setEvalBranchQuota(1_000_000);
- var names: []const [:0]const u8 = &.{};
- const s = @typeInfo(T).@"struct";
- for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or excluded(T, name) or kindOf(Canon(F)) == .skip) continue;
- if (opaqueTo(F)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is " ++ @typeName(F) ++ ", which no walk sees into: say what it is (`replica`)");
- names = names ++ .{name};
- }
- return names;
- }
-}
-
-/// The type a dump walks field `name` of `T` as.
-fn FieldDump(comptime T: type, comptime name: []const u8) type {
- const F = @FieldType(T, name);
- if (comptime cutArray(T, name)) return Prefix(Canon(@typeInfo(F).array.child));
- return Canon(F);
-}
-
-/// A fixed array a `len` cuts, which a dump writes as far as it says. A
-/// slice it cuts (a text's room for its ranges, made whole) is written
-/// whole, room and all, which only plain numbers may be: a load gives it
-/// the room it had.
-fn cutArray(comptime T: type, comptime name: []const u8) bool {
- const F = @FieldType(T, name);
- if (comptime lengthOf(T, name) == null) return false;
- if (@typeInfo(F) == .array) return true;
- if (!plain(Element(F))) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is a slice a `len` cuts, of what a dump cannot write past the cut");
- return false;
-}
-
-/// Every bit pattern one of its values: what a dump may write where
-/// nothing was ever written.
-fn plain(comptime T: type) bool {
- return switch (@typeInfo(T)) {
- .int, .float => true,
- .array => |a| plain(a.child),
- .@"struct" => |st| st.layout != .@"packed" and blk: {
- for (st.field_types) |F| if (!plain(F)) break :blk false;
- break :blk true;
- },
- else => false,
- };
-}
-
-fn children(comptime T: type) []const type {
- comptime {
- return switch (kindOf(T)) {
- .optional => &.{Canon(@typeInfo(T).optional.child)},
- .one, .slice => &.{Canon(@typeInfo(T).pointer.child)},
- .array => &.{Canon(@typeInfo(T).array.child)},
- .prefix => &.{T.element},
- .@"struct" => blk: {
- var out: []const type = &.{};
- for (dumpFields(T)) |name| out = out ++ .{FieldDump(T, name)};
- break :blk out;
- },
- .@"union" => blk: {
- var out: []const type = &.{};
- for (@typeInfo(T).@"union".field_types) |F| out = out ++ .{Canon(F)};
- break :blk out;
- },
- else => &.{},
- };
- }
-}
-
-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);
- for (children(T)) |C| out = collect(C, out);
- return out;
- }
-}
-
-/// Every type the walk of `roots` reaches, each once.
-fn graph(comptime roots: []const type) []const type {
- comptime {
- @setEvalBranchQuota(100_000_000);
- var list: []const type = &.{};
- for (roots) |R| list = collect(Canon(R), list);
- return list;
- }
-}
-
-/// The types the walk of `roots` reaches that walk themselves by hand (a
-/// `digest` or a `dumpWrite` of their own): the ones whose digest can take
-/// what their dump does not carry, which the one walk holds for the rest.
-pub fn handWalked(comptime roots: []const type) []const type {
- comptime {
- var out: []const type = &.{};
- for (graph(roots)) |T| switch (@typeInfo(T)) {
- .@"struct", .@"union" => if (@hasDecl(T, "dumpWrite") or (@hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void)) {
- out = out ++ .{T};
- },
- else => {},
- };
- return out;
- }
-}
-
-fn indexIn(comptime types: []const type, comptime T: type) u32 {
- comptime {
- @setEvalBranchQuota(100_000_000);
- for (types, 0..) |U, i| if (U == T) return i;
- @compileError("walk: not in the dump's table: " ++ @typeName(T));
- }
-}
-
-/// How many bytes an integer of `bits` is written in: its own size.
-fn intBytes(bits: u16) usize {
- return if (bits == 0) 0 else if (bits <= 8) 1 else if (bits <= 16) 2 else if (bits <= 32) 4 else if (bits <= 64) 8 else 16;
-}
-
-fn writeName(w: *std.Io.Writer, name: []const u8) !void {
- try w.writeAll(std.mem.asBytes(&@as(u16, @intCast(name.len))));
- try w.writeAll(name);
-}
-
-fn writeU32(w: *std.Io.Writer, n: u32) !void {
- try w.writeAll(std.mem.asBytes(&n));
-}
-
-fn writeTable(comptime types: []const type, w: *std.Io.Writer) !void {
- try writeU32(w, types.len);
- inline for (types) |T| {
- const k = comptime kindOf(T);
- try w.writeByte(@backingInt(k));
- switch (k) {
- .int => {
- try w.writeByte(@intFromBool(@typeInfo(T).int.signedness == .signed));
- try w.writeAll(std.mem.asBytes(&@as(u16, @typeInfo(T).int.bits)));
- },
- .float => try w.writeAll(std.mem.asBytes(&@as(u16, @typeInfo(T).float.bits))),
- .@"enum" => {
- const e = @typeInfo(T).@"enum";
- const tag = @typeInfo(e.tag_type).int;
- try w.writeByte(@intFromBool(tag.signedness == .signed));
- try w.writeAll(std.mem.asBytes(&@as(u16, tag.bits)));
- try writeU32(w, e.field_names.len);
- inline for (e.field_names, e.field_values) |name, value| {
- try writeName(w, name);
- try w.writeAll(std.mem.asBytes(&@as(i128, value)));
- }
- },
- .array => {
- try w.writeAll(std.mem.asBytes(&@as(u64, @typeInfo(T).array.len)));
- try writeU32(w, comptime indexIn(types, children(T)[0]));
- },
- .optional, .one, .slice, .prefix, .error_union => try writeU32(w, comptime indexIn(types, children(T)[0])),
- .@"struct" => {
- const names = comptime dumpFields(T);
- try writeU32(w, names.len);
- inline for (names) |name| {
- try writeName(w, name);
- try writeU32(w, comptime indexIn(types, FieldDump(T, name)));
- }
- },
- .@"union" => {
- const u = @typeInfo(T).@"union";
- try writeU32(w, u.field_names.len);
- inline for (u.field_names, u.field_types) |name, F| {
- try writeName(w, name);
- try writeU32(w, comptime indexIn(types, Canon(F)));
- }
- },
- .custom => try writeName(w, @typeName(T)),
- .skip, .void, .bool, .err, .bitset => {},
- }
- }
-}
-
-/// Integers by value, in the bytes `intBytes` gives them: a `u21`'s
-/// padding is no part of it.
-fn putInt(comptime I: type, n: I, w: *std.Io.Writer) !void {
- const info = @typeInfo(I).int;
- const W = @Int(info.signedness, intBytes(info.bits) * 8);
- const wide: W = n;
- try w.writeAll(std.mem.asBytes(&wide));
-}
-
-/// The table of `types` as bytes, made once a process (it is the build's):
-/// a store record or a dump writes it, a load compares it.
-fn tableOf(comptime types: []const type) []const u8 {
- const Once = struct {
- // Of these types alone: a container that named none of its
- // function's parameters would be one for every table.
- const of = types;
- /// 0 none, 1 being made, 2 made.
- var state: std.atomic.Value(u8) = .init(0);
- var bytes: []const u8 = &.{};
- };
- if (Once.state.load(.acquire) == 2) return Once.bytes;
- if (Once.state.cmpxchgStrong(0, 1, .acquire, .monotonic) == null) {
- var out: std.Io.Writer.Allocating = .init(std.heap.page_allocator);
- writeTable(types, &out.writer) catch @panic("walk: out of memory for a dump's table");
- Once.bytes = out.toOwnedSlice() catch @panic("walk: out of memory for a dump's table");
- Once.state.store(2, .release);
- } else while (Once.state.load(.acquire) != 2) std.atomic.spinLoopHint();
- return Once.bytes;
-}
-
-/// A blob's bytes a dump left out (`Dump.deferred`): they go at `at`.
-pub const Deferred = struct { at: usize, bytes: []const u8 };
-
-/// Writes a dump of `roots`' values, one `put` each in order.
-pub fn Dump(comptime roots: []const type) type {
- return struct {
- const Self = @This();
- pub const types = graph(roots);
-
- gpa: std.mem.Allocator,
- out: std.Io.Writer.Allocating,
- memo: std.AutoHashMapUnmanaged(Key, u32) = .empty,
- /// Set: a `.blob`'s bytes (of `blob_min` and up) are not written but
- /// noted, where they go and what they are; the dump with them put
- /// back in place is the dump. A replica's join streams them from
- /// its writer thread (core/replica.zig), the session's step paying
- /// for the rest alone.
- deferred: ?*std.ArrayListUnmanaged(Deferred) = null,
- in_blob: bool = false,
-
- const Key = struct { addr: usize, len: usize, ty: u32 };
-
- pub fn init(gpa: std.mem.Allocator) !Self {
- var d: Self = .{ .gpa = gpa, .out = .init(gpa) };
- errdefer d.out.deinit();
- try d.out.writer.writeAll(dump_magic);
- try d.out.writer.writeAll(tableOf(types));
- return d;
- }
-
- pub fn deinit(d: *Self) void {
- d.memo.deinit(d.gpa);
- d.out.deinit();
- }
-
- /// The dump, the caller's (gpa).
- pub fn finish(d: *Self) ![]u8 {
- d.memo.deinit(d.gpa);
- d.memo = .empty;
- return d.out.toOwnedSlice();
- }
-
- pub fn put(d: *Self, comptime T: type, v: *const T) !void {
- try writeU32(&d.out.writer, comptime indexIn(types, Canon(T)));
- try d.value(T, v);
- }
-
- /// Whether the pointer or slice at `addr` was met before: its
- /// reference written if so, else 0 and it is noted.
- fn seen(d: *Self, comptime T: type, addr: usize, len: usize) Error!bool {
- const w = &d.out.writer;
- if (len == 0) {
- try writeU32(w, 0);
- return false;
- }
- const got = try d.memo.getOrPut(d.gpa, .{ .addr = addr, .len = len, .ty = comptime indexIn(types, Canon(T)) });
- if (got.found_existing) {
- try writeU32(w, got.value_ptr.*);
- return true;
- }
- got.value_ptr.* = @intCast(d.memo.count());
- try writeU32(w, 0);
- return false;
- }
-
- const Error = std.Io.Writer.Error || std.mem.Allocator.Error;
-
- fn items(d: *Self, comptime E: type, slice: []const E) Error!void {
- const w = &d.out.writer;
- try w.writeAll(std.mem.asBytes(&@as(u64, slice.len)));
- if (comptime flat(E)) return w.writeAll(std.mem.sliceAsBytes(slice));
- for (slice) |*e| try d.value(E, e);
- }
-
- fn value(d: *Self, comptime T: type, v: *const T) Error!void {
- if (comptime isAtomic(T)) return d.value(@FieldType(T, "raw"), &v.raw);
- const w = &d.out.writer;
- if (comptime isList(T)) {
- const E = @typeInfo(@FieldType(T, "items")).pointer.child;
- if (try d.seen([]E, @intFromPtr(v.items.ptr), v.items.len)) return;
- return d.items(E, v.items);
- }
- switch (comptime kindOf(T)) {
- .skip, .void => {},
- .bool => try w.writeByte(@intFromBool(v.*)),
- .int => try putInt(T, v.*, w),
- .float => try w.writeAll(std.mem.asBytes(v)),
- .@"enum" => try putInt(@typeInfo(T).@"enum".tag_type, @backingInt(v.*), w),
- .optional => if (v.*) |*payload| {
- try w.writeByte(1);
- try d.value(@typeInfo(T).optional.child, payload);
- } else try w.writeByte(0),
- .one => {
- const C = @typeInfo(T).pointer.child;
- if (try d.seen(T, @intFromPtr(v.*), @max(1, @sizeOf(C)))) return;
- try d.value(C, v.*);
- },
- .slice => {
- const E = @typeInfo(T).pointer.child;
- if (try d.seen(T, @intFromPtr(v.ptr), v.len)) return;
- if (comptime flat(E)) if (d.in_blob) if (d.deferred) |later| {
- const bytes = std.mem.sliceAsBytes(v.*);
- if (bytes.len >= blob_min) {
- try w.writeAll(std.mem.asBytes(&@as(u64, v.len)));
- return later.append(d.gpa, .{ .at = d.out.writer.end, .bytes = bytes });
- }
- };
- try d.items(E, v.*);
- },
- .array => {
- const E = @typeInfo(T).array.child;
- if (comptime flat(E)) return w.writeAll(std.mem.sliceAsBytes(v));
- for (v) |*e| try d.value(E, e);
- },
- .prefix => unreachable,
- .@"struct" => {
- const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
- inline for (comptime dumpFields(T)) |name| {
- const F = @FieldType(T, name);
- const was = d.in_blob;
- d.in_blob = was or comptime blob(T, name);
- defer d.in_blob = was;
- if (comptime cutArray(T, name)) {
- const all = &@field(v, name);
- try d.items(@typeInfo(F).array.child, all[0..@min(all.len, lengthIn(v, comptime lengthOf(T, name).?))]);
- } else if (packed_struct) {
- const copy: F = @field(v, name);
- try d.value(F, &copy);
- } else try d.value(F, &@field(v, name));
- }
- },
- .@"union" => {
- const tag = std.meta.activeTag(v.*);
- const ordinal: u16 = inline for (@typeInfo(T).@"union".field_names, 0..) |name, i| {
- if (tag == @field(std.meta.Tag(T), name)) break i;
- } else unreachable;
- try w.writeAll(std.mem.asBytes(&ordinal));
- switch (v.*) {
- inline else => |*payload| try d.value(@TypeOf(payload.*), payload),
- }
- },
- // Kinds an old dump's table may name (`skip`); no type walked here has them.
- .err, .error_union => unreachable,
- .custom => {
- const at = d.out.writer.end;
- try w.writeAll(&std.mem.toBytes(@as(u64, 0)));
- T.dumpWrite(v, d.gpa, w) catch return error.WriteFailed;
- const n: u64 = d.out.writer.end - at - 8;
- @memcpy(d.out.writer.buffer[at..][0..8], std.mem.asBytes(&n));
- },
- .bitset => {
- try w.writeAll(std.mem.asBytes(&@as(u64, v.bit_length)));
- const words = (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
- if (words > 0) try w.writeAll(std.mem.sliceAsBytes(v.masks[0..words]));
- },
- }
- }
- };
-}
-
-/// One value `T` as a dump of its own (gpa): a closed pane, a terminal's
-/// parts that are not its emulator.
-pub fn save(comptime T: type, gpa: std.mem.Allocator, v: *const T) ![]u8 {
- var d = try Dump(&.{T}).init(gpa);
- errdefer d.deinit();
- try d.put(T, v);
- return d.finish();
-}
-
-const DecodeError = error{ EndOfDump, BadDump, Incompatible, OutOfMemory };
-
-/// The allocators a `replica.alloc` annotation may name, beside the
-/// loader's own: `.alloc = .{ .{ "image", "image" } }` makes what field
-/// `image` holds with `allocs.image`.
-const Allocators = struct {
- image: ?std.mem.Allocator = null,
- terminal: ?std.mem.Allocator = null,
-};
-
-fn allocOf(comptime T: type, comptime name: []const u8) ?[]const u8 {
- if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "alloc")) return null;
- inline for (T.replica.alloc) |pair| if (comptime std.mem.eql(u8, pair[0], name)) return pair[1];
- return null;
-}
-
-fn countOf(n: u64) DecodeError!usize {
- return std.math.cast(usize, n) orelse error.BadDump;
-}
-
-/// 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 };
-
-/// A type as the dump's writer had it.
-const SrcType = struct {
- kind: Kind,
- signed: bool = false,
- bits: u16 = 0,
- child: u32 = 0,
- len: u64 = 0,
- /// A struct's or union's fields, an enum's names (and `value`s).
- fields: []const SrcField = &.{},
-};
-const SrcField = struct { name: []const u8, ty: u32 = 0, value: i128 = 0 };
-
-/// Reads a dump of `roots`, one `into` or `get` each in order: a `Loader`
-/// told this build's table of them.
-pub fn Load(comptime roots: []const type) type {
- return struct {
- pub fn init(gpa: std.mem.Allocator, bytes: []const u8) DecodeError!Loader {
- return Loader.init(gpa, bytes, tableOf(graph(roots)));
- }
- };
-}
-
-/// `Load`'s reader, one for every root set: it reads by the dump's own
-/// table, and this build's (`table`) only says whether the two are one.
-pub const Loader = struct {
- const Self = @This();
-
- /// Where what is read is made (a `replica.alloc` field's own
- /// allocator while it is read).
- gpa: std.mem.Allocator,
- /// The loader's own lists'.
- own: std.mem.Allocator,
- bytes: []const u8,
- at: usize = 0,
- arena: std.heap.ArenaAllocator,
- src: []SrcType = &.{},
- /// Its table is this build's: no name is asked.
- same: bool = false,
- /// Each pointer and slice made so far: what a reference finds, and
- /// what `rollback` frees.
- shared: std.ArrayList(Made) = .empty,
- /// What a type's `dumpRead` made, freed by its `dumpFree` too.
- customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty,
- /// What was let go, for the person whose session it is.
- notes: std.ArrayList(u8) = .empty,
- /// The field being read, for a note.
- field: []const u8 = "",
- /// Where a field's annotation (`replica.alloc`) says its values are
- /// made instead of `gpa`.
- allocs: Allocators = .{},
-
- 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) };
- errdefer l.arena.deinit();
- if (!std.mem.startsWith(u8, bytes, dump_magic)) return error.BadDump;
- l.at = dump_magic.len;
- const table_at = l.at;
- try l.readTable();
- l.same = std.mem.eql(u8, table, bytes[table_at..l.at]);
- return l;
- }
-
- pub fn deinit(l: *Self) void {
- l.shared.deinit(l.own);
- l.customs.deinit(l.own);
- l.notes.deinit(l.own);
- l.arena.deinit();
- }
-
- /// Everything read so far freed: a load that fails leaves nothing.
- /// What it was read into must not be used after (nor freed).
- pub fn rollback(l: *Self) void {
- for (l.customs.items) |c| c.free(c.ptr, c.gpa);
- for (l.shared.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
- l.customs.clearRetainingCapacity();
- l.shared.clearRetainingCapacity();
- }
-
- 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 });
- return l.shared.items.len - 1;
- }
-
- fn take(l: *Self, n: usize) DecodeError![]const u8 {
- if (l.bytes.len - l.at < n) return error.EndOfDump;
- defer l.at += n;
- return l.bytes[l.at..][0..n];
- }
-
- fn scalar(l: *Self, comptime T: type) DecodeError!T {
- return std.mem.bytesToValue(T, try l.take(@sizeOf(T)));
- }
-
- /// A count, as this machine counts (a wasm32 one has 32 bits).
- fn count(l: *Self) DecodeError!usize {
- return countOf(try l.scalar(u64));
- }
-
- fn name(l: *Self) DecodeError![]const u8 {
- return l.take(try l.scalar(u16));
- }
-
- fn readTable(l: *Self) DecodeError!void {
- const a = l.arena.allocator();
- const n = try l.scalar(u32);
- if (n > l.bytes.len) return error.BadDump;
- l.src = try a.alloc(SrcType, n);
- for (l.src) |*t| {
- const k = std.enums.fromInt(Kind, (try l.take(1))[0]) orelse return error.BadDump;
- t.* = .{ .kind = k };
- switch (k) {
- .int => {
- t.signed = (try l.take(1))[0] != 0;
- t.bits = try l.scalar(u16);
- },
- .float => t.bits = try l.scalar(u16),
- .@"enum" => {
- t.signed = (try l.take(1))[0] != 0;
- t.bits = try l.scalar(u16);
- const list = try a.alloc(SrcField, try l.scalar(u32));
- for (list) |*f| f.* = .{ .name = try l.name(), .value = try l.scalar(i128) };
- t.fields = list;
- },
- .array => {
- t.len = try l.scalar(u64);
- t.child = try l.scalar(u32);
- },
- .optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32),
- .@"struct", .@"union" => {
- const nfields = try l.scalar(u32);
- if (nfields > l.bytes.len) return error.BadDump;
- const list = try a.alloc(SrcField, nfields);
- for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) };
- t.fields = list;
- },
- .custom => _ = try l.name(),
- .skip, .void, .bool, .err, .bitset => {},
- }
- }
- for (l.src) |t| {
- if (t.child >= n) return error.BadDump;
- for (t.fields) |f| if (f.ty >= n) return error.BadDump;
- }
- }
-
- pub fn note(l: *Self, comptime fmt: []const u8, args: anytype) void {
- if (l.notes.items.len > 4096) return;
- l.notes.print(l.own, fmt ++ "\n", args) catch {};
- }
-
- /// A note on a type's field, its names given as run-time strings:
- /// one instance of `note` (and of std's `print`) a message, where
- /// a tuple of the comptime names made one a type, field and message.
- fn noteField(l: *Self, comptime what: []const u8, type_name: []const u8, field: []const u8) void {
- l.note("{s}.{s}: " ++ what, .{ type_name, field });
- }
-
- fn root(l: *Self) DecodeError!u32 {
- const ty = try l.scalar(u32);
- if (ty >= l.src.len) return error.BadDump;
- return ty;
- }
-
- /// The next root, made: what it points at is `gpa`'s.
- pub fn get(l: *Self, comptime T: type) DecodeError!T {
- var out: T = undefined;
- try l.fresh(T, &out);
- try l.value(T, try l.root(), &out);
- return out;
- }
-
- /// The next root read into `out` as it stands: a field the dump
- /// holds is replaced (what it held is not freed), every other one
- /// is left as it is. A field another build cannot give is left too,
- /// and noted.
- pub fn into(l: *Self, comptime T: type, out: *T) DecodeError!void {
- const ty = try l.root();
- const s = l.src[ty];
- if (s.kind != .@"struct") return error.BadDump;
- try l.fields(T, s, out, true);
- }
-
- fn fresh(l: *Self, comptime T: type, out: *T) DecodeError!void {
- freshOf(T, out, l.gpa);
- }
-
- /// Whether the source's `ty` and `T` are of one kind, else the
- /// source's value passed over.
- fn kindMatches(l: *Self, comptime T: type, ty: u32) DecodeError!bool {
- if (l.same) return true;
- const want = comptime kindOf(Canon(T));
- const got = l.src[ty].kind;
- if (got == want) return true;
- // A field that came to hold a count and so many, or stopped.
- if ((want == .array and got == .prefix) or (want == .prefix and got == .array)) return true;
- try l.skip(ty);
- return false;
- }
-
- fn readInt(l: *Self, comptime I: type, s: SrcType) DecodeError!I {
- if (l.same) {
- const info = @typeInfo(I).int;
- const W = @Int(info.signedness, intBytes(info.bits) * 8);
- return @intCast(try l.scalar(W));
- }
- const n = intBytes(s.bits);
- const raw = try l.take(n);
- var wide: u128 = 0;
- for (raw, 0..) |b, i| wide |= @as(u128, b) << @intCast(i * 8);
- if (s.signed and n > 0) {
- const shift: u7 = @intCast(128 - n * 8);
- const signed: i128 = @as(i128, @bitCast(wide << shift)) >> shift;
- return std.math.cast(I, signed) orelse error.Incompatible;
- }
- return std.math.cast(I, wide) orelse error.Incompatible;
- }
-
- /// `T` read from the source's type `ty` into `out`, which `fresh`
- /// has made ready.
- fn value(l: *Self, comptime T: type, ty: u32, out: *T) DecodeError!void {
- if (comptime isAtomic(T)) {
- const R = @FieldType(T, "raw");
- var raw: R = undefined;
- try l.fresh(R, &raw);
- try l.value(R, ty, &raw);
- out.* = .{ .raw = raw };
- return;
- }
- // A field this build compiles out (a void field): passed over,
- // said only when it held something.
- if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) {
- const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0);
- try l.skip(ty);
- if (held) l.note("{s}: not in this build", .{l.field});
- return;
- };
- if (!try l.kindMatches(T, ty)) return error.Incompatible;
- const s = l.src[ty];
- if (comptime isList(T)) {
- const E = @typeInfo(@FieldType(T, "items")).pointer.child;
- const got = try l.slice(E, s);
- out.* = .empty;
- out.items = got;
- out.capacity = got.len;
- return;
- }
- switch (comptime kindOf(T)) {
- .skip, .void => {},
- .bool => out.* = (try l.take(1))[0] != 0,
- .int => out.* = try l.readInt(T, s),
- .float => out.* = if (l.same or s.bits == @typeInfo(T).float.bits) try l.scalar(T) else return error.Incompatible,
- .@"enum" => {
- const e = @typeInfo(T).@"enum";
- if (l.same) {
- out.* = @fromBackingInt(@intCast(try l.readInt(e.tag_type, s)));
- return;
- }
- const n = try l.readInt(i128, s);
- const was = for (s.fields) |f| {
- if (f.value == n) break f.name;
- } else null;
- if (was) |w| inline for (e.field_names) |field| if (std.mem.eql(u8, w, field)) {
- out.* = @field(T, field);
- return;
- };
- if (e.mode == .nonexhaustive and was == null)
- if (std.math.cast(e.tag_type, n)) |tag| {
- out.* = @fromBackingInt(@intCast(tag));
- return;
- };
- l.note("{s}: no {s} here", .{ l.field, was orelse "such value" });
- return error.Incompatible;
- },
- .optional => {
- const C = @typeInfo(T).optional.child;
- if ((try l.take(1))[0] == 0) {
- out.* = null;
- return;
- }
- if (comptime kindOf(Canon(C)) == .skip) {
- out.* = if (comptime C == std.mem.Allocator) l.gpa else null;
- return;
- }
- // A slice's or a pointer's null is its address: set to
- // an undefined payload, the optional itself is undefined,
- // and ReleaseSafe's optimizer read it as null (a pane's
- // `?[]u8` command one byte long, every field after it out
- // of step). Read through a local and set it from that.
- if (comptime @typeInfo(C) == .pointer) {
- var payload: C = undefined;
- try l.value(C, s.child, &payload);
- out.* = payload;
- return;
- }
- out.* = @as(C, undefined);
- try l.fresh(C, &out.*.?);
- l.value(C, s.child, &out.*.?) catch |err| {
- out.* = null;
- return err;
- };
- },
- .one => {
- const C = @typeInfo(T).pointer.child;
- if (try l.ref()) |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| {
- l.gpa.destroy(one);
- return err;
- };
- try l.fresh(C, one);
- l.value(C, s.child, one) catch |err| {
- // Left half made: no later reference may find it.
- l.shared.items[at].dead = true;
- return err;
- };
- out.* = one;
- },
- .slice => {
- const E = @typeInfo(T).pointer.child;
- const got = try l.slice(E, s);
- if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T));
- out.* = got;
- },
- .array => {
- const E = @typeInfo(T).array.child;
- const n: u64 = if (s.kind == .prefix) try l.scalar(u64) else s.len;
- try l.elements(E, s.child, n, out);
- },
- .prefix => unreachable,
- .@"struct" => try l.fields(T, s, out, false),
- .@"union" => {
- const u = @typeInfo(T).@"union";
- const ordinal = try l.scalar(u16);
- if (ordinal >= s.fields.len) return error.BadDump;
- const was = s.fields[ordinal];
- inline for (u.field_names, u.field_types, 0..) |field, F, i| {
- if (if (l.same) ordinal == i else std.mem.eql(u8, was.name, field)) {
- out.* = @unionInit(T, field, undefined);
- try l.fresh(F, &@field(out.*, field));
- return l.value(F, was.ty, &@field(out.*, field));
- }
- }
- try l.skip(was.ty);
- l.note("{s}: no {s} here", .{ l.field, was.name });
- return error.Incompatible;
- },
- .err, .error_union => unreachable,
- .custom => {
- const bytes = try l.take(try l.count());
- T.dumpRead(out, l.gpa, bytes) catch |err| {
- if (err == error.OutOfMemory) return error.OutOfMemory;
- l.note("{s}: {t}", .{ l.field, err });
- return error.Incompatible;
- };
- if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) });
- },
- .bitset => {
- const bits = try l.count();
- out.* = try .initEmpty(l.gpa, bits);
- 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)));
- },
- }
- }
-
- /// 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 {
- 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;
- 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))];
- const n = try l.count();
- if (n == 0) return &.{};
- if (n > l.bytes.len) return error.BadDump;
- const many = try l.gpa.alloc(E, n);
- const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| {
- l.gpa.free(many);
- return err;
- };
- l.elements(E, s.child, n, many) catch |err| {
- l.shared.items[at].dead = true;
- return err;
- };
- return many;
- }
-
- /// `n` elements of the source's type `ty` into `out` (an array or
- /// a slice), as many as it holds, the rest passed over.
- fn elements(l: *Self, comptime E: type, ty: u32, n: u64, out: []E) DecodeError!void {
- const keep: usize = @intCast(@min(n, out.len));
- const s = l.src[ty];
- // Bytes copied whole between builds when both sides agree on
- // them: integers and bools (an enum's numbers may not be the other's).
- const bulk = if (comptime flat(E)) l.same or (comptime flatHash(E)) and s.kind == (comptime kindOf(E)) and
- (s.kind == .bool or (s.bits == @bitSizeOf(E) and s.signed == (@typeInfo(E) == .int and @typeInfo(E).int.signedness == .signed))) else false;
- if (bulk) {
- if (n > l.bytes.len) return error.EndOfDump;
- @memcpy(std.mem.sliceAsBytes(out[0..keep]), try l.take(keep * @sizeOf(E)));
- _ = try l.take(@intCast((n - keep) * @sizeOf(E)));
- return;
- }
- // An array of optional pointers (a session's panes): one that
- // cannot be read is left out, not the array.
- const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
- var failed = false;
- for (0..try countOf(n)) |i| {
- if (i >= keep) {
- try l.skip(ty);
- continue;
- }
- try l.fresh(E, &out[i]);
- l.value(E, ty, &out[i]) catch |err| {
- if (err != error.Incompatible) return err;
- if (droppable) {
- out[i] = null;
- l.note("{s}[{d}] left out", .{ l.field, i });
- } else failed = true;
- };
- }
- if (failed) return error.Incompatible;
- }
-
- fn fields(l: *Self, comptime T: type, s: SrcType, out: *T, existing: bool) DecodeError!void {
- const names = comptime dumpFields(T);
- const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
- const outer = l.field;
- defer l.field = outer;
- if (l.same) {
- if (s.fields.len != names.len) return error.BadDump;
- inline for (names, 0..) |field, k| {
- l.field = field;
- try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing);
- }
- return;
- }
- var found: std.StaticBitSet(@max(1, names.len)) = .empty;
- var failed = false;
- for (s.fields) |f| {
- const k: ?usize = inline for (names, 0..) |field, k| {
- if (std.mem.eql(u8, f.name, field)) break k;
- } else null;
- const at = k orelse {
- try l.skip(f.ty);
- continue;
- };
- found.set(at);
- inline for (names, 0..) |field, i| if (i == at) {
- l.field = field;
- l.oneField(T, field, f.ty, out, packed_struct, existing) catch |err| {
- if (err != error.Incompatible) return err;
- const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
- if (comptime attr.default_value_ptr) |dp| {
- @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*;
- l.noteField("its kind changed; its default taken", @typeName(T), field);
- } else if (existing) {
- l.noteField("its kind changed; left as it was", @typeName(T), field);
- } else failed = true;
- };
- };
- }
- // A field the writer did not have: its default (`fresh`), or
- // the value cannot be made.
- inline for (names, 0..) |field, i| if (!found.isSet(i)) {
- const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
- if (comptime attr.default_value_ptr == null) {
- if (!existing) {
- l.noteField("not in the dump", @typeName(T), field);
- failed = true;
- }
- }
- };
- if (failed) return error.Incompatible;
- }
-
- fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void {
- const F = @FieldType(T, field);
- const gpa = l.gpa;
- defer l.gpa = gpa;
- if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| {
- l.gpa = a;
- };
- if (comptime cutArray(T, field)) {
- return l.value(F, ty, &@field(out, field));
- }
- // A struct held in place in one read as it stands (the root's):
- // what it does not hold stays as it is too.
- if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) {
- if (!try l.kindMatches(F, ty)) return error.Incompatible;
- return l.fields(F, l.src[ty], &@field(out, field), true);
- };
- if (packed_struct) {
- var copy: F = undefined;
- try l.fresh(F, &copy);
- try l.value(F, ty, &copy);
- @field(out, field) = copy;
- return;
- }
- try l.fresh(F, &@field(out, field));
- try l.value(F, ty, &@field(out, field));
- }
-
- /// The source's value of type `ty` passed over.
- fn skip(l: *Self, ty: u32) DecodeError!void {
- const s = l.src[ty];
- switch (s.kind) {
- .skip, .void => {},
- .bool => _ = try l.take(1),
- .int, .@"enum" => _ = try l.take(intBytes(s.bits)),
- .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");
- 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");
- l.shared.items[l.shared.items.len - 1].dead = true;
- }
- try l.skipMany(s.child, n);
- },
- .prefix => try l.skipMany(s.child, try l.scalar(u64)),
- .array => try l.skipMany(s.child, s.len),
- .@"struct" => for (s.fields) |f| try l.skip(f.ty),
- .@"union" => {
- const ordinal = try l.scalar(u16);
- if (ordinal >= s.fields.len) return error.BadDump;
- try l.skip(s.fields[ordinal].ty);
- },
- .err => _ = try l.name(),
- .error_union => if ((try l.take(1))[0] != 0) try l.skip(s.child) else {
- _ = try l.name();
- },
- .custom => _ = try l.take(try l.count()),
- .bitset => _ = try l.take((try l.count() + 63) / 64 * 8),
- }
- }
-
- fn skipMany(l: *Self, ty: u32, n: u64) DecodeError!void {
- const s = l.src[ty];
- if (s.kind == .int or s.kind == .bool) {
- const size: u64 = if (s.kind == .bool) 1 else intBytes(s.bits);
- if (n > l.bytes.len) return error.EndOfDump;
- _ = try l.take(@intCast(n * size));
- return;
- }
- for (0..try countOf(n)) |_| try l.skip(ty);
- }
-};
-
-/// `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 {
- if (comptime @typeInfo(T) != .@"struct" or isList(T) or isAtomic(T) or isBitset(T) or kindOf(T) == .custom or kindOf(T) == .skip) return;
- const s = @typeInfo(T).@"struct";
- inline for (s.field_names, s.field_types, s.field_attrs) |field, F, attr| {
- if (attr.@"comptime") continue;
- if (comptime attr.default_value_ptr) |dp| {
- @field(out, field) = @as(*const F, @ptrCast(@alignCast(dp))).*;
- } else if (comptime F == std.mem.Allocator) {
- @field(out, field) = gpa;
- } else if (comptime !walkedField(T, field)) {
- @compileError("walk: " ++ @typeName(T) ++ "." ++ field ++ " has no default to load to");
- }
- }
-}
-
-fn walkedField(comptime T: type, comptime field: []const u8) bool {
- inline for (comptime dumpFields(T)) |n| if (comptime std.mem.eql(u8, n, field)) return true;
- return false;
-}
-
-/// A value `save` made, `gpa`'s; what was let go is said in `notes` when
-/// it is given.
-pub fn load(comptime T: type, gpa: std.mem.Allocator, bytes: []const u8, notes: ?*std.ArrayList(u8)) DecodeError!T {
- var l = try Load(&.{T}).init(gpa, bytes);
- defer l.deinit();
- errdefer l.rollback();
- const v = try l.get(T);
- if (notes) |n| try n.appendSlice(gpa, l.notes.items);
- return v;
-}
-
-// ---- a dump as a database: the same walk, by name, into xitdb's maps ----
-//
-// A dump (Db.zig) is a xitdb database in memory, its bytes one value of the
-// state file, written by the walk by name: a struct is a map whose keys are
-// its fields' names (`putKey`: a reader goes through them by name, never by
-// a hash of its own), a union a map of its one field, a slice, an array or
-// a list of records a list, of plain numbers one bytes value (its format
-// tag the numbers' kind and width), an enum the bytes of its name, a number
-// a uint or an int (a wider one its bytes), an optional an absent key (an
-// explicit none where the field's default is not null), a type with
-// `dumpWrite` its bytes, and a `.blob`'s text of `blob_min` bytes and up
-// its BLAKE3 hash (tag "b3"): the text is kept once beside the dump
-// (`Blob`). A pointer or a slice met again is the first one's value again:
-// what two fields share is shared again.
-//
-// Another build reads it by name: a field the dump has not takes its
-// default, a key this build has not is passed over, a value of another kind
-// takes its default and is said (`notes`); with no default the value it is
-// part of is refused, and an element of an array of optional pointers (a
-// session's panes) is then left out, nothing above it.
-
-pub const Mem = xitdb.Database(.memory, u256);
-
-/// A text a dump keeps beside it, once: its BLAKE3 hash and its bytes (the
-/// session's, while the dump is made).
-pub const Blob = struct { hash: [32]u8, bytes: []const u8 };
-
-/// A field's key: its name's word, unique within its struct (a reader
-/// matches names, so another build's words need not be these).
-fn nameKey(comptime name: []const u8) u256 {
- return comptime std.hash.Wyhash.hash(0, name);
-}
-
-/// Whether a run of `E` is one bytes value: plain numbers.
-fn numbers(comptime E: type) bool {
- return switch (@typeInfo(E)) {
- .int => |i| @sizeOf(E) * 8 == i.bits and @sizeOf(E) <= 8,
- .bool => true,
- .float => |f| f.bits == 32 or f.bits == 64,
- else => false,
- };
-}
-
-/// A run of numbers' format tag: their kind and byte width ("u4", "i8", "b1").
-fn numbersTag(comptime E: type) [2]u8 {
- const kind: u8 = switch (@typeInfo(E)) {
- .int => |i| if (i.signedness == .signed) 'i' else 'u',
- .bool => 'b',
- .float => 'f',
- else => unreachable,
- };
- return .{ kind, '0' + @sizeOf(E) };
-}
-
-const blob_tag = "b3".*;
-const wide_tag = "w8".*;
-const custom_tag = "cu".*;
-const bitset_tag = "bs".*;
-
-fn typeWord(comptime T: type) u64 {
- return comptime std.hash.Wyhash.hash(0, @typeName(T));
-}
-
-/// Writes values into a database in memory, by name (see above).
-pub const Put = struct {
- gpa: std.mem.Allocator,
- /// Each pointer and slice written, by address, length and type, and
- /// where its value is: met again, that value is written again.
- memo: std.AutoHashMapUnmanaged(Key, xitdb.Slot) = .empty,
- /// The blobs met, each once.
- blobs: std.ArrayListUnmanaged(Blob) = .empty,
- in_blob: bool = false,
-
- const Key = struct { addr: usize, len: usize, ty: u64 };
- const Cursor = Mem.Cursor(.read_write);
-
- pub fn deinit(w: *Put) void {
- w.memo.deinit(w.gpa);
- w.blobs.deinit(w.gpa);
- }
-
- /// `v` written as `name`'s value in `map` (a dump's roots).
- pub fn member(w: *Put, map: Mem.HashMap(.read_write), comptime name: []const u8, comptime T: type, v: *const T) anyerror!void {
- try map.putKey(comptime nameKey(name), .{ .bytes = name });
- var at = try map.putCursor(comptime nameKey(name));
- _ = try w.value(T, v, &at);
- }
-
- /// `v` written at `c`; where its value is.
- pub fn value(w: *Put, comptime T: type, v: *const T, c: *Cursor) anyerror!xitdb.Slot {
- if (comptime isAtomic(T)) return w.value(@FieldType(T, "raw"), &v.raw, c);
- if (comptime isList(T)) return w.many(@typeInfo(@FieldType(T, "items")).pointer.child, v.items, c, true);
- switch (comptime kindOf(T)) {
- .skip, .void => try c.write(.{ .slot = null }),
- .bool => try c.write(.{ .uint = @intFromBool(v.*) }),
- .int => if (@typeInfo(T).int.bits <= 64) {
- try c.write(if (@typeInfo(T).int.signedness == .signed) .{ .int = v.* } else .{ .uint = v.* });
- } else {
- const wide: i128 = @intCast(v.*);
- try c.write(.{ .bytes_object = .{ .value = std.mem.asBytes(&wide), .format_tag = wide_tag } });
- },
- .float => try c.write(.{ .float = v.* }),
- .@"enum" => if (std.enums.tagName(T, v.*)) |name| {
- try c.write(.{ .bytes = name });
- } else try c.write(.{ .int = @intCast(@backingInt(v.*)) }),
- .optional => {
- const C = @typeInfo(T).optional.child;
- if (v.*) |*payload| {
- // An allocator, say, is no state: there or not, which a
- // load answers with its own.
- if (comptime kindOf(Canon(C)) == .skip) try c.write(.{ .uint = 1 }) else return w.value(C, payload, c);
- } else try c.write(.{ .slot = null });
- },
- .one => {
- const C = @typeInfo(T).pointer.child;
- const key: Key = .{ .addr = @intFromPtr(v.*), .len = @max(1, @sizeOf(C)), .ty = typeWord(T) };
- if (w.memo.get(key)) |slot| {
- try c.write(.{ .slot = slot });
- return slot;
- }
- const slot = try w.value(C, v.*, c);
- try w.memo.put(w.gpa, key, slot);
- return slot;
- },
- .slice => return w.many(@typeInfo(T).pointer.child, v.*, c, true),
- .array => return w.many(@typeInfo(T).array.child, v, c, false),
- .prefix => unreachable,
- .@"struct" => return w.fields(T, v, c),
- .@"union" => {
- const map = try Mem.HashMap(.read_write).init(c.*);
- switch (v.*) {
- inline else => |*payload, tag| {
- const name = @tagName(tag);
- try map.putKey(comptime nameKey(name), .{ .bytes = name });
- var at = try map.putCursor(comptime nameKey(name));
- _ = try w.value(@TypeOf(payload.*), payload, &at);
- },
- }
- return map.slot();
- },
- // No type a dump walks has them.
- .err, .error_union => unreachable,
- .custom => {
- var buf: [4096]u8 = undefined;
- var out = try c.writer(&buf);
- try T.dumpWrite(v, w.gpa, &out.interface);
- out.format_tag = custom_tag;
- try out.finish();
- },
- .bitset => {
- const words = (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
- var buf: [64]u8 = undefined;
- var out = try c.writer(&buf);
- try out.interface.writeAll(std.mem.asBytes(&@as(u64, v.bit_length)));
- if (words > 0) try out.interface.writeAll(std.mem.sliceAsBytes(v.masks[0..words]));
- out.format_tag = bitset_tag;
- try out.finish();
- },
- }
- return c.slot();
- }
-
- /// A run of `E`: numbers as one bytes value (a blob's text by its
- /// hash), records as a list; a slice met again (`shared`) its first
- /// value.
- fn many(w: *Put, comptime E: type, items: []const E, c: *Cursor, comptime shared: bool) anyerror!xitdb.Slot {
- const key: Key = .{ .addr = @intFromPtr(items.ptr), .len = items.len, .ty = typeWord([]const E) };
- if (shared and items.len > 0) if (w.memo.get(key)) |slot| {
- try c.write(.{ .slot = slot });
- return slot;
- };
- const slot = if (comptime numbers(E)) slot: {
- const bytes = std.mem.sliceAsBytes(items);
- if (E == u8 and w.in_blob and bytes.len >= blob_min) {
- var sum: [32]u8 = undefined;
- std.crypto.hash.Blake3.hash(bytes, &sum, .{});
- const known = for (w.blobs.items) |b| {
- if (std.mem.eql(u8, &b.hash, &sum)) break true;
- } else false;
- if (!known) try w.blobs.append(w.gpa, .{ .hash = sum, .bytes = bytes });
- try c.write(.{ .bytes_object = .{ .value = &sum, .format_tag = blob_tag } });
- } else try c.write(.{ .bytes_object = .{ .value = bytes, .format_tag = numbersTag(E) } });
- break :slot try c.slot();
- } else slot: {
- const list = try Mem.ArrayList(.read_write).init(c.*);
- for (items) |*e| {
- var at = try list.appendCursor();
- _ = try w.value(E, e, &at);
- }
- break :slot try list.slot();
- };
- if (shared and items.len > 0) try w.memo.put(w.gpa, key, slot);
- return slot;
- }
-
- fn fields(w: *Put, comptime T: type, v: *const T, c: *Cursor) anyerror!xitdb.Slot {
- const map = try Mem.HashMap(.read_write).init(c.*);
- const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
- inline for (comptime dumpFields(T)) |name| {
- const F = @FieldType(T, name);
- if (comptime kindOf(Canon(F)) != .void) put: {
- // Null where the field's default is: no key at all.
- if (comptime @typeInfo(F) == .optional and defaultIsNull(T, name)) if (@field(v, name) == null) break :put;
- const was = w.in_blob;
- w.in_blob = was or comptime blob(T, name);
- defer w.in_blob = was;
- try map.putKey(comptime nameKey(name), .{ .bytes = name });
- var at = try map.putCursor(comptime nameKey(name));
- if (comptime cutArray(T, name)) {
- const all = &@field(v, name);
- _ = try w.many(@typeInfo(F).array.child, all[0..@min(all.len, lengthIn(v, comptime lengthOf(T, name).?))], &at, false);
- } else if (comptime packed_struct) {
- const copy: F = @field(v, name);
- _ = try w.value(F, &copy, &at);
- } else _ = try w.value(F, &@field(v, name), &at);
- }
- }
- return map.slot();
- }
-};
-
-fn defaultIsNull(comptime T: type, comptime name: []const u8) bool {
- const F = @FieldType(T, name);
- const attr = @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, name).?];
- const dp = attr.default_value_ptr orelse return false;
- return @as(*const F, @ptrCast(@alignCast(dp))).* == null;
-}
-
-/// Reads values a `Put` wrote, by name, as another build may have written
-/// them (see above).
-pub const Get = struct {
- /// Where what is read is made (a `replica.alloc` field's own allocator
- /// while it is read).
- gpa: std.mem.Allocator,
- /// The reader's own lists'.
- own: std.mem.Allocator,
- /// The texts its blobs' hashes name (Db.zig's `blobs`), by hash.
- blobs: ?Mem.HashMap(.read_only) = null,
- /// Each pointer and slice made so far: what a value met again is, and
- /// what `rollback` frees.
- made: std.ArrayList(Made) = .empty,
- /// Where each value made is: met again, the same one.
- memo: std.AutoHashMapUnmanaged(u128, usize) = .empty,
- /// What a type's `dumpRead` made, freed by its `dumpFree` too.
- customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty,
- /// What was let go, for the person whose session it is.
- notes: std.ArrayList(u8) = .empty,
- /// The field being read, for a note.
- field: []const u8 = "",
- allocs: Allocators = .{},
-
- const Cursor = Mem.Cursor(.read_only);
- pub const Error = error{ BadDump, Incompatible, OutOfMemory };
-
- pub fn init(gpa: std.mem.Allocator) Get {
- return .{ .gpa = gpa, .own = gpa };
- }
-
- pub fn deinit(l: *Get) void {
- l.made.deinit(l.own);
- l.memo.deinit(l.own);
- l.customs.deinit(l.own);
- l.notes.deinit(l.own);
- }
-
- /// Everything read so far freed: a load that fails leaves nothing.
- /// What it was read into must not be used after (nor freed).
- pub fn rollback(l: *Get) void {
- for (l.customs.items) |c| c.free(c.ptr, c.gpa);
- for (l.made.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
- l.customs.clearRetainingCapacity();
- l.made.clearRetainingCapacity();
- l.memo.clearRetainingCapacity();
- }
-
- pub fn note(l: *Get, comptime fmt: []const u8, args: anytype) void {
- if (l.notes.items.len > 4096) return;
- l.notes.print(l.own, fmt ++ "\n", args) catch {};
- }
-
- /// A note on a type's field, its names given at run time (Load's).
- fn noteField(l: *Get, comptime what: []const u8, type_name: []const u8, field: []const u8) void {
- l.note("{s}.{s}: " ++ what, .{ type_name, field });
- }
-
- /// The value at `c`, made: what it points at is `gpa`'s.
- pub fn get(l: *Get, comptime T: type, c: Cursor) Error!T {
- var out: T = undefined;
- try l.fresh(T, &out);
- try l.value(T, c, &out);
- return out;
- }
-
- /// The struct at `c` read into `out` as it stands: a field the dump
- /// holds is replaced (what it held is not freed), every other one is
- /// left as it is, and one another build cannot give is left too, and
- /// noted.
- pub fn into(l: *Get, comptime T: type, c: Cursor, out: *T) Error!void {
- try l.fields(T, c, out, true);
- }
-
- /// Where the value of `name` is in the map at `c` (a dump's roots), by
- /// its name; null when it is not there.
- pub fn member(c: Cursor, name: []const u8) Error!?Cursor {
- const map = Mem.HashMap(.read_only).init(c) catch return error.BadDump;
- var it = map.iterator() catch return error.BadDump;
- while (it.next() catch return error.BadDump) |kv_at| {
- const kv = kv_at.readKeyValuePair() catch return error.BadDump;
- var buf: [64]u8 = undefined;
- const got = kv.key_cursor.readBytes(&buf) catch continue;
- if (std.mem.eql(u8, got, name)) return kv.value_cursor;
- }
- return null;
- }
-
- fn fresh(l: *Get, comptime T: type, out: *T) Error!void {
- freshOf(T, out, l.gpa);
- }
-
- fn slotWord(slot: xitdb.Slot) u128 {
- return @as(u72, @bitCast(slot));
- }
-
- fn slotOf(c: Cursor) Error!xitdb.Slot {
- return c.slot() catch error.BadDump;
- }
-
- /// Whether the value at `slot` has a place of its own (an inline number
- /// or a short text is its slot alone: no identity to share).
- fn placed(slot: xitdb.Slot) bool {
- return switch (slot.tag) {
- .none, .uint, .int, .float, .short_bytes => false,
- else => true,
- };
- }
-
- /// 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 });
- 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| {
- _ = l.made.pop();
- return err;
- };
- return at;
- }
-
- /// The value made before for the same place, when there was one.
- fn again(l: *Get, slot: xitdb.Slot) 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;
- return m.bytes;
- }
-
- /// `T` read from `c` into `out`, which `fresh` has made ready.
- fn value(l: *Get, comptime T: type, c: Cursor, out: *T) Error!void {
- if (comptime isAtomic(T)) {
- const R = @FieldType(T, "raw");
- var raw: R = undefined;
- try l.fresh(R, &raw);
- try l.value(R, c, &raw);
- out.* = .{ .raw = raw };
- return;
- }
- const slot = try slotOf(c);
- if (comptime isList(T)) {
- const got = try l.slice(@typeInfo(@FieldType(T, "items")).pointer.child, c, slot);
- out.* = .empty;
- out.items = got;
- out.capacity = got.len;
- return;
- }
- switch (comptime kindOf(T)) {
- .skip, .void => {},
- .bool => out.* = switch (slot.tag) {
- .uint => slot.value != 0,
- else => return error.Incompatible,
- },
- .int => out.* = try l.int(T, c, slot),
- .float => out.* = switch (slot.tag) {
- .float => @floatCast(@as(f64, @bitCast(slot.value))),
- else => return error.Incompatible,
- },
- .@"enum" => {
- const e = @typeInfo(T).@"enum";
- switch (slot.tag) {
- .bytes, .short_bytes => {
- var buf: [256]u8 = undefined;
- const name = c.readBytes(&buf) catch return error.Incompatible;
- inline for (e.field_names) |field| if (std.mem.eql(u8, name, field)) {
- out.* = @field(T, field);
- return;
- };
- l.note("{s}: no {s} here", .{ l.field, name });
- return error.Incompatible;
- },
- .int, .uint => if (e.mode == .nonexhaustive) {
- const n: i64 = @bitCast(slot.value);
- out.* = @fromBackingInt(@intCast(std.math.cast(e.tag_type, n) orelse return error.Incompatible));
- } else return error.Incompatible,
- else => return error.Incompatible,
- }
- },
- .optional => {
- const C = @typeInfo(T).optional.child;
- if (slot.tag == .none) {
- out.* = null;
- return;
- }
- if (comptime kindOf(Canon(C)) == .skip) {
- out.* = if (comptime C == std.mem.Allocator) l.gpa else null;
- return;
- }
- // Through a local, as the byte loader does: a pointer's
- // null is its address.
- if (comptime @typeInfo(C) == .pointer) {
- var payload: C = undefined;
- try l.value(C, c, &payload);
- out.* = payload;
- return;
- }
- out.* = @as(C, undefined);
- try l.fresh(C, &out.*.?);
- l.value(C, c, &out.*.?) catch |err| {
- out.* = null;
- return err;
- };
- },
- .one => {
- const C = @typeInfo(T).pointer.child;
- if (try l.again(slot)) |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| {
- l.gpa.destroy(one);
- return err;
- };
- try l.fresh(C, one);
- l.value(C, c, one) catch |err| {
- // Left half made: no later value may be it.
- l.made.items[at].dead = true;
- return err;
- };
- out.* = one;
- },
- .slice => {
- if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T));
- out.* = try l.slice(@typeInfo(T).pointer.child, c, slot);
- },
- .array => try l.elements(@typeInfo(T).array.child, c, slot, out),
- .prefix => unreachable,
- .@"struct" => try l.fields(T, c, out, false),
- .@"union" => {
- const u = @typeInfo(T).@"union";
- const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
- var it = map.iterator() catch return error.BadDump;
- const kv_at = (it.next() catch return error.BadDump) orelse return error.Incompatible;
- const kv = kv_at.readKeyValuePair() catch return error.BadDump;
- var buf: [256]u8 = undefined;
- const name = kv.key_cursor.readBytes(&buf) catch return error.Incompatible;
- inline for (u.field_names, u.field_types) |field, F| if (std.mem.eql(u8, name, field)) {
- out.* = @unionInit(T, field, undefined);
- try l.fresh(F, &@field(out.*, field));
- return l.value(F, kv.value_cursor, &@field(out.*, field));
- };
- l.note("{s}: no {s} here", .{ l.field, name });
- return error.Incompatible;
- },
- .err, .error_union => unreachable,
- .custom => {
- const got = c.readBytesObjectAlloc(l.own, null) catch return error.Incompatible;
- defer l.own.free(got.value);
- T.dumpRead(out, l.gpa, got.value) catch |err| {
- if (err == error.OutOfMemory) return error.OutOfMemory;
- l.note("{s}: {t}", .{ l.field, err });
- return error.Incompatible;
- };
- if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) });
- },
- .bitset => {
- const got = c.readBytesObjectAlloc(l.own, null) catch return error.Incompatible;
- defer l.own.free(got.value);
- if (got.value.len < 8) return error.BadDump;
- const bits = countOf(std.mem.bytesToValue(u64, got.value[0..8])) catch return error.BadDump;
- 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);
- if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), got.value[8..]);
- },
- }
- }
-
- fn int(l: *Get, comptime I: type, c: Cursor, slot: xitdb.Slot) Error!I {
- _ = l;
- return switch (slot.tag) {
- .uint => std.math.cast(I, slot.value) orelse error.Incompatible,
- .int => std.math.cast(I, @as(i64, @bitCast(slot.value))) orelse error.Incompatible,
- .bytes, .short_bytes => wide: {
- var buf: [16]u8 = undefined;
- const got = c.readBytesObject(&buf) catch return error.Incompatible;
- if (got.value.len != 16 or !std.mem.eql(u8, &(got.format_tag orelse return error.Incompatible), &wide_tag)) return error.Incompatible;
- break :wide std.math.cast(I, std.mem.bytesToValue(i128, got.value[0..16])) orelse error.Incompatible;
- },
- else => error.Incompatible,
- };
- }
-
- /// Numbers' `bytes` (format `tag`) as `E`s into `out`, as many as fit:
- /// another width of the same kind (another build's) converted one by
- /// one. How many the bytes hold.
- fn convert(comptime E: type, bytes: []const u8, tag: [2]u8, out: []E) Error!usize {
- const width: usize = if (tag[1] >= '1' and tag[1] <= '8') tag[1] - '0' else return error.BadDump;
- if (bytes.len % width != 0) return error.BadDump;
- const n = bytes.len / width;
- const fits = @min(n, out.len);
- if (std.mem.eql(u8, &tag, &numbersTag(E))) {
- @memcpy(std.mem.sliceAsBytes(out[0..fits]), bytes[0 .. fits * width]);
- return n;
- }
- if (tag[0] != numbersTag(E)[0]) return error.Incompatible;
- for (out[0..fits], 0..) |*e, i| {
- const raw = bytes[i * width ..][0..width];
- e.* = switch (@typeInfo(E)) {
- .int => |info| if (info.signedness == .signed) cast: {
- var wide: i64 = 0;
- @memcpy(std.mem.asBytes(&wide)[0..width], raw);
- if (width < 8) {
- const shift: u6 = @intCast(64 - width * 8);
- wide = (wide << shift) >> shift;
- }
- break :cast std.math.cast(E, wide) orelse return error.Incompatible;
- } else cast: {
- var wide: u64 = 0;
- @memcpy(std.mem.asBytes(&wide)[0..width], raw);
- break :cast std.math.cast(E, wide) orelse return error.Incompatible;
- },
- .float => if (width == 8) @floatCast(std.mem.bytesToValue(f64, raw[0..8])) else if (width == 4) @floatCast(std.mem.bytesToValue(f32, raw[0..4])) else return error.Incompatible,
- .bool => raw[0] != 0,
- else => unreachable,
- };
- }
- return n;
- }
-
- /// The numbers' bytes at `c` and their format tag, `alloc`'s.
- fn numbersAt(c: Cursor, alloc: std.mem.Allocator) Error!struct { bytes: []u8, tag: [2]u8 } {
- const got = c.readBytesObjectAlloc(alloc, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.Incompatible;
- const bytes: []u8 = @constCast(got.value);
- const tag = got.format_tag orelse {
- alloc.free(bytes);
- return error.Incompatible;
- };
- return .{ .bytes = bytes, .tag = tag };
- }
-
- /// 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 (comptime numbers(E)) {
- switch (slot.tag) {
- .bytes, .short_bytes => {},
- else => return error.Incompatible,
- }
- if (E == u8) if (try l.blob(c, slot)) |text| return text;
- // A text, as it is written: its bytes are the slice.
- if (E == u8) {
- const got = try numbersAt(c, l.gpa);
- if (!std.mem.eql(u8, &got.tag, &numbersTag(u8))) {
- l.gpa.free(got.bytes);
- return error.Incompatible;
- }
- if (got.bytes.len == 0) {
- l.gpa.free(got.bytes);
- return &.{};
- }
- _ = l.keep(got.bytes, .@"1", slot) catch |err| {
- l.gpa.free(got.bytes);
- return err;
- };
- return got.bytes;
- }
- const got = try numbersAt(c, l.own);
- defer l.own.free(got.bytes);
- const width: usize = if (got.tag[1] >= '1' and got.tag[1] <= '8') got.tag[1] - '0' else return error.BadDump;
- 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| {
- l.gpa.free(many);
- return err;
- };
- _ = convert(E, got.bytes, got.tag, many) catch |err| {
- l.made.items[at].dead = true;
- return err;
- };
- return many;
- }
- const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible;
- const n = countOf(list.count() catch return error.BadDump) catch return error.BadDump;
- 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| {
- l.gpa.free(many);
- return err;
- };
- l.listInto(E, list, many) catch |err| {
- l.made.items[at].dead = true;
- return err;
- };
- return many;
- }
-
- /// A blob's text, when `c` holds a blob's hash: made in `gpa`'s.
- fn blob(l: *Get, c: Cursor, slot: xitdb.Slot) Error!?[]u8 {
- var buf: [32]u8 = undefined;
- const got = c.readBytesObject(&buf) catch return null;
- const tag = got.format_tag orelse return null;
- if (!std.mem.eql(u8, &tag, &blob_tag) or got.value.len != 32) return null;
- const texts = l.blobs orelse return error.BadDump;
- 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, null) 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.gpa.free(bytes);
- return err;
- };
- return bytes;
- }
-
- /// An array of `E` at `c`: as many as it holds, the rest as they are.
- fn elements(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot, out: []E) Error!void {
- if (comptime numbers(E)) {
- switch (slot.tag) {
- .bytes, .short_bytes => {},
- else => return error.Incompatible,
- }
- const got = try numbersAt(c, l.own);
- defer l.own.free(got.bytes);
- _ = try convert(E, got.bytes, got.tag, out);
- return;
- }
- const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible;
- try l.listInto(E, list, out);
- }
-
- /// The list's elements into `out`, as many as fit; an element of an
- /// array of optional pointers (a session's panes) that cannot be read is
- /// left out, not the array.
- fn listInto(l: *Get, comptime E: type, list: Mem.ArrayList(.read_only), out: []E) Error!void {
- const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
- var failed = false;
- var it = list.iterator() catch return error.BadDump;
- var i: usize = 0;
- while (it.next() catch return error.BadDump) |at| : (i += 1) {
- if (i >= out.len) break;
- try l.fresh(E, &out[i]);
- l.value(E, at, &out[i]) catch |err| {
- if (err != error.Incompatible) return err;
- if (droppable) {
- out[i] = null;
- l.note("{s}[{d}] left out", .{ l.field, i });
- } else failed = true;
- };
- }
- if (failed) return error.Incompatible;
- }
-
- fn fields(l: *Get, comptime T: type, c: Cursor, out: *T, existing: bool) Error!void {
- const names = comptime dumpFields(T);
- const outer = l.field;
- defer l.field = outer;
- const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
- var found: std.StaticBitSet(@max(1, names.len)) = .empty;
- var failed = false;
- var it = map.iterator() catch return error.BadDump;
- while (it.next() catch return error.BadDump) |kv_at| {
- const kv = kv_at.readKeyValuePair() catch return error.BadDump;
- var buf: [256]u8 = undefined;
- // A key that is no field's name of this build: passed over.
- const name = kv.key_cursor.readBytes(&buf) catch continue;
- const k: ?usize = inline for (names, 0..) |field, k| {
- if (std.mem.eql(u8, name, field)) break k;
- } else null;
- const at = k orelse continue;
- found.set(at);
- inline for (names, 0..) |field, i| if (i == at) {
- l.field = field;
- l.oneField(T, field, kv.value_cursor, out, existing) catch |err| {
- if (err != error.Incompatible) return err;
- const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
- if (comptime attr.default_value_ptr) |dp| {
- @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*;
- l.noteField("its kind changed; its default taken", @typeName(T), field);
- } else if (existing) {
- l.noteField("its kind changed; left as it was", @typeName(T), field);
- } else failed = true;
- };
- };
- }
- // A field the writer did not have (or held null at a null default):
- // its default (`fresh`), or the value cannot be made.
- inline for (names, 0..) |field, i| if (!found.isSet(i)) {
- const F = @FieldType(T, field);
- const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
- if (comptime attr.default_value_ptr == null and kindOf(Canon(F)) != .void) {
- if (!existing) {
- l.noteField("not in the dump", @typeName(T), field);
- failed = true;
- }
- } else if (comptime @typeInfo(F) == .optional and defaultIsNull(T, field)) if (existing) {
- // A null left out: null here too.
- @field(out, field) = null;
- };
- };
- if (failed) return error.Incompatible;
- }
-
- fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void {
- const F = @FieldType(T, field);
- const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
- const gpa = l.gpa;
- defer l.gpa = gpa;
- if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| {
- l.gpa = a;
- };
- // A field this build compiles out (a void field): passed over,
- // said when it held something.
- if (comptime kindOf(Canon(F)) == .void) {
- if ((try slotOf(c)).tag != .none) l.note("{s}: not in this build", .{l.field});
- return;
- }
- if (comptime cutArray(T, field)) {
- const slot = try slotOf(c);
- return l.elements(@typeInfo(F).array.child, c, slot, &@field(out, field));
- }
- // A struct held in place in one read as it stands (the root's):
- // what it does not hold stays as it is too.
- if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) {
- return l.fields(F, c, &@field(out, field), true);
- };
- if (packed_struct) {
- var copy: F = undefined;
- try l.fresh(F, &copy);
- try l.value(F, c, &copy);
- @field(out, field) = copy;
- return;
- }
- try l.fresh(F, &@field(out, field));
- try l.value(F, c, &@field(out, field));
- }
-};
-
-test "a value comes back from its bytes" {
- const E = union(enum) { key: struct { cp: u21, text: []const u8 }, tick, failed: anyerror!u32 };
- var buf: [256]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- const values = [_]E{ .{ .key = .{ .cp = 'x', .text = "x" } }, .tick, .{ .failed = error.FileNotFound }, .{ .failed = 9 } };
- for (&values) |*v| try encode(E, v, &w);
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- var r: Reader = .{ .bytes = w.buffered() };
- for (&values) |*v| try std.testing.expectEqual(digest(E, v), digest(E, &try decode(E, &r, arena.allocator())));
- try std.testing.expectEqual(r.bytes.len, r.at);
-}
-
-test "an error is taped by its name, which another build reads back as its own" {
- // The build's number for an error is its own: 451 of 505 names were
- // numbered otherwise in a Linux window's build than a terminal's, so a
- // window replica read a terminal session's FileNotFound as another.
- var buf: [64]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- const failed: error{ FileNotFound, NotDir }!u32 = error.NotDir;
- try encode(@TypeOf(failed), &failed, &w);
- try std.testing.expectEqualSlices(u8, "\x00\x06\x00NotDir", w.buffered());
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- var r: Reader = .{ .bytes = w.buffered() };
- try std.testing.expectError(error.NotDir, try decode(@TypeOf(failed), &r, arena.allocator()));
- // A name this build's set lacks (an OS's own): the tape is another
- // build's, and the replay diverges rather than read some other error.
- r = .{ .bytes = "\x00\x0c\x00FileTooLarge" };
- try std.testing.expectError(error.NoSuchError, decode(@TypeOf(failed), &r, arena.allocator()));
- // An anyerror (a host's report) is read back as one of tape.Failure's.
- const Report = struct { err: anyerror };
- w = .fixed(&buf);
- try encode(Report, &.{ .err = error.FileNotFound }, &w);
- r = .{ .bytes = w.buffered() };
- try std.testing.expectEqual(error.FileNotFound, (try decode(Report, &r, arena.allocator())).err);
-}
-
-test "an enum is digested by its name, which another build may number otherwise" {
- // registry.Builtin as a Linux build makes it (Tty9p in it) and as a
- // FreeBSD one does: LocationsConfig is another number in each.
- const Linux = enum { Look, Tty9p, LocationsConfig };
- const FreeBSD = enum { Look, LocationsConfig };
- const S = struct { from: Linux, also: [2]Linux };
- const T = struct { from: FreeBSD, also: [2]FreeBSD };
- try std.testing.expectEqual(digest(S, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }), digest(T, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }));
- try std.testing.expect(digest(S, &.{ .from = .Look, .also = .{ .Look, .Look } }) != digest(S, &.{ .from = .Tty9p, .also = .{ .Look, .Look } }));
-}
-
-test "a digest is of values: the same text at two addresses is one digest" {
- const S = struct { name: []const u8, n: u32, next: ?*const u32 };
- const a = "same text";
- var b: [9]u8 = undefined;
- @memcpy(&b, a);
- const x: u32 = 7;
- const y: u32 = 7;
- try std.testing.expectEqual(digest(S, &.{ .name = a, .n = 1, .next = &x }), digest(S, &.{ .name = &b, .n = 1, .next = &y }));
- try std.testing.expect(digest(S, &.{ .name = a, .n = 1, .next = &x }) != digest(S, &.{ .name = a, .n = 2, .next = &x }));
-}
-
-test "an annotated field is in no digest, and a length cuts its array" {
- const S = struct {
- kept: u32,
- cache: u32,
- ring: [4]u8,
- ring_len: u8,
- pub const replica = .{ .derived = .{"cache"}, .len = .{.{ "ring", "ring_len" }} };
- };
- try std.testing.expectEqual(
- digest(S, &.{ .kept = 1, .cache = 2, .ring = .{ 1, 2, 9, 9 }, .ring_len = 2 }),
- digest(S, &.{ .kept = 1, .cache = 3, .ring = .{ 1, 2, 0, 0 }, .ring_len = 2 }),
- );
-}
-
-test "an optional slice comes back, and the fields after it" {
- const S = struct { before: u32 = 0, command: ?[]u8 = null, after: u32 = 0 };
- var text = "sleep 30".*;
- const bytes = try save(S, std.testing.allocator, &.{ .before = 1, .command = &text, .after = 2 });
- defer std.testing.allocator.free(bytes);
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- const back = try load(S, arena.allocator(), bytes, null);
- try std.testing.expectEqualStrings("sleep 30", back.command.?);
- try std.testing.expectEqual(2, back.after);
-}
-
-test "a dump comes back whole: shared things shared, lists and runs as long as they were" {
- const gpa = std.testing.allocator;
- const Leaf = struct { n: u21, name: []const u8 };
- const Mode = enum { a, b, c };
- const S = struct {
- mode: Mode = .a,
- leaf: *Leaf,
- same_leaf: *Leaf,
- text: []u8,
- same_text: []u8,
- list: std.ArrayList(u16) = .empty,
- maybe: ?Leaf = null,
- either: union(enum) { none, some: u32, many: []const u16 } = .none,
- ring: [4]u8 = @splat(0),
- ring_len: u8 = 0,
- room: []i32 = &.{},
- room_len: u8 = 0,
- cache: u64 = 7,
- alloc: std.mem.Allocator,
- flags: packed struct { x: bool = false, y: u3 = 0 } = .{},
- pub const replica = .{ .derived = .{"cache"}, .len = .{ .{ "ring", "ring_len" }, .{ "room", "room_len" } } };
- };
- var leaf: Leaf = .{ .n = 0x1fffff, .name = "leaf" };
- var room = [_]i32{ 4, 5, -1, -1 };
- var text = "shared text".*;
- var list: std.ArrayList(u16) = .empty;
- defer list.deinit(gpa);
- try list.appendSlice(gpa, &.{ 1, 2, 3 });
- const x: S = .{ .mode = .c, .leaf = &leaf, .same_leaf = &leaf, .text = &text, .same_text = &text, .list = list, .maybe = .{ .n = 3, .name = "maybe" }, .either = .{ .many = &.{ 9, 8 } }, .ring = .{ 5, 6, 0xAA, 0xAA }, .ring_len = 2, .room = &room, .room_len = 2, .cache = 99, .alloc = gpa, .flags = .{ .x = true, .y = 5 } };
- const bytes = try save(S, gpa, &x);
- defer gpa.free(bytes);
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- const y = try load(S, arena.allocator(), bytes, null);
- try std.testing.expectEqual(digest(S, &x), digest(S, &y));
- try std.testing.expect(y.leaf == y.same_leaf and y.text.ptr == y.same_text.ptr);
- try std.testing.expectEqual(@as(u64, 7), y.cache);
- try std.testing.expectEqualSlices(u16, &.{ 1, 2, 3 }, y.list.items);
- try std.testing.expectEqual(true, y.flags.x);
- // A slice its `len` cuts keeps its room.
- try std.testing.expectEqual(@as(usize, 4), y.room.len);
- try std.testing.expectEqualSlices(i32, &.{ 4, 5 }, y.room[0..2]);
- // A fixpoint: what was read is written as it was.
- const again = try save(S, gpa, &y);
- defer gpa.free(again);
- try std.testing.expectEqualSlices(u8, bytes, again);
-}
-
-test "a dump crosses builds: a field added takes its default, one removed is passed over, one changed is left out" {
- const gpa = std.testing.allocator;
- const Old = struct {
- const Color = enum { red, green, blue };
- const Pane = struct { name: []const u8, color: Color = .red, gone: u32 = 1, width: u16 = 0, kind: u32 = 0 };
- panes: [3]?*Pane = @splat(null),
- count: u8 = 0,
- renamed: u32 = 0,
- };
- const New = struct {
- // Values renumbered and one added before the others.
- const Color = enum { cyan, blue, red, green };
- const Wide = struct { a: u8 };
- const Pane = struct { added: bool = true, color: Color = .cyan, width: u32 = 0, name: []const u8, kind: Wide = .{ .a = 4 } };
- // A pane's required field changed kind: that pane is left out.
- const Strict = struct { name: u8 };
- panes: [4]?*Pane = @splat(null),
- count: u16 = 0,
- renamed_now: u32 = 5,
- };
- var one: Old.Pane = .{ .name = "one", .color = .blue, .gone = 9, .width = 300, .kind = 2 };
- var two: Old.Pane = .{ .name = "two", .color = .green };
- const old: Old = .{ .panes = .{ &one, null, &two }, .count = 2, .renamed = 7 };
- const bytes = try save(Old, gpa, &old);
- defer gpa.free(bytes);
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- // The notes are made where the load's values are.
- var notes: std.ArrayList(u8) = .empty;
- const new = try load(New, arena.allocator(), bytes, &notes);
- try std.testing.expectEqual(@as(u16, 2), new.count);
- try std.testing.expectEqual(@as(u32, 5), new.renamed_now);
- const a = new.panes[0].?;
- try std.testing.expectEqualStrings("one", a.name);
- try std.testing.expectEqual(New.Color.blue, a.color);
- try std.testing.expectEqual(@as(u32, 300), a.width);
- try std.testing.expect(a.added);
- try std.testing.expectEqual(@as(u8, 4), a.kind.a);
- try std.testing.expect(new.panes[1] == null and new.panes[3] == null);
- try std.testing.expectEqual(New.Color.green, new.panes[2].?.color);
- try std.testing.expect(std.mem.indexOf(u8, notes.items, "kind") != null);
-
- const Strict = struct {
- const Pane = struct { name: u8 };
- panes: [3]?*Pane = @splat(null),
- count: u8 = 0,
- };
- notes.clearRetainingCapacity();
- const strict = try load(Strict, arena.allocator(), bytes, &notes);
- try std.testing.expect(strict.panes[0] == null and strict.panes[2] == null);
- try std.testing.expectEqual(@as(u8, 2), strict.count);
- try std.testing.expect(std.mem.indexOf(u8, notes.items, "left out") != null);
-
- // And back: the newer build's dump read by the older one.
- const newer = try save(New, gpa, &new);
- defer gpa.free(newer);
- const back = try load(Old, arena.allocator(), newer, null);
- try std.testing.expectEqualStrings("two", back.panes[2].?.name);
- try std.testing.expectEqual(@as(u32, 1), back.panes[0].?.gone);
- try std.testing.expectEqual(Old.Color.blue, back.panes[0].?.color);
-}
-
-test "a dump that is not one, or is cut short, is refused" {
- const gpa = std.testing.allocator;
- const S = struct { a: u32, b: []const u8 };
- try std.testing.expectError(error.BadDump, load(S, gpa, "not a dump", null));
- const bytes = try save(S, gpa, &.{ .a = 1, .b = "bee" });
- defer gpa.free(bytes);
- // What it made before the end is freed again.
- try std.testing.expectError(error.EndOfDump, load(S, gpa, bytes[0 .. bytes.len - 2], null));
-}
-
-test "a blob of 4 KiB and up is digested by its length, what it holds told by its keeper's revision; a smaller one by its bytes" {
- const gpa = std.testing.allocator;
- const File = struct {
- pub const replica = .{ .blob = .{"content"} };
- content: []u8,
- revision: u32 = 0,
- };
- const text = try gpa.alloc(u8, 64 << 10);
- defer gpa.free(text);
- @memset(text, 'a');
- var f: File = .{ .content = text };
- const before = digest(File, &f);
- // Written in place: the same digest, until its revision says so.
- text[1000] = 'b';
- try std.testing.expectEqual(before, digest(File, &f));
- f.revision += 1;
- try std.testing.expect(digest(File, &f) != before);
- // Another length is another digest.
- f.revision = 0;
- f.content = text[0 .. text.len - 1];
- try std.testing.expect(digest(File, &f) != before);
- // A small one by its bytes.
- var small = "abc".*;
- f.content = &small;
- const was = digest(File, &f);
- small[1] = 'x';
- try std.testing.expect(digest(File, &f) != was);
-}
-
-test "a shape's numbers are written as {d} writes them" {
- inline for (.{ 0, 7, 10, 65535, -1, -300, std.math.minInt(i128), std.math.maxInt(u128) }) |n|
- try std.testing.expectEqualStrings(std.fmt.comptimePrint("{d}", .{n}), comptime decimal(n));
-}
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 c465b52f..adfbc52a 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/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
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));