diff options
| -rw-r--r-- | abi/wire.zig | 5 | ||||
| -rw-r--r-- | core/Core.zig | 6 | ||||
| -rw-r--r-- | core/File.zig | 503 | ||||
| -rw-r--r-- | core/Output.zig | 1 | ||||
| -rw-r--r-- | core/Places.zig | 11 | ||||
| -rw-r--r-- | core/Query.zig | 40 | ||||
| -rw-r--r-- | core/Text.zig | 11 | ||||
| -rw-r--r-- | core/draw.zig | 3 | ||||
| -rw-r--r-- | core/jj.zig | 173 | ||||
| -rw-r--r-- | core/look.zig | 18 | ||||
| -rw-r--r-- | core/mouse.zig | 14 | ||||
| -rw-r--r-- | core/ninep/events.zig | 4 | ||||
| -rw-r--r-- | core/normal.zig | 52 | ||||
| -rw-r--r-- | core/panes.zig | 62 | ||||
| -rw-r--r-- | core/replica.zig | 154 | ||||
| -rw-r--r-- | core/rollback.zig | 3 | ||||
| -rw-r--r-- | core/root.zig | 4 | ||||
| -rw-r--r-- | core/surface.zig | 4 | ||||
| -rw-r--r-- | core/views.zig | 17 | ||||
| -rw-r--r-- | dev/glide.zig | 43 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 60 | ||||
| -rw-r--r-- | test/daemon.py | 2 | ||||
| -rw-r--r-- | test/kitty.zig | 2 | ||||
| -rw-r--r-- | test/panes.zig | 28 | ||||
| -rw-r--r-- | test/perf.zig | 14 | ||||
| -rw-r--r-- | test/terminal.zig | 2 |
26 files changed, 1030 insertions, 206 deletions
diff --git a/abi/wire.zig b/abi/wire.zig index ea5998e6..f558cb9a 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,9 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 35: a view's top is a line and a row of that line's wrapped rows: a +/// file's `scroll_row` (and its share's in each view) in the dump and the +/// digest; a dump without it loads at its lines' first rows; /// 34: the `Changes` layer's lines are the pane's buffer's while it is /// shown: a file pane's `read_only` places and `layer` in the dump and the /// digest, its buffer dumped whole while it has them (a clean file's text @@ -73,7 +76,7 @@ const build_info = @import("build_info"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 34; +pub const version: u16 = 35; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Core.zig b/core/Core.zig index 4c8aa2eb..1894247d 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -3871,11 +3871,11 @@ test "raw terminal cursor follows its active row only while that row is visible" try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x); try std.testing.expectEqual(body_y + 2, live.y); - pane.scrollBy(-1); + pane.scrollBy(p.settings.tab, -1); const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, scrolled.x); try std.testing.expectEqual(live.y + 1, scrolled.y); - pane.scrollBy(-@as(i32, pane.rows)); + pane.scrollBy(p.settings.tab, -@as(i32, pane.rows)); try std.testing.expect((try p.render(frame.allocator())).cursor == null); pane.followOutput(); const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; @@ -3929,7 +3929,7 @@ test "tty output follows only from the bottom" { try std.testing.expect(bottom > 0); // Scrolled back, the reader stays put however much the shell prints. - sp.scrollBy(-10); + sp.scrollBy(p.settings.tab, -10); p.sync(); const parked = sp.termTop(); try std.testing.expect(parked < bottom); diff --git a/core/File.zig b/core/File.zig index b2df6c0f..86861792 100644 --- a/core/File.zig +++ b/core/File.zig @@ -98,7 +98,7 @@ pub const State = struct { /// from the text whenever it is wanted. // Syntax caches must not load through the dump loader's core allocator. pub const replica = .{ - .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" }, + .derived = .{ "cap", "line_starts", "line_cap", "widest", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" }, // Big texts, dumped and sent by their hash (core/walk.zig). The // text is written in place by `replace`, but never while a join // sends it (memory.zig `pin`): then an edit puts a new buffer in @@ -160,11 +160,18 @@ pub const State = struct { /// A directory pane's entries (Dir.zig), its output `.dir`. listing: ?panes.Dir.State = null, mini: ?Mini.State = null, + /// The view's top: the line its first row is of, and that row of the + /// line's wrapped rows (`Top`): each view's own (views.zig), digested, + /// dumped. scroll: usize = 0, + scroll_row: u32 = 0, /// `line_starts[i]` is line i's byte offset. Empty means not built yet. line_starts: []usize = &.{}, /// The room `line_starts` has, as `cap` is `content`'s. line_cap: usize = 0, + /// The widest any line is, found with the index and kept with it + /// (`Widest`): what tells a view whose rows are its lines (`oneRow`). + widest: Widest = .{}, /// One tree_sitter_gpa-owned syntax.Syn byte per highlighted source byte. highlights: []u8 = &.{}, location_rows: []locations.Row = &.{}, @@ -605,6 +612,16 @@ pub fn renderedLineDisplayCol(tab: u16, pane: *const Pane, row: i32, line_text: pub fn fitEnd(tab: u16, text: []const u8, start: usize, width: usize) usize { var end = start; var used: usize = 0; + // A vector of printable ASCII at a time, a cell a byte, while the width + // is past it and the byte after it is ASCII too: what the loop below + // takes a byte at a time (it leaves the ASCII byte a non-ASCII one + // follows to the grapheme walk). Every row walk is this loop. + while (used + lanes < width and end + lanes < text.len and text[end + lanes] < 0x80) { + const v: Lanes = text[end..][0..lanes].*; + if (@reduce(.Or, v -% @as(Lanes, @splat(0x20)) >= @as(Lanes, @splat(0x5f)))) break; + used += lanes; + end += lanes; + } while (used < width and end < text.len) { const b = text[end]; if (b < 0x20 or b >= 0x7f) break; @@ -629,20 +646,91 @@ pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { if (f.line_starts.len > 0) return f.line_starts; // Exact allocation: deinitPane frees `line_starts` itself, so the stored // slice must span the complete allocation rather than spare capacity. - const starts = try gpa.alloc(usize, lineCount(f.content)); + const found = countLines(f.content); + const starts = try gpa.alloc(usize, found.newlines + 1); starts[0] = 0; - var i: usize = 1; - var off: usize = 0; - while (std.mem.indexOfScalarPos(u8, f.content, off, '\n')) |nl| { - off = nl + 1; - starts[i] = off; - i += 1; - } + f.widest = .{ .bytes = fillLines(f.content, 0, starts[1..]), .tabbed = found.tabbed }; f.line_starts = starts; f.line_cap = 0; return starts; } +/// The widest a text's lines are, at most: the most bytes between two +/// newlines, and whether a tab is among them. A tab is `tab` cells, any +/// other byte at most one (graphemeDisplayWidth), so a line is never +/// wider than its bytes, times the tab width where a tab may be. Made +/// with the line index and kept by its edits, only ever made wider: an +/// edit taking the widest line away leaves it so (`oneRow` then walks, +/// and finds the same rows). +pub const Widest = struct { + bytes: usize = 0, + tabbed: bool = false, + + fn cells(w: Widest, tab: u16) usize { + return if (w.tabbed) w.bytes *| @max(tab, 1) else w.bytes; + } +}; + +const lanes = std.simd.suggestVectorLength(u8) orelse 16; +const Lanes = @Vector(lanes, u8); + +/// The newlines in `bytes` and whether a tab is among them: a lane's own +/// sum a vector, added up every 255 (std.mem.count's popcount of a mask is +/// a dozen instructions a vector on a baseline x86-64). +fn countLines(bytes: []const u8) struct { newlines: usize, tabbed: bool } { + const one: Lanes = @splat(1); + const zero: Lanes = @splat(0); + var newlines: usize = 0; + var tabs = zero; + var i: usize = 0; + while (bytes.len - i >= lanes) { + var sums = zero; + for (0..@min((bytes.len - i) / lanes, 255)) |_| { + const v: Lanes = bytes[i..][0..lanes].*; + sums += @select(u8, v == @as(Lanes, @splat('\n')), one, zero); + tabs |= @select(u8, v == @as(Lanes, @splat('\t')), one, zero); + i += lanes; + } + newlines += @reduce(.Add, @as(@Vector(lanes, u16), sums)); + } + var tabbed = @reduce(.Or, tabs) != 0; + for (bytes[i..]) |b| { + newlines += @intFromBool(b == '\n'); + tabbed = tabbed or b == '\t'; + } + return .{ .newlines = newlines, .tabbed = tabbed }; +} + +/// The start after each newline of `bytes` (its byte `off` past it) into +/// `out`, a vector at a time, a newline's place off its mask (a search for +/// each cost a short line ~57 instructions); and the most bytes of `bytes` +/// between two newlines or an end. +fn fillLines(bytes: []const u8, off: usize, out: []usize) usize { + const Mask = @Int(.unsigned, lanes); + var n: usize = 0; + var from: usize = 0; + var widest: usize = 0; + var i: usize = 0; + while (i + lanes <= bytes.len) : (i += lanes) { + const v: Lanes = bytes[i..][0..lanes].*; + var nl: Mask = @bitCast(v == @as(Lanes, @splat('\n'))); + while (nl != 0) : (nl &= nl - 1) { + const at = i + @ctz(nl); + widest = @max(widest, at - from); + from = at + 1; + out[n] = off + from; + n += 1; + } + } + for (bytes[i..], i..) |b, at| if (b == '\n') { + widest = @max(widest, at - from); + from = at + 1; + out[n] = off + from; + n += 1; + }; + return @max(widest, bytes.len - from); +} + /// The whole buffer of a text's bytes, its room past them included. fn textRoom(f: *const State) []u8 { return f.content.ptr[0..@max(f.cap, f.content.len)]; @@ -668,7 +756,10 @@ pub const Span = struct { head: usize, tail: usize }; fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes: []const u8) void { const starts = f.line_starts; const room = indexRoom(f); - const n = starts.len - (std.sort.upperBound(usize, starts, off + len, ascending) - std.sort.upperBound(usize, starts, off, ascending)) + std.mem.count(u8, bytes, "\n"); + const first = std.sort.upperBound(usize, starts, off, ascending); + const found = countLines(bytes); + const added = found.newlines; + const n = starts.len - (std.sort.upperBound(usize, starts, off + len, ascending) - first) + added; var out = room; if (n > room.len) { out = gpa.alloc(usize, n + @max(n / 8, 512)) catch { @@ -679,10 +770,17 @@ fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes: }; @memcpy(out[0..starts.len], starts); } else pardes.rollback.Epoch.wrote(gpa, usize, room, starts.len, n, off, f.content[off..][0..len], bytes.len); - shiftStarts(out, starts.len, n, off, len, bytes); + const inside = shiftStarts(out, starts.len, n, off, len, bytes); if (out.ptr != room.ptr) pardes.memory.freeRaw(gpa, room); f.line_starts = out[0..n]; f.line_cap = out.len; + // The widest: what the edit put in, and the two lines it joined at + // its ends (the line `off` is on, the one its last newline starts). + const total = f.content.len - len + bytes.len; + const ends = [2]usize{ first - 1, first - 1 + added }; + var widest = @max(f.widest.bytes, inside); + for (ends) |l| widest = @max(widest, (if (l + 1 < n) f.line_starts[l + 1] - 1 else total) - f.line_starts[l]); + f.widest = .{ .bytes = widest, .tabbed = f.widest.tabbed or found.tabbed }; } /// The first `len` of `room`, a line index, through the edit that puts @@ -692,7 +790,8 @@ fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes: /// only the moving is a pass over the index, and only from the edit on. The /// edit turned round (`cut` its length in, `bytes` what it took out) gives /// the index before it back: a rollback's (core/rollback.zig `unwrite`). -pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, bytes: []const u8) void { +/// The most bytes of `bytes` between two newlines or an end (fillLines). +pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, bytes: []const u8) usize { const starts = room[0..len]; const kept = std.sort.upperBound(usize, starts, off, ascending); const moved = len - std.sort.upperBound(usize, starts, off + cut, ascending); @@ -709,13 +808,7 @@ pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, } else for (0..moved) |k| { room[to + k] = room[from + k] - cut + bytes.len; } - var i = kept; - var at: usize = 0; - while (std.mem.indexOfScalarPos(u8, bytes, at, '\n')) |nl| { - at = nl + 1; - room[i] = off + at; - i += 1; - } + return fillLines(bytes, off, room[kept..]); } /// line count, O(1) once the index is warm @@ -982,9 +1075,9 @@ pub fn relayer(p: *Pardes, f: *State, new: []u8, spans: []ReadOnly, layer: u32) // selection's anchor and ranges in the live view, a cursor and a top // line in the others. const Place = struct { row: *i32, col: *i32, at: usize }; - const Top = struct { line: *usize, at: usize }; + const Kept = struct { line: *usize, at: usize }; var places: std.ArrayList(Place) = .empty; - var tops: std.ArrayList(Top) = .empty; + var tops: std.ArrayList(Kept) = .empty; const At = struct { fn of(q: *Pardes, g: *State, row: i32, col: i32) usize { const r: usize = @intCast(@max(0, row)); @@ -1031,7 +1124,7 @@ pub fn relayer(p: *Pardes, f: *State, new: []u8, spans: []ReadOnly, layer: u32) place.row.* = @intCast(pos.row); place.col.* = @intCast(pos.col); } - for (tops.items) |top| top.line.* = positionIn(p.gpa, f, bufferOffset(f, top.at, false)).row; + for (tops.items) |kept| kept.line.* = positionIn(p.gpa, f, bufferOffset(f, kept.at, false)).row; return true; } @@ -1222,6 +1315,7 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who tf.cap = f.cap; tf.line_starts = f.line_starts; tf.line_cap = f.line_cap; + tf.widest = f.widest; if (!told and tf.context.revision == f.revision -% 1) tf.context.revision = f.revision; // Its copy of the read-only lines, moved as this one's were (the // layer's own edit sets them after, jj.showLayer). @@ -1409,6 +1503,7 @@ pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane { .cap = f.cap, .line_starts = f.line_starts, .line_cap = f.line_cap, + .widest = f.widest, .history = f.history, .revision = f.revision, .saved_revision = f.saved_revision, @@ -1419,6 +1514,7 @@ pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane { .on_disk = f.on_disk, .mtime = f.mtime, .scroll = f.scroll, + .scroll_row = f.scroll_row, .tree_context = f.tree_context, .twin = f.twin, }; @@ -1650,11 +1746,309 @@ fn pageEnd(tab: u16, pane: *Pane) usize { } fn setPageScroll(pane: *Pane, line: usize) void { + setTop(pane, .{ .line = @min(line, nlines(pane.gpa, &pane.file.?) -| 1) }); +} + +/// A view's top: the line its first row is of (`State.scroll`) and that +/// row of the line's rows as wrapped (`State.scroll_row`; one row +/// unwrapped). A scroll moves it by rows through the lines. +pub const Top = struct { line: usize, row: u32 = 0 }; + +/// The row of line `line` that shows its byte `col` (a line's last row +/// every byte past its start, as wrapRow has it), as fillBody wraps it. +pub fn rowOf(tab: u16, pane: *const Pane, line: usize, col: usize) u32 { + return rowIn(tab, pane, line, col).row; +} + +/// The rows line `line` takes in `pane`'s view. +pub fn lineRows(tab: u16, pane: *const Pane, line: usize) u32 { + return rowIn(tab, pane, line, std.math.maxInt(usize)).rows; +} + +/// Whether every line of `pane`'s view is one row: none wider than a row +/// (the text's widest, kept with its index), so its rows are its lines and +/// the walks below are line arithmetic, nothing read. +fn oneRow(tab: u16, pane: *const Pane) bool { + const width = wrapWidth(pane, pane.view.wrap); const f = &pane.file.?; - const to = @min(line, nlines(pane.gpa, f) -| 1); - if (to == f.scroll) return; - f.scroll = to; - f.syntax_dirty = true; + return width == 0 or (f.line_starts.len > 0 and f.widest.cells(tab) <= width); +} + +const RowIn = struct { row: u32, rows: u32 }; + +/// rowOf's row and lineRows' rows, in one walk of the line: the one walk +/// of a line's rows every map from rows to lines asks, beside the +/// geometry's own map of the body (the same `fitEnd` at the same width). +fn rowIn(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn { + if (pane.file != null and oneRow(tab, pane)) { + if (builtin.mode == .debug) std.debug.assert(rowWalked(tab, pane, line, col).rows == 1); + return .{ .row = 0, .rows = 1 }; + } + return rowWalked(tab, pane, line, col); +} + +fn rowWalked(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn { + const f = if (pane.file) |*file| file else return .{ .row = 0, .rows = 1 }; + const width = wrapWidth(pane, pane.view.wrap); + if (width == 0) return .{ .row = 0, .rows = 1 }; + const text = sourceLine(pane, @intCast(line)); + // No more bytes than a row has cells and no tab is one row: a tab is + // `tab` cells, any other byte at most one (Widest); no grapheme walked + // (the lines a page or a margin crosses, nearly all of a source's). + if (text.len <= width and std.mem.indexOfScalar(u8, text, '\t') == null) { + if (builtin.mode == .debug) std.debug.assert(fitEnd(tab, text, 0, width) >= text.len); + return .{ .row = 0, .rows = 1 }; + } + var guide: [1024]u8 = undefined; + var at: usize = 0; + var row: u32 = 0; + var found: ?u32 = null; + while (true) { + const end = fitEnd(tab, text, at, width - displayWidth(tab, guideOf(f, text, at, width, &guide))); + if (found == null and col < end) found = row; + if (end >= text.len or end <= at) return .{ .row = found orelse row, .rows = row + 1 }; + at = end; + row += 1; + } +} + +/// Where `pane`'s view starts: a row past its line's last (the text +/// rewrapped, an edit, the layer's lines come or gone) is read as its +/// last, as the geometry's walk found it (no walk of the line a frame). +pub fn top(tab: u16, pane: *Pane) Top { + const f = &pane.file.?; + if (f.scroll_row == 0) return .{ .line = f.scroll }; + geometry(tab, pane); + return .{ .line = f.scroll, .row = pane.top_skip.row }; +} + +pub fn setTop(pane: *Pane, to: Top) void { + const f = &pane.file.?; + if (to.line != f.scroll) f.syntax_dirty = true; + f.scroll = to.line; + f.scroll_row = to.row; +} + +/// The place `n` rows below `from` (above it, `n` negative) through the +/// lines' rows, held at the text's first row and at its last line's last; +/// and the rows it moved. +pub fn walkRows(tab: u16, pane: *Pane, from: Top, n: i64) Walked { + return walkKnown(tab, pane, from, n, null); +} + +/// A line's rows its caller has walked already (show's, the cursor's +/// line): a walk reads them, not the line again. +const Known = struct { line: usize, rows: u32 }; + +const Walked = struct { to: Top, moved: i64 }; + +fn walkKnown(tab: u16, pane: *Pane, from: Top, n: i64, known: ?Known) Walked { + const last = nlines(pane.gpa, &pane.file.?) -| 1; + if (!oneRow(tab, pane)) return walkedRows(tab, pane, from, n, last, known); + const to = if (n < 0) from.line -| @abs(n) else if (from.line >= last) from.line else @min(from.line +| @abs(n), last); + const w: Walked = .{ .to = .{ .line = to }, .moved = @as(i64, @intCast(to)) - @as(i64, @intCast(from.line)) }; + if (builtin.mode == .debug) std.debug.assert(std.meta.eql(w, walkedRows(tab, pane, from, n, last, known))); + return w; +} + +fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Known) Walked { + const map = mapFresh(pane); + var t = from; + var rows = rowsOf(tab, pane, map, known, t.line); + t.row = @min(t.row, rows - 1); + var left = n; + while (left > 0) { + const room = rows - 1 - t.row; + if (left <= room) { + t.row += @intCast(left); + left = 0; + } else if (t.line >= last) { + left -= room; + t.row = rows - 1; + break; + } else { + left -= room + 1; + t.line += 1; + t.row = 0; + rows = rowsOf(tab, pane, map, known, t.line); + } + } + while (left < 0) { + if (-left <= t.row) { + t.row -= @intCast(-left); + left = 0; + } else if (t.line == 0) { + left += t.row; + t.row = 0; + break; + } else { + left += t.row + 1; + t.line -= 1; + rows = rowsOf(tab, pane, map, known, t.line); + t.row = rows - 1; + } + } + return .{ .to = t, .moved = n - left }; +} + +/// The rows from `from` down to line `line`'s first row (up to it, +/// negative), or null when it is more than `bound` rows away. +pub fn rowsTo(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 { + if (!oneRow(tab, pane)) return rowsWalked(tab, pane, from, line, bound); + const d = @as(i64, @intCast(line)) - @as(i64, @intCast(from.line)) - from.row; + const to: ?i64 = if ((line > from.line and d > bound) or (line < from.line and -d > bound)) null else d; + if (builtin.mode == .debug) std.debug.assert(std.meta.eql(to, rowsWalked(tab, pane, from, line, bound))); + return to; +} + +fn rowsWalked(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 { + const map = mapFresh(pane); + var d: i64 = -@as(i64, from.row); + var l = from.line; + while (l < line) : (l += 1) { + d += rowsOf(tab, pane, map, null, l); + if (d > bound) return null; + } + while (l > line) { + l -= 1; + d -= rowsOf(tab, pane, map, null, l); + if (-d > bound) return null; + } + return d; +} + +/// Whether `pane`'s map (the geometry) is of the view as it is now: only +/// then may a walk read a line's rows off it (derived state, made by +/// whoever asked first). +fn mapFresh(pane: *const Pane) bool { + return pane.wrap_n > 0 and pane.geometry_key == geometryKey(pane, &pane.file.?); +} + +/// The rows line `line` takes: counted off the map when the map is fresh +/// and holds all of them in the body (no line walked: a page, a cursor +/// past the body's edge), else walked (lineRows). +fn rowsOf(tab: u16, pane: *const Pane, map: bool, known: ?Known, line: usize) u32 { + if (known) |k| if (k.line == line) return k.rows; + if (map and pane.wrap_n > pane.context_rows and line >= pane.wrap_line[pane.context_rows] and line <= pane.wrap_line[pane.wrap_n - 1]) { + const f = &pane.file.?; + var rows: u32 = 0; + var i: usize = pane.context_rows; + while (i < pane.wrap_n) : (i += 1) { + if (pane.wrap_line[i] == line) { + // Rows of it above the top are not in the map. + if (rows == 0 and i == pane.context_rows and line == f.scroll and pane.top_skip.row > 0) break; + rows += 1; + } else if (rows > 0) return rows; + } + } + return lineRows(tab, pane, line); +} + +/// `pane`'s view moved `delta` rows (a wheel's notch is one): the rows it +/// moved. +pub fn scrollRows(tab: u16, pane: *Pane, delta: i64) i64 { + geometry(tab, pane); + const t = top(tab, pane); + // Down to a row the body shows: the map has it, its line and its row in + // that line, no line walked (a notch, a page). + const i = @as(i64, pane.context_rows) + delta; + if (delta > 0 and pane.wrap_n > 0 and i < shownRows(tab, pane) + @as(i64, pane.context_rows)) { + const k: usize = @intCast(i); + const line: usize = @intCast(pane.wrap_line[k]); + if (line < nlines(pane.gpa, &pane.file.?)) { + var row: u32 = if (line == t.line) t.row else 0; + for (pane.wrap_line[pane.context_rows..k]) |l| row += @intFromBool(l == pane.wrap_line[k]); + setTop(pane, .{ .line = line, .row = row }); + return delta; + } + } + const w = walkRows(tab, pane, t, delta); + setTop(pane, w.to); + return w.moved; +} + +/// The rows of `pane`'s body under its context rows, of its geometry as +/// the view is now (made again first if stale: a key's step reads it +/// before any draw, and only the state it is made of may decide it). +pub fn shownRows(tab: u16, pane: *Pane) u16 { + geometry(tab, pane); + const visible = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n; + return @max(1, if (pane.wrap_n == 0) pane.rows else visible -| pane.context_rows); +} + +/// The view moved when line `line_at`'s row that shows its byte `col` is +/// out of the body's margins (`margin_rows` rows, helix's scrolloff, at +/// most half of it): by the rows that show the line's rows whole inside +/// them, or that row where the line is taller than they leave. A cursor's +/// (Pane.ensureCursorVisible's, for a file) or a result's. +pub fn show(tab: u16, pane: *Pane, line_at: i32, col: i32, margin_rows: i64) void { + const f = &pane.file.?; + geometry(tab, pane); + const t = top(tab, pane); + // The line held at the top (a sticky context row): as it is. + if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == t.line) { + for (pane.wrap_line[0..pane.context_rows]) |row| if (row == line_at) return; + } + const body: i64 = shownRows(tab, pane); + const margin: i64 = @min(margin_rows, @divTrunc(body - 1, 2)); + // The row in the body (the map's, made just now), or none: the line is + // above the top, or below the map. Inside the band the view stays, and + // no line is walked (a key's step, nearly always). + const mapped: i64 = pane.wrapRow(tab, line_at, col).row - @as(i64, pane.context_rows); + const row: ?i64 = if (mapped >= 0 and mapped < @max(pane.wrap_n, pane.rows) -| pane.context_rows) mapped else null; + if (row) |r| if (r >= margin and r <= body - 1 - margin) return; + const line: usize = @intCast(@max(0, line_at)); + const at = rowIn(tab, pane, line, @intCast(@max(0, col))); + const known: Known = .{ .line = line, .rows = at.rows }; + if (pane.follow_edges != 0 and (row == null or row.? < 0 or row.? >= body)) pane.follow_crossed = true; + const whole = at.rows <= body - 2 * margin; + if (if (row) |r| r < margin else line <= t.line) { + if (pane.follow_edges & 1 != 0) return; + setTop(pane, walkKnown(tab, pane, .{ .line = line, .row = if (whole) 0 else at.row }, -margin, known).to); + } else if (if (row) |r| r > body - 1 - margin else true) { + if (pane.follow_edges & 2 != 0) return; + // The margin only reveals text: a pane its whole text fits in + // never scrolls for it; a longer one keeps helix's clamp at the + // text's last line. + var past = walkKnown(tab, pane, .{ .line = line, .row = if (whole) at.rows - 1 else at.row }, margin, known).to; + if (t.line == 0 and t.row == 0 and pane.textFits()) { + const stop = @max(line, nlines(pane.gpa, f) -| 1 -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))); + if (past.line > stop) past = .{ .line = stop, .row = lineRows(tab, pane, stop) - 1 }; + } + setTop(pane, walkKnown(tab, pane, past, -(body - 1), known).to); + } +} + +/// The line whose first row (no wrapped line's later row) is nearest body +/// row `from` inside the body's band (`margin` rows in from each edge, at +/// most half of it, under its context rows): the first at or below it +/// going `.down`, else the last above it; `.up` the other way round. Where +/// a view key leaves a cursor (Text.scrollViewMove, normal.halfPageMove); +/// null when the band has none (inside a line taller than the body): the +/// cursor stays. +pub fn textRowLine(tab: u16, pane: *Pane, from: i64, margin: i64, way: enum { down, up }) ?i32 { + geometry(tab, pane); + const lines: i32 = @intCast(nlines(pane.gpa, &pane.file.?)); + const held: i64 = pane.context_rows; + const shown: i64 = shownRows(tab, pane); + const m = @min(margin, @divTrunc(shown - 1, 2)); + const lo = held + m; + const hi = held + shown - 1 - m; + for ([2]i64{ if (way == .down) 1 else -1, if (way == .down) -1 else 1 }) |step| { + var vr = std.math.clamp(held + from, lo, hi); + while (vr >= lo and vr <= hi) : (vr += step) { + const w = pane.wrapAt(tab, @intCast(vr)); + if ((w.at == 0 or !pane.body_wrapped) and w.line < lines) return w.line; + } + } + return null; +} + +/// A call stack's row after its line's first starts with its tree's guide +/// (locations.treeContinuation), in `buffer`; any other row with none. +fn guideOf(f: *const State, text: []const u8, at: usize, width: usize, buffer: *[1024]u8) []const u8 { + if (at == 0 or width <= 1 or f.output == null or !std.meta.eql(f.output.?.from, Output.Origin{ .query = .callstack })) return ""; + return locations.treeContinuation(text, buffer, width - 1); } /// `pane` out of its Follow chain (Unfollow, or a chain down to it): a @@ -2131,12 +2525,12 @@ fn prepareContextRows(pane: *Pane, file: *State) void { if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return; const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row // The declarations are the file's lines; the rows, the buffer's. - const top = fileRow(file, file.scroll); + const top_line = fileRow(file, file.scroll); for (file.context.declarations) |declaration| { - if (declaration.start_line >= top) break; - if (declaration.end_line < top) continue; + if (declaration.start_line >= top_line) break; + if (declaration.end_line < top_line) continue; var line = declaration.start_line; - while (line <= declaration.header_end_line and line < top) : (line += 1) { + while (line <= declaration.header_end_line and line < top_line) : (line += 1) { if (pane.context_rows >= capacity) return; const row = bufferRow(file, line); if (pane.context_rows > 0 and row <= pane.wrap_line[pane.context_rows - 1]) continue; @@ -2186,6 +2580,11 @@ pub fn geometry(tab: u16, pane: *Pane) void { const key = geometryKey(pane, f); if (pane.geometry_key == key) return; pane.geometry_key = key; + // The key of what the map was made from: the walk brings the text's + // index and tables up to it (`line_starts`, `tables.revision`, in the + // key), and with the key from before, a step's second ask made it all + // again. + defer pane.geometry_key = geometryKey(pane, f); pane.body_rows = 0; pane.body_visible_rows = 0; pane.context_row_limit = null; @@ -2228,7 +2627,7 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 { if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0, f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len, pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h, - pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat), + pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat), f.scroll_row, }; // One hash of them laid out as words: every reader of the map asks for // this key, a hundred times a frame. @@ -2256,6 +2655,20 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State var body_line: usize = f.scroll; var body_at: usize = 0; var written: usize = 0; + var guide_buffer: [1024]u8 = undefined; + // The top line from the view's row in it (`top`): the rows above + // skipped, never past its last; walked once a geometry (the map's + // pass), its text's pass a frame starting where that walk ended. + if (record_wrap) { + var skipped: u32 = 0; + while (skipped < f.scroll_row and width > 0 and body_line < total) : (skipped += 1) { + const text = sourceLine(pane, @intCast(body_line)); + const end = fitEnd(tab, text, body_at, width - displayWidth(tab, guideOf(f, text, body_at, width, &guide_buffer))); + if (end >= text.len or end <= body_at) break; + body_at = end; + } + pane.top_skip = .{ .row = skipped, .at = body_at }; + } else body_at = pane.top_skip.at; for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| { if (i > 0) { if (dst) |out| out[written] = '\n'; @@ -2265,12 +2678,7 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State const row = if (context) @as(usize, @intCast(pane.wrap_line[i])) else body_line; const at = if (context) 0 else body_at; const text = if (row < total) sourceLine(pane, @intCast(row)) else ""; - var guide_buffer: [1024]u8 = undefined; - const guide = if (at > 0 and width > 1 and f.output != null and - std.meta.eql(f.output.?.from, Output.Origin{ .query = .callstack })) - locations.treeContinuation(text, &guide_buffer, width - 1) - else - ""; + const guide = guideOf(f, text, at, width, &guide_buffer); const pad = displayWidth(tab, guide); // Headers use one screen row per source row, preserving signatures // without allowing a long ancestor to consume the whole viewport. @@ -2709,6 +3117,11 @@ test "the ASCII run in fitEnd survives an exhaustive byte sweep" { } test "the ASCII run in fitEnd cuts where the grapheme walk would" { + const run = struct { + fn of(comptime c: u8, comptime n: usize) [n]u8 { + return @splat(c); + } + }.of; const reference = struct { fn fitEnd(text: []const u8, start: usize, width: usize) usize { var end = start; @@ -2739,6 +3152,12 @@ test "the ASCII run in fitEnd cuts where the grapheme walk would" { // an ASCII byte followed by a continuation byte is NOT its own cluster "e\u{0301}x", "\u{1f1e6}\u{1f1e7}ok", + // runs longer than a vector (the vector loop), each ending at a + // non-ASCII byte, a combining mark, a tab, or the text's end + &(run('x', 40) ++ "\u{00e9}".* ++ run('y', 40)), + &(run('a', 32) ++ "\u{0301}".* ++ run('b', 17)), + &(run('c', 47) ++ "\t".* ++ run('d', 20)), + &run('z', 100), }; for (cases) |text| { var width: usize = 0; @@ -2769,7 +3188,7 @@ test "a line index shifted in place equals a rebuilt one, and the edit turned ro const del = r.uintAtMost(usize, @min(12, text.items.len - at)); var ins: [12]u8 = undefined; const ins_len = r.uintAtMost(usize, 12); - for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)]; + for (ins[0..ins_len]) |*c| c.* = "ab\n\t"[r.uintLessThan(usize, 4)]; const before = try gpa.dupe(usize, f.line_starts); defer gpa.free(before); const cut = try gpa.dupe(u8, text.items[at..][0..del]); @@ -2781,12 +3200,18 @@ test "a line index shifted in place equals a rebuilt one, and the edit turned ro const want = try lineIndex(gpa, &fresh); defer gpa.free(want); try std.testing.expectEqualSlices(usize, want, f.line_starts); + // The kept widest is never less than the text's, made anew exact. + var widest: usize = 0; + var lines = std.mem.splitScalar(u8, text.items, '\n'); + while (lines.next()) |line| widest = @max(widest, line.len); + try std.testing.expectEqual(Widest{ .bytes = widest, .tabbed = std.mem.indexOfScalar(u8, text.items, '\t') != null }, fresh.widest); + try std.testing.expect(f.widest.bytes >= widest and (f.widest.tabbed or !fresh.widest.tabbed)); // Every tenth turned round in a copy, as a rollback takes it back. if (round % 10 == 0) { const room = try gpa.alloc(usize, indexRoom(&f).len); defer gpa.free(room); @memcpy(room[0..f.line_starts.len], f.line_starts); - shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut); + _ = shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut); try std.testing.expectEqualSlices(usize, before, room[0..before.len]); } } diff --git a/core/Output.zig b/core/Output.zig index a1e5865e..380fadb1 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -1041,6 +1041,7 @@ pub fn openErrors(p: *Pardes, id: usize, content: []u8) !void { pub fn resetBody(p: *Pardes, pane: *Pane) void { const v = p.view(); pane.file.?.scroll = 0; + pane.file.?.scroll_row = 0; pane.body.cur_row = 0; pane.body.cur_col = 0; pane.body.cur_pinned = true; diff --git a/core/Places.zig b/core/Places.zig index 1c24e992..6c3ac9ab 100644 --- a/core/Places.zig +++ b/core/Places.zig @@ -561,9 +561,12 @@ pub fn goTo(set: *Places, tab: u16, pane: *Pane, i: usize, add: bool) void { } set.current = i; set.gen +%= 1; - const off = pane.scroll(); - if (t.cur_row < off or t.cur_row >= off + @as(i32, pane.rows)) - pane.scrollBy(t.cur_row - off - @divTrunc(@as(i32, pane.rows), 2)); + // Off the view, its row half the body's rows down (as zz). + const line: usize = @intCast(@max(0, t.cur_row)); + const row = panes.File.rowOf(tab, pane, line, @intCast(@max(0, t.cur_col))); + const body: i64 = panes.File.shownRows(tab, pane); + const on = if (panes.File.rowsTo(tab, pane, panes.File.top(tab, pane), line, @intCast(body))) |d| d + row else -1; + if (on < 0 or on >= body) panes.File.setTop(pane, panes.File.walkRows(tab, pane, .{ .line = line, .row = row }, -@divTrunc(body, 2)).to); t.show(tab); } @@ -634,7 +637,7 @@ pub fn restore(set: *Places, tab: u16, pane: *Pane) void { r.head = @min(r.head, f.content.len); } pane.body.setRanges(tab, f.content, set.snap, &.{}, set.snap_pri, set.snap_expl); - f.scroll = set.snap_scroll; + panes.File.setTop(pane, .{ .line = set.snap_scroll }); f.syntax_dirty = true; pane.hscroll = set.snap_hscroll; } diff --git a/core/Query.zig b/core/Query.zig index 228cdd0e..92a3d9f2 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -344,7 +344,7 @@ pub fn toLineOne(p: *Pardes, id: usize) void { t.cur_pinned = true; rp.query.?.seen_row = 0; edit.enterInsert(p.editor(), t, .line_end, 1) catch |err| return p.reportError(.at(id), "query", err); - showCurrent(rp); + showCurrent(p.settings.tab, rp); } /// The rows' state for a new question: nothing found yet. @@ -456,7 +456,7 @@ fn makeAllRows(p: *Pardes, id: usize) !void { // The current one: the first hit row, until a step moves it. if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); countCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); } /// The names the query matches, best first, `Names.max_rows` of them: each @@ -528,7 +528,7 @@ fn makeNameRows(p: *Pardes, id: usize) !void { // The best is current until a step or a click moves it. q.current = if (shown > 0) 0 else null; countCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); if (q.current == null) blankPreview(p, id) else showTarget(p, id); } @@ -1151,7 +1151,7 @@ fn showPlacesCurrent(p: *Pardes, id: usize) void { }; // Stepped out of the window the live rows are: made again around it. if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64); - showCurrent(rp); + showCurrent(p.settings.tab, rp); } fn firstHit(q: *const Query) ?usize { @@ -1226,7 +1226,7 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { q.more = p.stream.busyFor(rp.serial); q.current = current orelse firstHit(q); countGrepCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); if (q.current == null) blankPreview(p, id) else if (!shown) showTarget(p, id); } @@ -1317,7 +1317,7 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v if (t.mode == .insert) edit.exitInsert(p.editor(), t); t.vsel.active = false; t.nsel = 0; - caretTo(rp, q.current orelse 0); + caretTo(p.settings.tab, rp, q.current orelse 0); showTarget(p, qid); } @@ -1438,7 +1438,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { } } countCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); } // ---- the current row ---- @@ -1447,7 +1447,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { /// elsewhere, line 1 kept when it can be. Its mark is `paint`'s, drawn /// from `current`: no selection, so no click, sweep or chord clears it and /// no B2 or B3 borrows it. -fn showCurrent(rp: *Pane) void { +fn showCurrent(tab: u16, rp: *Pane) void { const q = rp.query orelse return; if (rp.body.cur_row != 0 and rp.focus == .body) return; const c = q.current orelse return; @@ -1455,24 +1455,19 @@ fn showCurrent(rp: *Pane) void { // Typed into, line 1 stays in view whatever the current row: what you // type is never scrolled away (the live rows start just before the // current one, so it sits under line 1). Frozen, the row is scrolled to. - if (!q.frozen) { - if (rp.scroll() != 0) rp.scrollBy(-rp.scroll()); - return; - } - const off = rp.scroll(); - const shown = off + @as(i32, rp.rows) - 1; - if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); + if (rp.file == null) return; + if (!q.frozen) return panes.File.setTop(rp, .{ .line = 0 }); + panes.File.show(tab, rp, r, 0, 0); } /// The caret on item `i`'s row, the row in view. -fn caretTo(rp: *Pane, i: usize) void { +fn caretTo(tab: u16, rp: *Pane, i: usize) void { const r: i32 = @intCast(i + 1); rp.body.cur_row = r; rp.body.cur_col = 0; rp.body.cur_pinned = true; rp.query.?.seen_row = r; - const off = rp.scroll(); - if (r >= off + @as(i32, rp.rows)) rp.scrollBy(r - off - @as(i32, rp.rows) + 1) else if (r < off) rp.scrollBy(r - off); + if (rp.file != null) panes.File.show(tab, rp, r, 0, 0); } /// The first of pane `tp`'s places on line `line` (1-based), if any. @@ -1503,7 +1498,7 @@ fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q); } else countCurrent(q); } else countCurrent(q) else countCurrent(q); - showCurrent(rp); + showCurrent(p.settings.tab, rp); if (show) showTarget(p, id); } @@ -1562,6 +1557,7 @@ fn blankPreview(p: *Pardes, qid: usize) void { File.setContent(p, f, empty); f.saved_revision = f.revision; f.scroll = 0; + f.scroll_row = 0; } /// Where the current row points, shown with the keyboard left where it is: @@ -1679,6 +1675,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void File.setContent(p, f, bytes); f.saved_revision = f.revision; f.scroll = 0; + f.scroll_row = 0; f.syntax_dirty = true; pane.hscroll = 0; // another file: its own places, found below @@ -1688,6 +1685,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void look.clearNavigationSelection(p, pane); if (at.line == 0 or at.line > File.nlines(p.gpa, f)) { f.scroll = 0; + f.scroll_row = 0; f.syntax_dirty = true; pane.body.cur_row = 0; pane.body.cur_col = 0; @@ -1907,7 +1905,7 @@ pub fn cancel(p: *Pardes, id: usize) void { q.frozen = true; rp.body.cur_row = 0; rp.body.cur_col = 0; - showCurrent(rp); + showCurrent(p.settings.tab, rp); // Its places again, as Enter left them. if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| { const owner = p.panes[oid].?; @@ -1973,7 +1971,7 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { // The caret on the rows goes to the current row, as j and k // would have taken it there. if (t.cur_row != 0) if (q.current) |c| { - caretTo(rp, c); + caretTo(p.settings.tab, rp, c); }; return true; } diff --git a/core/Text.zig b/core/Text.zig index 54d69a74..ba544bff 100644 --- a/core/Text.zig +++ b/core/Text.zig @@ -339,10 +339,19 @@ pub fn scrollViewMove(t: *Text, tab: u16, text: []const u8, range: modal.Selecti if (t.what != .body) return; const w = t.pane() orelse return; const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2)); - w.scrollBy(delta); + w.scrollBy(tab, delta); const top = w.scroll(); const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); const cur = modal.selectionCursor(text, range); + // A file's rows are not its lines: a line's first row at the margin, + // none (inside a line taller than the body) leaving the cursor be. + if (w.file != null) { + const snap = File.textRowLine(tab, w, if (delta > 0) margin else File.shownRows(tab, w) - 1 - margin, margin, if (delta > 0) .down else .up) orelse return; + const head = File.textLineStart(t, text, @intCast(snap)); + if (if (delta > 0) head <= cur else head >= cur) return; + const anchor = if (t.select) range.anchor else head; + return setRange(t, tab, text, 0, .{ .anchor = anchor, .head = head }, false); + } if (delta > 0) { const snap: i32 = @max(0, @min(top + margin, last_row)); const head = File.textLineStart(t, text, @intCast(snap)); diff --git a/core/draw.zig b/core/draw.zig index 5263f7bf..ff76aa75 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -111,7 +111,8 @@ pub fn place(p: *Pardes, s: *Surface) void { // path, a generated text's revision with it (rows rewritten as its // view moved are another text's); none for a terminal or a picture. const doc: u64 = if (pane.file) |f| std.hash.Wyhash.hash(if (f.output != null) f.revision else 0, f.path) else 0; - s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .doc = doc, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); + const row: u32 = if (pane.file != null) panes.File.top(p.settings.tab, pane).row else 0; + s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .row = row, .doc = doc, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } }; // A kind's rail is its paint's (drawPane); every other pane's is // here. diff --git a/core/jj.zig b/core/jj.zig index 176ead49..c1d07662 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -3306,6 +3306,179 @@ test "a description is whole, its title and its author never cut: in a pane narr } } +/// 60 numbered lines, line 20 of 130 numbered words (12 rows or more at +/// 60 columns), and a change to line 40 whose title wraps over several +/// rows: the rows a view scrolls through, the layer's description among +/// them. +const Tall = struct { + const title = "a title long enough to wrap: the description of this change says what it does and why at some length, " ++ + "and then says it again in other words, and once more, so that no pane of sixty columns holds it in fewer than four rows " ++ + "beside its author and its age"; + + fn repo(gpa: std.mem.Allocator) !?Repo { + var base: std.ArrayList(u8) = .empty; + defer base.deinit(gpa); + var changed: std.ArrayList(u8) = .empty; + defer changed.deinit(gpa); + for (0..60) |i| { + const from = base.items.len; + if (i == 20) { + for (0..130) |w| try base.print(gpa, "t{d:0>3} ", .{w}); + try base.append(gpa, '\n'); + } else try base.print(gpa, "line {d:0>2}\n", .{i}); + try changed.appendSlice(gpa, if (i == 40) "line 40 changed\n" else base.items[from..]); + } + return Repo.with(gpa, &.{ .{ base.items, "base" }, .{ changed.items, title } }, null); + } + + /// The buffer's line the description is. + fn description(f: *const File.State) !usize { + for (f.layer.lines) |l| if (std.mem.indexOf(u8, f.content[l.at..][0..l.len], title[0..20]) != null) + return std.mem.count(u8, f.content[0..l.at], "\n"); + return error.NoDescription; + } + + /// The rows of the text above line `line`'s row that shows its byte + /// `col`, in `pane`'s view. + fn rowsAbove(tab: u16, pane: *Pane, line: usize, col: usize) usize { + var n: usize = File.rowOf(tab, pane, line, col); + for (0..line) |l| n += File.lineRows(tab, pane, l); + return n; + } +}; + +test "a view scrolls by rows through a line wrapped over 12 rows and a change's description wrapped over several (a line of the layer): a wheel's notch is one row down the whole text and back, PageDown and PageUp a page of rows, zj and zk one; a held j and k keep the cursor's row three rows inside the body" { + const gpa = testing.allocator; + var repo = try Tall.repo(gpa) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false }); + defer p.deinit(); + const tab = p.settings.tab; + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + p.update(.{ .command = "Changes @-" }); + p.sync(); + const f = &pane.file.?; + try testing.expect(File.lineRows(tab, pane, 20) >= 12); + try testing.expect(File.lineRows(tab, pane, try Tall.description(f)) >= 4); + var total: usize = 0; + for (0..File.nlines(gpa, f)) |l| total += File.lineRows(tab, pane, l); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const shot = struct { + fn of(q: *Pardes, w: *Pane, a: std.mem.Allocator) ![]const []const u8 { + return Ghosts.rows(q, w, a, try a.alloc([]const u8, 256)); + } + }.of; + const rect = p.view().rects[id]; + const at = .{ .col = rect.x + 10, .row = p.bodyTop(pane, rect) + 5 }; + const notch = struct { + fn of(down: bool, x: u16, y: u16) pardes.Event { + return .{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, .col = x, .row = y } }; + } + }.of; + // Every row of the text at the body's top in turn, a notch each: the + // body's rows one up. + var was = try shot(p, pane, arena.allocator()); + const kept = was.len - 1; + var all: std.ArrayList([]const u8) = .empty; + try all.append(arena.allocator(), was[0]); + while (true) { + p.update(notch(true, at.col, at.row)); + const now = try shot(p, pane, arena.allocator()); + if (std.mem.eql(u8, now[0], was[0])) break; + for (now[0 .. kept - 1], was[1..kept]) |n, w| try testing.expectEqualStrings(w, n); + try all.append(arena.allocator(), now[0]); + was = now; + } + try testing.expectEqual(total, all.items.len); + // And back up, a row a notch. + var back = all.items.len - 1; + while (back > 0) : (back -= 1) { + p.update(notch(false, at.col, at.row)); + const now = try shot(p, pane, arena.allocator()); + try testing.expectEqualStrings(all.items[back - 1], now[0]); + for (now[1..kept], was[0 .. kept - 1]) |n, w| try testing.expectEqualStrings(w, n); + was = now; + } + const indexOf = struct { + fn in(rows: []const []const u8, row: []const u8) usize { + for (rows, 0..) |r, i| if (std.mem.eql(u8, r, row)) return i; + return rows.len; + } + }.in; + // PageDown and PageUp: a page of rows each, the text's last row at the + // top the furthest. + var top: usize = 0; + while (top < all.items.len - 1) { + p.update(.{ .key = .{ .cp = pardes.Key.page_down } }); + top = @min(top + pane.rows, all.items.len - 1); + try testing.expectEqual(top, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0])); + } + while (top > 0) { + p.update(.{ .key = .{ .cp = pardes.Key.page_up } }); + top -|= pane.rows; + try testing.expectEqual(top, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0])); + } + // zj and zk: a row each, through line 20's rows and the description's. + for (0..all.items.len - 1) |n| { + for ("zj") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); + try testing.expectEqual(n + 1, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0])); + } + for (0..all.items.len - 1) |n| { + for ("zk") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); + try testing.expectEqual(all.items.len - 2 - n, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0])); + } + // A held j from the first line to the last and a held k back: the + // cursor's row three rows (`scroll_off`) inside the body's edges, or + // as far as the text before or after it goes. + p.update(.{ .command = "Look a.zig:1" }); + const body = File.shownRows(tab, pane); + for ("jk") |cp| for (0..total) |_| { + p.update(.{ .key = .{ .cp = cp, .text = &[_]u8{cp} } }); + const t = File.top(tab, pane); + const cur = Tall.rowsAbove(tab, pane, @intCast(pane.body.cur_row), @intCast(pane.body.cur_col)); + const on = cur - Tall.rowsAbove(tab, pane, t.line, 0) - t.row; + try testing.expect(on >= @min(pardes.config.scroll_off, cur)); + try testing.expect(on <= body - 1 - @min(pardes.config.scroll_off, total - 1 - cur)); + }; +} + +test "a client wheels its session's view a row a notch into a change's description wrapped over several rows (a line of the layer), agreeing with the session at every notch; a client joined over that view loads its row" { + var repo = try Tall.repo(testing.allocator) orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + const R = pardes.replica; + const a = try R.Authority.init(testing.allocator, .{ .cols = 60, .rows = 24 }, .{}); + defer a.deinit(); + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); + defer r.deinit(); + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) })); + r.confirm(try a.local(.{ .command = "Changes @-" })); + r.settle(); + const id = a.core.view().active; + const af = &a.core.panes[id].?.file.?; + const desc = try Tall.description(af); + const rect = a.core.view().rects[id]; + const notch: pardes.Event = .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } }; + var n: usize = 0; + while (af.scroll != desc or af.scroll_row != 2) : (n += 1) { + if (n > 300) return error.NeverThere; + const m = try testing.allocator.dupe(u8, try r.input(notch)); + defer testing.allocator.free(m); + r.confirm(try a.take(m)); + r.settle(); + try testing.expect(r.diverged == null); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); + const rf = &r.core().panes[id].?.file.?; + try testing.expectEqual(af.scroll, rf.scroll); + try testing.expectEqual(af.scroll_row, rf.scroll_row); + } + try R.loadsAsSession(a, 2); +} + test "at one place a change's ghost rows come before its description: a line it changed and the next it took away, then its description" { const gpa = testing.allocator; const fn_text = "fn f() void {\n a();\n b();\n c();\n d();\n}\n"; diff --git a/core/look.zig b/core/look.zig index b240b6e2..f60b90f5 100644 --- a/core/look.zig +++ b/core/look.zig @@ -423,9 +423,7 @@ pub fn jumpResult(p: *Pardes, id: usize, row: usize) bool { rp.body.nsel = 0; rp.body.cur_row = r; rp.body.cur_pinned = true; - const off = rp.scroll(); - const last = off + @as(i32, rp.rows) - 1; - if (r < off) rp.scrollBy(r - off) else if (r > last) rp.scrollBy(r - last); + if (rp.file != null) panes.File.show(p.settings.tab, rp, r, 0, 0); var realbuf: [4096]u8 = undefined; const span = if (tr.commands) wholeRowSpan(ln) @@ -744,14 +742,9 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at_in: Spot, landing: enum { center, }; if (pane.file) |*f| { if (at.line > panes.File.nlines(p.gpa, f)) return; - if (landing == .center) { - // center, clamp at top; a text that fits is shown whole - const next = if (pane.textFits()) 0 else (at.line - 1) -| pane.rows / 2; - if (next != f.scroll) { - f.scroll = next; - f.syntax_dirty = true; - } - } + // centred (its first row of text half the body's rows down, as + // zz), clamped at the top; a text that fits is shown whole + if (landing == .center) panes.File.setTop(pane, if (pane.textFits()) .{ .line = 0 } else panes.File.walkRows(p.settings.tab, pane, .{ .line = at.line - 1, .row = panes.File.rowOf(p.settings.tab, pane, at.line - 1, 0) }, -@as(i64, pane.rows / 2)).to); } pane.body.cur_row = @intCast(at.line - 1); pane.body.cur_col = if (at.col > 0) @intCast(at.col - 1) else 0; @@ -2195,6 +2188,7 @@ test "Look on a diff: headers and a hunk line's prefix are the whole line, hover // Back to the diff, scrolled to its top again. p.view().active = 0; pane.file.?.scroll = 0; + pane.file.?.scroll_row = 0; p.sync(); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); @@ -2268,6 +2262,7 @@ test "a click, a 9P whole-line look and an empty event write-back take one expan for (points) |at| { p.view().active = 0; pane.file.?.scroll = 0; + pane.file.?.scroll_row = 0; pane.body.cur_row = 0; p.sync(); _ = frame.reset(.retain_capacity); @@ -2344,6 +2339,7 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5 pane.body.cur_col = case.col; pane.body.cur_pinned = true; pane.file.?.scroll = 0; + pane.file.?.scroll_row = 0; p.sync(); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); diff --git a/core/mouse.zig b/core/mouse.zig index 2d731acf..14700995 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -702,7 +702,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { const id = hovered orelse return; const pane = p.panes[id].?; if (!programWheel(p, id, m, mcol, mrow)) - pane.scrollBy(if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows); + pane.scrollBy(p.settings.tab, if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows); }, .wheel_left, .wheel_right => { if (m.kind != .press) return; @@ -779,7 +779,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { return pane.places.goTo(p.settings.tab, pane, i, false); }; // gutter scrollbar: a left click scrolls UP to that row - pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); + pane.scrollBy(p.settings.tab, -(@as(i32, mrow) - @as(i32, body_y))); } else { const on_tag = mrow >= tag_y and mrow < tag_y + pane.tag_rows; if (on_tag and mcol < r.x + TAG_TEXT_INSET) return; @@ -847,7 +847,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { if (mcol < r.x + config.GUTTER and !on_tag) { const local = @as(i32, mrow) - @as(i32, body_y); if (m.button == config.look_button) v.active = id; - pane.scrollBy(if (m.button == config.look_button) local else -local); + pane.scrollBy(p.settings.tab, if (m.button == config.look_button) local else -local); } else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, v.pointer_tag_hit)) |pointed| { if (m.button == config.look_button) v.active = id; pane.clearPointerSelection(@backingInt(m.button)); @@ -1150,11 +1150,15 @@ pub fn edgeScroll(p: *Pardes) void { const sl = &pane.sel[sel_slot]; if (s.anchor == null) s.anchor = sweepPoint(p, pane, sl.r0, sl.c0) orelse return; const before = pane.scroll(); - pane.scrollBy(s.edge); + // A file's view moves by rows (File.Top), a terminal's rows are lines. + const moved: i64 = if (pane.file != null) panes.File.scrollRows(p.settings.tab, pane, s.edge) else blk: { + pane.scrollBy(p.settings.tab, s.edge); + break :blk pane.scroll() - before; + }; // The start's row follows its text while it is on the screen, and // stays on the body's edge row once it is off (the anchor keeps it). const top: i32 = pane.tag_rows; - sl.r0 = std.math.clamp(sl.r0 - (pane.scroll() - before), top, top + @as(i32, pane.rows) - 1); + sl.r0 = std.math.clamp(sl.r0 - @as(i32, @intCast(moved)), top, top + @as(i32, pane.rows) - 1); } /// The text position under a body cell of the sweep's space. diff --git a/core/ninep/events.zig b/core/ninep/events.zig index f1e17324..e18b5d96 100644 --- a/core/ninep/events.zig +++ b/core/ninep/events.zig @@ -1406,14 +1406,14 @@ test "a click in the body reports the offsets of the word it takes, so the recor }) |c| for ([_]pardes.Mouse.Button{ config.look_button, config.exec_button }, [_][]const u8{ c.look, c.exec }) |button, want| { // The pointer rests on the word first, as a hand's does, and // the hover preview comes up under it. - p.panes[id].?.scrollBy(c.scroll); + p.panes[id].?.scrollBy(p.settings.tab, c.scroll); _ = try p.render(frame.allocator()); p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = c.x, .row = c.y } }); for (0..200) |_| p.update(.tick); p.update(.{ .mouse = .{ .button = button, .kind = .press, .col = c.x, .row = c.y } }); p.update(.{ .mouse = .{ .button = button, .kind = .release, .col = c.x, .row = c.y } }); try testing.expectEqualStrings(want, call(p, .{ .tag = 2, .op = .read, .node = event, .handle = h, .size = 256 }).bytes); - p.panes[id].?.scrollBy(-c.scroll); + p.panes[id].?.scrollBy(p.settings.tab, -c.scroll); }; // A click on nothing expands to nothing, and acme then says // nothing (look.c:37, exec.c:141). diff --git a/core/normal.zig b/core/normal.zig index 89fd72f6..61f8f26b 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -946,14 +946,31 @@ fn verticalMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, do t.sticky_col = @intCast(goal); } -/// Ctrl-d/u: scroll half a page AND move the cursor by the same rows +/// Ctrl-d/u: the view half the body's rows on, and the cursor where it +/// stood on the screen (inside the margins): on the line whose first row is +/// now there, the next one the way it went past a wrapped line's later +/// row, and the rows the view could not move (the text's end) further. +/// None in the body (inside a line taller than it): it stays, off the +/// view, and the view where it went. A terminal's rows are its lines: both +/// move by them. fn halfPageMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, down: bool) void { // a view to move through is a body's; a tag or an answer is all shown if (t.what != .body) return; const w = t.pane() orelse return; const half: i32 = @max(1, @divTrunc(@as(i32, w.rows), 2)); - w.scrollBy(if (down) half else -half); - verticalMove(tab, t, text, range, down, @intCast(half), 0); + if (w.file == null) { + w.scrollBy(tab, if (down) half else -half); + return verticalMove(tab, t, text, range, down, @intCast(half), 0); + } + const body: i64 = File.shownRows(tab, w); + const margin = @min(config.scroll_off, @divTrunc(body - 1, 2)); + const from = File.top(tab, w); + const line: usize = @intCast(@max(0, t.cur_row)); + const on: i64 = if (File.rowsTo(tab, w, from, line, @intCast(body))) |d| d + File.rowOf(tab, w, line, @intCast(@max(0, t.cur_col))) else if (line < from.line) 0 else body - 1; + const moved = File.scrollRows(tab, w, if (down) half else -half); + const to = File.textRowLine(tab, w, on + (if (down) half else -half) - moved, margin, if (down) .down else .up) orelse return; + if (to == t.cur_row) return; + verticalMove(tab, t, text, range, to > t.cur_row, @abs(to - t.cur_row), 0); } /// gt/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window) @@ -1235,13 +1252,28 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! // helix align_view: the cursor's row goes `above` rows down the // view, the middle of an odd one and the upper middle of an even one .view_top, .view_center, .view_bottom => if (t.what == .body) { - const above: i32 = switch (a.role) { - .view_top => 0, - .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2), - else => @as(i32, pane.rows) - 1, - }; - pane.scrollBy(t.cur_row - (pane.scroll() + above)); - pane.ensureCursorVisible(p.settings.tab); + // In rows: zt shows the cursor's line from its first row, a + // line taller than the body from the cursor's. + const tab = p.settings.tab; + if (pane.file == null) { + const above: i32 = switch (a.role) { + .view_top => 0, + .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2), + else => @as(i32, pane.rows) - 1, + }; + pane.scrollBy(tab, t.cur_row - (pane.scroll() + above)); + } else { + const body: i64 = File.shownRows(tab, pane); + const line: usize = @intCast(@max(0, t.cur_row)); + const row = File.rowOf(tab, pane, line, @intCast(@max(0, t.cur_col))); + const at: File.Top = .{ .line = line, .row = if (a.role == .view_top and row < body) 0 else row }; + File.setTop(pane, File.walkRows(tab, pane, at, switch (a.role) { + .view_top => 0, + .view_center => -@divTrunc(body - 1, 2), + else => -(body - 1), + }).to); + } + pane.ensureCursorVisible(tab); }, // helix align_view_middle: the cursor's column to the middle of an // unwrapped view diff --git a/core/panes.zig b/core/panes.zig index 02ee805f..b238992a 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -31,7 +31,7 @@ pub const Pane = struct { /// it (views.zig). (The 9P server's part of `fs` says so in its type.) pub const replica = .{ .local = .{ "pv", "pv_known" }, - .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan" }, + .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "top_skip", "notices", "pan" }, .len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, // A picture's memory is its own allocator's (a dump loaded makes // it there). @@ -309,6 +309,10 @@ pub const Pane = struct { wrap_n: u16 = 0, /// A row map also exists for sticky headers when soft wrapping is off. body_wrapped: bool = false, + /// Where the geometry's walk found the view's top inside its line's + /// rows (File.Top): the row it is and the bytes of the line before it; + /// a frame's text starts there with no walk again. + top_skip: struct { row: u32 = 0, at: usize = 0 } = .{}, context_rows: u16 = 0, body_rows: u16 = 0, body_visible_rows: u16 = 0, @@ -636,15 +640,11 @@ pub const Pane = struct { return .{ .row = -1, .at = 0 }; } - pub fn scrollBy(pane: *Pane, delta: i32) void { - if (pane.file) |*f| { - const max: i64 = @intCast(File.nlines(pane.gpa, f) -| 1); - const n = std.math.clamp(@as(i64, @intCast(f.scroll)) + delta, 0, max); - const next: usize = @intCast(n); - if (next != f.scroll) { - f.scroll = next; - f.syntax_dirty = true; - } + /// The view moved `delta` rows: a file's through its lines' wrapped + /// rows (File.Top), a terminal's through its history. + pub fn scrollBy(pane: *Pane, tab: u16, delta: i32) void { + if (pane.file != null) { + _ = File.scrollRows(tab, pane, delta); } else if (pane.addon == null) { // the vt scrolls in SHELL rows; convert through the edit buffer. // The alternate screen has no history (ghostty's scrolls none): @@ -669,42 +669,14 @@ pub const Pane = struct { pub fn ensureCursorVisible(pane: *Pane, tab: u16) void { File.geometry(tab, pane); - const off = pane.scroll(); - var in_context = false; - // The map is the view's as it is now (File.geometry): an ancestor is - // pinned only in the view it was found for. - if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == off) { - for (pane.wrap_line[0..pane.context_rows]) |row| { - if (row == pane.body.cur_row) { - in_context = true; - break; - } - } - } - // Scrolloff is measured in the ordinary body, excluding sticky rows. - var margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2)); - var last = off + @as(i32, pane.rows) - 1; - const visible_rows = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n; - if (pane.context_rows < visible_rows) { - const lines_shown = pane.wrap_line[visible_rows - 1] - pane.wrap_line[pane.context_rows]; - last = off + lines_shown; - margin = @min(margin, @divTrunc(@max(0, lines_shown), 2)); - } - if (!in_context) { - if (pane.follow_edges != 0 and (pane.body.cur_row < off or pane.body.cur_row > last)) pane.follow_crossed = true; + if (pane.file != null) File.show(tab, pane, pane.body.cur_row, pane.body.cur_col, config.scroll_off) else { + // A terminal's rows are its lines. + const off = pane.scroll(); + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2)); + const last = off + @as(i32, pane.rows) - 1; if (pane.body.cur_row < off + margin) { - if (pane.follow_edges & 1 == 0) pane.scrollBy(pane.body.cur_row - margin - off); - } else if (pane.body.cur_row > last - margin and pane.follow_edges & 2 == 0) { - var to = pane.body.cur_row + margin; - if (pane.file) |*f| { - // The margin only reveals text: a pane its whole text - // fits in never scrolls for it. A longer one keeps - // helix's clamp at the buffer's last line. - const lines: i32 = @intCast(File.nlines(pane.gpa, f)); - to = @min(to, if (off == 0 and pane.textFits()) @max(pane.body.cur_row, lines - 1 - @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) else lines - 1); - } - pane.scrollBy(@max(0, to - last)); - } + pane.scrollBy(tab, pane.body.cur_row - margin - off); + } else if (pane.body.cur_row > last - margin) pane.scrollBy(tab, pane.body.cur_row + margin - last); } if (pane.file) |f| { if (pane.body_wrapped) return; diff --git a/core/replica.zig b/core/replica.zig index 57dd4eed..f62cd629 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -4491,6 +4491,160 @@ test "bytes: a client's wheel over a terminal is its own view's: applied at once try std.testing.expect(placeIn(b.r.core(), b.r.view, id).? < back); } +test "a view's top is a line and a row of its block: a client's wheel into a line wrapped over rows moves it a row a notch, the session agrees through a rollback, and a dump keeps the row" { + const gpa = std.testing.allocator; + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + // Line 3 is 60 words: four rows at this width. + for (0..40) |i| if (i == 3) { + for (0..60) |w| try text.print(gpa, "w{d:0>3} ", .{w}); + try text.append(gpa, '\n'); + } else try text.print(gpa, "line {d}\n", .{i}); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); + defer a.deinit(); + const was = Stepping.begin(&a.t, null); + _ = try a.core.setTestFile(text.items); + was.end(); + _ = try a.unit(0, 0); + const id = a.core.view().active; + // A client joined from the session's dump: the text is in it. + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + const rect = a.core.view().rects[id]; + const notch: pardes.Event = .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } }; + // Three notches to line 3's first row, two into its block. + for (0..5) |_| { + const m = try gpa.dupe(u8, try r.input(notch)); + defer gpa.free(m); + r.confirm(try a.take(m)); + r.settle(); + try agrees(a, r); + } + for ([_]*Pardes{ a.core, r.core() }) |core| { + try std.testing.expectEqual(@as(usize, 3), core.panes[id].?.file.?.scroll); + try std.testing.expectEqual(@as(u32, 2), core.panes[id].?.file.?.scroll_row); + } + // A notch of the client's on top of the session's own key (one that + // leaves the view be): the copy put back, the notch applied over it. + const again = try gpa.dupe(u8, try r.input(notch)); + defer gpa.free(again); + r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } })); + r.settle(); + r.confirm(try a.take(again)); + r.settle(); + try agrees(a, r); + try std.testing.expectEqual(@as(u32, 3), r.core().panes[id].?.file.?.scroll_row); + // A client joining over the view scrolled into the block has the row. + const late = try joinedNow(a, 2, 0); + defer late.deinit(); + try agrees(a, late); + try std.testing.expectEqual(@as(u32, 3), late.core().panes[id].?.file.?.scroll_row); + // The client's view keys, each after the session drew (its geometry + // made for the frame; the client's is not): what a key reads of the + // body's rows is made of the state alone (the soak's divergence at a + // Ctrl-b, before File.shownRows laid the geometry out first). + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + for ([_]pardes.Key{ .{ .cp = 'b', .ctrl = true }, .{ .cp = 'f', .ctrl = true }, .{ .cp = 'd', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'e', .ctrl = true } }) |k| { + for (0..3) |_| { + { + const drew = Stepping.begin(&a.t, null); + defer drew.end(); + _ = try a.core.render(arena.allocator()); + } + const m = try gpa.dupe(u8, try r.input(.{ .key = k })); + defer gpa.free(m); + r.confirm(try a.take(m)); + r.settle(); + try agrees(a, r); + } + } + // A session's dump keeps the row. + const bytes = try pardes.dump.dumpBytes(a.core); + defer gpa.free(bytes); + const loaded = try pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, bytes, null); + defer loaded.deinit(); + try std.testing.expectEqual(walk.digest(Pardes, a.core), walk.digest(Pardes, loaded)); + try std.testing.expectEqual(a.core.panes[id].?.file.?.scroll_row, loaded.panes[id].?.file.?.scroll_row); +} + +test "a text's views under random orders of the session's and a client's keys, wheels and draws, keys of the session's between a client's and its confirm (rollbacks): every side agrees (an explorer of a view's rows)" { + const gpa = std.testing.allocator; + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + // Lines of one row and of several (wrapped at 80 columns). + for (0..120) |i| if (i % 7 == 3) { + for (0..20 + i % 40) |w| try text.print(gpa, "w{d:0>3} ", .{w}); + try text.append(gpa, '\n'); + } else try text.print(gpa, "line {d}\n", .{i}); + const keys = [_]pardes.Key{ + .{ .cp = 'j', .text = "j" }, .{ .cp = 'k', .text = "k" }, + .{ .cp = 'w', .text = "w" }, .{ .cp = 'b', .text = "b" }, + .{ .cp = 'b', .ctrl = true }, .{ .cp = 'f', .ctrl = true }, + .{ .cp = 'd', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, + .{ .cp = 'G', .text = "G" }, .{ .cp = 'z', .text = "z" }, + .{ .cp = 't', .text = "t" }, .{ .cp = 'i', .text = "i" }, + .{ .cp = 'x', .text = "x" }, .{ .cp = pardes.Key.escape }, + .{ .cp = '/', .text = "/" }, .{ .cp = pardes.Key.enter }, + }; + for (0..view_orders) |seed| { + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); + defer a.deinit(); + const was = Stepping.begin(&a.t, null); + _ = try a.core.setTestFile(text.items); + was.end(); + _ = try a.unit(0, 0); + const id = a.core.view().active; + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + const opened = try a.openView(1); + r.view = opened.view; + r.confirm(opened.unit); + r.settle(); + try agrees(a, r); + var prng: std.Random.DefaultPrng = .init(seed); + const rand = prng.random(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + for (0..150) |_| { + const rect = a.core.views[r.view].?.rects[id]; + const at = .{ .col = rect.x + 10, .row = rect.y + rect.h / 2 }; + const ev: pardes.Event = switch (rand.uintLessThan(u8, 10)) { + 0 => .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = at.col, .row = at.row } }, + 1 => .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = at.col, .row = at.row } }, + else => .{ .key = keys[rand.uintLessThan(usize, keys.len)] }, + }; + if (rand.boolean()) { + const drew = Stepping.begin(&a.t, null); + defer drew.end(); + _ = arena.reset(.retain_capacity); + _ = try a.core.render(arena.allocator()); + } + if (rand.uintLessThan(u8, 4) == 0) _ = r.draw(.{ .ctx = null, .f = null }); + if (rand.uintLessThan(u8, 3) == 0) { + // The session's own key, then nothing of the client's. + r.confirm(try a.local(.{ .key = keys[rand.uintLessThan(usize, keys.len)] })); + r.settle(); + } else { + const m = try gpa.dupe(u8, try r.input(ev)); + defer gpa.free(m); + // Sometimes the session's own key first: the client's + // applied at once is rolled back and replayed. + if (rand.uintLessThan(u8, 3) == 0) { + r.confirm(try a.local(.{ .key = keys[rand.uintLessThan(usize, keys.len)] })); + r.settle(); + } + r.confirm(try a.take(m)); + r.settle(); + } + agrees(a, r) catch |err| { + std.debug.print("seed {d}: diverged\n", .{seed}); + return err; + }; + } + } +} + /// Seeds of the explorer below a run of the suite takes; 3,000 were run /// once (reports/pardes-term-join-10.md). const view_orders = 30; diff --git a/core/rollback.zig b/core/rollback.zig index 61fb7b89..2702594c 100644 --- a/core/rollback.zig +++ b/core/rollback.zig @@ -249,7 +249,8 @@ pub const Epoch = struct { const cut = e.taken.items[w.at..][0..w.cut]; if (w.index) { const room = @as([*]usize, @ptrFromInt(w.addr))[0..w.room]; - pardes.panes.File.shiftStarts(room, w.len, w.was, w.off, w.ins, cut); + // The text's widest is the copy's, put back with it. + _ = pardes.panes.File.shiftStarts(room, w.len, w.was, w.off, w.ins, cut); } else { const room = @as([*]u8, @ptrFromInt(w.addr))[0..w.room]; const tail = w.len - w.off - w.ins; diff --git a/core/root.zig b/core/root.zig index 773c7588..7056935d 100644 --- a/core/root.zig +++ b/core/root.zig @@ -751,10 +751,10 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, .{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" }, - .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state; a tab change resets the key" }, + .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len top_skip", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state; a tab change resets the key" }, .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, - .{ "File.zig", "cap line_starts line_cap", "the text's line index, of its bytes" }, + .{ "File.zig", "cap line_starts line_cap widest", "the text's line index, of its bytes, and the widest line it found (an upper bound: which walk answers, never what)" }, .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest; what a step asks a worker to paint is never decided by them, Stream.paintRows)" }, .{ "File.zig", "allocator", "ContextCache's: what its declarations were made with, the parse's or a load's (a machine's handle, no state)" }, .{ "File.zig", "declarations", "ContextCache's: the text's at its revision (dumped, digested), parsed again from the text at a load" }, diff --git a/core/surface.zig b/core/surface.zig index 5b381958..98696721 100644 --- a/core/surface.zig +++ b/core/surface.zig @@ -130,9 +130,11 @@ pub const Region = struct { /// A notice's index in its pane's `notices`. notice: u8 = 0, /// A body's view: the first line it shows (a file's scroll, a - /// terminal's grid offset), and the text it shows (`draw.place`'s doc: + /// terminal's grid offset) and which of that line's wrapped rows its + /// first row is (File.Top), and the text it shows (`draw.place`'s doc: /// 0 for a terminal or a picture), which a frontend's glide follows. line: i32 = 0, + row: u32 = 0, doc: u64 = 0, /// A body drawn as a strip of pictures (a PDF): how far down the strip /// it shows, in pixels. Its placements are laid at the whole pixel; a diff --git a/core/views.zig b/core/views.zig index f414eb6c..4f2d5744 100644 --- a/core/views.zig +++ b/core/views.zig @@ -63,9 +63,11 @@ pub const PaneView = struct { follow_scroll: usize = 0, scrolled_to: ?usize = null, body: Part(Text, &body_fields) = .{}, - /// A document's scroll and size; a terminal's size is its pty's, which - /// every view shows (sized by its last typist, `Pardes.sync`). + /// A document's scroll (its top: File.Top) and size; a terminal's size + /// is its pty's, which every view shows (sized by its last typist, + /// `Pardes.sync`). scroll: usize = 0, + scroll_row: u32 = 0, cols: u16 = 1, rows: u16 = 1, @@ -252,7 +254,10 @@ fn extract(pane: *const Pane) PaneView { var v: PaneView = .{ .cols = pane.cols, .rows = pane.rows }; copy(&pane_fields, &v, pane); copy(&body_fields, &v.body, &pane.body); - if (pane.file) |f| v.scroll = f.scroll; + if (pane.file) |f| { + v.scroll = f.scroll; + v.scroll_row = f.scroll_row; + } return v; } @@ -269,6 +274,7 @@ fn apply(pane: *Pane, v: *const PaneView) void { // brought back inside it. const lines = File.nlines(pane.gpa, f); f.scroll = @min(v.scroll, lines -| 1); + f.scroll_row = v.scroll_row; if (pane.body.cur_row >= lines) { pane.body.vsel.active = false; pane.body.nsel = 0; @@ -552,7 +558,10 @@ pub fn within(p: *Pardes, k: u8, ctx: anytype, comptime f: fn (@TypeOf(ctx), *Pa pane.cols = pv.cols; pane.rows = pv.rows; } - if (pane.file) |*file| file.scroll = pv.scroll; + if (pane.file) |*file| { + file.scroll = pv.scroll; + file.scroll_row = pv.scroll_row; + } pv.body.sels = &.{}; pv.body.nsel = 0; }; diff --git a/dev/glide.zig b/dev/glide.zig index 62e44bb7..9d622b3d 100644 --- a/dev/glide.zig +++ b/dev/glide.zig @@ -2,8 +2,9 @@ //! scroll, on its own clock, from the frames it draws alone. Whatever //! scrolls a text (a wheel's lines, Ctrl-d, a page, G, n, a Look) scrolls //! the core at once, so every key and click acts on where the text is; the -//! frontend sees a body's first line move between two frames (Region.line) -//! and its picture follows there, critically damped (text never passes its +//! frontend sees a body's top move between two frames (Region.line, and +//! Region.row: a row inside a wrapped line, File.Top) and its picture +//! follows there, critically damped (text never passes its //! mark), every distance on the same law. The GUI draws it at the pixel; //! the tty at whole rows (tui.zig's glideRows). Nothing here reaches back //! into the core. @@ -60,9 +61,9 @@ pub const Glide = struct { caret_row: ?u16 = null, caret_rides: bool = false, /// Each body as the last frame showed it, by its pane: its serial, - /// first line, text and place, so a view that moved since is found - /// whatever moved it. - seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i32 = 0, doc: u64 = 0, rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 } } = @splat(.{}), + /// top (a line and a row of it), text and place, so a view that + /// moved since is found whatever moved it. + seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i32 = 0, row: u32 = 0, doc: u64 = 0, rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 } } = @splat(.{}), /// Each body's rows held at its top while it scrolls (a source's /// sticky context rows, TreeContext), its frontend's to say: they do /// not move, so a move is measured, and the rows that left are kept, @@ -121,7 +122,9 @@ pub const Glide = struct { /// The frame about to be drawn, at `now_ns` on the frontend's clock: /// the glide moves on to now, and a body whose first line moved since /// the last frame (the same text in the same place) is measured against - /// that frame and kicks it. A terminal's view glides only under the + /// that frame and kicks it: a move of lines guessed at as many rows (as + /// unwrapped), one inside a line's wrapped rows known in rows. A + /// terminal's view glides only under the /// wheel (`wheeled`: its output scrolls it at every line, and that is no /// glide); not one the frontend moves by the pixel (`direct`). One glide /// at a time: the focused body's, else the one that moved most. @@ -139,24 +142,26 @@ pub const Glide = struct { } var pick: ?pardes.Region = null; var delta: i64 = 0; + var lines: i64 = 0; var shown: [pardes.MAX_PANES]bool = @splat(false); for (surface.regionList()) |region| { if (region.kind != .body or region.owner >= glide.seen.len) continue; const id: usize = region.owner; shown[id] = true; const was = glide.seen[id]; - glide.seen[id] = .{ .serial = region.serial, .line = region.line, .doc = region.doc, .rect = region.rect }; - if (was.serial != region.serial or was.doc != region.doc or was.line == region.line) continue; + glide.seen[id] = .{ .serial = region.serial, .line = region.line, .row = region.row, .doc = region.doc, .rect = region.rect }; + if (was.serial != region.serial or was.doc != region.doc or (was.line == region.line and was.row == region.row)) continue; // The last frame drew this body where it is now: a pane that // moved or was resized in the same step has no picture to glide // from. if (!std.meta.eql(was.rect, region.rect)) continue; if (region.doc == 0 and wheeled != id) continue; if (direct == id) continue; - const moved = @as(i64, region.line) - was.line; + const moved = if (region.line != was.line) @as(i64, region.line) - was.line else @as(i64, region.row) - was.row; if (pick) |best| if (best.active or (!region.active and @abs(moved) <= @abs(delta))) continue; pick = region; delta = moved; + lines = @as(i64, region.line) - was.line; } for (&glide.seen, shown) |*seen, here| if (!here) { seen.* = .{}; @@ -179,8 +184,8 @@ pub const Glide = struct { if (glide.before.len < n) return glide.stop(); for (0..r.h) |row| @memcpy(glide.before[row * w ..][0..w], glide.last[(@as(usize, r.y) + row) * glide.last_cols + r.x ..][0..w]); glide.dir = @intCast(std.math.sign(delta)); - glide.pending_lines += @floatFromInt(@abs(delta)); - glide.measure(gpa, surface); + glide.pending_lines += @floatFromInt(@abs(lines)); + glide.measure(gpa, surface, @floatFromInt(@abs(delta))); } /// This frame's cells and caret, for the next frame's measure. @@ -202,8 +207,9 @@ pub const Glide = struct { } /// Finds how far the pane's body rows moved, `dir` rows at a time, by - /// the rows of `surface` against `before`; keeps the rows that left. - fn measure(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { + /// the rows of `surface` against `before` (`guess` rows tried first); + /// keeps the rows that left. + fn measure(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface, guess_rows: f32) void { const w = glide.bw(); const x0 = glide.rect.x + config.GUTTER; if (w == 0 or glide.body_h == 0 or x0 + w > surface.cols or glide.body_y + glide.body_h > surface.rows or glide.before.len < @as(usize, w) * glide.body_h) return glide.stop(); @@ -218,9 +224,10 @@ pub const Glide = struct { }; // The least shift under which the rows agree, but for a few: the // cursor's line and its number's weight move with the scroll. The - // lines the core moved are tried first: unwrapped, they are the - // rows, and one pass over the body settles it (the search over - // every shift was 6 ms of the first frame of a page in Debug). + // rows guessed are tried first: the lines the core moved, which are + // the rows unwrapped, or the rows inside a wrapped line; one pass over the + // body settles it (the search over every shift was 6 ms of the + // first frame of a page in Debug). const agrees = struct { fn at(gl: *const Glide, surf: *const pardes.Surface, x: u16, width: u16, height: u16, kk: u16) bool { if (kk == 0 or kk + 3 > height) return false; @@ -239,7 +246,7 @@ pub const Glide = struct { return true; } }; - const guess: u16 = @intFromFloat(@min(glide.pending_lines, @as(f32, @floatFromInt(h)))); + const guess: u16 = @intFromFloat(@min(guess_rows, @as(f32, @floatFromInt(h)))); // A body's lines or more: every row moved off, none in common. var shift: u16 = if (guess >= h) 0 else if (agrees.at(glide, surface, x0, w, h, guess)) guess else found: for (1..h) |k| { if (agrees.at(glide, surface, x0, w, h, @intCast(k))) break :found @intCast(k); @@ -252,7 +259,7 @@ pub const Glide = struct { // None in common: a body's move from the last frame's body, if the // lines moved are that many (rows that merely changed, a small // scroll the rows cannot show, land at once). - if (shift == 0 and glide.pending_lines + 3 < @as(f32, @floatFromInt(h))) return glide.stop(); + if (shift == 0 and guess_rows + 3 < @as(f32, @floatFromInt(h))) return glide.stop(); const far = shift == 0; if (far) shift = h; glide.caret_rides = !far and if (glide.caret_row) |old| if (surface.cursor) |c| diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 2756f69b..0f1fe0e6 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -1773,10 +1773,9 @@ const Input = struct { /// Pane `id`'s first row shown, after the inputs posted: the session's /// own window asks (a wheel's rows stop where the pane does); a replica /// client's speculation may wait on the session, so it never asks. - fn scrollOf(in: *const Input, id: usize) ?i32 { + fn scrollOf(in: *const Input, id: usize) ?[2]i64 { if (in.client != null) return null; - const pane = in.core.panes[id] orelse return null; - return pane.scroll(); + return topOf(in.core.panes[id] orelse return null); } fn close(in: *Input) void { @@ -3301,6 +3300,12 @@ fn notchOf(raw_y: f32, integer_y: i32) ?i32 { const Glide = pardes.glide.Glide; +/// Where a pane's view starts, to tell a wheel's row moved it: its line, +/// and a file's row of that line's wrapped rows (File.Top). +fn topOf(pane: *pardes.Pane) [2]i64 { + return .{ pane.scroll(), if (pane.file) |f| f.scroll_row else 0 }; +} + /// Feeds a wheel's notches to the core, and keeps what moved the view for /// the frame's glide (Glide.frame). fn stepGlide(g: *Gui, core: *pardes.Pardes) void { @@ -3322,10 +3327,10 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes) void { while (left != 0) { const down = left > 0; left += if (down) -1 else 1; - const was = pane.scroll(); + const was = topOf(pane); // Shift: pardes's own scroll, never a program's wheel. core.update(.{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, .col = g.scroll_col, .row = g.scroll_row, .shift = true } }); - if (pane.scroll() == was) break; + if (std.mem.eql(i64, &topOf(pane), &was)) break; wheeled = id; } if (wheeled != null) core.needs_frame = true; @@ -3541,7 +3546,7 @@ fn scrollRows(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { }, }); // A replica client's rows may wait on the session: it never asks. - if (was != null and in.scrollOf(id) == was) { + if (was != null and std.mem.eql(i64, &in.scrollOf(id).?, &was.?)) { resetScroll(g); return false; } @@ -6544,16 +6549,19 @@ test "a wheel over codex in a terminal reaches its pty as the mouse reports it a try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); } -test "a notch scrolls the core at once and the picture glides after it, a wrapped line's rows at a time" { +test "a notch scrolls the core at once and the picture glides after it, a row a notch: a wrapped line's rows one by one" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); - // Lines of two rows each at this width, numbered so no two rows match. + // Lines of two rows each at this width, numbered so no two rows match; + // line 3 of 80 numbered words, five rows or more. var text: std.ArrayList(u8) = .empty; defer text.deinit(gpa); for (0..60) |i| { try text.print(gpa, "{d:0>4} ", .{i}); - try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); + if (i == 3) { + for (0..80) |w| try text.print(gpa, "w{d:0>3} ", .{w}); + } else try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); try text.append(gpa, '\n'); } _ = try core.setTestFile(text.items); @@ -6570,26 +6578,42 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe g.scroll_col = r.x + 10; g.scroll_row = r.y + r.h - 2; const body_y = core.bodyTop(core.panes[core.view().active].?, r); - const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y + 1) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); + const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); defer gpa.free(row_before); // The window has drawn the view once (Glide.frame finds a view that moved). g.now_ns = now; glideFrame(&g, gpa, s); - // One notch down: the core is a line on at once. + // One notch down: the core is a row on at once, line 0's second. g.scroll_notch = 1; - const scrolled = core.panes[core.view().active].?.scroll(); + const f = &core.panes[core.view().active].?.file.?; stepGlide(&g, core); - try std.testing.expectEqual(scrolled + 1, core.panes[core.view().active].?.scroll()); + try std.testing.expectEqual(@as(usize, 0), f.scroll); + try std.testing.expectEqual(@as(u32, 1), f.scroll_row); _ = arena.reset(.retain_capacity); s = try core.render(arena.allocator()); glideFrame(&g, gpa, s); // The window's own motion: it draws its frames while it moves. try std.testing.expect(frontendMoving(&g)); - // Its two rows: the picture two rows behind, the rows that left kept, - // nearest first. - try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); - try std.testing.expectEqual(@as(u16, 2), g.glide.nabove); + // Its row: the picture a row behind, the row that left kept. + try std.testing.expectApproxEqAbs(@as(f32, -1), g.glide.follow.offset, 1e-4); + try std.testing.expectEqual(@as(u16, 1), g.glide.nabove); try std.testing.expect(pardes.glide.sameRow(g.glide.above[0 .. r.w - config.GUTTER], row_before)); + // Notch by notch to line 5, through line 3's rows: a row more + // behind each, never a line's rows at once. + var lag = g.glide.follow.offset; + var notches: usize = 1; + while (f.scroll < 5) : (notches += 1) { + g.scroll_notch = 1; + stepGlide(&g, core); + _ = arena.reset(.retain_capacity); + s = try core.render(arena.allocator()); + glideFrame(&g, gpa, s); + try std.testing.expectApproxEqAbs(lag - 1, g.glide.follow.offset, 1e-4); + lag = g.glide.follow.offset; + } + const line3: usize = pardes.panes.File.lineRows(core.settings.tab, core.panes[core.view().active].?, 3); + try std.testing.expect(line3 >= 5); + try std.testing.expectEqual(2 + 2 + 2 + line3 + 2, notches); // Frame by frame it comes back, never past, and settles. var frames: usize = 0; while (g.glide.moving()) : (frames += 1) { @@ -7746,7 +7770,7 @@ test "a body tells its first line" { const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); - pane.scrollBy(8); + pane.scrollBy(core.settings.tab, 8); core.sync(); const s = try core.render(core.scratch.allocator()); const body = for (s.regionList()) |region| { diff --git a/test/daemon.py b/test/daemon.py index 90977ef4..cfdac2ec 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -328,7 +328,7 @@ class Replica: """A replica's connection (abi/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 34 + WIRE = 35 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/kitty.zig b/test/kitty.zig index 0bd849c2..37e64949 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -1224,7 +1224,7 @@ test "kitty: scrolled back by pardes, an image shows on its row; scrolled forwar r.feed(0, &nl); try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(20)).len); // Back to the top of the history: the marker row is the body's first. - pane.scrollBy(-1000); + pane.scrollBy(pardes.config.tab_width, -1000); const o = r.origin(0); const drawn = try r.placesOf(20); try std.testing.expectEqual(@as(usize, 1), drawn.len); diff --git a/test/panes.zig b/test/panes.zig index bd39beba..eea4b36d 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -157,7 +157,7 @@ const BodyHitTests = struct { p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([60][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(10); + pane.scrollBy(pardes.config.tab_width, 10); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); p.sync(); @@ -205,7 +205,7 @@ const LineNumberLookTests = struct { p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([60][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(30); + pane.scrollBy(pardes.config.tab_width, 30); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); p.sync(); @@ -219,7 +219,7 @@ const LineNumberLookTests = struct { const rows = [_]u16{ 1, pane.context_rows + 3 }; for (rows) |row| { // Each Look recentres the view; come back under the headers. - pane.scrollBy(30 - pane.scroll()); + pane.scrollBy(pardes.config.tab_width, 30 - pane.scroll()); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); const expected = pane.wrapAt(config.tab_width, row).line; @@ -262,7 +262,7 @@ const TreeContextTests = struct { const pane = try setZigFile(p, "const Box = struct {\n\n // omitted member comment\n\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*))) ++ " }\n};\n"); p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(10); + pane.scrollBy(pardes.config.tab_width, 10); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); p.sync(); @@ -278,7 +278,7 @@ const TreeContextTests = struct { // A one-pixel separator remains inside its existing header row. try std.testing.expectEqual(row, layer.bodyHit(x, y, 10, 20, 8, 10).?.row); } - pane.scrollBy(-5); + pane.scrollBy(pardes.config.tab_width, -5); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 2), layer.context_rows); try std.testing.expect(layer.hasContextBorderAfter(0)); @@ -317,7 +317,7 @@ const TreeContextTests = struct { const pane = try setZigFile(p, source); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); - pane.scrollBy(7); + pane.scrollBy(pardes.config.tab_width, 7); p.sync(); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 0), pane.context_rows); @@ -348,7 +348,7 @@ const TreeContextTests = struct { p.update(.{ .key = .{ .cp = Key.escape } }); var previous: u16 = pane.context_rows; while (pane.scroll() > 0) { - pane.scrollBy(-1); + pane.scrollBy(pardes.config.tab_width, -1); _ = try p.render(frame.allocator()); try std.testing.expect(pane.context_rows <= previous); previous = pane.context_rows; @@ -357,7 +357,7 @@ const TreeContextTests = struct { try std.testing.expectEqual(@as(u16, 0), pane.context_rows); try std.testing.expectEqual(@as(i32, 0), pane.wrapRow(config.tab_width, 0, pane.body.cur_col).row); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(7); + pane.scrollBy(pardes.config.tab_width, 7); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 0), pane.context_rows); } @@ -370,7 +370,7 @@ const TreeContextTests = struct { p.sync(); p.settings.wrap = false; try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(8); + pane.scrollBy(pardes.config.tab_width, 8); pane.hscroll = 4; var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); @@ -409,7 +409,9 @@ const TreeContextTests = struct { p.sync(); p.settings.wrap = true; try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); - pane.scrollBy(2); + // The view's top on line 2 (a scroll's rows would stop in line 0's + // three: File.Top). + panes.File.setTop(pane, .{ .line = 2 }); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); p.sync(); @@ -994,7 +996,7 @@ test "terminal output keeps following new rows after scrollback eviction" { for (0..3) |phase| { if (phase > 0) { pane.body.mode = .normal; - pane.scrollBy(-30); + pane.scrollBy(pardes.config.tab_width, -30); try std.testing.expect(pane.termTop() < pages.scrollbar().total - pane.rows); pardes.keys.enterTty(p, 0); } @@ -2032,7 +2034,7 @@ const OutputTests = struct { try std.testing.expectEqual(next, panes.Output.nextResult(restored_file.content, restored_file.location_rows, path, .{ .line = 2, .col = 5 })); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); - result.scrollBy(-1000); + result.scrollBy(pardes.config.tab_width, -1000); layout.compute(p); const surface = try p.render(frame.allocator()); const rect = p.view().rects[pane.search_pane.?]; @@ -2690,7 +2692,7 @@ const TerminalTests = struct { p.update(.{ .output = .{ .pane = .at(0), .bytes = bytes } }); } p.shell_rows.stale = true; - pane.scrollBy(-20); + pane.scrollBy(pardes.config.tab_width, -20); // ONE buffer line standing in for SIX shell rows: everything below slides // UP five, so the last rows of the body resolve past the viewport's bottom diff --git a/test/perf.zig b/test/perf.zig index 8622e31b..f36d64ac 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -631,7 +631,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u for (0..warmup + reps) |n| { if (op != .deep_selection) seek(pane, fx, n); _ = try frame(core); // settle the view at the new spot, untimed - const before = .{ .row = pane.body.cur_row, .col = pane.body.cur_col, .scroll = pane.scroll(), .len = pane.file.?.content.len }; + const before = .{ .row = pane.body.cur_row, .col = pane.body.cur_col, .scroll = pane.scroll(), .scroll_row = pane.file.?.scroll_row, .len = pane.file.?.content.len }; const rect = core.view().rects[id]; const wheel_col = rect.x + pardes.config.GUTTER; const wheel_row = rect.y + pardes.BOX_H; @@ -658,9 +658,11 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u return error.RenderChangedDocument, .key_down => if (pane.body.cur_row != before.row + 1) return error.DownDidNotMove, .key_right => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) return error.RightDidNotMove, - .page_down => if (pane.scroll() <= before.scroll and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) + // A view moves by rows (File.Top): inside a wrapped line's + // block its line stays and its row goes on. + .page_down => if (!past(pane, before.scroll, before.scroll_row) and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) return error.PageDidNotScroll, - .wheel => if (pane.scroll() <= before.scroll and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) + .wheel => if (!past(pane, before.scroll, before.scroll_row) and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) return error.WheelDidNotScroll, .edit_char, .edit_twin => { if (pane.file.?.content.len != before.len + 1 or pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) @@ -1884,6 +1886,7 @@ fn seek(pane: *pardes.Pane, fx: Fixture, n: usize) void { const span = @max(1, fx.lines * 8 / 10); const row = fx.lines / 10 + (n *% 7919) % span; f.scroll = @min(row, fx.lines -| 1); + f.scroll_row = 0; f.syntax_dirty = true; pane.body.cur_row = @intCast(f.scroll); pane.body.cur_col = if (fx.cols > 200) @intCast(fx.cols * 3 / 4) else 0; @@ -2401,3 +2404,8 @@ fn readFileAlloc(path: []const u8) ![]u8 { } return buf; } + +/// Whether `pane`'s view's top is past (`line`, `row`). +fn past(pane: *pardes.Pane, line: i32, row: u32) bool { + return pane.scroll() > line or (pane.scroll() == line and pane.file.?.scroll_row > row); +} diff --git a/test/terminal.zig b/test/terminal.zig index 03bcd294..2873c278 100644 --- a/test/terminal.zig +++ b/test/terminal.zig @@ -107,7 +107,7 @@ test "document construction allocates only the pane and has inert terminal defau try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); try std.testing.expectEqual(Term.Modes{}, modes(pane.terminal)); try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal)); - pane.scrollBy(100); + pane.scrollBy(pardes.config.tab_width, 100); pane.followOutput(); pane.resizeGrid(undefined, 80, 24); // no terminal: the core is never read try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); |
