diff options
Diffstat (limited to 'src/File.zig')
| -rw-r--r-- | src/File.zig | 571 |
1 files changed, 159 insertions, 412 deletions
diff --git a/src/File.zig b/src/File.zig index 6df49c98..7acf8dd6 100644 --- a/src/File.zig +++ b/src/File.zig @@ -13,7 +13,6 @@ const filesystem = @import("fs.zig"); const syntax = @import("syntax.zig"); const diff = @import("diff.zig"); const tracy = @import("tracy.zig"); -const dump = @import("dump.zig"); const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); const Colors = @import("colors.zig"); @@ -31,6 +30,7 @@ const long_paint: usize = 16 << 10; /// Content and primary selection at one file edit boundary. Keeping only the /// primary avoids putting Text.max_selections ranges in every history entry. pub const Snapshot = struct { + pub const replica = .{ .blob = .{"content"} }; content: []u8, cur_row: i32, cur_col: i32, @@ -104,6 +104,7 @@ fn restoreName(p: *Pardes, pane: *Pane, f: *State, snap: Snapshot) void { } pub const History = struct { + pub const replica = .{ .len = .{ .{ "undo", "undo_len" }, .{ "redo", "redo_len" } } }; undo: [limits.undo_max]Snapshot = undefined, undo_len: usize = 0, redo: [limits.undo_max]Snapshot = undefined, @@ -137,6 +138,14 @@ pub const History = struct { /// A file pane's backing: owned content, its derived caches, and undo history. pub const State = struct { + /// What the replay digest leaves out (src/walk.zig): what is made again + /// from the text whenever it is wanted. + pub const replica = .{ + .derived = .{ "line_starts", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_history", "tables" }, + // Replaced whole at every edit (setContentSpan), never written. + .blob = .{ "content", "line_starts", "location_rows" }, + }; + path: []u8, content: []u8, revision: u32 = 0, @@ -216,231 +225,6 @@ pub const State = struct { pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; -pub fn dumpPane( - p: *Pardes, - arena: std.mem.Allocator, - pane: *const Pane, - file: *const State, - tag: []const u8, - body: []const u8, - scroll: usize, - origin: []const u8, - origin_arg: []const u8, -) !dump.Pane { - const dirty = file.revision != file.saved_revision; - const on_disk = onDisk(file.path); - // A clean file's text is its file's: read from disk when restored, so - // a change made there since is what comes back. Any other is kept, once. - const from_disk = file.output == null and !dirty and on_disk; - // What an unsaved pane's text was read against: the disk as it is, or, - // when a change there was seen already, something it is not. - const disk_hash: ?u64 = if (file.output != null or !dirty or !on_disk) null else if (file.disk_newer) |newer| newer +% 1 else blk: { - const bytes = filesystem.read(p, file.path) catch break :blk null; - defer p.gpa.free(bytes); - break :blk std.hash.Wyhash.hash(0, bytes); - }; - return .{ - .kind = .file, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .file = .{ - .tree_context = file.tree_context, - // A query pane's rows are its own (line 1 the query, gutter - // numbers), not location rows Restore reads: it comes back as - // plain text. - .location_rows = if (pane.query != null) &.{} else try dumpLocationRows(arena, file.location_rows), - .path = file.path, - .content_b64 = if (from_disk) "" else try dump.encodeBytes(arena, file.content), - .dirty = dirty, - .disk_hash = disk_hash, - .on_disk = on_disk, - .origin = origin, - .origin_arg = origin_arg, - .mini_source = if (file.mini) |mini| mini.source else "", - .mini_colors_b64 = if (file.mini) |mini| try dump.encodeBytes(arena, mini.colors) else "", - }, - }; -} - -fn dumpLocationRows(arena: std.mem.Allocator, rows: []const locations.Row) ![]const dump.LocationRow { - const saved = try arena.alloc(dump.LocationRow, rows.len); - for (rows, saved) |row, *out| out.* = .{ - .kind = @fromBackingInt(@intCast(@backingInt(row.kind))), - .declaration = row.declaration, - .mark_occurrence = row.mark_occurrence, - .source_column = row.source_column, - .path = row.path, - .line = row.at.line, - .col = row.at.col, - .end_line = row.at.end_line, - .end_col = row.at.end_col, - .location_end = row.location_end, - .code_start = row.code_start, - .colors_b64 = try dump.encodeBytes(arena, row.colors), - }; - return saved; -} - -fn sameSavedLocation(a: dump.LocationRow, b: dump.LocationRow) bool { - return std.mem.eql(u8, a.path, b.path) and a.line == b.line and a.col == b.col and - a.end_line == b.end_line and a.end_col == b.end_col; -} - -fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow) ![]locations.Row { - return restoreOutputLocationRows(gpa, content, saved, false); -} - -fn restoreOutputLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow, callstack: bool) ![]locations.Row { - if (saved.len == 0) return &.{}; - if (saved.len > std.mem.count(u8, content, "\n") + 1) return error.InvalidLocationRows; - const rows = try gpa.alloc(locations.Row, saved.len); - var initialized: usize = 0; - errdefer { - for (rows[0..initialized]) |row| { - gpa.free(row.path); - gpa.free(row.colors); - } - gpa.free(rows); - } - var lines = std.mem.splitScalar(u8, content, '\n'); - var previous_line: []const u8 = ""; - for (saved, rows, 0..) |row, *out, index| { - const line = lines.next() orelse return error.InvalidLocationRows; - if ((!callstack and row.path.len == 0) or row.path.len >= 4096 or - row.location_end > row.code_start or row.code_start > line.len or - (row.kind == .match and row.location_end == 0) or - (row.declaration and row.kind != .context) or - row.line > std.math.maxInt(i32) or row.col > std.math.maxInt(i32) or - row.end_line > std.math.maxInt(i32) or row.end_col > std.math.maxInt(i32)) - return error.InvalidLocationRows; - if (callstack) { - if (row.location_end > 0) { - const prefix = locations.treePrefix(line); - const parsed = locations.parseRaw(line[prefix.end..]); - if (row.kind != .match or parsed.at.line == 0 or - !std.mem.eql(u8, parsed.path, row.path) or - parsed.at.line != row.line or parsed.at.col != row.col or - parsed.at.end_line != row.end_line or parsed.at.end_col != row.end_col or - prefix.end + parsed.end != row.location_end or - prefix.end + parsed.code_start != row.code_start) return error.InvalidLocationRows; - } else if (row.kind == .preview) { - if (index == 0 or saved[index - 1].kind != .match or !sameSavedLocation(saved[index - 1], row)) return error.InvalidLocationRows; - } else if (row.kind != .context or (row.path.len == 0 and (row.line != 0 or row.code_start != line.len))) return error.InvalidLocationRows; - } else { - const inline_row = row.code_start > row.location_end and row.code_start > 0 and line[row.code_start - 1] == '\t'; - const address_row = !inline_row and row.location_end > 0 and row.code_start == line.len; - const source_row = row.location_end == 0 and row.code_start == 0; - if (!inline_row and !address_row and !source_row) return error.InvalidLocationRows; - if (row.kind == .preview) { - if (!source_row or index == 0) return error.InvalidLocationRows; - const previous = saved[index - 1]; - if (previous.kind != .match or previous.location_end == 0 or previous.code_start != previous_line.len or previous_line[previous_line.len - 1] == '\t' or - !sameSavedLocation(previous, row)) return error.InvalidLocationRows; - } - if (address_row) { - if (index + 1 >= saved.len) return error.InvalidLocationRows; - const following = saved[index + 1]; - const expected: @TypeOf(row.kind) = if (row.kind == .match) .preview else .context; - if (following.kind != expected or following.code_start != 0 or following.location_end != 0 or - following.declaration != row.declaration or !sameSavedLocation(row, following)) return error.InvalidLocationRows; - } - } - const code_len = line.len - row.code_start; - if (row.colors_b64.len > std.base64.standard.Encoder.calcSize(code_len)) return error.InvalidLocationRows; - const colors = try dump.decodeBytes(gpa, row.colors_b64); - errdefer gpa.free(colors); - if (colors.len != 0 and colors.len != code_len) return error.InvalidLocationRows; - for (colors) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidLocationRows; - const path = try gpa.dupe(u8, row.path); - out.* = .{ - .kind = @fromBackingInt(@intCast(@backingInt(row.kind))), - .declaration = row.declaration, - .mark_occurrence = row.mark_occurrence, - .source_column = row.source_column, - .path = path, - .at = .{ .line = row.line, .col = row.col, .end_line = row.end_line, .end_col = row.end_col }, - .location_end = row.location_end, - .code_start = row.code_start, - .colors = colors, - }; - initialized += 1; - previous_line = line; - } - if (lines.next()) |remaining| if (remaining.len != 0 or lines.next() != null) return error.InvalidLocationRows; - return rows; -} - -test "a clean pane whose file was never on disk comes back clean from a Restore; one whose file has gone is said deleted" { - if (comptime !pardes.hosted) return; - for ([_]bool{ false, true }) |was_on_disk| { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const id = p.freeSlot().?; - const pane = try restore(p, id, .{ - .kind = .file, - .tag = "", - .body = "", - .file = .{ .path = "/tmp/pardes-never-written/init", .content = "", .on_disk = was_on_disk }, - }); - try std.testing.expectEqual(was_on_disk, pane.file.?.disk_gone); - try std.testing.expectEqual(pane.file.?.saved_revision, pane.file.?.revision); - } -} - -test "location metadata restore rejects offsets and invalid syntax bytes" { - const gpa = std.testing.allocator; - var row: dump.LocationRow = .{ - .kind = .context, - .path = "x.zig", - .line = 1, - .location_end = 0, - .code_start = 3, - }; - const rows = try restoreLocationRows(gpa, "| \tx\n", &.{row}); - defer locations.freeRows(gpa, rows); - try std.testing.expectEqualStrings("x.zig", rows[0].path); - row.code_start = 8; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); - row.code_start = 3; - row.colors_b64 = "/w=="; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); - row.colors_b64 = ""; - row.kind = .match; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); -} - -test "stacked location metadata requires matching adjacent preview ownership" { - const gpa = std.testing.allocator; - const header = "x.c:2:1-3"; - const content = header ++ "\nfoo\n"; - const match: dump.LocationRow = .{ .kind = .match, .path = "x.c", .line = 2, .col = 1, .end_line = 2, .end_col = 3, .location_end = header.len, .code_start = header.len }; - const preview: dump.LocationRow = .{ .kind = .preview, .path = "x.c", .line = 2, .col = 1, .end_line = 2, .end_col = 3, .location_end = 0, .code_start = 0 }; - const restored = try restoreLocationRows(gpa, content, &.{ match, preview }); - defer locations.freeRows(gpa, restored); - try std.testing.expectEqual(.preview, restored[1].kind); - try std.testing.expectEqual(restored[0].at, restored[1].at); - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "foo\n", &.{preview})); - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, header ++ "\n", &.{match})); - var inline_match = match; - inline_match.code_start += 1; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, header ++ "\t\nfoo\n", &.{ inline_match, preview })); - var wrong = preview; - wrong.path = "other.c"; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); - wrong = preview; - wrong.line = 3; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); - wrong = preview; - wrong.code_start = 1; - try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); -} - pub fn graphemeDisplayWidth(grapheme: []const u8) usize { if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1; @@ -509,10 +293,13 @@ pub fn rawDisplayCol(line_text: []const u8, raw_col: usize) usize { return displayWidth(line_text[0..bounded]) +| (raw_col -| line_text.len); } +/// Walked only as far as the column: a row's last byte, a million bytes +/// into a line, is found without measuring the rest of it. Only a line +/// that ends before the column is measured whole (it is short). pub fn rawAtDisplay(line_text: []const u8, display_col: usize) usize { - const width = displayWidth(line_text); - if (display_col > width) return line_text.len +| (display_col - width); - return byteAtDisplay(line_text, display_col); + const at = byteAtDisplay(line_text, display_col); + if (at < line_text.len) return at; + return line_text.len +| (display_col -| displayWidth(line_text)); } pub fn byteAtDisplayFrom(line_text: []const u8, from_raw: usize, display_col: usize) usize { @@ -1018,128 +805,6 @@ pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { return pane; } -pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { - const saved = src.file.?; - if (saved.mini_source.len > 0) { - const encoded_limit = std.base64.standard.Encoder.calcSize(Mini.max_output_bytes); - if (saved.mini_source.len >= 4096 or saved.content.len > Mini.max_output_bytes or - saved.content_b64.len > encoded_limit or saved.mini_colors_b64.len > encoded_limit) - return error.InvalidMini; - } - // A clean file's text is read from its file: one changed on disk since - // the dump comes back changed, never as the old text marked clean (and - // a dump from before, which kept it, is read so too). Gone from disk, the - // dump's text if it kept one. - const from_disk: ?[]u8 = if (Output.fromWord(saved.origin) == null and !saved.dirty and saved.on_disk and - saved.mini_source.len == 0 and filesystem.localPath(saved.path) != null) - filesystem.read(p, saved.path) catch null - else - null; - const content: []u8 = if (from_disk) |bytes| bytes else if (saved.content_b64.len > 0) - try dump.decodeBytes(p.gpa, saved.content_b64) - else - try p.gpa.dupe(u8, saved.content); - errdefer p.gpa.free(content); - const path = try p.gpa.dupe(u8, saved.path); - errdefer p.gpa.free(path); - - const output: ?Output.State = if (Output.fromWord(saved.origin)) |origin| blk: { - var value: Output.State = .{ .from = origin }; - try Output.setArg(&value, saved.origin_arg); - break :blk value; - } else null; - - if (saved.location_rows.len != 0 and output == null) return error.InvalidLocationRows; - const is_callstack = if (output) |state| std.meta.eql(state.from, Output.Origin{ .query = .callstack }) else false; - const location_rows = try restoreOutputLocationRows(p.gpa, content, saved.location_rows, is_callstack); - errdefer locations.freeRows(p.gpa, location_rows); - - var mini: ?Mini.State = null; - errdefer if (mini) |*state| state.deinit(p.gpa); - if (saved.mini_source.len > 0) { - if (output == null or !std.meta.eql(output.?.from, Output.Origin{ .cmd = .Mini })) return error.InvalidMini; - const source = try p.gpa.dupe(u8, saved.mini_source); - errdefer p.gpa.free(source); - const colors = try dump.decodeBytes(p.gpa, saved.mini_colors_b64); - errdefer p.gpa.free(colors); - if (colors.len != content.len or colors.len > Mini.max_output_bytes) return error.InvalidMini; - for (colors) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidMini; - mini = .{ .source = source, .colors = colors }; - } else if (saved.mini_colors_b64.len > 0) return error.InvalidMini; - - const history = try History.create(p.gpa); - errdefer p.gpa.destroy(history); - const pane = try p.newDocPane(id); - pane.file = .{ - .path = path, - .content = content, - .output = output, - .mini = mini, - .location_rows = location_rows, - .scroll = src.scroll, - .revision = @intFromBool(saved.dirty), - // Restored with unsaved text, it has text to lose as an edited pane - // has: a hash its text does not match, so Exit, Restore, Del and - // get ask first (builtins.warnModifiedIn reads only edited panes). - .saved_hash = if (saved.dirty) std.hash.Wyhash.hash(0, content) +% 1 else null, - .history = history, - }; - pane.file.?.tree_context = saved.tree_context and supportsContext(pane); - pane.body.cur_pinned = true; - pane.body.cur_row = @intCast(src.scroll); - // Its dot as it was, where the view the dump kept shows it. - if (saved.dot) |dot| if (dot[0] <= dot[1] and dot[1] <= content.len) { - const a = modal.positionAt(content, dot[0]); - const h = modal.positionAt(content, if (dot[1] > dot[0]) modal.prevGrapheme(content, dot[1]) else dot[0]); - pane.body.vsel = .{ .active = dot[1] > dot[0], .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; - pane.body.cur_row = @intCast(h.row); - pane.body.cur_col = @intCast(h.col); - }; - pane.cols = @max(1, src.cols); - pane.rows = @max(1, src.rows); - // A directory pane is its directory as it is now, laid out at the next - // sync; one that cannot be read keeps the text the dump kept. - if (output) |o| if (o.from == .dir) { - const f = &pane.file.?; - if (panes.Dir.read(p.gpa, panes.Dir.ofName(path))) |names| { - f.listing = .{ .names = names, .revision = f.revision }; - } else |_| f.listing = .{ .names = &.{}, .revision = f.revision -% 1 }; - }; - if (output == null and filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true, .mode = .baseline_disk } }); - // Its file gone from disk since the dump: its text is nowhere else now, - // so it comes back as one deleted on disk, dirty, and Del, Exit and - // Restore ask before throwing it away. - // One never on disk (Config's new file, a name not yet saved) is - // restored as it was: clean, and nothing deleted. - if (output == null and saved.on_disk and !onDisk(path)) deleted(p, @intCast(id)); - // Unsaved, and its file changed on disk since the text was read: said, - // and its first Save asks before overwriting the newer file. - if (saved.disk_hash) |read_against| if (output == null and onDisk(path)) { - if (filesystem.read(p, path)) |bytes| { - defer p.gpa.free(bytes); - if (std.hash.Wyhash.hash(0, bytes) != read_against) changed(p, @intCast(id), bytes); - } else |_| {} - }; - // An older dump says nothing of what the text was read against: its - // first Save asks, as for a file changed on disk, rather than guess. - if (saved.dirty and saved.disk_hash == null and output == null and onDisk(path)) { - if (filesystem.read(p, path)) |bytes| { - defer p.gpa.free(bytes); - const f = &pane.file.?; - f.disk_newer = std.hash.Wyhash.hash(0, bytes); - f.disk_newer_warned = false; - } else |_| {} - } - return pane; -} - -/// Whether `path` names a file on this host's disk now. -fn onDisk(path: []const u8) bool { - if (comptime !pardes.hosted) return false; - const local = filesystem.localPath(path) orelse return false; - return @import("exec.zig").kindOf(local) != null; -} - pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.output == null) for (p.panes, 0..) |slot, id| { if (slot == pane) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); @@ -1151,10 +816,12 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (p.panes[id].?.file.?.line_starts.ptr == file.line_starts.ptr) break true; } else false; p.gpa.free(file.path); - if (ntwins == 0) p.gpa.free(file.content); + // Raw, as every text is freed (a replica's rollback copy pins them, + // src/rollback.zig, and a safe build's free writes over what it frees). + if (ntwins == 0) pardes.memory.freeUnfilled(p.gpa, file.content); if (file.listing) |listing| p.gpa.free(listing.names); if (file.mini) |*mini| mini.deinit(p.gpa); - if (file.line_starts.len > 0 and !index_shared) p.gpa.free(file.line_starts); + if (file.line_starts.len > 0 and !index_shared) pardes.memory.freeRaw(p.gpa, file.line_starts); if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); p.gpa.free(file.pager_spans); locations.freeRows(p.gpa, file.location_rows); @@ -1178,6 +845,7 @@ fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { } pub const DroppedMarks = struct { + pub const replica = .{ .blob = .{"rows"} }; len: usize, hash: u64, rows: []locations.Row, @@ -1200,7 +868,12 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { // the caller did not say, is what the line index wants anyway. var twins: [pardes.MAX_PANES]usize = undefined; const ntwins = twinsOf(p, f, &twins); - const span: ?Span = span_in orelse if (ntwins > 0) spanOf(f.content, new) else null; + // The views not live keep their place in it as twins do (views.zig). + const viewed = pardes.views.several(p); + const span: ?Span = span_in orelse if (ntwins > 0 or viewed) spanOf(f.content, new) else null; + var parked: ParkedPlaces = .{}; + if (viewed) parked.before(p, f, span.?, new.len); + defer if (viewed) parked.after(p); var moved: [pardes.MAX_PANES]struct { cursor: usize, scroll: usize } = undefined; for (twins[0..ntwins], 0..) |id, i| { const t = p.panes[id].?; @@ -1241,16 +914,17 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { f.saved_len = f.content.len; } // Raw: `free` overwrites a safe build's freed memory, a whole file's - // worth per keystroke. - if (f.content.len > 0) p.gpa.rawFree(f.content, .of(u8), @returnAddress()); + // worth per keystroke; and its digest word goes (src/walk.zig). + pardes.memory.freeUnfilled(p.gpa, f.content); f.content = new; f.revision +%= 1; f.splice = .{ .revision = f.revision, .head = known.head, .tail = known.tail, .old_len = old_len }; if (f.saved_hash) |h| if ((f.saved_len orelse new.len) == new.len and std.hash.Wyhash.hash(0, new) == h) { f.saved_revision = f.revision; }; - f.mtime = pardes.ctlfs.events.now(); - if (f.line_starts.len > 0) p.gpa.free(f.line_starts); + // The clock the session that recorded read (src/tape.zig). + f.mtime = pardes.tape.value(.mtime, pardes.ctlfs.events.now, .{}); + if (f.line_starts.len > 0) pardes.memory.freeRaw(p.gpa, f.line_starts); f.line_starts = starts; if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); f.highlights = &.{}; @@ -1262,7 +936,7 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { const tf = &t.file.?; // Its own index, built while the shared one was empty, goes; the // shared one, freed above, is replaced. - if (tf.line_starts.len > 0 and tf.line_starts.ptr != old_starts) p.gpa.free(tf.line_starts); + if (tf.line_starts.len > 0 and tf.line_starts.ptr != old_starts) pardes.memory.freeRaw(p.gpa, tf.line_starts); tf.content = f.content; tf.line_starts = f.line_starts; tf.revision = f.revision; @@ -1292,6 +966,50 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { } } +/// Each other view's cursor and scroll on a text being changed, as offsets +/// moved by the splice (`spliced`), put back as places in the new text once +/// it is in: a view not live keeps its place, as a twin does. Its +/// selections go, as a twin's do. +const ParkedPlaces = struct { + const max = pardes.MAX_PANES * pardes.views.max; + at: [max]struct { pane: *Pane, view: u8, cursor: usize, scroll: usize } = undefined, + n: usize = 0, + + fn before(pp: *ParkedPlaces, p: *Pardes, f: *State, span: Span, new_len: usize) void { + for (p.panes) |slot| { + const pane = slot orelse continue; + const tf = if (pane.file) |*file| file else continue; + if (tf != f and (f.twin == 0 or tf.twin != f.twin)) continue; + for (0..pardes.views.max) |k| { + if (k == p.view or !pardes.views.isOpen(p, @intCast(k)) or pp.n == max) continue; + const v = &pane.pv[k]; + const at = lineStart(p.gpa, tf, @intCast(@max(0, v.body.cur_row))) + @as(usize, @intCast(@max(0, v.body.cur_col))); + pp.at[pp.n] = .{ + .pane = pane, + .view = @intCast(k), + .cursor = spliced(@min(at, f.content.len), f.content.len, new_len, span), + .scroll = spliced(@min(lineStart(p.gpa, tf, v.scroll), f.content.len), f.content.len, new_len, span), + }; + pp.n += 1; + } + } + } + + fn after(pp: *ParkedPlaces, p: *Pardes) void { + for (pp.at[0..pp.n]) |a| { + const tf = &(a.pane.file orelse continue); + const v = &a.pane.pv[a.view]; + const cursor = positionIn(p.gpa, tf, @min(a.cursor, tf.content.len)); + v.body.cur_row = @intCast(cursor.row); + v.body.cur_col = @intCast(cursor.col); + v.body.vsel.active = false; + v.body.msel.active = false; + v.body.nsel = 0; + v.scroll = positionIn(p.gpa, tf, @min(a.scroll, tf.content.len)).row; + } + } +}; + /// Where an offset into the old text is in the new, after the splice that /// kept `span` at either end: past it, moved by what it added; inside it, /// at its start, as acme moves a clone's q0 (textinsert, textdelete). @@ -1425,45 +1143,6 @@ pub fn leaveTwins(p: *Pardes, f: *State) void { if (n == 1) p.panes[twins[0]].?.file.?.twin = 0; } -/// Restore's: pane `id`, restored on its own, back on pane `of`'s buffer -/// as the Zerox twin it was dumped as (dump.File.twin_of). Not a file pane -/// there (a dump edited by hand), it stays on its own. -pub fn relink(p: *Pardes, of: usize, id: usize, dot: ?[2]u32) void { - const src = p.panes[of] orelse return; - const pane = p.panes[id] orelse return; - const sf = if (src.file) |*file| file else return; - const f = if (pane.file) |*file| file else return; - if (sf.output != null or f.output != null or sf.mini != null) return; - if (sf.twin == 0) { - const group = p.gpa.dupe(u8, sf.path) catch return; - p.twin_groups.append(p.gpa, .{ .id = p.next_twin, .saved_revision = sf.saved_revision, .saved_hash = sf.saved_hash, .saved_len = sf.saved_len, .disk_newer = sf.disk_newer, .disk_gone = sf.disk_gone, .path = group }) catch return p.gpa.free(group); - sf.twin = p.next_twin; - p.next_twin +%= 1; - } - p.gpa.free(f.content); - if (f.line_starts.len > 0) p.gpa.free(f.line_starts); - f.history.destroy(p.gpa); - f.content = sf.content; - f.line_starts = sf.line_starts; - f.history = sf.history; - f.revision = sf.revision; - f.saved_revision = sf.saved_revision; - f.saved_hash = sf.saved_hash; - f.saved_len = sf.saved_len; - f.twin = sf.twin; - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = &.{}; - f.syntax_dirty = true; - // Its dot as dumped, read now that its text is back. - if (dot) |d| if (d[0] <= d[1] and d[1] <= f.content.len) { - const a = modal.positionAt(f.content, d[0]); - const h = modal.positionAt(f.content, if (d[1] > d[0]) modal.prevGrapheme(f.content, d[1]) else d[0]); - pane.body.vsel = .{ .active = d[1] > d[0], .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; - pane.body.cur_row = @intCast(h.row); - pane.body.cur_col = @intCast(h.col); - }; -} - pub const TwinGroup = struct { id: u32, saved_revision: u32, @@ -1644,6 +1323,8 @@ pub fn redo(p: *Pardes, pane: *Pane) void { /// `<file> deleted on disk (Save writes it again)`, logged `changed /// <serial> deleted`. pub fn deleted(p: *Pardes, id: u8) void { + const taped = pardes.tape.enter(p, .{ .file_deleted = id }); + defer pardes.tape.leave(p, taped); const pane = p.panes[id] orelse return; const f = if (pane.file) |*file| file else return; if (f.disk_gone) return; @@ -1700,6 +1381,17 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { /// re-highlight the visible window of any file whose syntax went stale /// (edit, scroll, load) — visible-range-first so big files stay snappy +/// The declarations a TreeContext pane's context rows are drawn from, for +/// its text as it is now: found in the step (Pardes.sync), never only by a +/// render, since the view's geometry is made of them (`geometry`). +pub fn refreshContext(p: *Pardes, pane: *Pane, f: *State) void { + if (!f.tree_context or !supportsContext(pane) or f.context_revision == f.revision) return; + const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, f.content) catch return; + if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations); + f.context_declarations = declarations; + f.context_revision = f.revision; +} + pub fn refreshHighlights(p: *Pardes) void { const tz = tracy.zone(@src(), "refreshHighlights"); defer tz.end(); @@ -1707,12 +1399,6 @@ pub fn refreshHighlights(p: *Pardes) void { const pane = slot orelse continue; if (pane.file == null) continue; const f = &pane.file.?; - if (f.tree_context and supportsContext(pane) and f.context_revision != f.revision) { - const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, f.content) catch continue; - if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations); - f.context_declarations = declarations; - f.context_revision = f.revision; - } if (f.mini != null) { f.syntax_dirty = false; continue; @@ -1904,18 +1590,79 @@ pub fn visualRow(line: []const u8, col: usize, width: usize) VisualRow { } } -pub fn bodyText(arena: std.mem.Allocator, pane: *Pane, f: *State, wrap: bool) ![]const u8 { - const width = wrapWidth(pane, wrap); +/// The body's text as it is shown: its geometry's rows, each a line's +/// number and its stretch of the line. +pub fn bodyText(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const u8 { + geometry(pane); + const out = try arena.alloc(u8, pane.geometry_len); + const filled = fillBody(out, pane, f, wrapWidth(pane, pane.view.wrap), false); + std.debug.assert(filled == out.len); + return out; +} + +/// The pane's view geometry for its state as it is now: the wrap map (the +/// line, column and pad each body row starts at), the context rows, and how +/// many rows the body layer has. Made again when anything it is made of +/// changes (`geometryKey`), by whoever asks first, the render or a step that +/// reads it: so a core that never draws has the geometry of one that does +/// (docs/next-daemon.md). What it reads of the session is the pane's `view`, +/// which each step sets. +pub fn geometry(pane: *Pane) void { + const f = if (pane.file) |*file| file else return; + const key = geometryKey(pane, f); + if (pane.geometry_key == key) return; + pane.geometry_key = key; + pane.body_rows = 0; + pane.body_visible_rows = 0; + pane.context_row_limit = null; + pane.geometry_len = mapRows(pane, f); + // A body with context rows is a layer taller than the grid's rows, its + // context rows at the tagline's height (body_layer.joinBody). + const v = pane.view; + if (!v.layered or pane.collapsed or v.rect_h <= pane.tag_rows) return; + const logical_rows = @min(@as(usize, pane.rows) + pane.context_rows, pane.wrap_line.len); + if (pane.context_rows == 0 or logical_rows <= pane.context_rows) return; + pane.body_rows = @intCast(logical_rows); + const bh: usize = @max(1, v.body_h); + const th: usize = std.math.clamp(v.tagline_h, 1, bh); + const body_pixels = @as(usize, v.rect_h - pane.tag_rows) * bh; + const limit: u16 = @intCast(@min(pane.context_rows, (body_pixels -| bh) / th)); + pane.context_row_limit = limit; + pane.body_visible_rows = @intCast(@min(logical_rows, limit + @max(1, (body_pixels -| @as(usize, limit) * th) / bh))); + pane.geometry_len = mapRows(pane, f); +} + +/// One walk of the rows the body shows, recording the wrap map: the bytes +/// its text takes. +fn mapRows(pane: *Pane, f: *State) usize { + const width = wrapWidth(pane, pane.view.wrap); pane.body_wrapped = width > 0; f.tables.ensure(pane.gpa, f); prepareContextRows(pane, f); - pane.wrap_n = 0; + return fillBody(null, pane, f, width, true); +} - const len = fillBody(null, pane, f, width, false); - const out = try arena.alloc(u8, len); - const filled = fillBody(out, pane, f, width, true); - std.debug.assert(filled == out.len); - return out; +/// Everything the geometry is made of, hashed: the text (its revision and +/// length), where it is scrolled, the pane's size, its tables as far as +/// they have been read, its context declarations, the session's view. +fn geometryKey(pane: *const Pane, f: *const State) u64 { + const t = &f.tables; + const facts = .{ + f.revision, f.content.len, f.scroll, pane.hscroll, + pane.rows, pane.cols, pane.tag_rows, pane.collapsed, + pane.query != null, f.pager, f.mini != null, f.output != null, + 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, if (t.pending) |r| r.at else std.math.maxInt(usize), + pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h, + pane.view.rect_h, + }; + // One hash of them laid out as words: every reader of the map asks for + // this key, a hundred times a frame. + var words: [facts.len]u64 = undefined; + inline for (facts, &words) |fact, *w| w.* = if (@TypeOf(fact) == bool) @intFromBool(fact) else if (@typeInfo(@TypeOf(fact)).int.signedness == .signed) @bitCast(@as(i64, fact)) else fact; + // Never the "made for nothing" key a reset leaves (`geometry_key = 0`). + return std.hash.Wyhash.hash(0x9e0, std.mem.sliceAsBytes(&words)) | 1; } /// Run the file-body row walk. With no destination it is the exact sizing |
