//! A file at a revision, as jj shows it (PARDES.md "Changes on the source //! view"): the address `path@rev`, with a place `path@rev:line`, which a //! Look resolves anywhere, and `At ` in a file's pane. //! //! What jj says is the session machine's: it is run out of the turn as a //! site of the step's tape (`Site.jj`), its answer recorded; a replica //! replays the answer and never runs jj. A revision's pane is an output //! (`Output.Origin.revision`, its argument the revision), named //! `path@rev`, coloured as its file (File.langPath), read-only (File.edit //! refuses its text a change; a bare Save says why). const std = @import("std"); const pardes = @import("root.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; const File = pardes.panes.File; const Output = pardes.panes.Output; const look = @import("look.zig"); const layout = @import("layout.zig"); const diff = @import("diff.zig"); const syntax = @import("syntax.zig"); /// What jj answered: why not, in its own words (its first line, without /// `Error: `), or the file's bytes. The caller's, in the allocator the site /// was given. pub const Shown = union(enum) { refused: []u8, bytes: []u8 }; /// The longest text a revision's pane takes. const bytes_max = 256 << 20; /// `text`, not a file of its own, read as `path@rev`: the text before its /// first `@` the path, the rest the revision (`main`, `@-`, `main@origin`). pub fn split(text: []const u8) ?struct { path: []const u8, rev: []const u8 } { const at = std.mem.indexOfScalar(u8, text, '@') orelse return null; if (at == 0 or at + 1 == text.len or text[at - 1] == '/') return null; return .{ .path = text[0..at], .rev = text[at + 1 ..] }; } /// The file at `path` (absolute) at revision `rev`, as jj shows it. pub fn show(p: *Pardes, path: []const u8, rev: []const u8) Shown { const set = fileset(p.scratch.allocator(), path) catch return refusal(p.gpa, "out of memory"); return p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dirOf(path), @as([]const []const u8, &.{ "file", "show", "-r", rev, "--", set }) }); } fn dirOf(path: []const u8) []const u8 { return std.Io.Dir.path.dirname(path) orelse "/"; } /// The name of `path` as a fileset of that one file in its directory, /// taken literally whatever it is called. fn fileset(arena: std.mem.Allocator, path: []const u8) ![]u8 { var set: std.ArrayList(u8) = .empty; try set.appendSlice(arena, "file:\""); for (std.Io.Dir.path.basename(path)) |c| { if (c == '"' or c == '\\') try set.append(arena, '\\'); try set.append(arena, c); } try set.append(arena, '"'); return set.toOwnedSlice(arena); } /// jj with `args`, run in `dir`: what it printed, or its refusal. The /// working copy is left alone (`--ignore-working-copy`): an editor's read /// makes no operation, and `@` is the working copy as jj last saw it. fn runHost(gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) Shown { // The tape's io spawns nothing (its allocator fails, its environment is // empty): one of its own, with this process's environment. var threaded: std.Io.Threaded = .init_single_threaded; threaded.allocator = gpa; threaded.environ = .{ .process_environ = .{ .block = .{ .slice = std.mem.span(std.c.environ) } } }; threaded.environ_initialized = false; const io = threaded.io(); var argv: std.ArrayList([]const u8) = .empty; defer argv.deinit(gpa); argv.appendSlice(gpa, &.{ "jj", "--ignore-working-copy", "--color=never", "--no-pager" }) catch return refusal(gpa, "out of memory"); argv.appendSlice(gpa, args) catch return refusal(gpa, "out of memory"); // As Stream's children: this thread's mask is the child's. const none = std.posix.sigemptyset(); var kept: std.posix.sigset_t = undefined; std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, &kept); var child = std.process.spawn(io, .{ .argv = argv.items, .cwd = .{ .path = dir }, .stdin = .ignore, .stdout = .pipe, .stderr = .pipe }) catch |err| { std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null); return refusal(gpa, if (err == error.FileNotFound) "no jj" else @errorName(err)); }; std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null); defer child.kill(io); // One after the other, on an io with no thread to read both at once: // jj says a refusal in a line and nothing on stdout. var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var err: std.ArrayList(u8) = .empty; defer err.deinit(gpa); for ([_]std.Io.File{ child.stdout.?, child.stderr.? }, [_]*std.ArrayList(u8){ &out, &err }, [_]usize{ bytes_max, 64 << 10 }) |from, to, cap| { var chunk: [64 * 1024]u8 = undefined; while (to.items.len <= cap) { const n = from.readStreaming(io, &.{&chunk}) catch break; if (n == 0) break; to.appendSlice(gpa, chunk[0..n]) catch return refusal(gpa, "out of memory"); } } const term = child.wait(io) catch |e| return refusal(gpa, @errorName(e)); if (out.items.len > bytes_max) return refusal(gpa, "too much to show"); if (term == .exited and term.exited == 0) return .{ .bytes = out.toOwnedSlice(gpa) catch return refusal(gpa, "out of memory") }; var first = std.mem.trim(u8, err.items[0 .. std.mem.indexOfScalar(u8, err.items, '\n') orelse err.items.len], " \t\r"); if (std.mem.startsWith(u8, first, "Error: ")) first = first["Error: ".len..]; return refusal(gpa, if (first.len > 0) first else "jj failed"); } fn refusal(gpa: std.mem.Allocator, why: []const u8) Shown { return .{ .refused = gpa.dupe(u8, why) catch &.{} }; } /// A revision's pane: the file it is of (its name without `@rev`) and the /// revision. Null for any other pane. pub fn of(f: *const File.State) ?struct { path: []const u8, rev: []const u8 } { // The pane's own, not a copy: the revision is a slice of it. const o = if (f.output) |*o| o else return null; if (o.from != .revision) return null; return .{ .path = f.path[0 .. f.path.len - o.arg().len - 1], .rev = o.arg() }; } /// `path` (absolute) at `rev` in a pane: the one showing it focused, else /// one made beside pane `near` (or, with `replace`, in its place: it goes), /// wearing `near`'s layers; its cursor on line `line` (0: the first). Said /// at `near` when jj refuses. The pane's id. pub fn open(p: *Pardes, near: usize, path: []const u8, rev: []const u8, at: look.Spot, replace: bool) ?usize { const name = std.fmt.allocPrint(p.scratch.allocator(), "{s}@{s}", .{ path, rev }) catch return null; for (p.panes, 0..) |slot, i| if (slot) |shown| if (shown.file) |*f| if (of(f) != null and std.mem.eql(u8, f.path, name)) { look.focusPaneLine(p, i, at, .center); return i; }; if (rev.len > Output.max_arg) return refused(p, near, "a revision that long"); const free = p.freeSlot() orelse { p.reportError(.at(near), "At", error.NoPaneSlots); return null; }; const bytes = switch (show(p, path, rev)) { .refused => |why| { defer p.gpa.free(why); return refused(p, near, why); }, .bytes => |b| b, }; const pane = Output.open(p, free, std.Io.Dir.path.dirname(path) orelse "/", .revision, rev, bytes) catch |err| { p.gpa.free(bytes); p.reportError(.at(near), "At", err); return null; }; const f = &pane.file.?; const owned = p.gpa.dupe(u8, name) catch { p.removePane(free, near) catch {}; return null; }; p.gpa.free(f.path); f.path = owned; if (p.panes[near]) |from| pane.layers = from.layers; layout.placeNew(p, near, near, free, .doc); if (replace) p.removePane(near, free) catch |err| p.reportError(.at(free), "At", err); layout.compute(p); // Sized for its place before it is centred there. p.sync(); look.focusPaneLine(p, free, at, .center); return free; } fn refused(p: *Pardes, id: usize, why: []const u8) ?usize { var line: pardes.Kind.Buf(512) = .{}; p.reportFailure(id, line.print("At: {s}", .{why[0..@min(why.len, 480)]})); return null; } /// The `At` word (builtins.zig registers it): in a file's pane, that file /// at revision `rev` beside it; in a revision's pane, the same file at /// `rev` in its place, its cursor's line kept; bare there, the file. pub fn word(c: pardes.builtins.Ctx) void { const p = c.p; const f = if (c.pane.file) |*file| file else return p.reportFailure(c.id, "At: only a file's pane takes it"); const rev = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); const at: look.Spot = .{ .line = @intCast(@max(0, c.pane.body.cur_row) + 1) }; if (of(f)) |r| { if (rev.len == 0) return look.lookAt(p, c.id, r.path); const path = p.scratch.allocator().dupe(u8, r.path) catch return; _ = open(p, c.id, path, rev, at, true); return; } if (f.output != null or pardes.filesystem.localPath(f.path) == null) return p.reportFailure(c.id, "At: only a file's pane takes it"); if (rev.len == 0) return p.reportFailure(c.id, "At: which revision?"); _ = open(p, c.id, f.path, rev, at, false); } /// A Look at `text` (a path relative to `dir`, then `@rev`) that names no /// file: a file at a revision, if the path is a file. False when it is not /// one, for the look to go on. pub fn looked(p: *Pardes, id: usize, dir: []const u8, text: []const u8, at: look.Spot) bool { const r = split(text) orelse return false; const path = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, r.path }) catch return false; if (pardes.filesystem.localPath(path) == null or pardes.exec.kindOf(p.tape, path) != .file) return false; _ = open(p, id, path, r.rev, at, false); return true; } // ---- `Changes [revset]` (PARDES.md: pinned changes as lanes): what jj // answers for it, kept as flat arrays, the session's ---- /// What jj answered for a pane's `Changes`: replicated state, the /// session's (`Pardes.changes`, by the pane's serial: a client never runs /// jj; one that joins late has it in the dump), its revset with it, drawn /// by each view that shows them (File.Layers.lanes: a view holds that, not /// the revset; one set a pane, so a view's `Changes other` replaces what /// every view shows). From two jj runs off the loop (`Ask`): the changes /// with their diffs of the file (`jj log -p --git`, the diffs read with /// diff.zig's walk), and who wrote each line of the shown revision (`jj /// file annotate`). pub const Changes = struct { pub const replica = .{ .len = .{.{ "revset", "revset_len" }} }; /// The pane's (its serial). serial: u32, revset: [revset_max]u8 = undefined, revset_len: u8 = 0, /// The revset's changes that touch the file, oldest first. pins: []Pin = &.{}, /// A value a line of the shown revision. lines: []Line = &.{}, /// Each pin's hunks in the file, a pin's together, each in place order. hunks: []Hunk = &.{}, /// The ghost rows' text: the lines the hunks took away, hunk after /// hunk, each with its `\n`; then each pin's description row. ghost_text: []u8 = &.{}, /// The rows a view shows that the text has not, in `at` order. ghosts: []Ghost = &.{}, /// The words a changed line changed: byte ranges of a line (`Line`), or /// of `ghost_text` (`Ghost`), each `.{ from, to }`. marks: [][2]u32 = &.{}, pub fn deinit(c: *Changes, gpa: std.mem.Allocator) void { gpa.free(c.pins); gpa.free(c.lines); gpa.free(c.hunks); gpa.free(c.ghost_text); gpa.free(c.ghosts); gpa.free(c.marks); c.* = .{ .serial = c.serial }; } pub fn pinned(c: *const Changes) []const u8 { return c.revset[0..c.revset_len]; } pub const revset_max = 64; }; /// What jj answered for pane `serial`'s `Changes` (`Pardes.changes`), if anything. pub fn answered(p: *Pardes, serial: u32) ?*Changes { for (p.changes.answers.items) |*c| if (c.serial == serial) return c; return null; } /// What jj answered for pane `serial`'s `Churn` (`Pardes.changes`), counted. pub fn churned(p: *Pardes, serial: u32) ?*Heat { for (p.changes.heats.items) |*h| if (h.serial == serial) return h; return null; } /// Pane `serial`'s answers let go (the pane's end). pub fn forget(p: *Pardes, serial: u32) void { for (p.changes.answers.items, 0..) |*c, i| if (c.serial == serial) { c.deinit(p.gpa); _ = p.changes.answers.swapRemove(i); break; }; forgetHeat(p, serial); } fn forgetHeat(p: *Pardes, serial: u32) void { for (p.changes.heats.items, 0..) |*h, i| if (h.serial == serial) { h.deinit(p.gpa); _ = p.changes.heats.swapRemove(i); return; }; } /// A pane's `Churn [window]` (PARDES.md "Changes on the source view": /// churn per declaration): for each line, how many of the window's changes /// touched the declaration it is in (tree-sitter's innermost, as /// TreeContext finds them; 0 outside any), counted in every process from /// jj's raw answer (`heatOf`), replicated state as `Changes` is, riding /// with the lines through edits. pub const Heat = struct { pub const replica = .{ .len = .{.{ "revset", "revset_len" }} }; serial: u32, /// The window as jj was asked it. revset: [Changes.revset_max]u8 = undefined, revset_len: u8 = 0, lines: []u16 = &.{}, /// The file's hottest declaration's count, the gradient's top. hottest: u16 = 0, /// jj's raw answer until it is counted (`parsed`): its log, then its /// text of the revision from `pending_was` on. pending: []u8 = &.{}, pending_was: u32 = 0, pub fn deinit(h: *Heat, gpa: std.mem.Allocator) void { gpa.free(h.lines); gpa.free(h.pending); } pub fn window(h: *const Heat) []const u8 { return h.revset[0..h.revset_len]; } }; /// A pinned change, as `jj log` says it. pub const Pin = struct { pub const replica = .{ .len = .{ .{ "author", "author_len" }, .{ "title", "title_len" } } }; id: [8]u8, /// Its author's time, in seconds since the epoch. time: i64, author: [32]u8 = undefined, author_len: u8 = 0, /// Its description's first line, cut to fit. title: [96]u8 = undefined, title_len: u8 = 0, }; /// A line of the shown revision: which pin wrote it (its place in /// `Changes.pins`) or none, and whether that pin added it whole (no line /// it took away stood in its place) or changed one. pub const Line = struct { pin: PinIndex, whole: bool = false, /// The pins whose lanes run down it, outermost (oldest) first (`nest`). lanes: [levels]PinIndex = @splat(.none), /// A changed line's words that came (`Changes.marks[marks..][0..nmarks]`, /// byte ranges of the line). marks: u32 = 0, nmarks: u16 = 0, }; /// The lanes a row shows at most (a window's strips the same). pub const levels = pardes.Lane.levels; pub const PinIndex = enum(u16) { none = std.math.maxInt(u16), _, }; /// The changes a `Changes` takes at most. pub const pins_max = 64; /// A run of lines a pin took away and wrote in their place, in its own /// revisions' numbers (from 1; `old_len` 0: it only wrote, after old line /// `old_start`). pub const Hunk = struct { /// Its pin, or `carrier`: a change between the pins the revset does /// not pin (its hunks only carry places, `carried`). pin: u16, /// Its change's place in jj's answer, oldest first. step: u16, old_start: u32, old_len: u32, new_start: u32, new_len: u32, /// Its removed lines' text: `Changes.ghost_text[removed..][0..removed_len]`. removed: u32, removed_len: u32, pub const carrier = std.math.maxInt(u16); }; /// A row a view shows that is not a line of the text (PARDES.md "Changes on /// the source view": a ghost row): a line a pin took away whole, drawn where /// it stood, red across; or a pin's description (`id title author age`), /// after its last line, in its lane's colour. No number, the cursor steps /// over it, search and selection do not see it; a Look on it goes to its /// line in the revision it came from (`lookGhost`). A line a pin CHANGED /// is a ghost row too: its old text right above the line, the words that /// went in red, the line with the words that came in green. pub const Ghost = struct { /// The line of the shown text it stands before (`lines.len`: after the /// last). It rides with the text as the lines' values do (`splice`). at: u32, pin: u16, kind: Kind, /// Its line, from 1: a line taken away, in its pin's parent; a /// description, its pin's first line written, in the pin's revision. line: u32, /// Its text, `Changes.ghost_text[text..][0..len]`, no `\n`. text: u32, len: u32, /// A changed line's: the words that went (`Changes.marks`). marks: u32 = 0, nmarks: u16 = 0, /// A line taken away whole; a line's old text, the line that took its /// place right below it; a pin's description. pub const Kind = enum(u8) { deleted, changed, description }; }; /// The `Changes` word (builtins.zig registers it): in a file's pane (or a /// revision's), the changes `revset` names pinned on the pane and shown in /// this view; another revset replaces them (in every view that shows /// them). Bare: shown in this view or not, the pane's pinned ones (none /// yet: `@`, the change against its parent). What jj refuses is said in /// its words. pub fn changesWord(c: pardes.builtins.Ctx) void { const p = c.p; const pane = c.pane; const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Changes: only a file's pane takes it"); const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (arg.len == 0 and pane.layers.lanes > 0) { pane.layers.lanes = 0; return; } const cells: u8 = if (p.view().frontend.windowed) 2 else levels; if (arg.len == 0 and answered(p, pane.serial) != null) { pane.layers.lanes = cells; return; } const revset = if (arg.len == 0) "@" else arg; if (revset.len > Changes.revset_max) return p.reportFailure(c.id, "Changes: a revset that long"); const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r| .{ .path = r.path, .rev = r.rev } else if (f.output == null and pardes.filesystem.localPath(f.path) != null) .{ .path = f.path, .rev = "@" } else return p.reportFailure(c.id, "Changes: only a file's pane takes it"); pane.layers.lanes = cells; ask(p, .changes, c.id, pane.serial, shown.path, shown.rev, revset); } /// The `Churn` word (builtins.zig registers it): in a file's pane (or a /// revision's), how many changes in `window` touched each declaration, /// shown in this view as a heat lane after the line number and a strip by /// the scroll thumb. The window: a revset, or a span of time back from now /// (`3d`, `2w`, `6m`, `1y`: what the file's history has in it); bare, shown /// here or not, and with none counted yet the file's whole history (`::` /// the revision shown). pub fn churnWord(c: pardes.builtins.Ctx) void { const p = c.p; const pane = c.pane; const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Churn: only a file's pane takes it"); const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (arg.len == 0 and pane.layers.heat > 0) { pane.layers.heat = 0; return; } if (arg.len == 0 and churned(p, pane.serial) != null) { pane.layers.heat = 1; return; } const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r| .{ .path = r.path, .rev = r.rev } else if (f.output == null and pardes.filesystem.localPath(f.path) != null) .{ .path = f.path, .rev = "@" } else return p.reportFailure(c.id, "Churn: only a file's pane takes it"); var buf: [Changes.revset_max]u8 = undefined; const window = spanOf(&buf, shown.rev, arg) orelse arg; if (window.len > Changes.revset_max) return p.reportFailure(c.id, "Churn: a window that long"); pane.layers.heat = 1; ask(p, .churn, c.id, pane.serial, shown.path, shown.rev, window); } /// `arg` as a revset: bare, every change of the revision's history; a span /// of time (a count and `h`, `d`, `w`, `m` or `y`), its changes since then /// (jj's `author_date`); null for a revset. fn spanOf(buf: []u8, rev: []const u8, arg: []const u8) ?[]const u8 { if (arg.len == 0) return std.fmt.bufPrint(buf, "::({s})", .{rev}) catch null; const n = std.fmt.parseInt(u16, arg[0 .. arg.len - 1], 10) catch return null; const unit: []const u8 = switch (arg[arg.len - 1]) { 'h' => "hours", 'd' => "days", 'w' => "weeks", 'm' => "months", 'y' => "years", else => return null, }; return std.fmt.bufPrint(buf, "::({s}) & author_date(after:\"{d} {s} ago\")", .{ rev, n, unit }) catch null; } // ---- jj off the loop (Stream.zig's model) ---- /// A `Changes` asked of jj: the pane (by serial), the file it shows and the /// revision whose lines are annotated, the revset. Its two runs go on a /// worker where the host has one (the `search` effect: Stream.start), their /// raw answers back as one input (`Event.search`) stamped /// with its generation, which the step takes (`receive`): a replica replays /// that input and never runs jj. With no worker (a test), on the loop, each /// run a site of the step's tape. pub const Ask = struct { gpa: std.mem.Allocator, kind: Kind = .changes, /// What its answer is made with: the shell's, which frees a batch. out: std.mem.Allocator, gen: u32, serial: u32, path: []u8, rev: []u8, revset: []u8, /// `Changes`' (with who wrote each line), or `Churn`'s (with jj's text /// of the revision, which the counts are lined up with). pub const Kind = enum(u8) { changes, churn }; fn make(gpa: std.mem.Allocator, kind: Kind, gen: u32, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) error{OutOfMemory}!*Ask { const a = try gpa.create(Ask); errdefer gpa.destroy(a); const owned = try std.mem.concat(gpa, u8, &.{ path, rev, revset }); a.* = .{ .gpa = gpa, .kind = kind, .out = gpa, .gen = gen, .serial = serial, .path = owned[0..path.len], .rev = owned[path.len..][0..rev.len], .revset = owned[path.len + rev.len ..] }; return a; } pub fn deinit(a: *Ask) void { a.gpa.free(a.path.ptr[0 .. a.path.len + a.rev.len + a.revset.len]); a.gpa.destroy(a); } }; /// The session's `Changes` (`Pardes.changes`): jj's answers, a pane's by /// its serial; the `Changes` jj runs for, one at a time, the one asked /// while it runs (only the last asked is pinned), and how many were asked /// (the generation). In every digest of the session: nothing until a /// `Changes` is asked, then one update while nothing is asked of jj. pub const Session = struct { answers: std.ArrayList(Changes) = .empty, heats: std.ArrayList(Heat) = .empty, task: ?Task = null, next: ?*Ask = null, count: u32 = 0, pub fn digest(c: *const Session, h: *pardes.walk.Hasher) void { if (c.count == 0) return; const bits: u64 = c.count | @as(u64, @intFromBool(c.task != null)) << 32 | @as(u64, @intFromBool(c.next != null)) << 33; h.update(std.mem.asBytes(&bits)); pardes.walk.hash(std.ArrayList(Changes), &c.answers, h); pardes.walk.hash(std.ArrayList(Heat), &c.heats, h); if (c.task) |*t| pardes.walk.hash(Task, t, h); if (c.next) |n| pardes.walk.hash(Ask, n, h); } /// The session's end: the worker canceled, the asks and the answers /// let go. pub fn deinit(c: *Session, gpa: std.mem.Allocator) void { if (c.task) |t| { c.task = null; if (t.future) |f| pardes.Stream.join(f, t.io.?, .cancel); t.ask.deinit(); } if (c.next) |a| { c.next = null; a.deinit(); } for (c.answers.items) |*a| a.deinit(gpa); c.answers.deinit(gpa); for (c.heats.items) |*h| h.deinit(gpa); c.heats.deinit(gpa); } }; /// The `Changes` jj runs for, and its worker. pub const Task = struct { // The worker the host started for it, live: a replica has none. pub const replica = .{ .authority = .{ "future", "io" } }; ask: *Ask, future: ?std.Io.Future(void) = null, io: ?std.Io = null, }; /// A `Changes` generation has this bit (a search's and a parse's count /// from 0; a paint's has the top one). pub const gen_bit: u32 = 1 << 29; fn liveGen(c: *const Session) u32 { return gen_bit | (c.count & (gen_bit - 1)); } /// Ask jj of `revset` for pane `serial` (said at pane `id` while it runs): /// what the pane shows stays until the answer lands. fn ask(p: *Pardes, kind: Ask.Kind, id: usize, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) void { p.changes.count +%= 1; const a = Ask.make(p.gpa, kind, liveGen(&p.changes), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory"); p.setStatus(.at(id), if (kind == .churn) "Churn: jj\u{2026}" else "Changes: jj\u{2026}"); if (p.changes.task != null) { if (p.changes.next) |old| old.deinit(); p.changes.next = a; return; } go(p, a); } fn go(p: *Pardes, a: *Ask) void { p.changes.task = .{ .ask = a }; if (p.tape.has(p, .search)) return p.emit(.{ .search = .{ .gen = a.gen } }); runHere(p, a.gen, false); } /// The host's `search` effect for a `Changes` generation (Stream.start): /// its runs on a worker that sends to `sink`. pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void { const t = if (p.changes.task) |*t| t else return; if (t.ask.gen != gen or t.future != null) return; t.ask.out = gpa; // No worker to be had: here, its answer an input. t.future = io.concurrent(work, .{ t.ask, ctx, sink }) catch return runHere(p, gen, true); t.io = io; } fn work(a: *Ask, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void { const b = answer(null, a.out, a); if (!sink(ctx, b)) b.deinit(a.out); } /// With no worker: the runs here, each a site (a replica replays them). /// `in_call`: in the host's `search` entry, the answer handed in as an /// input, as a worker's is. pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void { const t = p.changes.task orelse return; if (t.ask.gen != gen or t.future != null) return; const b = answer(p, p.gpa, t.ask); defer b.deinit(p.gpa); if (in_call) p.update(.{ .search = b }) else receive(p, &b); } /// jj's two answers for `a`, raw, in `gpa`: through `p`'s tape when given /// (on the loop), else run here (a worker). fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batch { const failed = struct { fn f(g: std.mem.Allocator, at: *const Ask, why: []u8) pardes.Stream.Batch { _ = g; return .{ .gen = at.gen, .rows = why, .end = .failed }; } }.f; const set = fileset(gpa, a.path) catch return failed(gpa, a, refusal(gpa, "out of memory").refused); defer gpa.free(set); // The changes, oldest first, each with its diff of the file: one run. // With them the changes between the first and the shown revision that // the revset does not pin (marked so), whose hunks move the places of // the lines the older pins took away. const query = std.fmt.allocPrint(gpa, "(({s}) | (roots({s})::({s}))) & files({s})", .{ a.revset, a.revset, a.rev, set }) catch return failed(gpa, a, refusal(gpa, "out of memory").refused); defer gpa.free(query); const template = logTemplate(gpa, a.revset) catch return failed(gpa, a, refusal(gpa, "out of memory").refused); defer gpa.free(template); const log_args = [_][]const u8{ "log", "--no-graph", "--reversed", "-r", query, "-T", template, "--git", "--context=0", "--", set }; const logged = switch (runJj(p, gpa, dirOf(a.path), &log_args)) { .refused => |why| return failed(gpa, a, why), // The wall clock first, read where jj runs (an input, as jj's // answer is): the descriptions' ages are of it. .bytes => |bytes| stamped: { defer gpa.free(bytes); const now = if (p) |q| q.tape.value(.clock, wallSeconds, .{}) else wallSeconds(); break :stamped std.fmt.allocPrint(gpa, "{d}\n{s}", .{ now, bytes }) catch return failed(gpa, a, refusal(gpa, "out of memory").refused); }, }; var it = std.mem.splitScalar(u8, logged, '\n'); const any = while (it.next()) |l| { if (if (entryOf(l)) |e| e.pinned else false) break true; } else false; if (!any) return .{ .gen = a.gen, .rows = logged, .end = .done }; // Churn: jj's text of the revision, to line the counts up with the pane's. if (a.kind == .churn) return switch (runJj(p, gpa, dirOf(a.path), &.{ "file", "show", "-r", a.rev, "--", set })) { .refused => |why| { gpa.free(logged); return failed(gpa, a, why); }, .bytes => |shown| .{ .gen = a.gen, .rows = logged, .styles = shown, .end = .done }, }; // Who wrote each line: a path, not a fileset (annotate takes one file // as it is named). const annotate_args = [_][]const u8{ "file", "annotate", "-r", a.rev, "-T", "commit.change_id().short(8) ++ \"\\t\" ++ content", "--", std.Io.Dir.path.basename(a.path) }; return switch (runJj(p, gpa, dirOf(a.path), &annotate_args)) { .refused => |why| { gpa.free(logged); return failed(gpa, a, why); }, .bytes => |annotated| .{ .gen = a.gen, .rows = logged, .styles = annotated, .end = .done }, }; } /// The wall clock, in seconds since the epoch (a `.clock` read as `u32`: /// a replica's guess and a stamp answer it so too). fn wallSeconds() u32 { var ts: std.c.timespec = undefined; if (std.c.clock_gettime(.REALTIME, &ts) != 0) return 0; return std.math.cast(u32, ts.sec) orelse 0; } fn runJj(p: ?*Pardes, gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) Shown { return if (p) |q| q.tape.site(.jj, gpa, runHost, .{ gpa, dir, args }) else runHost(gpa, dir, args); } /// A `Changes` answer (`Event.search` with a `Changes` generation), /// borrowed: the last asked of its kind is parsed and pinned (or counted, /// a `Churn`'s) on its pane (the ask names it); an earlier one's, or a gone /// pane's, dropped. Then the one asked meanwhile goes. pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch) void { var revset: [Changes.revset_max]u8 = undefined; var revset_len: usize = 0; var serial: u32 = 0; var kind: Ask.Kind = .changes; if (p.changes.task) |t| if (t.ask.gen == b.gen) { p.changes.task = null; if (t.future) |f| pardes.Stream.join(f, t.io.?, .wait); serial = t.ask.serial; kind = t.ask.kind; revset_len = t.ask.revset.len; @memcpy(revset[0..revset_len], t.ask.revset); t.ask.deinit(); }; defer if (p.changes.task == null) if (p.changes.next) |next| { p.changes.next = null; go(p, next); }; if (revset_len == 0) return; // A later one of its kind asked meanwhile: only that one is shown. if (p.changes.next) |n| if (n.kind == kind) return; const id = p.paneBySerial(serial) orelse return; switch (kind) { .changes => pinAnswer(p, id, b, revset[0..revset_len]), .churn => heatAnswer(p, id, b, revset[0..revset_len]), } } /// A splice of `f`'s text, before its bytes go in (File.edit, the one /// place a text changes, an undo's too): each pane showing it that has /// pins keeps a value for each of its lines, so the values ride with the /// lines, never asking jj again: the lines a splice takes out take their /// values with them, and a line it puts in is nobody's. pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: []const u8) void { var i = p.changes.answers.items.len; while (i > 0) { i -= 1; const c = &p.changes.answers.items[i]; const id = p.paneBySerial(c.serial) orelse continue; const shown = if (p.panes[id].?.file) |*shown| shown else continue; if (shown.content.ptr != f.content.ptr) continue; splice(p.gpa, c, f.content, off, len, bytes) catch { // No room for it: its values would lie, so it goes. c.deinit(p.gpa); _ = p.changes.answers.swapRemove(i); showGhosts(p, p.panes[id].?); }; } i = p.changes.heats.items.len; while (i > 0) { i -= 1; const h = &p.changes.heats.items[i]; const id = p.paneBySerial(h.serial) orelse continue; const shown = if (p.panes[id].?.file) |*shown| shown else continue; if (shown.content.ptr != f.content.ptr) continue; _ = spliceValues(u16, p.gpa, &h.lines, 0, f.content, off, len, bytes) catch { h.deinit(p.gpa); _ = p.changes.heats.swapRemove(i); }; } } /// `c`'s values spliced as `text`'s lines are by the splice of `len` bytes /// at `off` for `bytes`. A splice that starts in a line's leading blanks /// (at its start, or after its indent, as `o` puts a line in) leaves that /// line's text after what it puts in: the lines it takes and puts come /// before it. Else the line it starts in keeps its value, and the lines /// taken and put come after it. fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len: usize, bytes: []const u8) error{OutOfMemory}!void { const cut = try spliceValues(Line, gpa, &c.lines, .{ .pin = .none }, text, off, len, bytes) orelse return; const from = cut.from; const take = cut.take; const put = cut.put; // A ghost row stands before the line it stood before; one before a // line taken out, before the line after what took its place. for (c.ghosts) |*g| { if (g.at <= from) continue; g.at = @intCast(if (g.at < from + take) from + put else g.at - take + put); } } /// A value a line, `values`, spliced as `splice` says, a line put in /// `none`; null when no line is taken or put. fn spliceValues(comptime T: type, gpa: std.mem.Allocator, values: *[]T, none: T, text: []const u8, off: usize, len: usize, bytes: []const u8) error{OutOfMemory}!?struct { from: usize, take: usize, put: usize } { const taken = std.mem.count(u8, text[off..][0..len], "\n"); const put = std.mem.count(u8, bytes, "\n"); if (taken == 0 and put == 0) return null; const line_start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0; const in_lead = std.mem.trimStart(u8, text[line_start..off], " \t").len == 0; const from = std.mem.count(u8, text[0..line_start], "\n") + @intFromBool(!in_lead); if (from > values.len) return null; const take = @min(taken, values.len - from); const next = try gpa.alloc(T, values.len - take + put); @memcpy(next[0..from], values.*[0..from]); @memset(next[from..][0..put], none); @memcpy(next[from + put ..], values.*[from + take ..]); gpa.free(values.*); values.* = next; return .{ .from = from, .take = take, .put = put }; } /// jj's answer `b` for `revset` parsed and pinned on pane `id`, or its /// refusal said there. fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []const u8) void { const pane = p.panes[id].?; var line: pardes.Kind.Buf(512) = .{}; const f = if (pane.file) |*file| file else return; // Nothing pinned yet: no gutter for it. defer if (answered(p, pane.serial) == null) { pane.layers.lanes = 0; }; if (b.end == .failed) return p.reportFailure(id, line.print("Changes: {s}", .{b.rows[0..@min(b.rows.len, 480)]})); var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, f.content) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)})); switch (got) { .refused => |why| { defer p.gpa.free(why); return p.reportFailure(id, line.print("Changes: {s}", .{why[0..@min(why.len, 480)]})); }, .read => |*changes| { if (changes.pins.len == 0) { changes.deinit(p.gpa); const shown = if (of(f)) |r| r.path else f.path; return p.reportFailure(id, line.print("Changes: no change of `{s}` touches {s}", .{ revset, std.Io.Dir.path.basename(shown) })); } @memcpy(changes.revset[0..revset.len], revset); changes.revset_len = @intCast(revset.len); changes.serial = pane.serial; if (answered(p, pane.serial)) |kept| { kept.deinit(p.gpa); kept.* = changes.*; } else p.changes.answers.append(p.gpa, changes.*) catch { changes.deinit(p.gpa); return p.reportFailure(id, "Changes: out of memory"); }; p.setStatus(.at(id), ""); showGhosts(p, pane); }, } } /// jj's answer `b` for a `Churn` of `window` on pane `id`, kept raw /// until the text's declarations are there (a worker's parse, /// Stream.parseFor: a big file's parse is seconds in a Debug build, never /// the loop's), then counted (`count`); or its refusal said there. fn heatAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, window: []const u8) void { const pane = p.panes[id].?; var line: pardes.Kind.Buf(512) = .{}; if (pane.file == null) return; if (b.end == .failed) { if (churned(p, pane.serial) == null) pane.layers.heat = 0; return p.reportFailure(id, line.print("Churn: {s}", .{b.rows[0..@min(b.rows.len, 480)]})); } var heat: Heat = .{ .serial = pane.serial, .revset_len = @intCast(window.len) }; @memcpy(heat.revset[0..window.len], window); heat.pending = std.mem.concat(p.gpa, u8, &.{ b.rows, b.styles }) catch return p.reportFailure(id, "Churn: out of memory"); heat.pending_was = @intCast(b.rows.len); if (churned(p, pane.serial)) |kept| { kept.deinit(p.gpa); kept.* = heat; } else p.changes.heats.append(p.gpa, heat) catch { heat.deinit(p.gpa); pane.layers.heat = 0; return p.reportFailure(id, "Churn: out of memory"); }; parsed(p, pane.serial); } /// A parse of pane `serial`'s text landed (Stream.receiveParse), or jj's /// answer did: a `Churn` waiting on it counted when the declarations are of /// the text as it is, else a parse of it asked. pub fn parsed(p: *Pardes, serial: u32) void { const h = churned(p, serial) orelse return; if (h.pending.len == 0) return; const id = p.paneBySerial(serial) orelse return; const pane = p.panes[id].?; const f = if (pane.file) |*file| file else return; var line: pardes.Kind.Buf(512) = .{}; if (!syntax.supportsPath(f.path)) { // No grammar for it (a revision's pane too: its name ends `@rev`). p.reportFailure(id, line.print("Churn: no declarations to count in {s}", .{std.Io.Dir.path.basename(f.path)})); pane.layers.heat = 0; return forgetHeat(p, serial); } if (f.context.revision != f.revision) return pardes.Stream.parseFor(p, id); const lines = heatOf(p.gpa, p.scratch.allocator(), h.pending[0..h.pending_was], h.pending[h.pending_was..], f.content, f.context.declarations, &h.hottest) catch |err| return p.reportFailure(id, line.print("Churn: {s}", .{@errorName(err)})); p.gpa.free(h.pending); h.pending = &.{}; h.lines = lines; if (h.hottest > 0) return p.setStatus(.at(id), ""); p.reportFailure(id, line.print("Churn: no change of `{s}` touches a declaration of {s}", .{ h.window(), std.Io.Dir.path.basename(File.langPath(f)) })); pane.layers.heat = 0; forgetHeat(p, serial); } /// For each line of `text` (`decls` its declarations), how many of the window's /// changes in `logged` (jj's log, `p` the window's, `c` a later change /// that only carries places) touched the declaration it is in: tree- /// sitter's innermost, a line in none 0. A change's hunk touches the lines /// it wrote, carried into the revision jj showed (`was`) through the later /// changes' hunks, then into `text` (`Moved`); a hunk that only took lines /// away, the line above where they stood. Each change counts once a /// declaration. `hottest`: the largest count. fn heatOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, was: []const u8, text: []const u8, decls: []const syntax.ContextDeclaration, hottest: *u16) error{OutOfMemory}![]u16 { var hunks: std.ArrayList(Hunk) = .empty; var removed: std.ArrayList(u8) = .empty; var windowed: std.ArrayList(bool) = .empty; var starts: std.ArrayList(usize) = .empty; var it = std.mem.splitScalar(u8, logged, '\n'); while (it.next()) |l| if (entryOf(l)) |e| { if (windowed.items.len == Hunk.carrier) break; try windowed.append(arena, e.pinned); try starts.append(arena, it.index orelse logged.len); }; try starts.append(arena, logged.len); for (starts.items[0 .. starts.items.len - 1], starts.items[1..], 0..) |from, to, i| try hunksOf(arena, arena, Hunk.carrier, @intCast(i), logged[from..to], text, &.{}, &hunks, &removed, undefined, undefined); const n = lineCount(text); const moved: Moved = .of(was, text); // Each line's innermost declaration (outermost first, so an inner one // writes over its container's lines). const none = std.math.maxInt(u32); const inner = try arena.alloc(u32, n); @memset(inner, none); for (decls, 0..) |d, k| { if (d.start_line >= n) continue; @memset(inner[d.start_line..@min(n, d.end_line + 1)], @intCast(k)); } const counts = try arena.alloc(u16, decls.len); @memset(counts, 0); // The last change each declaration was counted for. const seen = try arena.alloc(u32, decls.len); @memset(seen, none); for (hunks.items) |h| { if (!windowed.items[h.step] or n == 0) continue; const a = carried(hunks.items, h.step, h.new_start -| 1 + @intFromBool(h.new_len == 0), moved) orelse continue; const b = carried(hunks.items, h.step, h.new_start -| 1 + h.new_len, moved) orelse continue; const lo = @min(if (h.new_len == 0) a -| 1 else a, n - 1); for (inner[lo..@max(lo + 1, @min(b, n))]) |k| { if (k == none or seen[k] == h.step) continue; seen[k] = h.step; counts[k] +|= 1; } } const out = try gpa.alloc(u16, n); hottest.* = 0; for (out, inner) |*o, k| { o.* = if (k == none) 0 else counts[k]; hottest.* = @max(hottest.*, o.*); } return out; } /// The pane's ghost rows as its geometry reads them (`Pane.ghosts`): the /// session's answers' (one set a pane), its geometry made again when they /// change (each step while a view shows them, and as an answer lands). pub fn showGhosts(p: *Pardes, pane: *Pane) void { const ch = answered(p, pane.serial); const ghosts: []const Ghost = if (ch) |c| c.ghosts else &.{}; const text: []const u8 = if (ch) |c| c.ghost_text else ""; if (ghosts.ptr == pane.ghosts.ptr and ghosts.len == pane.ghosts.len and text.ptr == pane.ghost_text.ptr) return; pane.ghosts = ghosts; pane.ghost_text = text; pane.geometry_key = 0; } const Read = union(enum) { refused: []u8, read: Changes }; /// jj's answers parsed: `logged` (the pins, each with its diff of the /// file) and `annotated` (who wrote each line of `text`, what the pane /// shows: a line is matched to the line its change added by its text). fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, annotated: []const u8, text: []const u8) error{OutOfMemory}!Read { var out: Changes = .{ .serial = 0 }; const now = std.fmt.parseInt(i64, logged[0 .. std.mem.indexOfScalar(u8, logged, '\n') orelse logged.len], 10) catch 0; var kept = false; defer if (!kept) out.deinit(gpa); var pins: std.ArrayList(Pin) = .empty; defer pins.deinit(gpa); // Each change jj answered, oldest first: its pin (or `Hunk.carrier`) // and where its diff starts in `logged`; then the end. const Step = struct { pin: u16, diff: usize }; var steps: std.ArrayList(Step) = .empty; var it = std.mem.splitScalar(u8, logged, '\n'); while (it.next()) |l| if (entryOf(l)) |e| { if (e.pinned and pins.items.len == pins_max) return .{ .refused = try std.fmt.allocPrint(gpa, "more than {d} changes touch it", .{pins_max}) }; if (steps.items.len == Hunk.carrier) return .{ .refused = try std.fmt.allocPrint(gpa, "more than {d} changes between them touch it", .{Hunk.carrier}) }; if (e.pinned) try pins.append(gpa, e.pin); try steps.append(arena, .{ .pin = if (e.pinned) @intCast(pins.items.len - 1) else Hunk.carrier, .diff = it.index orelse logged.len }); }; try steps.append(arena, .{ .pin = Hunk.carrier, .diff = logged.len }); out.pins = try pins.toOwnedSlice(gpa); if (out.pins.len == 0) { kept = true; return .{ .read = out }; } var moved: Moved = undefined; out.lines = try provenance(gpa, arena, annotated, out.pins, text, &moved); // Each change's hunks, and which of its lines a pin added whole. var hunks: std.ArrayList(Hunk) = .empty; defer hunks.deinit(gpa); var removed: std.ArrayList(u8) = .empty; defer removed.deinit(gpa); var marks: std.ArrayList([2]u32) = .empty; defer marks.deinit(gpa); var taken: std.ArrayList(Taken) = .empty; for (steps.items[0 .. steps.items.len - 1], steps.items[1..], 0..) |s, next, i| try hunksOf(gpa, arena, s.pin, @intCast(i), logged[s.diff..next.diff], text, out.lines, &hunks, &removed, &marks, &taken); out.hunks = try hunks.toOwnedSlice(gpa); nest(out.lines, out.pins.len); out.ghosts = try ghostsOf(gpa, arena, out.pins, out.lines, out.hunks, taken.items, &removed, now, moved); out.ghost_text = try removed.toOwnedSlice(gpa); out.marks = try marks.toOwnedSlice(gpa); kept = true; return .{ .read = out }; } /// `jj log`'s line a change, before its diff: its id, `p` when `revset` /// pins it (else `c`), its author's time, its author, its description's /// first line, a tab between. fn logTemplate(gpa: std.mem.Allocator, revset: []const u8) error{OutOfMemory}![]u8 { var t: std.ArrayList(u8) = .empty; errdefer t.deinit(gpa); try t.appendSlice(gpa, "change_id.short(8) ++ \"\\t\" ++ if(self.contained_in(\""); for (revset) |c| { if (c == '"' or c == '\\') try t.append(gpa, '\\'); try t.append(gpa, c); } try t.appendSlice(gpa, "\"), \"p\", \"c\") ++ \"\\t\" ++ author.timestamp().utc().format(\"%s\") ++ \"\\t\" ++ author.name() ++ \"\\t\" ++ description.first_line() ++ \"\\n\""); return t.toOwnedSlice(gpa); } /// A `logTemplate` line, or null for a line of a diff (which starts with /// a blank, a sign, `@`, `\\` or a word and a blank: never eight of jj's /// id letters, k to z, and a tab). fn entryOf(l: []const u8) ?struct { pin: Pin, pinned: bool } { if (l.len < 11 or l[8] != '\t' or l[10] != '\t') return null; for (l[0..8]) |c| if (c < 'k' or c > 'z') return null; var cols = std.mem.splitScalar(u8, l[11..], '\t'); var pin: Pin = .{ .id = l[0..8].*, .time = std.fmt.parseInt(i64, cols.next() orelse "", 10) catch 0 }; const author = cols.next() orelse ""; pin.author_len = @intCast(@min(author.len, pin.author.len)); @memcpy(pin.author[0..pin.author_len], author[0..pin.author_len]); const title = cols.rest(); pin.title_len = @intCast(@min(title.len, pin.title.len)); @memcpy(pin.title[0..pin.title_len], title[0..pin.title_len]); return .{ .pin = pin, .pinned = l[9] == 'p' }; } /// Which pin wrote each line of `text` (what the pane shows: `whole` is the /// hunks' to say), a value a line, the caller's in `gpa`, from `annotated` /// (`jj file annotate`'s answer: an id, a tab and the line, a line each, of /// the revision it annotated, which is jj's last snapshot of a file and /// not the keys typed since): the two texts lined up by what they agree on /// at either end (`File.spanOf`, the editor's differ: a line inside both /// ends keeps its owner, a line only the pane has is nobody's); `moved`, /// where jj's lines stand in `text`. pub fn provenance(gpa: std.mem.Allocator, arena: std.mem.Allocator, annotated: []const u8, pins: []const Pin, text: []const u8, moved: *Moved) error{OutOfMemory}![]Line { var owners: std.ArrayList(PinIndex) = .empty; var was: std.ArrayList(u8) = .empty; var rows = std.mem.splitScalar(u8, annotated, '\n'); while (rows.next()) |row| { // The empty text after the last newline is no line. if (row.len == 0 and rows.peek() == null) break; const tab = std.mem.indexOfScalar(u8, row, '\t') orelse row.len; try owners.append(arena, for (pins, 0..) |pin, i| { if (std.mem.eql(u8, &pin.id, row[0..tab])) break @enumFromInt(i); } else .none); try was.appendSlice(arena, row[@min(tab + 1, row.len)..]); try was.append(arena, '\n'); } if (!std.mem.endsWith(u8, annotated, "\n") and was.items.len > 0) was.items.len -= 1; const out = try gpa.alloc(Line, lineCount(text)); @memset(out, .{ .pin = .none }); moved.* = .of(was.items, text); for (out[0..@min(moved.head, owners.items.len)], owners.items[0..@min(moved.head, owners.items.len)]) |*l, pin| l.pin = pin; const tail = @min(moved.tail, owners.items.len); for (out[out.len - tail ..], owners.items[owners.items.len - tail ..]) |*l, pin| l.pin = pin; return out; } /// Where jj's lines (the revision it annotated) stand in the pane's text, /// which has keys typed since (before the word, never snapshotted, or /// while jj ran): its first `head` lines and its last `tail` are the same /// lines, those between were rewritten. pub const Moved = struct { head: u32, tail: u32, /// jj's lines, and the text's. was: u32, now: u32, /// `was` (jj's text) lined up with `text` by what they agree on at /// either end (`File.spanOf`, the editor's differ). pub fn of(was: []const u8, text: []const u8) Moved { const was_n: u32 = @intCast(lineCount(was)); const now: u32 = @intCast(lineCount(text)); if (std.mem.eql(u8, was, text)) return .{ .head = was_n, .tail = 0, .was = was_n, .now = was_n }; const span = File.spanOf(was, text); const head = @min(std.mem.count(u8, was[0..span.head], "\n"), now, was_n); var tail = @min(tailLines(was, span.tail), now - head, was_n - head); // The line the two ends meet inside (an insertion before it shares its // indent with the line above) is the same line when its bytes are. if (head + tail < @min(now, was_n) and std.mem.eql(u8, lineFromEnd(was, tail), lineFromEnd(text, tail))) tail += 1; return .{ .head = @intCast(head), .tail = @intCast(tail), .was = was_n, .now = now }; } /// The text's place of jj's place `at` (before its line `at`), or null /// inside lines rewritten since: no place there tells the truth. fn place(m: Moved, at: u32) ?u32 { if (at >= m.was - m.tail) return at - (m.was - m.tail) + (m.now - m.tail); return if (at <= m.head) at else null; } }; /// `text`'s line `k` from its end (0: its last). fn lineFromEnd(text: []const u8, k: usize) []const u8 { var end = text.len - @intFromBool(std.mem.endsWith(u8, text, "\n")); for (0..k) |_| end = (std.mem.lastIndexOfScalar(u8, text[0..end], '\n') orelse return ""); const from = if (std.mem.lastIndexOfScalar(u8, text[0..end], '\n')) |nl| nl + 1 else 0; return text[from..end]; } /// The lines of `text`: one after each newline but a last one, as the /// annotation numbers them. fn lineCount(text: []const u8) usize { return std.mem.count(u8, text, "\n") + @intFromBool(text.len > 0 and text[text.len - 1] != '\n'); } /// How many of `text`'s lines lie whole in its last `tail` bytes. fn tailLines(text: []const u8, tail: usize) usize { if (tail == 0) return 0; const from = text.len - tail; // A line starts at `from`, and after each newline in the tail but the // text's last byte. const starts = if (from == 0) 1 else @intFromBool(text[from - 1] == '\n'); return starts + std.mem.count(u8, text[from .. text.len - 1], "\n"); } /// A line a pin took away (in hunk order, a pin's after another's): one /// line changed (`paired`, with the line it became, by its number in the /// pin's revision and, while it is shown, its line of the text) or taken /// away whole; the words that went, in `Changes.marks`. const Taken = struct { paired: bool, marks: u32, nmarks: u16, new: u32 = 0, shown: ?u32 = null, partner: usize = 0 }; /// Pin `k`'s hunks in `diffed` (its diff of the file, `--git --context=0`) onto /// `hunks`, their removed lines onto `removed`, what became of each onto /// `taken`; and each line of `text` pin `k` wrote (`lines`), matched in /// order by its text, marked `whole` when the change added it whole, else /// with the words that came. Which lines a run of lines taken away and /// written changed, and their words, is the patch view's alignment /// (hunks.format: its `inferEdits`), read off its rows. A change the /// revset does not pin (`k` is `Hunk.carrier`): its hunks alone. fn hunksOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, k: u16, step: u16, diffed: []const u8, text: []const u8, lines: []Line, hunks: *std.ArrayList(Hunk), removed: *std.ArrayList(u8), marks: *std.ArrayList([2]u32), taken: *std.ArrayList(Taken)) error{OutOfMemory}!void { const Added = struct { text: []const u8, whole: bool, marks: u32, nmarks: u16, new: u32, shown: ?u32 = null }; var added: std.ArrayList(Added) = .empty; var walk: diff.Walk = .{}; var it = std.mem.splitScalar(u8, diffed, '\n'); while (it.next()) |raw| { const l = walk.step(raw); switch (l.kind) { .hunk => { const h = diff.parseHunk(std.mem.trimEnd(u8, raw, "\r")).?; try hunks.append(gpa, .{ .pin = k, .step = step, .old_start = @intCast(h.old_start), .old_len = @intCast(h.old_count), .new_start = @intCast(h.new_start), .new_len = @intCast(h.new_count), .removed = @intCast(removed.items.len), .removed_len = 0 }); }, .removed => if (k != Hunk.carrier) { const body = std.mem.trimEnd(u8, raw, "\r")[1..]; try removed.appendSlice(gpa, body); try removed.append(gpa, '\n'); hunks.items[hunks.items.len - 1].removed_len += @intCast(body.len + 1); }, else => {}, } } if (k == Hunk.carrier) return; // The patch view's rows of the same diff: a line it paired is one // changed (its marker has no `ground_line`), its words `ground_emph`. const patch = format: { const ctx: @import("hunks.zig").Ctx = .{ .arena = arena }; break :format @import("hunks.zig").format(&ctx, "", diffed) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return, }; }; var said = std.mem.splitScalar(u8, patch.text, '\n'); var run_from = taken.items.len; var plus_from = added.items.len; for (patch.rows) |row| { const row_text = said.next() orelse break; if (row.kind == .hunk) { pairRun(taken.items[run_from..], added.items[plus_from..], plus_from); run_from = taken.items.len; plus_from = added.items.len; } if (row.kind != .added and row.kind != .removed) continue; const paired = row.styles.len > 0 and row.styles[0] & syntax.ground_line == 0; const from = marks.items.len; var i: usize = 1; while (i < row.styles.len) { if (row.styles[i] & syntax.ground_emph == 0) { i += 1; continue; } const run = i; while (i < row.styles.len and row.styles[i] & syntax.ground_emph != 0) i += 1; try marks.append(gpa, .{ @intCast(run - 1), @intCast(i - 1) }); } const nmarks: u16 = @intCast(marks.items.len - from); if (row.kind == .added) try added.append(arena, .{ .text = row_text[@min(1, row_text.len)..], .whole = !paired, .marks = @intCast(from), .nmarks = nmarks, .new = @intCast(row.new orelse 0) }) else try taken.append(arena, .{ .paired = paired, .marks = @intCast(from), .nmarks = nmarks }); } pairRun(taken.items[run_from..], added.items[plus_from..], plus_from); var next: usize = 0; var rows = std.mem.splitScalar(u8, text, '\n'); const taken_from = taken.items.len - count: { var n: usize = 0; for (hunks.items) |h| if (h.pin == k) { n += h.old_len; }; break :count @min(n, taken.items.len); }; for (lines, 0..) |*line, line_index| { const row = rows.next() orelse break; if (@intFromEnum(line.pin) != k) continue; const from = next; while (next < added.items.len and !std.mem.eql(u8, added.items[next].text, std.mem.trimEnd(u8, row, "\r"))) next += 1; if (next == added.items.len) { next = from; continue; } line.whole = added.items[next].whole; if (!line.whole) { line.marks = added.items[next].marks; line.nmarks = added.items[next].nmarks; } added.items[next].shown = @intCast(line_index); next += 1; } for (taken.items[taken_from..]) |*t| if (t.paired) { t.new = added.items[t.partner].new; t.shown = added.items[t.partner].shown; }; } /// A run's lines taken away paired with the lines written, in order (the /// alignment pairs each with a later one than the last it paired): each /// paired one's partner, by its place in `plus`'s list (from `base`). fn pairRun(minus: []Taken, plus: anytype, base: usize) void { var j: usize = 0; for (minus) |*m| if (m.paired) { while (j < plus.len and plus[j].whole) j += 1; if (j == plus.len) { m.paired = false; continue; } m.partner = base + j; j += 1; }; } /// A run longer than this (lines taken away in one hunk) shows none of /// them as ghost rows; the patch view's alignment gives up past 256 too. const max_run = 1024; /// The ghost rows (`Ghost`), in `at` order: each line a pin took away /// whole or changed, where it stood (`carried` into the text); and each /// pin's description after its last line (a pin none of whose lines is /// left: after its last ghost row, or where its last hunk wrote). At one /// place: the descriptions of pins whose lines end just above it, the /// newest first (an inner block closes first), then the lines taken away, /// older pins' first, each pin's description right after its own. A place /// inside lines rewritten since jj's snapshot (`Moved.place`) has no row. /// `text` holds the hunks' removed lines; the descriptions' rows go on /// after them. fn ghostsOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, pins: []const Pin, lines: []const Line, hunks: []const Hunk, taken: []const Taken, text: *std.ArrayList(u8), now: i64, moved: Moved) error{OutOfMemory}![]Ghost { const Made = struct { g: Ghost, rank: u64 }; var made: std.ArrayList(Made) = .empty; var ti: usize = 0; for (hunks) |h| { if (h.old_len == 0 or h.pin == Hunk.carrier) continue; const run = taken[@min(ti, taken.len)..@min(ti + h.old_len, taken.len)]; ti += h.old_len; // A changed line's old text right above the line; a line taken // away whole above the next changed one's, or after the run. var at = carried(hunks, h.step, if (h.new_len > 0) h.new_start - 1 + h.new_len else h.new_start, moved); var ats: [max_run]?u32 = undefined; if (run.len > max_run) continue; var k = run.len; while (k > 0) { k -= 1; if (run[k].paired) at = run[k].shown orelse carried(hunks, h.step, run[k].new -| 1, moved); ats[k] = at; } var from: usize = h.removed; for (run, 0..) |t, n| { const nl = std.mem.indexOfScalarPos(u8, text.items, from, '\n') orelse text.items.len; defer from = nl + 1; try made.append(arena, .{ .g = .{ .at = ats[n] orelse continue, .pin = h.pin, .kind = if (t.paired) .changed else .deleted, .line = h.old_start + @as(u32, @intCast(n)), .text = @intCast(from), .len = @intCast(nl - from), .marks = if (t.paired) t.marks else 0, .nmarks = if (t.paired) t.nmarks else 0 }, .rank = 1 << 32 | made.items.len << 1, }); } } for (pins, 0..) |pin, k| { var at: ?u32 = null; var rank: u64 = pins.len - k; var i = lines.len; while (i > 0) { i -= 1; if (@intFromEnum(lines[i].pin) == k) { at = @intCast(i + 1); break; } } if (at == null) { rank |= 2 << 32; for (made.items) |m| if (m.g.pin == k) { at = @max(at orelse 0, m.g.at); }; } var first: u32 = 0; var end: u32 = 0; var step: u16 = 0; for (hunks) |h| if (h.pin == k) { if (first == 0) first = h.new_start; end = if (h.new_len > 0) h.new_start - 1 + h.new_len else h.new_start; step = h.step; }; const place = at orelse carried(hunks, step, end, moved) orelse continue; // After its own ghost rows at its place. for (made.items) |m| if (m.g.pin == k and m.g.at == place) { rank = m.rank | 1; }; const at_text = text.items.len; try describe(gpa, text, pin, now); try made.append(arena, .{ .g = .{ .at = place, .pin = @intCast(k), .kind = .description, .line = @max(first, 1), .text = @intCast(at_text), .len = @intCast(text.items.len - at_text) }, .rank = rank, }); } std.sort.pdq(Made, made.items, {}, struct { fn before(_: void, a: Made, b: Made) bool { return if (a.g.at != b.g.at) a.g.at < b.g.at else a.rank < b.rank; } }.before); const out = try gpa.alloc(Ghost, made.items.len); for (out, made.items) |*o, m| o.* = m.g; return out; } /// Where the place after line `after` of step `from`'s revision (its /// change's place in jj's answer, `Hunk.step`) is in the text: moved by each later change's hunks before it (a pin's, or one /// between the pins the revset does not pin), or, inside a run of lines a /// later one took away, after what it wrote there; then from jj's lines /// to the text's (`moved`). fn carried(hunks: []const Hunk, from: u16, after: u32, moved: Moved) ?u32 { var pos: i64 = after; var i: usize = 0; while (i < hunks.len) { const j = hunks[i].step; var shift: i64 = 0; var inside: ?i64 = null; while (i < hunks.len and hunks[i].step == j) : (i += 1) { const h = hunks[i]; if (j <= from) continue; if (h.old_len == 0) { if (h.old_start < pos) shift += h.new_len; } else if (h.old_start + h.old_len - 1 <= pos) { shift += @as(i64, h.new_len) - h.old_len; } else if (h.old_start <= pos) inside = @as(i64, h.new_start) - 1 + h.new_len; } if (j > from) pos = inside orelse pos + shift; } return moved.place(@intCast(std.math.clamp(pos, 0, @as(i64, moved.was)))); } /// A pin's description row (PARDES.md: compact, one blank between): its /// id's first four letters, its title, its author's first name, its age /// short (`5h`, `2d`, `3w`, `4m`, `1y`; under an hour `now`), no "ago". fn describe(gpa: std.mem.Allocator, text: *std.ArrayList(u8), pin: Pin, now: i64) error{OutOfMemory}!void { const author = pin.author[0..pin.author_len]; try text.print(gpa, "{s} {s} {s} ", .{ pin.id[0..4], pin.title[0..pin.title_len], author[0 .. std.mem.indexOfScalar(u8, author, ' ') orelse author.len] }); const s = @max(0, now - pin.time); const day = 24 * 3600; for ([_]struct { u8, i64 }{ .{ 'y', 365 * day }, .{ 'm', 30 * day }, .{ 'w', 7 * day }, .{ 'd', day }, .{ 'h', 3600 } }) |unit| { if (s >= unit[1]) return text.print(gpa, "{d}{c}", .{ @divFloor(s, unit[1]), unit[0] }); } try text.appendSlice(gpa, "now"); } /// The bytes a description row has at most, cut (`fitted`). pub const row_max = 256; /// A description row (`describe`: `id title author age`) as a body row of /// `room` cells shows it: whole when it fits, else its title cut to the /// room left (a `…` where it is cut), so the author and the age stay at /// its end (PARDES.md: one compact row, both shown). pub fn fitted(tab: u16, said: []const u8, room: usize, buf: *[row_max]u8) []const u8 { if (said.len + 3 > row_max or File.displayWidth(tab, said) <= room) return said; var tail = said.len; for (0..2) |_| tail = std.mem.lastIndexOfScalar(u8, said[0..tail], ' ') orelse return said; const head = @min(5, tail); const keep = room -| File.displayWidth(tab, said[0..head]) -| File.displayWidth(tab, said[tail..]) -| 1; const title = if (keep == 0) "" else std.mem.trimEnd(u8, said[head..tail][0..File.fitEnd(tab, said[head..tail], 0, keep)], " "); var out: std.ArrayList(u8) = .initBuffer(buf); out.appendSliceAssumeCapacity(said[0..head]); out.appendSliceAssumeCapacity(title); out.appendSliceAssumeCapacity("\u{2026}"); out.appendSliceAssumeCapacity(said[tail..]); return out.items; } /// The lanes on ghost row `gi` (`ghosts[gi]`): those of the line above it /// that run on below it or whose description is this row or one after it /// at the same place, then its own pin's. fn ghostLanes(ch: *const Changes, ghosts: []const Ghost, gi: usize) [levels]PinIndex { const g = ghosts[gi]; var out: [levels]PinIndex = @splat(.none); var n: usize = 0; if (g.at > 0 and g.at - 1 < ch.lines.len) for (ch.lines[g.at - 1].lanes) |lane| { if (lane == .none) break; const below = g.at < ch.lines.len and std.mem.indexOfScalar(PinIndex, &ch.lines[g.at].lanes, lane) != null; const closes = for (ghosts[gi..]) |later| { if (later.at != g.at) break false; if (later.kind == .description and later.pin == @intFromEnum(lane)) break true; } else false; if (!below and !closes) continue; out[n] = lane; n += 1; }; if (n < levels and std.mem.indexOfScalar(PinIndex, out[0..n], @enumFromInt(g.pin)) == null) out[n] = @enumFromInt(g.pin); return out; } /// A ghost row's cells: a line taken away whole red across, its text in /// the line numbers' grey (dimmer than the text's ink); a description in /// its lane's colour, its author and age grey; `said`, the row's text as /// the body shows it (a description `fitted`). fn inkGhost(p: *Pardes, s: *pardes.Surface, g: Ghost, said: []const u8, marks: []const [2]u32, colours: []const [3]u8, x: u16, y: u16, w: u16) void { const th = p.theme(); switch (g.kind) { .deleted => s.tint(x, y, w, pardes.colors.Grounds.of(th).del.row, th.lineno), .changed => { const cells = @min(w, File.displayWidth(p.settings.tab, said)); for (0..cells) |c| s.at(x + @as(u16, @intCast(c)), y).style.fg = .{ .rgb = th.lineno }; for (marks[g.marks..][0..g.nmarks]) |m| { const from = File.displayWidth(p.settings.tab, said[0..@min(m[0], said.len)]); const to = @min(w, File.displayWidth(p.settings.tab, said[0..@min(m[1], said.len)])); if (from < to) s.tint(x + @as(u16, @intCast(from)), y, @intCast(to - from), pardes.colors.Grounds.of(th).del.emph, null); } }, .description => { // `id title author age`: the last two words grey. var grey = said.len; for (0..2) |_| grey = std.mem.lastIndexOfScalar(u8, said[0..grey], ' ') orelse 0; const lane_cells = File.displayWidth(p.settings.tab, said[0..grey]); const cells = @min(w, File.displayWidth(p.settings.tab, said)); for (0..cells) |c| s.at(x + @as(u16, @intCast(c)), y).style.fg = .{ .rgb = if (c < lane_cells) colours[g.pin % colours.len] else th.lineno }; }, } } /// A changed line's words that came (`marks`, byte ranges of line `row`), /// green on body row `vr`, as much of them as the row shows. fn inkCame(p: *Pardes, s: *pardes.Surface, pane: *Pane, marks: []const [2]u32, row: i32, vr: u16, x: u16, y: u16, w: u16) void { const tab = p.settings.tab; const len: u32 = @intCast(File.sourceLine(pane, row).len); const here = pane.wrapAt(tab, vr); const next = pane.wrapAt(tab, @as(i32, vr) + 1); const first: u32 = @intCast(here.at); const end: u32 = if (next.line == row and !next.ghost) @intCast(next.at) else len; for (marks) |m| { const lo = @max(first, @min(m[0], len)); const hi = @min(end, @min(m[1], len)); if (lo >= hi) continue; const from = here.pad + File.displayOffset(tab, pane, row, @intCast(first), @intCast(lo)); const to = @min(@as(i32, w), here.pad + File.displayOffset(tab, pane, row, @intCast(first), @intCast(hi))); if (from >= 0 and from < to) s.tint(x + @as(u16, @intCast(from)), y, @intCast(to - from), pardes.colors.Grounds.of(p.theme()).add.emph, null); } } /// The line `]g` (`forward`) or `[g` goes to from line `from` of pane's /// text: the next or the previous change's first line in this view (a run /// of lines one pin wrote, or where lines one took away stood); null with /// none shown, or none that way. pub fn nextChange(p: *Pardes, pane: *const Pane, from: usize, forward: bool) ?usize { if (pane.layers.lanes == 0) return null; const ch = answered(p, pane.serial) orelse return null; var best: ?usize = null; const Best = struct { fn take(b: *?usize, at: usize, here: usize, fwd: bool) void { if (if (fwd) at <= here else at >= here) return; if (b.*) |was| if (if (fwd) at >= was else at <= was) return; b.* = at; } }; for (ch.lines, 0..) |l, i| if (l.pin != .none and (i == 0 or ch.lines[i - 1].pin != l.pin)) Best.take(&best, i, from, forward); for (ch.ghosts) |g| if (g.kind == .deleted) Best.take(&best, @min(g.at, ch.lines.len -| 1), from, forward); return best; } /// A Look on body row `vr` of pane `id` when it is a ghost row (mouse.zig, /// a B3 click): the line it shows in the revision it came from, as the /// address `path@rev:line` opens it (a line taken away: its pin's parent's; /// a description: its pin's first line). False on any other row. pub fn lookGhost(p: *Pardes, id: usize, vr: i32) bool { const pane = p.panes[id].?; if (pane.layers.lanes == 0 or !pane.wrapAt(p.settings.tab, vr).ghost) return false; const ch = answered(p, pane.serial) orelse return false; const gi: usize = @intCast(-1 - pane.wrap_col[@intCast(vr)]); if (gi >= pane.ghosts.len) return false; const g = pane.ghosts[gi]; const f = &pane.file.?; const path = if (of(f)) |r| r.path else f.path; const rev: [9]u8 = ch.pins[g.pin].id ++ "-".*; _ = open(p, id, path, rev[0 .. if (g.kind == .description) 8 else 9], .{ .line = g.line }, false); return true; } /// Each line's lanes: the blocks of the pins that span it, oldest first. /// A pin's block runs from a line it wrote on to each next line it wrote /// while every line between was written by a newer pin: its lane unbroken /// down what it wrote, through what later pins rewrote inside it. An older /// pin's line (or one no pin wrote) ends a newer pin's block, so blocks /// nest, the older outside, and a block keeps its level down all its rows: /// the spine keeps its place, a nested change steps to the right on its /// rows only. Past `levels`, the innermost are not drawn. fn nest(lines: []Line, npins: usize) void { for (0..npins) |k| { var i: usize = 0; while (i < lines.len) { if (@intFromEnum(lines[i].pin) != k) { i += 1; continue; } var last = i; for (lines[i + 1 ..], i + 1..) |l, j| { const q = @intFromEnum(l.pin); if (q == k) last = j else if (l.pin == .none or q < k) break; } for (lines[i .. last + 1]) |*l| for (&l.lanes) |*lane| if (lane.* == .none) { lane.* = @enumFromInt(k); break; }; i = last + 1; } } } /// The lanes' colours, a pin's the `pin % len`th, oldest first: the /// theme's accents but the two that mean written and taken away (its green /// and red), in hue order from the top, each a hue `hue_apart` or more from /// the one kept before it (doom one: magenta, blue, yellow; cyan and /// orange go). Distinct colours, never one between two. pub fn laneColours(th: *const pardes.Theme, buf: *[8][3]u8) []const [3]u8 { const pal = th.palette; const grounds = [2][3]u8{ themeRed(th), if (pal) |c| c[2] else .{ 0x2e, 0xa0, 0x43 } }; const accents: [6][3]u8 = if (pal) |c| .{ c[3], c[4], c[5], c[6], th.num, th.kw } else .{ th.kw, th.num, th.str, th.box, th.column_box orelse th.box, th.comment }; var sorted: [6][3]u8 = undefined; var n: usize = 0; for (accents) |c| { // A grey is no accent; one near written or taken away means that. if (chroma(c) < 48 or hueApart(c, grounds[0]) < hue_apart or hueApart(c, grounds[1]) < hue_apart) continue; sorted[n] = c; n += 1; } std.sort.insertion([3]u8, sorted[0..n], {}, struct { fn above(_: void, a: [3]u8, b: [3]u8) bool { return hue(a) > hue(b); } }.above); var kept: usize = 0; for (sorted[0..n]) |c| { if (kept > 0 and hueApart(c, buf[kept - 1]) < hue_apart) continue; buf[kept] = c; kept += 1; } return buf[0..kept]; } /// Two hues closer than this are one colour to a lane (doom one's cyan is /// 12 degrees from its blue, its orange 11 from its yellow). const hue_apart = 15; fn chroma(c: [3]u8) u8 { return @max(c[0], c[1], c[2]) - @min(c[0], c[1], c[2]); } /// HSV's hue, in degrees. fn hue(c: [3]u8) f32 { const r: f32 = @floatFromInt(c[0]); const g: f32 = @floatFromInt(c[1]); const b: f32 = @floatFromInt(c[2]); const hi = @max(r, g, b); const d = hi - @min(r, g, b); if (d == 0) return 0; const h = if (hi == r) @mod((g - b) / d, 6) else if (hi == g) (b - r) / d + 2 else (r - g) / d + 4; return 60 * h; } fn hueApart(a: [3]u8, b: [3]u8) f32 { const d = @abs(hue(a) - hue(b)); return @min(d, 360 - d); } /// The pane's pinned changes as a view shows them, on its body's rows (body_layer.zig, while /// File.Layers.lanes is set): in the gutter's lane cells after the number a /// lane each pin whose block runs down the row, at its level, a glyph in a /// terminal, a strip of pixels in a window (Surface.lanes); and a line a /// pin added whole green across it, as a diff's added line; on a ghost row /// (`Ghost`) its lanes and its cells (`inkGhost`). Not yet: a changed /// line's words. pub fn paint(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { if (pane.layers.heat > 0) paintHeat(p, s, pane, r, tx, body_h); if (pane.layers.lanes > 0) paintLanes(p, s, pane, r, tx, tw, body_h); } /// The theme's red: what a change took away; churn's top. pub fn themeRed(th: *const pardes.Theme) [3]u8 { return if (th.palette) |c| c[1] else .{ 0xcf, 0x22, 0x2e }; } /// A count's colour on churn's gradient: smooth from the line numbers' /// grey to the theme's red, on a log scale of the count against the /// hottest; null for none. fn heatColour(th: *const pardes.Theme, count: u16, hottest: u16) ?[3]u8 { if (count == 0 or hottest == 0) return null; const t = @log(@as(f32, @floatFromInt(count)) + 1) / @log(@as(f32, @floatFromInt(hottest)) + 1); return pardes.colors.mixOklab(th.lineno, themeRed(th), t); } /// The heat lane: a cell after the line number (before the changes' /// lanes, which stay next to the text they mark), a half block in its /// line's colour; none on a ghost row or a line in no declaration. fn paintHeat(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, body_h: u16) void { const heat = churned(p, pane.serial) orelse return; const x = tx + File.gutterWidth(pane) - File.laneCells(pane) - 1; const body_y = p.bodyTop(pane, r); const scroll = pane.scroll(); var vr: u16 = pane.context_rows; while (vr < body_h) : (vr += 1) { const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break; if (vr < pane.wrap_n and pane.wrap_col[vr] < 0) continue; if (row < 0 or row >= heat.lines.len) continue; const rgb = heatColour(p.theme(), heat.lines[@intCast(row)], heat.hottest) orelse continue; var style = s.at(x, body_y + vr).style; style.fg = .{ .rgb = rgb }; s.set(x, body_y + vr, "\u{258c}", style); } } /// Churn's strip by the scroll thumb (draw.zig, while a view shows it): a /// rail row each, the hottest line of the lines that row stands for; in a /// terminal the rail's second cell's ground, for a pixel shell a list /// (Surface.heat). pub fn railHeat(p: *Pardes, s: *pardes.Surface, pane: *Pane, id: usize, rail: pardes.Rect) void { const heat = churned(p, pane.serial) orelse return; const total = heat.lines.len; if (rail.h == 0 or total == 0) return; for (0..rail.h) |row| { const lo = row * total / rail.h; const hi = @max(lo + 1, (row + 1) * total / rail.h); const rgb = heatColour(p.theme(), std.mem.max(u16, heat.lines[lo..@min(hi, total)]), heat.hottest) orelse continue; if (p.view().frontend.windowed) s.heat.append(p.gpa, .{ .owner = @intCast(id), .row = @intCast(row), .rgb = rgb }) catch {} else s.fill(rail.x + 1, rail.y + @as(u16, @intCast(row)), 1, 1, .{ .bg = .{ .rgb = rgb } }); } } fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { const ch = answered(p, pane.serial) orelse return; if (ch.lines.len == 0) return; var buf: [8][3]u8 = undefined; const colours = laneColours(p.theme(), &buf); if (colours.len == 0) return; const gutter = File.gutterWidth(pane); const cells = File.laneCells(pane); if (gutter >= tw or cells == 0) return; const first = tx + gutter - cells; const windowed = p.view().frontend.windowed; const ground = pardes.colors.Grounds.of(p.theme()).add.row; const body_y = p.bodyTop(pane, r); const scroll = pane.scroll(); var vr: u16 = pane.context_rows; while (vr < body_h) : (vr += 1) { const y = body_y + vr; const lanes: [levels]PinIndex = if (vr < pane.wrap_n and pane.wrap_col[vr] < 0) ghost: { const gi: usize = @intCast(-1 - pane.wrap_col[vr]); if (gi >= pane.ghosts.len) continue; const g = pane.ghosts[gi]; const said = pane.ghost_text[g.text..][0..g.len]; var fit: [row_max]u8 = undefined; inkGhost(p, s, g, if (g.kind == .description) fitted(p.settings.tab, said, File.bodyWidth(pane), &fit) else said, ch.marks, colours, tx + gutter, y, tw - gutter); break :ghost ghostLanes(ch, pane.ghosts, gi); } else line: { const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break; if (row < 0 or row >= ch.lines.len) continue; const line = ch.lines[@intCast(row)]; if (line.whole and line.pin != .none) s.tint(tx + gutter, y, tw - gutter, ground, null); if (!line.whole and line.nmarks > 0) inkCame(p, s, pane, ch.marks[line.marks..][0..line.nmarks], row, vr, tx + gutter, y, tw - gutter); break :line line.lanes; }; for (lanes, 0..) |lane, level| { if (lane == .none) break; const rgb = colours[@intFromEnum(lane) % colours.len]; if (windowed) { // A body a pixel shell draws as a layer is painted on a // temporary surface first: its lanes are not drawn yet. if (s == &p.surface) s.lanes.append(p.gpa, .{ .x = first, .y = y, .level = @intCast(level), .rgb = rgb }) catch {}; } else if (level < cells) { var style = s.at(first + @as(u16, @intCast(level)), y).style; style.fg = .{ .rgb = rgb }; s.set(first + @as(u16, @intCast(level)), y, "\u{258e}", style); } } } } // ---- tests ---- const testing = std.testing; test "path@rev splits at its first @: a path before it, a revision after" { const cases = [_]struct { []const u8, []const u8, []const u8 }{ .{ "a.zig@main", "a.zig", "main" }, .{ "core/File.zig@@-", "core/File.zig", "@-" }, .{ "x.zig@main@origin", "x.zig", "main@origin" }, }; for (cases) |c| { const got = split(c[0]).?; try testing.expectEqualStrings(c[1], got.path); try testing.expectEqualStrings(c[2], got.rev); } for ([_][]const u8{ "@p12", "a.zig@", "a.zig", "dir/@x" }) |text| try testing.expect(split(text) == null); } /// A jj repository in a test's directory: `a.zig` committed as `one`, then /// as `two`, and `three` in its working copy, never snapshotted. Null with /// no jj to run. const Repo = struct { tmp: testing.TmpDir, dir: []const u8, file: []const u8, const one = "const one = 1;\nconst x = 2;\n"; const two = "const two = 2;\nconst x = 2;\nconst y = 3;\n"; const three = "const three = 3;\n"; fn init(gpa: std.mem.Allocator) !?Repo { return with(gpa, &.{ .{ one, "one" }, .{ two, "two" } }, three); } /// `a.zig` committed as each text with its message, in order; then /// `working` in the working copy, never snapshotted. fn with(gpa: std.mem.Allocator, commits: []const [2][]const u8, working: ?[]const u8) !?Repo { var tmp = testing.tmpDir(.{}); errdefer tmp.cleanup(); var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; const dir = try gpa.dupe(u8, buf[0..try tmp.dir.realPath(testing.io, &buf)]); errdefer gpa.free(dir); if (!try run(gpa, dir, &.{ "git", "init" })) return null; for (commits) |c| { try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = c[0] }); if (!try run(gpa, dir, &.{ "commit", "-m", c[1] })) return null; } if (working) |text| try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = text }); return .{ .tmp = tmp, .dir = dir, .file = try std.fmt.allocPrint(gpa, "{s}/a.zig", .{dir}) }; } fn run(gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) !bool { var argv: std.ArrayList([]const u8) = .empty; defer argv.deinit(gpa); try argv.appendSlice(gpa, &.{ "jj", "--config=user.name=t", "--config=user.email=t@t", "--quiet" }); try argv.appendSlice(gpa, args); const r = std.process.run(gpa, testing.io, .{ .argv = argv.items, .cwd = .{ .path = dir } }) catch return false; gpa.free(r.stdout); gpa.free(r.stderr); return r.term == .exited and r.term.exited == 0; } fn deinit(r: *Repo, gpa: std.mem.Allocator) void { gpa.free(r.file); gpa.free(r.dir); r.tmp.cleanup(); } }; fn told(p: *Pardes, id: usize) []const u8 { const pane = p.panes[id].?; return pane.msg[0..pane.msg_len]; } test "At shows a file at a revision beside it, read-only, coloured as its file; a Look at path@rev:line goes to it; At in it turns it in place; jj's refusals are said" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); const file = p.view().active; try testing.expectEqualStrings(Repo.three, p.panes[file].?.file.?.content); p.update(.{ .command = "At @-" }); const shown = p.view().active; try testing.expect(shown != file); const pane = p.panes[shown].?; try testing.expectEqualStrings(Repo.two, pane.file.?.content); const name = try std.fmt.allocPrint(gpa, "{s}@@-", .{repo.file}); defer gpa.free(name); try testing.expectEqualStrings(name, try pardes.tagline.tagPrefix(p, pane)); try testing.expectEqualStrings(repo.file, File.langPath(&pane.file.?)); try testing.expect(pane.colorAlgo() == .source); // Read-only: a key's edit and a whole-text edit (dd) change nothing, and a bare Save says so. for ("iz") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); p.update(.{ .key = .{ .cp = pardes.Key.escape } }); for ("dd") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); try testing.expectEqualStrings(Repo.two, pane.file.?.content); p.update(.{ .command = "Save" }); try testing.expect(std.mem.indexOf(u8, told(p, shown), "is a revision, read-only") != null); // From the file's pane, a Look at the address with a line goes there. p.view().active = file; p.update(.{ .command = "Look a.zig@@-:3" }); try testing.expectEqual(shown, p.view().active); try testing.expectEqual(@as(i32, 2), pane.body.cur_row); // Turned to another revision in its place: one pane, the older text. p.update(.{ .command = "At @--" }); const turned = p.view().active; try testing.expect(p.panes[shown] == null); try testing.expectEqualStrings(Repo.one, p.panes[turned].?.file.?.content); var n: usize = 0; for (p.panes) |slot| if (slot) |s| if (s.file) |*f| { n += @intFromBool(of(f) != null); }; try testing.expectEqual(@as(usize, 1), n); // jj's refusals, in its words. p.update(.{ .command = "At nosuch" }); try testing.expect(std.mem.indexOf(u8, told(p, turned), "At: Revision `nosuch` doesn't exist") != null); p.view().active = file; p.update(.{ .command = "At" }); try testing.expect(std.mem.indexOf(u8, told(p, file), "At: which revision?") != null); // Bare in a revision's pane: the file. p.view().active = turned; p.update(.{ .command = "At" }); try testing.expectEqual(file, p.view().active); } test "a client replays the open of a file at a revision and ends equal" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); const R = pardes.replica; const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}); defer a.deinit(); const r = try R.Replica.init(gpa, 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}@@-:2", .{repo.file}) })); r.settle(); try testing.expect(r.diverged == null); const id = a.core.view().active; try testing.expectEqualStrings(Repo.two, a.core.panes[id].?.file.?.content); try testing.expectEqualStrings(Repo.two, r.core().panes[id].?.file.?.content); try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } test "Changes pins a revset's changes on the pane, shown in this view: who wrote each line, which it added whole, each one's hunks and what they took away; bare hides and shows them; jj's refusals are said" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false }); defer p.deinit(); 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].?; try testing.expectEqualStrings(Repo.two, pane.file.?.content); p.update(.{ .command = "Changes @--::@-" }); try testing.expectEqual(levels, pane.layers.lanes); const ch = answered(p, pane.serial).?; try testing.expectEqualStrings("@--::@-", ch.pinned()); try testing.expectEqual(@as(usize, 2), ch.pins.len); for (ch.pins, [_][]const u8{ "one", "two" }) |pin, title| { try testing.expectEqualStrings(title, pin.title[0..pin.title_len]); try testing.expectEqualStrings("t", pin.author[0..pin.author_len]); try testing.expect(pin.time > 0); } // `two` changed line 1 (`one`'s first) and added line 3 whole; line 2 is `one`'s, added whole. const one: PinIndex = @enumFromInt(0); const two: PinIndex = @enumFromInt(1); const want = [_]Line{ .{ .pin = two, .whole = false, .lanes = .{ two, .none, .none }, .marks = 2, .nmarks = 2 }, .{ .pin = one, .whole = true, .lanes = .{ one, .none, .none } }, .{ .pin = two, .whole = true, .lanes = .{ two, .none, .none } }, }; try testing.expectEqualSlices(Line, &want, ch.lines); // The patch view's alignment: the words that went (`one`, `1`), then // those that came (`two`, `2`), byte ranges of each line. try testing.expectEqualSlices([2]u32, &.{ .{ 6, 9 }, .{ 12, 13 }, .{ 6, 9 }, .{ 12, 13 } }, ch.marks); const hunks = [_]Hunk{ .{ .pin = 0, .step = 0, .old_start = 0, .old_len = 0, .new_start = 1, .new_len = 2, .removed = 0, .removed_len = 0 }, .{ .pin = 1, .step = 1, .old_start = 1, .old_len = 1, .new_start = 1, .new_len = 1, .removed = 0, .removed_len = 15 }, .{ .pin = 1, .step = 1, .old_start = 2, .old_len = 0, .new_start = 3, .new_len = 1, .removed = 15, .removed_len = 0 }, }; try testing.expectEqualSlices(Hunk, &hunks, ch.hunks); try testing.expectStringStartsWith(ch.ghost_text, "const one = 1;\n"); // Bare: not shown in this view; what jj said is kept on the pane. p.update(.{ .command = "Changes" }); try testing.expectEqual(0, pane.layers.lanes); try testing.expectEqual(@as(usize, 2), ch.pins.len); // Bare again: the pane's, shown again (jj not asked). p.update(.{ .command = "Changes" }); try testing.expectEqual(levels, pane.layers.lanes); try testing.expectEqual(ch, answered(p, pane.serial).?); // jj's refusal, in its words; what was shown stays. p.update(.{ .command = "Changes nosuch" }); try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: Revision `nosuch` doesn't exist") != null); try testing.expectEqualStrings("@--::@-", answered(p, pane.serial).?.pinned()); // `@`, the working copy's change, which (never snapshotted) touches nothing. p.update(.{ .command = "Changes @" }); try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: no change of `@` touches a.zig") != null); } test "the pinned changes are the pane's, shown in a view by its own bit: another view's Changes shows its set in both, and its bare Changes hides them there alone" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false }); defer p.deinit(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }); const pane = p.panes[p.view().active].?; const before = File.gutterWidth(pane); const other = p.openView().?; p.update(.{ .command = "Changes @--::@-" }); try testing.expectEqual(before + levels, File.gutterWidth(pane)); // A view of its own: nothing shown there until it asks. p.toView(other); try testing.expectEqual(0, pane.layers.lanes); try testing.expectEqual(before, File.gutterWidth(pane)); p.update(.{ .command = "Changes @-" }); try testing.expectEqualStrings("@-", answered(p, pane.serial).?.pinned()); try testing.expectEqual(@as(usize, 1), answered(p, pane.serial).?.pins.len); // The first view shows the new set, not nothing. p.toView(.at(0)); try testing.expectEqual(levels, pane.layers.lanes); // Hidden in the other view alone. p.toView(other); p.update(.{ .command = "Changes" }); try testing.expectEqual(0, pane.layers.lanes); p.toView(.at(0)); try testing.expectEqual(levels, pane.layers.lanes); try testing.expectEqual(before + levels, File.gutterWidth(pane)); } test "a client replays Changes from what the session's jj answered and ends equal" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); const R = pardes.replica; const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}); defer a.deinit(); const r = try R.Replica.init(gpa, 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(); try testing.expect(r.diverged == null); const id = a.core.view().active; try testing.expectEqual(@as(usize, 2), answered(a.core, a.core.panes[id].?.serial).?.pins.len); try testing.expectEqualSlices(Line, answered(a.core, a.core.panes[id].?.serial).?.lines, answered(r.core(), r.core().panes[id].?.serial).?.lines); try testing.expectEqualStrings("@--::@-", answered(r.core(), r.core().panes[id].?.serial).?.pinned()); try testing.expect(r.core().panes[id].?.layers.lanes > 0); try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); // Its pins and lanes cross a join whole (replica.zig `hand_walked`). try R.loadsAsSession(a, 2); } /// A session whose `Changes` runs on a worker (Stream.start), as a shell's /// does, its answer posted to an inbox, with a client of it. const WorkerJj = struct { const Inbox = @import("dev").host_io.Inbox; const R = pardes.replica; /// The host's: where its worker posts, and the core it starts for. const Shell = struct { q: Inbox, core: ?*Pardes = null }; shell: *Shell, a: *R.Authority, r: *R.Replica, /// The repository's `a.zig` open (`at`: `@@-`, its revision `@-`). id: usize, serial: u32, fn search(ctx: ?*anyopaque, gen: u32) void { const shell: *Shell = @ptrCast(@alignCast(ctx.?)); pardes.Stream.start(testing.io, testing.allocator, shell.core.?, gen, &shell.q, Inbox.pushSearch); } const vtable: pardes.Host.VTable = .{ .search = search }; fn init(repo: *const Repo, at: []const u8) !WorkerJj { const shell = try testing.allocator.create(Shell); shell.* = .{ .q = .{ .gpa = testing.allocator, .lsp_allocator = testing.allocator, .io = testing.io } }; const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{ .vtable = &vtable, .ctx = shell }); errdefer a.deinit(); shell.core = a.core; const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); var line: [4200]u8 = undefined; r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}{s}", .{ repo.file, at }) })); const id = a.core.view().active; return .{ .shell = shell, .a = a, .r = r, .id = id, .serial = a.core.panes[id].?.serial }; } fn deinit(w: *WorkerJj) void { w.r.deinit(); w.a.deinit(); w.shell.q.deinit(); testing.allocator.destroy(w.shell); } fn word(w: *WorkerJj, text: []const u8) !void { w.r.confirm(try w.a.local(.{ .command = text })); w.r.settle(); } /// Until no `Changes` is asked or running (five seconds at most): each /// answer the session's input, as its loop hands it, and the client's. fn land(w: *WorkerJj) !void { var waited: u32 = 0; while (w.a.core.changes.task != null or w.a.core.changes.next != null or w.a.core.stream.parse != null) : (waited += 1) { if (waited == 5000) return error.Timeout; var batch: Inbox.Batch = .{}; w.shell.q.takeInto(&batch); for (batch.slice()) |m| switch (m) { .search => |b| { defer b.deinit(testing.allocator); w.r.confirm(try w.a.local(.{ .search = b })); w.r.settle(); }, else => m.deinit(testing.allocator, testing.allocator), }; testing.io.sleep(.fromMilliseconds(1), .awake) catch {}; } try testing.expect(w.r.diverged == null); try testing.expectEqual(pardes.tape.digestOf(w.a.core), pardes.tape.digestOf(w.r.core())); } }; test "Changes asks jj on a worker: the word says so and returns, its answer lands as one input and pins; a client replays that input and ends equal" { var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); var w = try WorkerJj.init(&repo, "@@-"); defer w.deinit(); try w.word("Changes @--::@-"); // Asked, not answered: the word did not wait for jj. try testing.expect(answered(w.a.core, w.serial) == null); try testing.expect(std.mem.indexOf(u8, told(w.a.core, w.id), "Changes: jj") != null); try w.land(); try testing.expectEqual(@as(usize, 2), answered(w.a.core, w.serial).?.pins.len); try testing.expectEqualSlices(Line, answered(w.a.core, w.serial).?.lines, answered(w.r.core(), w.serial).?.lines); } test "a second Changes before the first's answer: only the second's pins" { var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); var w = try WorkerJj.init(&repo, "@@-"); defer w.deinit(); try w.word("Changes @--::@-"); try w.word("Changes @-"); try w.land(); const ch = answered(w.a.core, w.serial).?; try testing.expectEqualStrings("@-", ch.pinned()); try testing.expectEqual(@as(usize, 1), ch.pins.len); } test "the pane closed before its Changes answer: nothing pinned, nothing kept" { var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); var w = try WorkerJj.init(&repo, "@@-"); defer w.deinit(); try w.word("Changes @--::@-"); try w.word("Del"); try testing.expect(w.a.core.panes[w.id] == null or w.a.core.panes[w.id].?.serial != w.serial); try w.land(); try testing.expectEqual(@as(usize, 0), w.a.core.changes.answers.items.len); } test "Changes draws a lane a pinned change after the line number, nested ones a level to the right on their rows only, and a line one added whole green across it; bare again, the gutter as it was" { const gpa = testing.allocator; // `fn` wrote the function; `mid` rewrote its lines 3-4 as 3-6 (two // changed, two added whole); `shift` rewrote line 4 again. const fn_text = "fn f() void {\n a();\n b();\n c();\n g();\n h();\n i();\n}\n"; const mid_text = "fn f() void {\n a();\n b2();\n c2();\n x();\n y();\n g();\n h();\n i();\n}\n"; const shift_text = "fn f() void {\n a();\n b2();\n c3();\n x();\n y();\n g();\n h();\n i();\n}\n"; var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, null) orelse return error.SkipZigTest; defer repo.deinit(gpa); for ([_]bool{ false, true }) |windowed| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed }); defer p.deinit(); 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].?; const before = File.gutterWidth(pane); p.update(.{ .command = "Changes ::@" }); try testing.expectEqual(@as(usize, 3), answered(p, pane.serial).?.pins.len); const cells: u16 = if (windowed) 2 else levels; try testing.expectEqual(before + cells, File.gutterWidth(pane)); p.sync(); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const s = try p.render(arena.allocator()); const body = s.region(.body, id).?.rect; const first = body.x + before; var buf: [8][3]u8 = undefined; const colours = laneColours(p.theme(), &buf); try testing.expect(colours.len >= 3); const ground = pardes.colors.Grounds.of(p.theme()).add.row; // Lines 1-10, each on the row the view draws it at (ghost rows // stand between): `fn`'s spine on all; `mid` on 3-6; `shift` on 4. const want = [_][]const u8{ "0", "0", "01", "012", "01", "01", "0", "0", "0", "0" }; for (want, 0..) |lanes, row| { const y = body.y + @as(u16, @intCast(pane.wrapRow(p.settings.tab, @intCast(row), 0).row)); if (windowed) { var n: usize = 0; for (s.lanes.items) |lane| if (lane.y == y) { try testing.expectEqual(first, lane.x); try testing.expectEqual(lanes[lane.level] - '0', lane.level); try testing.expectEqual(colours[lane.level], lane.rgb); n += 1; }; try testing.expectEqual(lanes.len, n); } else for (0..levels) |level| { const cell = s.at(first + @as(u16, @intCast(level)), y); if (level < lanes.len) { try testing.expectEqualStrings("\u{258e}", cell.grapheme()); try testing.expectEqual(pardes.Color{ .rgb = colours[level] }, cell.style.fg); } else if (!cell.default and !std.mem.eql(u8, cell.grapheme(), " ")) { std.debug.print("row {d} level {d}: [{s}] {any}\n", .{ row, level, cell.grapheme(), cell.style }); return error.TestUnexpectedResult; } } // `fn`'s lines it still has (1, 2, 7-10) and `mid`'s x() and // y() (5, 6) were added whole; b2 (3) and c3 (4) changed one. const whole = row != 2 and row != 3; const text_cell = s.at(body.x + File.gutterWidth(pane) + 1, y); try testing.expectEqual(whole, std.meta.eql(text_cell.style.bg, pardes.Color{ .rgb = ground })); } if (!windowed) try testing.expectEqual(@as(usize, 0), s.lanes.items.len); p.update(.{ .command = "Changes" }); try testing.expectEqual(before, File.gutterWidth(pane)); } } /// A function `fn` wrote, two of its lines `cut` took away whole, and one /// `mid` rewrote as two (one changed, one added whole). const Ghosts = struct { const fn_text = "fn f() void {\n a();\n b();\n c();\n d();\n e();\n}\n"; const cut_text = "fn f() void {\n a();\n b();\n e();\n}\n"; const mid_text = "fn f() void {\n a();\n b2();\n x();\n e();\n}\n"; fn repo() !?Repo { return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ cut_text, "cut" }, .{ mid_text, "mid" } }, null); } /// The body's rows as this view shows them, whole. fn rows(p: *Pardes, pane: *Pane, arena: std.mem.Allocator, out: [][]const u8) ![]const []const u8 { var it = std.mem.splitScalar(u8, try File.bodyText(p.settings.tab, arena, pane, &pane.file.?), '\n'); var n: usize = 0; while (it.next()) |row| : (n += 1) out[n] = row; return out[0..n]; } /// Each row's text after the gutter, and its number (blank: none). fn text(pane: *const Pane, row: []const u8) []const u8 { return row[@min(row.len, File.gutterWidth(pane))..]; } fn number(pane: *const Pane, row: []const u8) []const u8 { return std.mem.trim(u8, row[0..@min(row.len, File.gutterWidth(pane))], " "); } /// The rows a `Changes ::@` shows: `said` each pin's description; /// `b();` the old text of the line `mid` changed, right above it. fn want(said: [3][]const u8) [12][]const u8 { return .{ "fn f() void {", " a();", " b();", " b2();", " x();", said[2], " c();", " d();", said[1], " e();", "}", said[0] }; } }; fn saidOf(arena: std.mem.Allocator, ch: *const Changes) ![3][]const u8 { var said: [3][]const u8 = undefined; for (&said, ch.pins, [_][]const u8{ "fn", "cut", "mid" }) |*d, pin, title| d.* = try std.fmt.allocPrint(arena, "{s} {s} t now", .{ pin.id[0..4], title }); return said; } test "Changes draws what the text has not where it stood, as ghost rows: a line a change took away whole red across, each change's description after its last line in its lane's colour; no number, their lanes, the rows below moved down in this view alone" { const gpa = testing.allocator; var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(gpa); for ([_]bool{ false, true }) |windowed| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed }); defer p.deinit(); 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].?; const other = p.openView().?; p.update(.{ .command = "Changes ::@" }); const ch = answered(p, pane.serial).?; try testing.expectEqual(@as(usize, 3), ch.pins.len); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const said = try saidOf(arena.allocator(), ch); var buf: [64][]const u8 = undefined; const got = try Ghosts.rows(p, pane, arena.allocator(), &buf); const want = Ghosts.want(said); const numbers = [_][]const u8{ "1", "2", "", "3", "4", "", "", "", "", "5", "6", "" }; for (want, numbers, got[0..want.len]) |w, n, row| { try testing.expectEqualStrings(w, Ghosts.text(pane, row)); try testing.expectEqualStrings(n, Ghosts.number(pane, row)); } // Drawn: each row's lanes (pins by level), its ground, a ghost's ink. p.sync(); const s = try p.render(arena.allocator()); const body = s.region(.body, id).?.rect; const first = body.x + File.gutterWidth(pane) - File.laneCells(pane); var cbuf: [8][3]u8 = undefined; const colours = laneColours(p.theme(), &cbuf); const grounds = pardes.colors.Grounds.of(p.theme()); const lanes = [_][]const u8{ "0", "0", "02", "02", "02", "02", "01", "01", "01", "0", "0", "0" }; const Ground = enum { none, add, del }; const ground = [_]Ground{ .add, .add, .none, .none, .add, .none, .del, .del, .none, .add, .add, .none }; for (lanes, ground, 0..) |pins, gr, row| { const y = body.y + @as(u16, @intCast(row)); if (windowed) { var n: usize = 0; for (s.lanes.items) |lane| if (lane.y == y) { try testing.expectEqual(colours[pins[lane.level] - '0'], lane.rgb); n += 1; }; try testing.expectEqual(pins.len, n); } else for (pins, 0..) |pin, level| { const cell = s.at(first + @as(u16, @intCast(level)), y); try testing.expectEqualStrings("\u{258e}", cell.grapheme()); try testing.expectEqual(pardes.Color{ .rgb = colours[pin - '0'] }, cell.style.fg); } const cell = s.at(body.x + File.gutterWidth(pane) + 1, y); const bg: ?[3]u8 = switch (gr) { .none => null, .add => grounds.add.row, .del => grounds.del.row, }; if (bg) |rgb| try testing.expectEqual(pardes.Color{ .rgb = rgb }, cell.style.bg) else { try testing.expect(!std.meta.eql(cell.style.bg, pardes.Color{ .rgb = grounds.add.row })); try testing.expect(!std.meta.eql(cell.style.bg, pardes.Color{ .rgb = grounds.del.row })); } } // A description's id and title in its lane's colour; a line taken // away in the numbers' grey. for ([_]u16{ 5, 8, 11 }, [_]usize{ 2, 1, 0 }) |row, pin| try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(body.x + File.gutterWidth(pane), body.y + row).style.fg); try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(body.x + File.gutterWidth(pane) + 4, body.y + 6).style.fg); // The changed line: on its old text the word that went (`b`) red, // on it the word that came (`b2`) green; the rest of each neither. const text_x = body.x + File.gutterWidth(pane); for ([_]u16{ 4, 5 }, [_]bool{ true, false }) |col, went| try testing.expectEqual(went, std.meta.eql(s.at(text_x + col, body.y + 2).style.bg, pardes.Color{ .rgb = grounds.del.emph })); for ([_]u16{ 4, 5, 6 }, [_]bool{ true, true, false }) |col, came| try testing.expectEqual(came, std.meta.eql(s.at(text_x + col, body.y + 3).style.bg, pardes.Color{ .rgb = grounds.add.emph })); // The other view shows no lanes: its rows are the text's, unmoved. p.toView(other); const plain = try Ghosts.rows(p, pane, arena.allocator(), &buf); var lines = std.mem.splitScalar(u8, Ghosts.mid_text, '\n'); for (plain[0..6]) |row| try testing.expectEqualStrings(lines.next().?, Ghosts.text(pane, row)); p.toView(.at(0)); try testing.expectEqualStrings(said[2], Ghosts.text(pane, (try Ghosts.rows(p, pane, arena.allocator(), &buf))[5])); } } test "the cursor steps over ghost rows and selection does not see them; ]g and [g go from change to change; a Look on one opens its line in the revision it came from" { const gpa = testing.allocator; var repo = try Ghosts.repo() 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(); 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 ::@" }); const key = struct { fn send(q: *Pardes, keys: []const u8) void { for (keys) |k| q.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); } }.send; // From `x();` (line 4) a `j` is on `e();` (line 5), three ghost rows below. p.update(.{ .command = "Look a.zig:4" }); try testing.expectEqual(@as(i32, 3), pane.body.cur_row); key(p, "j"); try testing.expectEqual(@as(i32, 4), pane.body.cur_row); try testing.expectEqual(@as(i32, 9), pane.wrapRow(p.settings.tab, 4, 0).row); // All selected: a ghost row keeps its own ground. key(p, "%"); p.sync(); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); var s = try p.render(arena.allocator()); var body = s.region(.body, id).?.rect; const x = body.x + File.gutterWidth(pane) + 4; try testing.expectEqual(pardes.Color{ .rgb = pardes.colors.Grounds.of(p.theme()).del.row }, s.at(x, body.y + 6).style.bg); try testing.expect(!std.meta.eql(s.at(x, body.y + 6).style.bg, s.at(x, body.y + 4).style.bg)); key(p, ";"); // ]g, [g: the changes start on lines 1 (fn), 3 (mid) and 5 (fn again, // after the lines cut took away). p.update(.{ .command = "Look a.zig:1" }); for ([_]i32{ 2, 4, 4 }) |want| { key(p, "]g"); try testing.expectEqual(want, pane.body.cur_row); } for ([_]i32{ 2, 0 }) |want| { key(p, "[g"); try testing.expectEqual(want, pane.body.cur_row); } // A Look (B3) on `c();`'s ghost row: fn's revision (cut's parent) at its line 4. p.sync(); s = try p.render(arena.allocator()); body = s.region(.body, id).?.rect; p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y + 6 } }); p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y + 6 } }); const shown = p.view().active; try testing.expect(shown != id); const f = &p.panes[shown].?.file.?; try testing.expect(of(f) != null); try testing.expectEqualStrings(Ghosts.fn_text, f.content); try testing.expectEqual(@as(i32, 3), p.panes[shown].?.body.cur_row); } test "ghost rows ride with the text: a line deleted above moves them up, a line they stood before deleted puts them before the next; a client replays it equal" { var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); const R = pardes.replica; const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .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 serial = a.core.panes[a.core.view().active].?.serial; const ats = struct { fn of(ch: *const Changes, out: []u32) []u32 { for (ch.ghosts, out[0..ch.ghosts.len]) |g, *o| o.* = g.at; return out[0..ch.ghosts.len]; } }.of; var got: [8]u32 = undefined; // mid's description, cut's two lines and its description before `e();` // (line 5), fn's after the last. try testing.expectEqualSlices(u32, &.{ 2, 4, 4, 4, 4, 6 }, ats(answered(a.core, serial).?, &got)); // `a();` deleted: each one a line up. r.confirm(try a.local(.{ .command = "Look a.zig:2" })); for (";xd") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } })); r.settle(); try testing.expectEqualSlices(u32, &.{ 1, 3, 3, 3, 3, 5 }, ats(answered(a.core, serial).?, &got)); // `e();`, the line they stood before, deleted: they stand before `}`. r.confirm(try a.local(.{ .command = "Look a.zig:4" })); for (";xd") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } })); r.settle(); try testing.expectEqualStrings("fn f() void {\n b2();\n x();\n}\n", a.core.panes[a.core.view().active].?.file.?.content); try testing.expectEqualSlices(u32, &.{ 1, 3, 3, 3, 3, 4 }, ats(answered(a.core, serial).?, &got)); try testing.expect(r.diverged == null); try testing.expectEqualSlices(Ghost, answered(a.core, serial).?.ghosts, answered(r.core(), serial).?.ghosts); try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } test "a description's ghost row keeps its author and age: in a pane narrower than the row its title gives way, cut to the room" { const gpa = testing.allocator; const title = "a title long enough that no narrow pane holds the whole of it beside its author and its age"; var repo = try Repo.with(gpa, &.{.{ "fn f() void {\n a();\n}\n", title }}, null) orelse return error.SkipZigTest; defer repo.deinit(gpa); for ([_]bool{ false, true }) |windowed| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 50, .rows = 20, .windowed = windowed }); defer p.deinit(); 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 ::@" }); const ch = answered(p, pane.serial).?; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); var buf: [64][]const u8 = undefined; const got = try Ghosts.rows(p, pane, arena.allocator(), &buf); const row = Ghosts.text(pane, got[3]); const room = pane.cols - File.gutterWidth(pane) - 1; try testing.expect(File.displayWidth(p.settings.tab, row) <= room); try testing.expectStringStartsWith(row, try std.fmt.allocPrint(arena.allocator(), "{s} a title long", .{ch.pins[0].id[0..4]})); try testing.expectStringEndsWith(row, "\u{2026} t now"); // Drawn: the id and the title in its lane's colour, the author and // the age grey, at the row's end. p.sync(); const s = try p.render(arena.allocator()); const body = s.region(.body, id).?.rect; const x = body.x + File.gutterWidth(pane); var cbuf: [8][3]u8 = undefined; try testing.expectEqual(pardes.Color{ .rgb = laneColours(p.theme(), &cbuf)[0] }, s.at(x, body.y + 3).style.fg); const age_x = x + @as(u16, @intCast(File.displayWidth(p.settings.tab, row))) - 1; try testing.expectEqualStrings("w", s.at(age_x, body.y + 3).grapheme()); try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(age_x, body.y + 3).style.fg); try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(age_x - 4, body.y + 3).style.fg); } } 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"; const chg_text = "fn f() void {\n a();\n b2();\n d();\n}\n"; var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ chg_text, "chg" } }, null) 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(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); const pane = p.panes[p.view().active].?; p.update(.{ .command = "Changes ::@" }); const ch = answered(p, pane.serial).?; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const said = [2][]const u8{ try std.fmt.allocPrint(arena.allocator(), "{s} fn t now", .{ch.pins[0].id[0..4]}), try std.fmt.allocPrint(arena.allocator(), "{s} chg t now", .{ch.pins[1].id[0..4]}) }; var buf: [64][]const u8 = undefined; const got = try Ghosts.rows(p, pane, arena.allocator(), &buf); const want = [_][]const u8{ "fn f() void {", " a();", " b();", " b2();", " c();", said[1], " d();", "}", said[0] }; for (want, got[0..want.len]) |w, row| try testing.expectEqualStrings(w, Ghosts.text(pane, row)); } test "a change the revset does not pin, between two it does, moves the older one's ghost rows to where they stand: jj's answer has its hunks" { const gpa = testing.allocator; const fn_text = "fn f() void {\n a();\n b();\n c();\n d();\n}\n"; // `old` takes `c();` away; `mid` (not pinned) writes two lines above // it; `last` changes `d();`. const old_text = "fn f() void {\n a();\n b();\n d();\n}\n"; const mid_text = "fn f() void {\n a();\n x();\n y();\n b();\n d();\n}\n"; const last_text = "fn f() void {\n a();\n x();\n y();\n b();\n d2();\n}\n"; var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ old_text, "old" }, .{ mid_text, "mid" }, .{ last_text, "last" } }, null) 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(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); const pane = p.panes[p.view().active].?; p.update(.{ .command = "Changes @--- | @-" }); const ch = answered(p, pane.serial).?; try testing.expectEqual(@as(usize, 2), ch.pins.len); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const said = [2][]const u8{ try std.fmt.allocPrint(arena.allocator(), "{s} old t now", .{ch.pins[0].id[0..4]}), try std.fmt.allocPrint(arena.allocator(), "{s} last t now", .{ch.pins[1].id[0..4]}) }; var buf: [64][]const u8 = undefined; const got = try Ghosts.rows(p, pane, arena.allocator(), &buf); const want = [_][]const u8{ "fn f() void {", " a();", " x();", " y();", " b();", " c();", said[0], " d();", " d2();", said[1], "}" }; for (want, got[0..want.len]) |w, row| try testing.expectEqualStrings(w, Ghosts.text(pane, row)); } test "lines typed between the word and jj's answer: the ghost rows stand where they stood, carried across them" { var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); var w = try WorkerJj.init(&repo, ""); defer w.deinit(); try w.word("Changes ::@"); try testing.expect(answered(w.a.core, w.serial) == null); // A line opened above `a();` before the answer lands. try w.word("Look a.zig:2"); for ("Oz();") |k| w.r.confirm(try w.a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } })); w.r.confirm(try w.a.local(.{ .key = .{ .cp = pardes.Key.escape } })); try w.land(); try testing.expectStringStartsWith(w.a.core.panes[w.id].?.file.?.content, "fn f() void {\n z();\n a();\n"); var got: [8]u32 = undefined; const ch = answered(w.a.core, w.serial).?; for (ch.ghosts, got[0..ch.ghosts.len]) |g, *o| o.* = g.at; try testing.expectEqualSlices(u32, &.{ 3, 5, 5, 5, 5, 7 }, got[0..ch.ghosts.len]); try testing.expectEqualSlices(Ghost, ch.ghosts, answered(w.r.core(), w.serial).?.ghosts); } /// A function three changes wrote: `fn` all of it, `mid` its lines 3-6 /// (rewriting two, adding two), `shift` line 4 again. const Stack = struct { const fn_text = "fn f() void {\n a();\n b();\n c();\n g();\n h();\n i();\n}\n"; const mid_text = "fn f() void {\n a();\n b2();\n c2();\n x();\n y();\n g();\n h();\n i();\n}\n"; const shift_text = "fn f() void {\n a();\n b2();\n c3();\n x();\n y();\n g();\n h();\n i();\n}\n"; /// Who wrote each of shift_text's lines: fn 0, mid 1, shift 2. const pins = [_]u16{ 0, 0, 1, 2, 1, 1, 0, 0, 0, 0 }; fn repo(working: ?[]const u8) !?Repo { return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, working); } }; fn pinsOf(ch: *const Changes, out: []u16) []u16 { for (ch.lines, out[0..ch.lines.len]) |l, *o| o.* = @intFromEnum(l.pin); return out[0..ch.lines.len]; } test "Changes lines jj's annotation up with the pane's text: a line jj has not seen (typed, not snapshotted) is nobody's, the lines after it keep their changes" { // The file on disk has a line more than jj's last snapshot of it. const working = "fn f() void {\n a();\n b2();\n c3();\n x();\n new();\n y();\n g();\n h();\n i();\n}\n"; var repo = try Stack.repo(working) orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false }); defer p.deinit(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); const pane = p.panes[p.view().active].?; try testing.expectEqualStrings(working, pane.file.?.content); p.update(.{ .command = "Changes ::@" }); const none = @intFromEnum(PinIndex.none); var got: [16]u16 = undefined; try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, none, 1, 0, 0, 0, 0 }, pinsOf(answered(p, pane.serial).?, &got)); } test "the lanes ride with the text: a line typed in a nested block is nobody's, its undo puts the values back, a deleted line takes its value; a client replays it equal" { var repo = try Stack.repo(null) orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); const R = pardes.replica; const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}); defer a.deinit(); const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); defer r.deinit(); const Keys = struct { fn send(au: *R.Authority, re: *R.Replica, keys: []const u8) !void { for (keys) |k| { const ev: pardes.Event = if (k == 27) .{ .key = .{ .cp = pardes.Key.escape } } else .{ .key = .{ .cp = k, .text = &[_]u8{k} } }; re.confirm(try au.local(ev)); } re.settle(); } }; 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 serial = a.core.panes[a.core.view().active].?.serial; const ch = answered(a.core, serial).?; var got: [16]u16 = undefined; try testing.expectEqualSlices(u16, &Stack.pins, pinsOf(ch, &got)); const before = try testing.allocator.dupe(Line, ch.lines); defer testing.allocator.free(before); const none = @intFromEnum(PinIndex.none); // A line opened below `c3();` (line 4, inside mid's block): nobody's; // the rows around keep their lanes. r.confirm(try a.local(.{ .command = "Look a.zig:4" })); try Keys.send(a, r, "oz\x1b"); try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, none, 1, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got)); try testing.expectEqual(before[3].lanes, answered(a.core, serial).?.lines[3].lanes); try testing.expectEqual(before[4].lanes, answered(a.core, serial).?.lines[5].lanes); // Undone: the values as they were. try Keys.send(a, r, "u"); try testing.expectEqualSlices(Line, before, answered(a.core, serial).?.lines); // `x();` (line 5, mid's) deleted: its value goes with it. r.confirm(try a.local(.{ .command = "Look a.zig:5" })); try Keys.send(a, r, ";xd"); try testing.expectEqualStrings(Stack.shift_text[0..41] ++ Stack.shift_text[50..], a.core.panes[a.core.view().active].?.file.?.content); try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got)); try testing.expectEqual(before[5].lanes, answered(a.core, serial).?.lines[4].lanes); try testing.expect(r.diverged == null); try testing.expectEqualSlices(Line, answered(a.core, serial).?.lines, answered(r.core(), serial).?.lines); try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } test "a client's own line opened over pinned changes, rolled back by the session's key first: the lanes it spliced under its copy are the copy's again, freed once; the client ends equal" { var repo = try Stack.repo(null) orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); const R = pardes.replica; const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .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.confirm(try a.local(.{ .command = "Look a.zig:4" })); r.settle(); const serial = a.core.panes[a.core.view().active].?.serial; // The client opens a line below: an edit of the file, whose step splices // the pinned lines' values (jj.edited) under the copy it takes. const typed = try testing.allocator.dupe(u8, try r.input(.{ .key = .{ .cp = 'o', .text = "o" } })); defer testing.allocator.free(typed); try testing.expectEqual(@as(usize, 1), r.applied); // The session's own key comes first: the copy put back, the `o` applied // again over it, then confirmed. r.confirm(try a.local(.{ .key = .{ .cp = 'k', .text = "k" } })); r.settle(); r.confirm(try a.take(typed)); r.settle(); try testing.expect(r.diverged == null); try testing.expectEqualSlices(Line, answered(a.core, serial).?.lines, answered(r.core(), serial).?.lines); try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } /// Two functions four changes wrote: `fn` both, `f2` and `f3` rewrote /// f's line, `g2` g's: f three changes, g two. const Churned = struct { const fn_text = "fn f() void {\n a();\n}\n\nfn g() void {\n b();\n}\n"; const f2_text = "fn f() void {\n a2();\n}\n\nfn g() void {\n b();\n}\n"; const f3_text = "fn f() void {\n a3();\n}\n\nfn g() void {\n b();\n}\n"; const g2_text = "fn f() void {\n a3();\n}\n\nfn g() void {\n b2();\n}\n"; fn repo() !?Repo { return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ f2_text, "f2" }, .{ f3_text, "f3" }, .{ g2_text, "g2" } }, null); } }; test "Churn counts the changes that touched each declaration and draws them after the line number and by the scroll thumb, grey to red on a log scale; bare again, off" { const gpa = testing.allocator; var repo = try Churned.repo() orelse return error.SkipZigTest; defer repo.deinit(gpa); for ([_]bool{ false, true }) |windowed| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed }); defer p.deinit(); 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].?; const before = File.gutterWidth(pane); p.update(.{ .command = "Churn" }); const heat = churned(p, pane.serial).?; try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, heat.lines); try testing.expectEqual(@as(u16, 3), heat.hottest); try testing.expectEqual(before + 1, File.gutterWidth(pane)); // Drawn: a cell after the number, f's the theme's red, g's along // the way from the numbers' grey at ln 3 / ln 4, none between. p.sync(); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const s = try p.render(arena.allocator()); const body = s.region(.body, id).?.rect; const x = body.x + File.gutterWidth(pane) - 1; const red = themeRed(p.theme()); const warm = pardes.colors.mixOklab(p.theme().lineno, red, @log(3.0) / @log(4.0)); for (0..7) |row| { const cell = s.at(x, body.y + @as(u16, @intCast(row))); if (row == 3) { try testing.expectEqualStrings(" ", cell.grapheme()); continue; } try testing.expectEqualStrings("\u{258c}", cell.grapheme()); try testing.expectEqual(pardes.Color{ .rgb = if (row < 3) red else warm }, cell.style.fg); } // By the scroll thumb: the rail's first row holds f's lines. const rail = s.region(.rail, id).?.rect; if (windowed) { const strip = for (s.heat.items) |h| { if (h.owner == id and h.row == 0) break h; } else return error.TestExpectedEqual; try testing.expectEqual(red, strip.rgb); } else try testing.expectEqual(pardes.Color{ .rgb = red }, s.at(rail.x + 1, rail.y).style.bg); // Bare again: hidden, the gutter as it was; again: shown, jj not asked. p.update(.{ .command = "Churn" }); try testing.expectEqual(before, File.gutterWidth(pane)); p.update(.{ .command = "Churn" }); try testing.expectEqual(before + 1, File.gutterWidth(pane)); try testing.expectEqual(heat, churned(p, pane.serial).?); } } test "Churn's window: a revset, or a span of time back from now; jj's refusal said" { const gpa = testing.allocator; var repo = try Churned.repo() 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(); 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].?; // f3 and g2 alone: one each. p.update(.{ .command = "Churn @--::@" }); try testing.expectEqualSlices(u16, &.{ 1, 1, 1, 0, 1, 1, 1 }, churned(p, pane.serial).?.lines); // The last week: all four, just made. p.update(.{ .command = "Churn 1w" }); try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, churned(p, pane.serial).?.lines); try testing.expectEqualStrings("::(@) & author_date(after:\"1 weeks ago\")", churned(p, pane.serial).?.window()); p.update(.{ .command = "Churn nosuch" }); try testing.expect(std.mem.indexOf(u8, told(p, id), "Churn: Revision `nosuch` doesn't exist") != null); } test "Churn on a worker: jj's answer kept raw, counted when the worker's parse of the text lands; the client equal" { var repo = try Churned.repo() orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); var w = try WorkerJj.init(&repo, ""); defer w.deinit(); try w.word("Churn"); try w.land(); try testing.expectEqualSlices(u16, &.{ 3, 3, 3, 0, 2, 2, 2 }, churned(w.a.core, w.serial).?.lines); try testing.expectEqualSlices(u16, churned(w.a.core, w.serial).?.lines, churned(w.r.core(), w.serial).?.lines); } test "Churn's counts ride with the text, and a client replays them equal" { var repo = try Churned.repo() orelse return error.SkipZigTest; defer repo.deinit(testing.allocator); const R = pardes.replica; const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .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 = "Churn" })); r.settle(); const serial = a.core.panes[a.core.view().active].?.serial; // `a3();` deleted: its value goes with it. r.confirm(try a.local(.{ .command = "Look a.zig:2" })); for (";xd") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } })); r.settle(); try testing.expectEqualSlices(u16, &.{ 3, 3, 0, 2, 2, 2 }, churned(a.core, serial).?.lines); try testing.expect(r.diverged == null); try testing.expectEqualSlices(u16, churned(a.core, serial).?.lines, churned(r.core(), serial).?.lines); try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } test "a B3 click on path@rev:line in running text opens the file at that revision there" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); try repo.tmp.dir.writeFile(testing.io, .{ .sub_path = "notes.txt", .data = "see a.zig@@-:2 here\n" }); const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/notes.txt", .{repo.dir}) }); const notes = p.view().active; p.sync(); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const s = try p.render(arena.allocator()); const body = s.region(.body, notes).?.rect; // On the `@` of the address, the body's first row. const x: u16 = body.x + File.gutterWidth(p.panes[notes].?) + @as(u16, "see a.zig".len); p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y } }); p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y } }); const shown = p.view().active; try testing.expect(shown != notes); const f = &p.panes[shown].?.file.?; try testing.expect(of(f) != null); try testing.expectEqualStrings(Repo.two, f.content); try testing.expectEqual(@as(i32, 1), p.panes[shown].?.body.cur_row); } test "a revision's text is read-only over 9P too: an open to write it is refused in words" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }); const pane = p.panes[p.view().active].?; try testing.expect(of(&pane.file.?) != null); const th = @import("ninep/harness.zig"); const tree = @import("ninep/tree.zig"); for ([_]tree.PaneFile{ .body, .data, .xdata, .sel }) |file| { const got = th.call(p, .{ .tag = 1, .op = .open, .node = tree.Node.of(pane.serial, file), .omode = 1 }); try testing.expectEqual(@as(u16, 30), got.errno()); try testing.expectEqual(@as(u16, 30), @import("cloud9").fs.enameErrno(got.reply.ename)); } // Reading it is as any text's. try testing.expectEqual(@as(u16, 0), th.call(p, .{ .tag = 1, .op = .open, .node = tree.Node.of(pane.serial, .body), .omode = 0 }).errno()); try testing.expectEqualStrings(Repo.two, pane.file.?.content); }