From 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 22:03:14 -0300 Subject: core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/panes.zig | 1904 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1904 insertions(+) create mode 100644 core/panes.zig (limited to 'core/panes.zig') diff --git a/core/panes.zig b/core/panes.zig new file mode 100644 index 00000000..fe57793a --- /dev/null +++ b/core/panes.zig @@ -0,0 +1,1904 @@ +const std = @import("std"); +const pardes = @import("root.zig"); +const views = @import("views.zig"); +const config = @import("config.zig"); +const modal = @import("modal.zig"); +const limits = memory.limits; +const panes = @This(); +const Pardes = pardes.Pardes; +const exec = @import("exec.zig"); +const look = @import("look.zig"); +const layout = @import("layout.zig"); +const tagline = @import("tagline.zig"); +const tape = @import("tape.zig"); +const dump = @import("dump.zig"); +const memory = @import("memory.zig"); +const ctlfs = @import("ninep/tree.zig"); +const Pipe = @import("Pipe.zig"); +const Key = pardes.Key; +const Cell = pardes.Cell; +const BOX_H = pardes.BOX_H; +const MAX_PANES = pardes.MAX_PANES; +const effect_path_cap = pardes.effect_path_cap; + +/// An owned editable buffer and the absolute surface row of its first line. +/// Files use row zero; terminal overlays may begin anywhere in scrollback. +pub const EditText = struct { text: []u8, row0: i32 }; + +pub const Pane = struct { + /// What the replay digest leaves out (core/walk.zig): the view's geometry, + /// made again from the rest (File.geometry); the 9P server's record of + /// the pane's opens and readers; the other views' share of it (views.zig). + pub const replica = .{ + .local = .{ "pv", "pv_known" }, + .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan" }, + .authority = .{"fs"}, + .len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, + // A picture's memory is its own allocator's (a dump loaded makes + // it there). + .alloc = .{ .{ "addon", "image" }, .{ "pdf", "image" }, .{ "terminal", "terminal" } }, + }; + /// The words that throw unsaved text away (builtins.zig warnModified). + pub const Discarding = enum { Exit, Restore, get, Del, Delcol }; + + /// One mouse sweep, per button: the press (c0, r0) and where it is now + /// (c1, r1), a stream between them as acme's (edit.sweepCols). c/r are + /// text-area relative; r counts from the tag's first row (the body + /// starts at Pane.tag_rows). + pub const Sel = struct { + state: enum { none, dragging, done } = .none, + source_id: u64 = 0, + c0: i32 = 0, + c1: i32 = 0, + r0: i32 = 0, + r1: i32 = 0, + }; + + /// A captured sweep keeps one source span per rendered row. Wrapped + /// segments remain separate rows when copied, even when they share a + /// source line. + pub const PointerRow = struct { + row: i32, + lo: usize, + hi: usize, + /// Not the sweep's last row: its highlight runs to the right edge. + to_edge: bool = false, + raw_terminal: bool = false, + prompt_bytes: usize = 0, + }; + pub const PointerSelection = struct { + gesture: Sel, + rows: []PointerRow, + raw_text: ?[]u8 = null, + }; + pub const LookSpot = struct { + row: i32, + col0: i32, + col1: i32, + }; + + /// A PDF pane as a dump of a build before the pdf addon kept it, read + /// to open it as the addon's (dump.zig revivePane); never written. + pub const LegacyPdf = struct { + path: []u8 = &.{}, + page: usize = 0, + fit: enum { width, height } = .width, + tint: enum { disabled, filtered, full } = .filtered, + }; + + /// What an open prompt is asking. The answer is typed into `input`. + pub const Prompt = union(enum) { + none, + search, + pipe: modal.Normal.PipeBehavior, + /// Save on a scratch buffer or a terminal: the answer is a path to write to. + save, + /// Del from the keyboard with open panes both above and below: which + /// one takes the rows. Nothing is typed; one key answers. + del_side, + /// An exec from a file's body with several REPLs bound for its + /// language: which one takes it (exec.zig routeToRepl). One key + /// answers, the question being in `question`. + repl_choice, + /// A new name for the file, drafted in place of the path on the + /// tagline after a click there; Enter commits it, as a buffer name + /// and never a disk rename. + name, + }; + + pub const Cwd = union(enum) { none, inherited: *Pane, owned: []u8 }; + pub const Focus = enum { body, tag }; + pub const SessionView = struct { wrap: bool = true, layered: bool = true, body_h: u32 = 0, tagline_h: u32 = 0, rect_h: u16 = 0 }; + terminal: ?*Term.State = null, + gpa: std.mem.Allocator, + serial: u32 = 0, + /// What the control filesystem keeps of this pane -- addr and limit, the + /// event queue and its readers, a run waiting on the shell -- lives and + /// dies with it, as acme keeps the same on its Window + /// (editors/acme/dat.h:226-266). + fs: pardes.ctlfs.pane.State = .{}, + /// The body: what the pane shows and edits, its cursor, selections, + /// mode and edit-buffer undo. + body: Text = .{}, + vweight: f32 = 1, + /// A folded pane keeps its expansion weight, but occupies only its tag row. + collapsed: bool = false, + /// The serial of the pane this one is attached to, its owner: a query + /// pane or its +Preview sits right under its owner in the owner's + /// column, takes its rows from the owner alone, and moves, folds and + /// closes with it (layout.zig, "Attached panes"). An owner that is + /// gone, or a pane no longer right under its owner's group, leaves it + /// an ordinary pane (layout.keepGroups). + attached_to: ?u32 = null, + /// This pane is a query pane: its line 1 the query, its rows made live + /// from a source (Query.zig, gpa-owned). + query: ?*Query = null, + cols: u16, + rows: u16, + greet: bool = false, + /// Its shell could not be started (Pardes.shellFailed): a run hears + /// `error shell gone` at once. + shell_failed: bool = false, + /// Its shell has printed something, so it has made its chdir: until + /// then /proc says this process's directory, not the shell's + /// (Pardes.setCwd keeps the one it was started in). + shell_spoke: bool = false, + /// A shell has run in it (Pardes.acknowledgeShell): a Term whose first + /// shell fails to start closes, one started again keeps its pane. + had_shell: bool = false, + /// What pardes typed for a shell not ready for it yet: queued until it + /// is started (`spawn`) and then at its prompt (`input`). + pending_command: struct { + bytes: []u8 = &.{}, + wait: enum { none, spawn, input } = .none, + } = .{}, + /// The last command line pardes typed into this terminal (an exec, a + /// middle click, a pty/run): its first word, which Kill matches, and + /// the shell's command count its start (C mark) reaches. + sent_command: ?struct { + pub const replica = .{ .len = .{.{ "word", "len" }} }; + word: [64]u8 = undefined, + len: u8 = 0, + seq: u32 = 0, + } = null, + /// A command pane (exec.zig runCommand): the line its child runs as + /// `$SHELL -c`, owned, where an interactive terminal has null. + command: ?[]u8 = null, + /// The pane whose tag or text the command was run from, its child's + /// `$winid` (acme's name); 0 for one from a column's or the workspace's + /// tag, which no pane owns. + command_from: u32 = 0, + /// The command's child has exited, and with what status (null: unknown, + /// shown `exit ?`). + command_done: bool = false, + command_status: ?u8 = null, + /// Its pty is still open: a job the command left in the background may + /// be printing to it, and a reuse would hang it up. + command_pty: bool = false, + /// Its child pages as a terminal's does (`pardes -`, a +Pager), not + /// through cat: Look's `git show` of a commit (hunks.lookedAtCommit). + command_pages: bool = false, + /// The shell a terminal runs when it is not the configured one (`Term + /// fish`), owned. + shell: ?[]u8 = null, + /// An interactive terminal's tag text naming its shell, ` Term+fish ...` + /// (Pardes.acknowledgeShell); empty until the host says which it ran. + shell_tail: [96]u8 = undefined, + shell_tail_len: u8 = 0, + /// A terminal bound as a language's REPL (`Repl python`): an exec from + /// the body of a file in that language is sent to it (exec.zig + /// routeToRepl). `letter` makes its id, `python-a`, with the language's + /// name from grammar_manifest. + repl: ?struct { lang: u8, letter: u8 } = null, + /// It has been told that its program takes no bracketed paste. + repl_warned: bool = false, + /// Enters owed to a REPL after a bracketed paste (exec.sendToRepl): sent + /// with its next output, the paste taken, or at `repl_enter_due_ns`. + repl_enter: u8 = 0, + repl_enter_due_ns: u64 = 0, + /// When Del's question (`del_side`) goes up on the notice band, on the + /// shell's clock (config.del_question_delay_ns after it was asked). + question_due_ns: u64 = 0, + /// A question with its answers in it (`repl_choice`). + question: [96]u8 = undefined, + question_len: u8 = 0, + /// The newest message says where an exec was sent: it is tinted. + msg_sent: bool = false, + /// The revision an Exit or a Restore last warned this pane was modified + /// at, and which of them: only that word goes ahead on the warning + /// (builtins.zig warnModified). + discard_warned: ?struct { revision: u32, by: Discarding } = null, + file: ?File.State = null, + /// A pane of a kind (Kind.zig): a picture, or one a library brought. + addon: ?*@import("Kind.zig").Slot = null, + pdf: ?*LegacyPdf = null, + prompt: Prompt = .none, + /// The text an open prompt answers for: `s`/`S` select in it and `|` + /// pipes it. A header's is whichever has the keyboard; `/` and Save's + /// path always answer for the body. + prompt_for: Text.What = .body, + /// The answer to an open prompt: its marker and what is typed after it, + /// edited in insert mode and shown on the notice band, or a name draft + /// shown on the tagline in place of the path. It is its own text so a + /// prompt never touches the tag. + input: Text = .{ .what = .input }, + search_pane: ?usize = null, + search_row: ?usize = null, + /// Where in this pane's text the current search or list says to look + /// (`/`, `*`, a query pane's rows, n/N): tinted, ticked on the rail, + /// the current one selected (Places.zig). + places: Places = .{}, + look_at: ?LookSpot = null, + /// `gw`'s words, labelled in order while it waits for a label to be + /// typed (gpa-owned); `jump_first` is the label's first letter once typed. + jump: std.ArrayList(modal.Selection) = .empty, + jump_first: ?u8 = null, + sel_snap: [Text.max_selections]modal.Selection = undefined, + nsel_snap: u16 = 0, + sel_snap_pri: u16 = 0, + sel_snap_expl: bool = false, + /// The tag: what the user keeps after the computed prefix (the path, the + /// dirty marker, a PDF's page), its cursor, selections and undo. The + /// prefix is never stored in it, so it never moves the tag's cursor. + tag: Text = .{ .what = .tag }, + /// Which of the pane's texts the keyboard types into. + focus: Focus = .body, + /// Display columns hidden to reveal the tag caret; tag addresses stay whole. + tag_scroll: u16 = 0, + /// Rows the tag takes on screen: one per line of it, as many as the pane + /// has room for with a body row to spare. Set with the geometry in sync. + /// Pointer rows count from the tag's first, so a body starts at this one. + tag_rows: u16 = 1, + /// The tag's first line on screen. A tag with more lines than rows + /// scrolls to keep its caret in view while it has the keyboard; pointer + /// rows count from this line, not the tag's first. + tag_top: u16 = 0, + /// The tag shows all its rows (acme's `tagexpand`, on by default); off, + /// one row, as acme's Tagup leaves it. Down on the + /// tag's last line and Up on its first, typing, or Alt-Down and Alt-Up + /// in the tag, as acme's arrows in a tag (plan9port text.c:776). + tag_expanded: bool = true, + /// How long the tag's computed prefix was when its positions were last + /// placed. They count from the start of the prefix, so when it grows or + /// shrinks (a rename, the dirty marker, a PDF's page) what follows it + /// moves with it. + tag_lead: usize = 0, + cwd: Cwd = .none, + hscroll: i32 = 0, + /// A Follow chain's page (File.followChain): the scroll the chain last + /// gave it, each view's; on the keyboard's page, whether a page comes + /// before (1) and after (2), whose edge the cursor crosses rather than + /// scrolling, and whether it crossed one this step. + follow_scroll: usize = 0, + follow_edges: u2 = 0, + follow_crossed: bool = false, + // Visible rows map to source lines and raw/display column origins. + wrap_line: [limits.wrap_rows]i32 = undefined, + wrap_col: [limits.wrap_rows]i32 = undefined, + wrap_pad: [limits.wrap_rows]u16 = @splat(0), + wrap_n: u16 = 0, + /// A row map also exists for sticky headers when soft wrapping is off. + body_wrapped: bool = false, + context_rows: u16 = 0, + body_rows: u16 = 0, + body_visible_rows: u16 = 0, + context_row_limit: ?u16 = null, + /// What the geometry above was made for (File.geometry), and the bytes + /// its text takes; 0 has it made again by whoever reads it next. + geometry_key: u64 = 0, + geometry_len: usize = 0, + /// The session's part of the geometry, as of the last step (`sync`). + /// Digested and dumped, not made again: a key's move reads it before its + /// step's `sync` (normal.halfPageMove's scroll), and a core loaded from a + /// dump has had none (Replica.initDump). + view: SessionView = .{}, + sel: [3]Sel = @splat(.{}), + pointer_selections: [3]?PointerSelection = @splat(null), + next_pointer_selection: u64 = 0, + + /// terminals only: the typed-text buffer standing in for shell rows + ovl: ?Text.EditBuffer = null, + tty_filter: bool = false, + msg: [256]u8 = undefined, + msg_len: u16 = 0, + /// Where the newest message line is in its life. + msg_life: MessageLife = .{}, + /// When it was said, in monotonic ms (Messages.expireUnattended). + msg_said_ms: i64 = 0, + /// The row (among the notice rows) the newest line holds for its life. + msg_slot: u8 = 0, + /// Earlier message lines still on screen, oldest first, each running its + /// own life: a new message stacks under them instead of replacing them. + msg_older: [message_stack]OlderMessage = undefined, + msg_older_len: u8 = 0, + /// The newest line is a builtin announcing itself in this step: what + /// the step says next replaces it rather than stacking under it. + msg_announcement: bool = false, + /// The newest line is a status (progress, a server's state): the next + /// line replaces it rather than stacking under it. + msg_status: bool = false, + /// The transient lines this pane shows between its body and its tagline: + /// a builtin's message, the pending leader chord, a prompt waiting for + /// input. Rebuilt every frame from the state that owns each one, so a + /// line that goes away is simply not added again and the rest close the + /// gap -- there is no second copy of the truth to fall out of step. The + /// body layer reserves exactly `len` rows for them, the way it already + /// reserves rows for sticky context headers. + notices: Notices = .{}, + /// Each other view's share of this pane, while it is not live + /// (views.zig): its cursor, scroll and place in that view's layout. + pv: [views.max]views.PaneView = undefined, + /// The views `pv` holds a share for (a pane retired before a view came + /// has none of it). + pv_known: u8 = 0, + /// The view that last typed into it: a terminal shown at two sizes takes + /// that view's (Pardes.sync). + sized_by: u8 = 0, + /// A terminal shown in a view shorter than it (one that does not size + /// it): the rows its top is passed over by, so its cursor stays in + /// sight (Pane.panFor); 0 everywhere else. + pan: u16 = 0, + /// The view whose step a `.name` prompt is (tagline.draftName): only + /// that view's focus leaving the pane drops it. + prompt_view: u8 = 0, + + pub const MessagePhase = enum { shown, lingering }; + /// One message line's life: shown, or lingering after the key or click + /// that dismissed it, `frame` frames of its linger gone. + pub const MessageLife = struct { + phase: MessagePhase = .shown, + frame: u16 = 0, + }; + /// Older message lines kept on screen under a new one. + pub const message_stack = 3; + pub const OlderMessage = struct { + pub const replica = .{ .len = .{.{ "text", "len" }} }; + text: [256]u8 = undefined, + len: u16 = 0, + life: MessageLife = .{}, + slot: u8 = 0, + + pub fn slice(line: *const OlderMessage) []const u8 { + return line.text[0..line.len]; + } + }; + + /// Move the newest line onto the stack of older ones, dropping the oldest + /// when it is full; the newest slot is left empty for what arrives. + pub fn pushOlderMessage(pane: *Pane) void { + if (pane.msg_older_len == message_stack) { + std.mem.copyForwards(OlderMessage, pane.msg_older[0 .. message_stack - 1], pane.msg_older[1..]); + pane.msg_older_len -= 1; + } + pane.msg_older[pane.msg_older_len] = .{ .text = pane.msg, .len = pane.msg_len, .life = pane.msg_life, .slot = pane.msg_slot }; + pane.msg_older_len += 1; + pane.msg_len = 0; + pane.msg_life = .{}; + } + + /// The first row no older line holds. A line keeps its row until it + /// leaves, and a new one fills the first gap: nothing on screen moves. + pub fn freeMessageSlot(pane: *const Pane) u8 { + var used: u8 = 0; + for (pane.msg_older[0..pane.msg_older_len]) |line| used |= @as(u8, 1) << @intCast(line.slot); + var slot: u8 = 0; + while (used & (@as(u8, 1) << @intCast(slot)) != 0) slot += 1; + return slot; + } + + pub fn removeOlderMessage(pane: *Pane, i: usize) void { + std.mem.copyForwards(OlderMessage, pane.msg_older[i .. pane.msg_older_len - 1], pane.msg_older[i + 1 .. pane.msg_older_len]); + pane.msg_older_len -= 1; + } + + pub const Notices = struct { + /// Painted bottom-up in this order, so a prompt keeps the row nearest + /// the tagline that it has always had, and its cursor with it. + /// `older` is an earlier message line still on screen; `index` says + /// which (`Pane.msg_older`). + pub const Kind = enum { older, message, leader, prompt }; + pub const max = @typeInfo(Kind).@"enum".field_names.len - 1 + message_stack; + + kinds: [max]Kind = undefined, + index: [max]u8 = @splat(0), + /// Each band's row below the body's top: message lines keep theirs, + /// so a band that leaves leaves a gap rather than moving the rest. + row: [max]u8 = @splat(0), + /// Where each band's chip starts, as an absolute grid column. A chip + /// is only as wide as its own text, so the rest of the row underneath + /// is ordinary body text and a click there has to reach it. + left: [max]u16 = @splat(std.math.maxInt(u16)), + len: u8 = 0, + + /// A band on the next row after every band so far. + pub fn push(n: *Notices, kind: Kind) void { + n.pushAt(kind, 0, n.span()); + } + + pub fn pushAt(n: *Notices, kind: Kind, index: u8, row: u8) void { + if (n.len >= max) return; + n.kinds[n.len] = kind; + n.index[n.len] = index; + n.row[n.len] = row; + n.left[n.len] = std.math.maxInt(u16); + n.len += 1; + } + + /// Is this cell inside the chip drawn for band `i`? Nothing else on + /// that row belongs to the notice. + pub fn covers(n: *const Notices, row: usize, col: u16) bool { + for (0..n.len) |i| if (n.row[i] == row) return col >= n.left[i]; + return false; + } + + /// Rows from the body's top down to the last band's. + pub fn span(n: *const Notices) u8 { + var rows: u8 = 0; + for (n.row[0..n.len]) |row| rows = @max(rows, row + 1); + return rows; + } + + pub fn slice(n: *const Notices) []const Kind { + return n.kinds[0..n.len]; + } + }; + + pub fn clearPointerSelection(pane: *Pane, slot: usize) void { + if (pane.pointer_selections[slot]) |selection| { + pane.gpa.free(selection.rows); + if (selection.raw_text) |text| pane.gpa.free(text); + } + pane.pointer_selections[slot] = null; + } + + pub fn rawPointerText(pane: *const Pane, gesture: Sel) ?[]const u8 { + if (gesture.state != .done or gesture.source_id == 0) return null; + for (pane.pointer_selections) |selection| { + if (selection) |saved| if (std.meta.eql(saved.gesture, gesture)) return saved.raw_text; + } + return null; + } + + pub fn pointerSelection(pane: *const Pane, gesture: Sel) ?[]PointerRow { + if (gesture.state != .done or gesture.source_id == 0) return null; + for (pane.pointer_selections) |selection| { + if (selection) |saved| if (std.meta.eql(saved.gesture, gesture)) return saved.rows; + } + return null; + } + + /// Add `text` to the end of the tag's own text, which starts out as the + /// default a pane of its kind shows. + pub fn appendTag(pane: *Pane, text: []const u8) !void { + const had = pane.tag.own orelse pardes.tagline.defaultTail(pane); + const grown = try std.mem.concat(pane.gpa, u8, &.{ had, text }); + if (pane.tag.own) |old| pane.gpa.free(old); + pane.tag.own = grown; + } + + /// Close an open prompt, answered or not. Its answer goes with it, and an + /// s/S preview keeps whatever it last previewed. + pub fn closePrompt(pane: *Pane) void { + pane.input.deinit(pane.gpa); + pane.prompt = .none; + pane.prompt_for = .body; + pane.nsel_snap = 0; + } + + /// What an open prompt shows on its notice band: the one answer every + /// painter of the band reads. + pub fn promptText(p: *const Pane) ?[]const u8 { + return switch (p.prompt) { + .none, .name => null, + .del_side => config.del_question, + .repl_choice => p.question[0..p.question_len], + else => p.input.own orelse "", + }; + } + + pub fn cwdSlice(p: *const Pane) []const u8 { + return switch (p.cwd) { + .none => "", + .owned => |dir| dir, + .inherited => |src| src.cwdSlice(), + }; + } + + pub fn clearCwd(pane: *Pane) void { + if (pane.cwd == .owned) pane.gpa.free(pane.cwd.owned); + pane.cwd = .none; + } + + pub fn setOwnedCwd(pane: *Pane, dir: []const u8) !void { + if (dir.len > limits.host_path_cap) return error.PathTooLong; + const copy = try pane.gpa.dupe(u8, dir); + pane.clearCwd(); + pane.cwd = .{ .owned = copy }; + } + + pub fn isTerminal(pane: *const Pane) bool { + return pane.file == null and pane.addon == null and pane.pdf == null; + } + + /// The one coloring choice keyed on what a pane IS, so the highlight + /// producer (refreshHighlights) and the render pass agree on the algorithm. + pub const ColorAlgo = enum { none, tty, source, diff, locations }; + pub fn colorAlgo(pane: *const Pane) ColorAlgo { + if (pane.isTerminal()) return .tty; + if (pane.file) |f| { + if (f.mini != null) return .source; + if (std.mem.endsWith(u8, f.path, ".diff") or std.mem.endsWith(u8, f.path, ".patch") or f.pager_diff) return .diff; + if (f.output != null) { + // A +Preview is a file's text: coloured as the file. + if (f.output.?.from == .preview) return .source; + const tr = Output.fileTraits(f.output); + if (tr.locations) return .locations; + if (!tr.saves) return .none; + } + return .source; + } + return .none; + } + + pub fn surfRow(pane: *const Pane, g: i32) i32 { + const o = pane.ovl orelse return g; + if (g <= o.row) return g; + const lines: i32 = @intCast(modal.lineCount(o.text)); + if (g >= o.row + o.rows) return g + lines - o.rows; + return @min(g, o.row + lines - 1); // inside the buffer: its own rows + } + + /// the inverse; every surface row inside the edit buffer maps to its anchor + pub fn gridRow(pane: *const Pane, s: i32) i32 { + const o = pane.ovl orelse return s; + if (s <= o.row) return s; + const lines: i32 = @intCast(modal.lineCount(o.text)); + if (s < o.row + lines) return o.row; + return s - lines + o.rows; + } + + /// current scroll offset: file top line, or the scrollback offset + pub fn scroll(pane: *Pane) i32 { + if (pane.file) |f| return @intCast(f.scroll); + return pane.surfRow(@as(i32, @intCast(Term.grid(pane.terminal).offset)) + pane.pan); + } + + pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32, pad: i32 = 0 } { + File.geometry(pane); + if (pane.wrap_n > 0 and vr >= 0 and vr < @as(i32, pane.wrap_n)) + return .{ .line = pane.wrap_line[@intCast(vr)], .at = pane.wrap_col[@intCast(vr)], .pad = pane.wrap_pad[@intCast(vr)] }; + // unwrapped: rows ARE lines, and the byte column a row starts at is the + // horizontal scroll (always 0 on a terminal, which never has one) + return .{ .line = pane.scroll() + vr, .at = pane.hscroll }; + } + + pub fn wrapRow(pane: *Pane, line: i32, col: i32) struct { row: i32, at: i32, pad: i32 = 0 } { + File.geometry(pane); + if (pane.wrap_n == 0) return .{ .row = line - pane.scroll(), .at = pane.hscroll }; + var i: u16 = 0; + while (i < pane.wrap_n) : (i += 1) { + if (pane.wrap_line[i] != line) continue; + // the LAST row of a line owns every column past its start, so a + // cursor parked on the trailing newline still has somewhere to draw + if (i + 1 < pane.wrap_n and pane.wrap_line[i + 1] == line and col >= pane.wrap_col[i + 1]) continue; + return .{ .row = @intCast(i), .at = pane.wrap_col[i], .pad = pane.wrap_pad[i] }; + } + return .{ .row = -1, .at = 0 }; + } + + pub fn scrollBy(pane: *Pane, delta: i32) void { + if (pane.file) |*f| { + const max: i64 = @intCast(File.nlines(pane.gpa, f) -| 1); + const n = std.math.clamp(@as(i64, @intCast(f.scroll)) + delta, 0, max); + const next: usize = @intCast(n); + if (next != f.scroll) { + f.scroll = next; + f.syntax_dirty = true; + } + } else if (pane.addon == null) { + // the vt scrolls in SHELL rows; convert through the edit buffer + if (tape.viewOnly("scroll a terminal")) return; + const state = pane.terminal orelse return; + const off: i32 = @intCast(Term.grid(state).offset); + Term.scroll(state, pane.gridRow(pane.surfRow(off) + delta) - off); + } + } + + /// Every line of the file's text fits in the body's rows; the empty + /// line after a final newline is no text. + pub fn textFits(pane: *Pane) bool { + if (pane.file) |*f| { + const lines = File.nlines(pane.gpa, f) - @intFromBool(std.mem.endsWith(u8, f.content, "\n")); + return lines <= pane.rows; + } + return false; + } + + pub fn ensureCursorVisible(pane: *Pane) void { + File.geometry(pane); + const off = pane.scroll(); + var in_context = false; + // The map is the view's as it is now (File.geometry): an ancestor is + // pinned only in the view it was found for. + if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == off) { + for (pane.wrap_line[0..pane.context_rows]) |row| { + if (row == pane.body.cur_row) { + in_context = true; + break; + } + } + } + // Scrolloff is measured in the ordinary body, excluding sticky rows. + var margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2)); + var last = off + @as(i32, pane.rows) - 1; + const visible_rows = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n; + if (pane.context_rows < visible_rows) { + const lines_shown = pane.wrap_line[visible_rows - 1] - pane.wrap_line[pane.context_rows]; + last = off + lines_shown; + margin = @min(margin, @divTrunc(@max(0, lines_shown), 2)); + } + if (!in_context) { + if (pane.follow_edges != 0 and (pane.body.cur_row < off or pane.body.cur_row > last)) pane.follow_crossed = true; + if (pane.body.cur_row < off + margin) { + if (pane.follow_edges & 1 == 0) pane.scrollBy(pane.body.cur_row - margin - off); + } else if (pane.body.cur_row > last - margin and pane.follow_edges & 2 == 0) { + var to = pane.body.cur_row + margin; + if (pane.file) |*f| { + // The margin only reveals text: a pane its whole text + // fits in never scrolls for it. A longer one keeps + // helix's clamp at the buffer's last line. + const lines: i32 = @intCast(File.nlines(pane.gpa, f)); + to = @min(to, if (off == 0 and pane.textFits()) @max(pane.body.cur_row, lines - 1 - @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) else lines - 1); + } + pane.scrollBy(@max(0, to - last)); + } + } + if (pane.file) |f| { + if (pane.body_wrapped) return; + const w: i32 = @max(1, @as(i32, pane.cols) - @as(i32, File.gutterWidth(pane))); + const hmargin: i32 = @min(config.scroll_off, @divTrunc(w - 1, 2)); + const line = modal.lineSlice(f.content, @intCast(@max(0, pane.body.cur_row))); + const raw_cur: usize = @intCast(@max(0, pane.body.cur_col)); + const raw_scroll: usize = @intCast(@max(0, pane.hscroll)); + // Measured from the view's left edge to the caret, never from the + // line's start: a 500 KB line was walked from byte 0 at every key + // (widths add, so the span alone is exact). + const apart = File.lineDisplayOffset(line, raw_scroll, raw_cur); + const back: ?i32 = if (apart < hmargin) hmargin else if (apart > w - 1 - hmargin) w - 1 - hmargin else null; + if (back) |cols| { + // The byte `cols` columns before the caret, looked for from a + // few bytes a column back (a grapheme is at most 4 a column). + const from = raw_cur -| @as(usize, @intCast(cols)) * 4; + const ahead = File.lineDisplayOffset(line, from, raw_cur) - cols; + pane.hscroll = @intCast(if (ahead <= 0) from else File.byteAtDisplayFrom(line, from, @intCast(ahead))); + } + } + } + + pub fn pinCursor(pane: *Pane) void { + if (pane.body.cur_pinned) return; + if (pane.file != null or pane.addon != null) { + pane.body.cur_row = pane.scroll(); + pane.body.cur_col = 0; + } else { + const grid = Term.grid(pane.terminal); + pane.body.cur_row = pane.surfRow(@as(i32, grid.cursor_y) + @as(i32, @intCast(grid.offset))); + pane.body.cur_col = grid.cursor_x; + } + pane.body.cur_pinned = true; + } + + /// Record and parse one live pty read, invalidate its motion surface, + /// and follow it only when the body (possibly parked under a tag edit) + /// is raw. + pub fn feedOutput(pane: *Pane, p: *Pardes, bytes: []const u8) void { + // There are no pty reads at all without an emulator to parse them into. + const state = pane.terminal orelse return; + if (tape.authorityOnly("a terminal's output")) return; + const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or + pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or + pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pane.pointerRowCount() > 0; + // A replica's emulator is what the authority's deltas make it; what + // pardes keeps over it moves as the authority's feed told it. + if (tape.screenReplica()) { + if (has_positions and pane.followRows(state, bytes)) if (paneIdOf(p, pane)) |id| p.setMessage(id, positions_lost); + return; + } + // Sticky bottom, as every other terminal does it: output drags the + // viewport down only when the viewport was already on the last row, + // so a reader scrolled back into the scrollback stays where they + // scrolled. + const grid = Term.grid(state); + const at_bottom = grid.offset + grid.len >= grid.total; + Term.cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); + if (!has_positions) { + _ = Term.feed(state, bytes, &.{}, &.{}, &.{}); + } else if (pane.followRows(state, bytes)) if (paneIdOf(p, pane)) |id| p.setMessage(id, positions_lost); + p.shell_rows.markStale(pane); + if (pane.body.mode == .tty and at_bottom) pane.followOutput(); + } + + /// Its terminal fed `bytes`, with every position kept over its rows + /// (the edit copy, the cursors and selections, their undo, the + /// pointer's rows) moved as the rows move (`Term.Told`). True when one + /// could not be kept (no memory for its pin). + fn followRows(pane: *Pane, state: *Term.State, bytes: []const u8) bool { + const on_replica = tape.screenReplica(); + const Group = struct { overlay: ?*Text.EditBuffer, cursor: *i32, selection: *Text.CharSel }; + var groups: [Text.history_max * 2 + 1]Group = undefined; + groups[0] = .{ + .overlay = if (pane.ovl) |*overlay| overlay else null, + .cursor = &pane.body.cur_row, + .selection = &pane.body.vsel, + }; + var ngroups: usize = 1; + for ([_][]Text.Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { + for (history) |*snapshot| { + groups[ngroups] = .{ + .overlay = if (snapshot.ovl) |*overlay| overlay else null, + .cursor = &snapshot.cur_row, + .selection = &snapshot.vsel, + }; + ngroups += 1; + } + } + // A position on a row of an edit copy's text stays on it (its line + // of the copy, `edit_row`); one below the copy is tracked on the + // shell row it stands for. + const Position = struct { target: *i32, overlay: ?*Text.EditBuffer, edit_row: ?i32 = null, grid: i32 = -1 }; + const position = struct { + fn of(target: *i32, overlay: ?*Text.EditBuffer) Position { + var grid = target.*; + if (overlay) |edit| { + const lines: i32 = @intCast(modal.lineCount(edit.text)); + if (grid >= edit.row and grid < edit.row +| lines) + return .{ .target = target, .overlay = edit, .edit_row = grid - edit.row }; + if (grid > edit.row) grid = grid -| lines +| edit.rows; + } + return .{ .target = target, .overlay = overlay, .grid = grid }; + } + }.of; + var spans: [groups.len]*Text.EditBuffer = undefined; + var nspans: usize = 0; + var positions: [groups.len * 2 + Text.max_selections * 2 + 4]Position = undefined; + var npositions: usize = 0; + for (groups[0..ngroups]) |group| { + if (group.overlay) |overlay| { + spans[nspans] = overlay; + nspans += 1; + } + positions[npositions] = position(group.cursor, group.overlay); + npositions += 1; + if (group.selection.active) { + positions[npositions] = position(&group.selection.row, group.overlay); + npositions += 1; + } + } + const overlay = groups[0].overlay; + // Where the live pane's own selections sit in `positions`: one whose + // row the program erased goes (below), as the edited copy does. + const vsel_at: ?usize = if (pane.body.vsel.active) 1 else null; + const sels_at = npositions; + var extra: [Text.max_selections * 2 + 2]*i32 = undefined; + var nextra: usize = 0; + for (pane.body.sels[0..pane.body.nsel]) |*selection| { + extra[nextra] = &selection.row; + extra[nextra + 1] = &selection.arow; + nextra += 2; + } + if (pane.body.last_edit) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + if (pane.look_at) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + for (extra[0..nextra]) |target| { + positions[npositions] = position(target, overlay); + npositions += 1; + } + var failed = false; + const pointer_positions = pane.gpa.alloc(Position, pane.pointerRowCount()) catch null; + defer if (pointer_positions) |held| pane.gpa.free(held); + if (pointer_positions) |held| { + var index: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + for (rows) |*row| { + held[index] = position(&row.row, if (row.raw_terminal) null else overlay); + index += 1; + } + }; + } else failed = true; + const pointers: []Position = pointer_positions orelse &.{}; + // The rows to track, in the order told: each copy's first and last + // row, then the positions, then the pointer's rows. On the stack, + // as the local path never allocated here but for the pointer's rows. + const n = 2 * nspans + npositions + pointers.len; + var track_buf: [512]i32 = undefined; + var rows_buf: [512]i32 = undefined; + var erased_buf: [512]bool = undefined; + // Out of memory for them, the read is parsed and nothing moves. + const track = if (n <= track_buf.len) track_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(state, bytes); + defer if (n > track_buf.len) pane.gpa.free(track); + const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(state, bytes); + defer if (n > rows_buf.len) pane.gpa.free(rows_after); + const erased_after = if (n <= erased_buf.len) erased_buf[0..n] else pane.gpa.alloc(bool, n) catch return feedLost(state, bytes); + defer if (n > erased_buf.len) pane.gpa.free(erased_after); + var k: usize = 0; + for (spans[0..nspans]) |span| for ([_]i32{ span.row, span.row +| (span.rows - 1) }) |row| { + track[k] = row; + k += 1; + }; + for ([_][]Position{ positions[0..npositions], pointers }) |batch| for (batch) |at| { + track[k] = at.grid; + k += 1; + }; + // A replica's emulator is fed by its authority's deltas: it is told + // what the authority's feed told. + const fed: Term.Told = if (on_replica) told: { + @memset(rows_after, 0); + @memset(erased_after, false); + break :told .{ .rows = rows_after, .erased = erased_after, .cleared = false, .alive = false, .failed = false }; + } else Term.feed(state, bytes, track, rows_after, erased_after); + const after = tape.value(.positions, keepTold, .{Term.Told{ .rows = fed.rows, .erased = fed.erased, .cleared = fed.cleared, .alive = fed.alive, .failed = failed or fed.failed }}); + if (after.rows.len != n or after.erased.len != n) return false; // a replica its authority's states apart (diverged) + failed = after.failed; + const at_position = 2 * nspans; + const at_pointer = at_position + npositions; + var moved = false; + var pointer_rows_lost = !after.alive or pointer_positions == null; + for (0..pointers.len) |i| if (after.erased[at_pointer + i]) { + pointer_rows_lost = true; + }; + // The program cleared the screen, or the rows the live copy stood on + // are gone (pruned, a reset): the copy goes with them, as what the + // program drew next. Kept, the emulator would move its rows to the + // top of what is left, over the program's new text. + var copy_lost = after.cleared or !after.alive; + for (spans[0..nspans], 0..) |span, i| { + if (span == overlay and after.erased[2 * i]) copy_lost = true; + const start = after.rows[2 * i]; + const rows = @max(1, after.rows[2 * i + 1] -| start +| 1); + moved = moved or start != span.row or rows != span.rows; + span.row = start; + span.rows = rows; + } + // The rule above for the copy holds for the selections: one whose + // row is gone (ED 3 erased its history row) goes too, rather than + // being clamped to the top. + const erased = after.erased[at_position..]; + const vsel_lost = if (vsel_at) |i| + erased[i] or (copy_lost and positions[i].edit_row != null) + else + false; + var sels_keep: [Text.max_selections]bool = undefined; + for (0..pane.body.nsel) |i| sels_keep[i] = !(erased[sels_at + 2 * i] or erased[sels_at + 2 * i + 1]); + for ([_][]Position{ positions[0..npositions], pointers }, [_]usize{ at_position, at_pointer }) |batch, first| for (batch, first..) |at, i| { + var row = after.rows[i]; + if (at.overlay) |edit| { + if (at.edit_row) |relative| { + row = edit.row +| relative; + } else if (row > edit.row) { + row = if (row < edit.row +| edit.rows) + edit.row + else + row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); + } + } + moved = moved or row != at.target.*; + at.target.* = row; + }; + if (pointer_rows_lost) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + if (vsel_lost) { + pane.body.vsel.active = false; + moved = true; + } + if (pane.body.nsel > 0) { + var kept: u16 = 0; + for (0..pane.body.nsel) |i| if (sels_keep[i]) { + pane.body.sels[kept] = pane.body.sels[i]; + kept += 1; + }; + if (kept != pane.body.nsel) { + moved = true; + if (kept == 0) pane.body.dropSels() else pane.body.nsel = kept; + } + } + if (copy_lost) if (pane.ovl) |copy| { + pane.gpa.free(copy.text); + pane.ovl = null; + moved = true; + }; + if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. + return failed; + } + + fn keepTold(t: Term.Told) Term.Told { + return t; + } + + fn feedLost(state: *Term.State, bytes: []const u8) bool { + if (!tape.screenReplica()) _ = Term.feed(state, bytes, &.{}, &.{}, &.{}); + return true; + } + + fn pointerRowCount(pane: *const Pane) usize { + var count: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + count += rows.len; + }; + return count; + } + + /// Its terminal's view snapped back onto live output. + pub fn followOutput(pane: *Pane) void { + if (tape.viewOnly("follow a terminal")) return; + const state = pane.terminal orelse return; + Term.follow(state); + } + + /// Its terminal's grid reflowed to `cols` by `rows`: on a screen-state + /// replica by its authority (the next delta says), on such an authority + /// once the step's unit is out (`resizeDeferred`). + pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { + // A screen-state client's speculation does what its replay does + // (its selections, never the grid): it waits for no round trip. + if (!tape.screenState() and tape.authorityOnly("resize a terminal")) return; + const state = pane.terminal orelse return; + if (cols != pane.cols) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + if (tape.screenReplica()) return; + // A client typing at another size than the last typist's read + // history rows its replay held as holes, and the rows came + // renumbered (2026-10-30): the authority's waits for the unit. + Term.resize(state, cols, rows, tape.screenAuthority()); + } + + /// The rows its terminal's top is passed over by in a view whose rect + /// `r` is shorter than it, one that does not size it (Pardes.sizes): as + /// many as keep its cursor's row in sight, as tmux pans a bigger window + /// in a smaller client. 0 in the view that sizes it, and in one tall + /// enough. + pub fn panFor(pane: *const Pane, p: *const Pardes, r: pardes.Rect) u16 { + if (pane.sized_by == p.live or pane.collapsed or !pane.isTerminal()) return 0; + const shown = r.h -| pane.tag_rows; + if (shown == 0 or shown >= pane.rows) return 0; + const state = pane.terminal orelse return 0; + const grid = Term.grid(state); + // The cursor's row in the viewport; past its end (scrolled back), + // its last row. + const row = grid.total - grid.len + grid.cursor_y; + const at: usize = if (row < grid.offset) 0 else @min(row - grid.offset, pane.rows - 1); + return @intCast(@min(pane.rows - shown, (at + 1) -| shown)); + } + + /// Whether a new terminal's greeting may be typed now: only at the + /// shell's first prompt (pardes's own marks: no command started; a + /// prompt drawn again for a resize is the same first prompt), with + /// nothing typed at it and no program on the alternate screen. Any + /// later moment is `.never`, for good: something has run or been typed + /// first, and an `ls` then would go into it. A shell pardes cannot mark + /// has no first prompt to find, and is never greeted. + pub fn greeting(pane: *const Pane) enum { wait, now, never } { + if (pane.fs.unmarked) return .never; + // Text typed into the edit buffer that stands in for the prompt row. + if (pane.ovl) |o| if (o.text.len > 0) return .never; + const state = pane.terminal orelse return .wait; + const at = Term.prompt(state); + // (Not `declined`: bash's first prompt comes after a D of its own.) + if (at.started > 0) return .never; + // At a prompt's input (the emulator's semantic marks, pardes's or + // the shell's own), before any command pardes's marks saw run. + if (!at.input_ready) return .wait; + return if (at.input_empty) .now else .never; + } + + /// Remembers a line pardes types into this terminal as the command it + /// started, for Kill: it runs from the shell's next C mark to its D. + /// ponytail: of several lines queued for a shell not up yet, only the + /// last is remembered, as the first of them. + pub fn noteCommand(pane: *Pane, line: []const u8) void { + const state = pane.terminal orelse return; + const said = std.mem.trim(u8, line, " \t"); + const word = said[0 .. std.mem.indexOfAny(u8, said, " \t") orelse said.len]; + var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = Term.prompt(state).started +% 1 }; + sent.len = @intCast(@min(word.len, sent.word.len)); + @memcpy(sent.word[0..sent.len], word[0..sent.len]); + pane.sent_command = sent; + } + + /// A line for a shell not ready for it (`pending_command`), queued + /// after the ones before it; false when the shell is ready now. + pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { + if (pane.pending_command.wait == .none) return false; + const old_len = pane.pending_command.bytes.len; + const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); + const bytes = if (old_len == 0) + try pane.gpa.alloc(u8, new_len) + else + try pane.gpa.realloc(pane.pending_command.bytes, new_len); + @memcpy(bytes[old_len..][0..command.len], command); + bytes[new_len - 1] = '\r'; + pane.pending_command.bytes = bytes; + pane.greet = false; + return true; + } + + /// The lines queued for its shell, written now that it is `ready`. + pub fn releasePendingCommand(pane: *Pane, p: *Pardes, id: usize, ready: bool) void { + if (!ready) return; + const bytes = pane.pending_command.bytes; + pane.pending_command = .{}; + if (bytes.len > 0) { + p.emitWrite(id, bytes); + pane.gpa.free(bytes); + } + } + + /// `run ` or `exit ` in the log. + /// The whole line, one record as `msg` carries its text: its control + /// characters, a newline too, become spaces (events.pushLog). A new pane is + /// announced first, so `new` comes before the `run` in it. + pub fn noteRun(pane: *Pane, p: *Pardes, what: []const u8, said: []const u8) void { + pardes.ctlfs.events.announce(p); + var buf: pardes.Kind.Buf(exec.command_max + 16) = .{}; + pardes.ctlfs.events.notePath(p, what, buf.print("{d} {s}", .{ pane.serial, std.mem.trim(u8, said, " \t\r\n") })); + } + + /// A command pane's child is gone: the pane stays, showing what it said + /// and how it ended, and is the next command's for its directory. + pub fn commandDone(pane: *Pane, p: *Pardes, id: usize, status: ?u8) void { + pane.command_done = true; + // A REPL it was is gone with its command; the pane's next is not one. + pane.repl = null; + pane.command_status = status; + pane.body.mode = .normal; + // Look's `git show`: its output went to a +Pager, the +Diff now; only a + // failure is worth the pane. + if (pane.command_pages) { + pane.command_pages = false; + if (status == 0) return p.removePane(id, null) catch |err| p.reportError(id, "close", err); + } + var buf: [16]u8 = undefined; + const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch unreachable else "?"; // an exit status fits 16 + var said: pardes.Kind.Buf(32) = .{}; + const lead = if (Term.grid(pane.terminal).cursor_x != 0) "\r\n" else ""; + pane.feedOutput(p, said.print("{s}exit {s}\r\n", .{ lead, code })); + pane.noteRun(p, "exit", code); + p.needs_frame = true; + } +}; + +pub const Text = @import("Text.zig"); + +pub const File = @import("File.zig"); + +pub const Output = @import("Output.zig"); + +pub const Places = @import("Places.zig"); +pub const Tables = @import("Tables.zig"); + +pub const Query = @import("Query.zig"); + +pub const Dir = @import("Dir.zig"); + +pub const mini = @import("mini.zig"); + +pub const Term = @import("Term.zig"); + +/// What a pane says when a position kept over its terminal's rows could +/// not follow the output (no memory for its pin), so it was reset. +pub const positions_lost = "terminal edit position reset: out of memory"; + +/// The sizes steps gave terminals (`Pane.resizeGrid`), made: between +/// units, on an authority with screen-state replicas (replica.Peers.unit). +pub fn resizeDeferred(p: *Pardes) void { + for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| if (Term.resizeDeferred(state)) + p.shell_rows.markStale(pane); +} + +/// A pane with nothing in it yet, `cols` by `rows`: what a file, a +/// directory, a kind's pane or a terminal is made from. +pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try gpa.create(Pane); + pane.* = .{ + .gpa = gpa, + .cols = cols, + .rows = rows, + }; + return pane; +} + +/// A terminal pane: a pane and its emulator. Slot ownership, serial +/// assignment and spawn effects remain core lifecycle invariants. +pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + if (tape.authorityOnly("open a terminal")) return error.OutOfMemory; + const pane = try createDoc(gpa, cols, rows); + errdefer gpa.destroy(pane); + pane.terminal = try Term.open(emulatorGpa(gpa), cols, rows); + pane.tty_filter = true; + return pane; +} + +/// A screen-state replica's emulators' allocator (`Term.State.gpa`): the C +/// heap, outside its rollback epoch: written by deltas while a copy is +/// held, no part of it is ever a copy's to save or put back. +pub const emulator_gpa = std.heap.c_allocator; + +/// What a terminal's emulator is made with, by `createTerminal` or a pane's +/// load (dump.loadPane, a closed terminal brought back): `gpa`, but on a +/// screen-state replica `emulator_gpa`. +pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator { + return if (tape.screenReplica()) emulator_gpa else gpa; +} + +// ---- the session's pane slots: making, finding, closing and freeing panes, and their prompts ---- + +const tutor_text = @embedFile("tutor.txt"); + +pub fn detachCwds(p: *Pardes, parents: []const *Pane) !void { + var copies: [MAX_PANES]?[]u8 = @splat(null); + errdefer for (copies) |copy| if (copy) |bytes| p.gpa.free(bytes); + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const source = switch (pane.cwd) { + .inherited => |parent| parent, + else => continue, + }; + for (parents) |parent| if (source == parent) { + copies[id] = try p.gpa.dupe(u8, paneDir(source)); + break; + }; + } + for (copies, 0..) |copy, id| if (copy) |bytes| { + p.panes[id].?.cwd = .{ .owned = bytes }; + }; +} + +// The slot closes now; allocation teardown waits one frame. Caller clears panes[id]. +pub fn deinitPane(p: *Pardes, pane: *Pane) !void { + try detachCwds(p, &.{pane}); + retirePane(p, pane); +} + +pub fn retirePane(p: *Pardes, pane: *Pane) void { + // Closed, a file is remembered with its dot: Recent and a jump back + // to it reopen it there. + p.noteClosed(pane); + panes.Output.dropUnsaved(p, pane); + // A query pane's places, in whatever panes it fed, go with it. + if (pane.query != null) panes.Query.release(p, pane); + if (pane.file) |*file| panes.File.leaveTwins(p, file); + const watched = (if (pane.file) |f| f.output == null else false) or (if (pane.addon) |k| k.path.len > 0 else false); + for (p.panes, 0..) |slot, id| if (slot == pane) { + if (watched) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); + if (pane.isTerminal()) p.emit(.{ .close_pty = .{ .pane = @intCast(id) } }); + // Its pty's end and its emulator are the authority's: a replica's + // speculation that closes a terminal waits for it. + if (pane.terminal != null) tape.poison("close a terminal"); + ctlfs.events.noteRetire(p, pane); + // ...and so do bytes still queued for the pty it no longer has. + p.dropPendingWrite(id); + }; + if (look.lookHoverPane(p)) |h| if (h < p.panes.len and p.panes[h] == pane) look.cancelLookHover(p); + p.retired_panes.retire(pane); +} + +// Retired panes keep their payloads until the following frame or core teardown. +pub fn teardownPane(p: *Pardes, pane: *Pane) void { + if (look.lookHoverPane(p)) |hovered| { + if (hovered < p.panes.len and p.panes[hovered] == pane) + look.cancelLookHover(p); + } + p.shell_rows.dropPane(pane); + for (0..pane.pointer_selections.len) |slot| pane.clearPointerSelection(slot); + if (pane.pending_command.bytes.len > 0) pane.gpa.free(pane.pending_command.bytes); + pane.pending_command = .{}; + if (pane.command) |line| p.gpa.free(line); + if (pane.shell) |bin| p.gpa.free(bin); + @import("Kind.zig").close(p, pane); + if (pane.pdf) |old| { + p.image_gpa.free(old.path); + p.image_gpa.destroy(old); + } + if (pane.file) |*file| panes.File.deinit(p, pane, file); + if (pane.ovl) |o| p.gpa.free(o.text); + views.tornDown(p, pane); + pane.body.deinit(p.gpa); + pane.tag.deinit(p.gpa); + pane.input.deinit(p.gpa); + pane.jump.deinit(p.gpa); + pane.places.deinit(p.gpa); + if (pane.query) |q| { + q.deinit(p.gpa); + p.gpa.destroy(q); + pane.query = null; + } + // A pane with none (a file's, a picker's, a preview's) closes in a + // speculation as anywhere. + if (pane.terminal) |state| if (!tape.authorityOnly("close a terminal")) { + Term.close(state, p.gpa); + pane.terminal = null; + }; + pane.clearCwd(); + pane.fs.deinit(p.gpa); + p.gpa.destroy(pane); +} + +pub fn reapPanes(p: *Pardes) void { + var reaped = false; + for (&p.retired_panes.previous) |*slot| if (slot.*) |pane| { + teardownPane(p, pane); + slot.* = null; + reaped = true; + }; + if (reaped) memory.trim(); + p.retired_panes.previous = p.retired_panes.current; + p.retired_panes.current = @splat(null); +} + +pub fn installPane(p: *Pardes, id: usize, pane: *Pane) void { + std.debug.assert(p.panes[id] == null); + p.next_serial += 1; + pane.serial = p.next_serial; + p.view().rects[id] = .{}; + p.panes[id] = pane; + views.installed(p, pane); + // /log hears of it once the update that made it ends, when it has + // its file, name and place (`ctlfs.events.announce`). + pane.fs.unannounced = true; +} + +pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { + std.debug.assert(p.panes[id] == null); + if (cwd.len > limits.host_path_cap) return error.PathTooLong; + const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); + // Named by the directory it is started in from the first, so the + // shell saying it is there is no rename (`new N /` then `rename`); + // out of memory for it, the shell names it when it says. + if (cwd.len > 0) pane.setOwnedCwd(cwd) catch {}; + std.debug.assert(pane.pending_command.bytes.len == 0); + pane.pending_command.wait = .spawn; + p.installPane(id, pane); + p.emitSpawn(id, pane.serial, cwd); + return pane; +} + +/// A child for pane `id` in `cwd`: a directory up to PATH_MAX, the ones +/// past the effect's inline buffer kept here for perform to give. +pub fn emitSpawn(p: *Pardes, id: usize, serial: u32, cwd: []const u8) void { + // A new shell has not said anything yet (setCwd's guard), whatever + // the one it replaces said. + if (p.panes[id]) |pane| pane.shell_spoke = false; + if (p.spawn_dirs[id]) |old| p.gpa.free(old); + p.spawn_dirs[id] = null; + if (cwd.len > effect_path_cap) p.spawn_dirs[id] = p.gpa.dupe(u8, cwd) catch null; + p.emit(.{ .spawn = .{ .pane = @intCast(id), .serial = serial, .cwd = .from(if (cwd.len > effect_path_cap) "" else cwd) } }); +} + +/// A command pane: a terminal whose child is `$SHELL -c line` rather +/// than an interactive shell, left showing its output and `exit N` when +/// it is done (exec.zig runCommand). +pub fn newCommand(p: *Pardes, id: usize, cwd: []const u8, line: []const u8) !*Pane { + std.debug.assert(p.panes[id] == null); + if (cwd.len > limits.host_path_cap) return error.PathTooLong; + const owned = try p.gpa.dupe(u8, line); + errdefer p.gpa.free(owned); + const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); + pane.command = owned; + pane.command_pty = true; + pane.body.mode = .tty; + // Its directory is the one it was run for, and says which of the + // directory's commands reuse it; the child's own cd does not move it. + pane.setOwnedCwd(cwd) catch {}; + p.installPane(id, pane); + p.emitSpawn(id, pane.serial, cwd); + return pane; +} + +pub fn newDocPane(p: *Pardes, id: usize) !*Pane { + std.debug.assert(p.panes[id] == null); + const pane = try panes.createDoc(p.gpa, p.view().screen_w, p.view().screen_h); + p.installPane(id, pane); + return pane; +} + +pub fn newScratch(p: *Pardes, from_id: usize, free: usize, kind: layout.NewPane) !*Pane { + // None asking (an empty window): the session's, as pane/new's is. + const src_or = p.panes[from_id]; + const content = try p.gpa.dupe(u8, ""); + errdefer p.gpa.free(content); + // A terminal that has not said where it is yet (the boot layout's) + // has no directory: the scratch is the session's, /+New. So is + // 9P's pane/new, and a New from a column's or the workspace's tag: + // no pane asked for it, whichever last had the keyboard (acme's new + // window has acme's directory). + const src = if (kind != .fs and !p.exec_header) src_or else null; + const dir = if (src) |s| paneDir(s) else ""; + const np = try panes.Output.open(p, free, if (dir.len == 0) p.sessionDir() else dir, .{ .cmd = .New }, "", content); + if (src) |s| np.cwd = .{ .inherited = s }; + np.body.cur_pinned = true; + return np; +} + +/// New: an empty scratch in `from_id`'s directory, placed as layout.placeNew +/// places it. +pub fn newScratchBelow(p: *Pardes, from_id: usize) void { + newScratchFor(p, from_id, .scratch); +} + +/// A scratch for New (`.scratch`) or 9P's pane/new (`.fs`). +pub fn newScratchFor(p: *Pardes, from_id: usize, kind: layout.NewPane) void { + const free = p.freeSlot() orelse return p.reportError(from_id, "New", error.NoPaneSlots); + _ = newScratch(p, from_id, free, kind) catch |err| return p.reportError(from_id, "New", err); + layout.placeNew(p, from_id, from_id, free, kind); +} + +pub fn freeSlot(p: *Pardes) ?usize { + return for (p.panes, 0..) |slot, i| { + if (slot == null and !p.reserved_slots[i]) break i; + } else null; +} + +/// The slot holding the pane with this serial, if it is still open. +pub fn paneBySerial(p: *Pardes, serial: u32) ?usize { + return for (p.panes, 0..) |slot, i| { + if (slot) |pane| if (pane.serial == serial) break i; + } else null; +} + +/// The pane a session word runs with in an empty window. +pub fn standIn(p: *Pardes) ?*Pane { + if (p.stand_in == null) p.stand_in = panes.createDoc(p.gpa, p.view().screen_w, p.view().screen_h) catch null; + return p.stand_in; +} + +pub fn paneIdOf(p: *const Pardes, pane: *const Pane) ?usize { + return std.mem.findScalar(?*const Pane, &p.panes, pane); +} + +pub fn openTutorView(p: *Pardes, id: usize) !*Pane { + const content = try p.gpa.dupe(u8, tutor_text); + errdefer p.gpa.free(content); + // A generated pane, named as every one is: `+` in the session's + // directory, never a bare path Save could write at the root. + const path = try std.Io.Dir.path.join(p.gpa, &.{ p.sessionDir(), "+Tutor" }); + errdefer p.gpa.free(path); + const history = try panes.File.History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(id); + pane.file = .{ .path = path, .content = content, .history = history }; + pane.body.cur_pinned = true; + return pane; +} + +pub fn setTestFile(p: *Pardes, content: []const u8) !*Pane { + const v = p.view(); + const copy = try p.gpa.dupe(u8, content); + errdefer p.gpa.free(copy); + const path = try p.gpa.dupe(u8, "/test.txt"); + errdefer p.gpa.free(path); + const history = try panes.File.History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try panes.createDoc(p.gpa, v.screen_w, v.screen_h); + errdefer p.gpa.destroy(pane); + try deinitPane(p, p.panes[0].?); + p.panes[0] = null; + pane.file = .{ .path = path, .content = copy, .history = history }; + p.installPane(0, pane); + pane.body.cur_pinned = true; + v.active = 0; + p.sync(); + return pane; +} + +pub fn paneDir(pane: *const Pane) []const u8 { + switch (pane.cwd) { + .inherited => |src| return paneDir(src), + .owned => |cwd| return cwd, + .none => {}, + } + if (pane.file) |f| return panes.Dir.ofName(f.path); + if (pane.addon) |k| if (k.path.len > 0) return std.Io.Dir.path.dirname(k.path) orelse "/"; + return pane.cwdSlice(); +} + +/// Close a pane; its rows go to `to`, or where layout.absorbVWeight +/// sends them when that is null. Focus on it follows its rows to the +/// pane that grew into them. A column outlives its panes, as acme's +/// does (cols.c:186): closing its last one leaves it empty, the keyboard +/// on its tag; only Delcol takes a column away. The session's last pane +/// closing ends the session. Every route that closes a pane comes +/// through here or removeColumn, so none picks focus for itself, and +/// none by recency. +pub fn removePane(p: *Pardes, id: usize, to: ?usize) error{OutOfMemory}!void { + const v = p.view(); + const pane = p.panes[id] orelse return; + // What is attached to it closes with it, first, each giving its rows + // back to it: then its rows, theirs among them, go where a pane's go. + for (0..p.panes.len) |k| if (p.panes[k]) |other| if (k != id and other.attached_to == pane.serial) { + if (layout.ownerOf(p, k) != id) continue; + try p.removePane(k, id); + layout.compute(p); + }; + // An attachment's rows go back to its owner and nobody else. + const owner = layout.ownerOf(p, id); + const place = layout.findPane(p, id); + const emptied = if (place) |f| (if (v.cols[f.col].n == 1) f.col else null) else null; + // What it was and where, for Panes to bring back (Store.zig). + const kept = p.store.keep(p, id); + errdefer if (kept) |k| k.free(p.recentGpa()); + // Before anything is torn down, so a failure here changes nothing. + try deinitPane(p, pane); + const gainer = layout.absorbVWeight(p, id, owner orelse to); + const beside = if (emptied) |c| layout.besideColumn(p, c, v.rects[id]) else null; + layout.removePane(p, id); + p.panes[id] = null; + views.gone(p, id); + if (kept) |k| p.store.close(p, k, gainer); + if (v.active != id) return; + // No pane left: the session is over. + v.active = gainer orelse beside orelse anyPane(p) orelse { + p.endSession(); + return p.emit(.quit); + }; + if (emptied) |c| if (v.header == null) tagline.enterHeader(p, c); +} + +/// The pane Last should fall back to when the jumplist has nothing: the +/// one below in this column, wrapping to the top, and any other live pane +/// failing that. A pane that opened beside this one and was never focused +/// -- the text pane the bare tty layout puts under the shell -- is not on +/// the jumplist, and alternating with it is exactly what Last is for. +pub fn neighbourPane(p: *Pardes, from: usize) ?usize { + if (layout.findPane(p, from)) |at| { + const n = p.view().cols[at.col].n; + if (n > 1) return p.view().cols[at.col].panes[(at.idx + 1) % n]; + } + for (p.panes, 0..) |slot, id| { + if (slot != null and id != from) return id; + } + return null; +} + +/// Any live pane: the last resort when nothing took the closed one's place. +pub fn anyPane(p: *const Pardes) ?usize { + for (p.panes, 0..) |slot, k| if (slot != null) return k; + return null; +} + +/// Open a prompt on `pane`'s notice band answering for `t`: the body, +/// the pane's tag, or the header that has the keyboard. +pub fn startPrompt(p: *Pardes, pane: *Pane, t: *Text, request: union(enum) { + search: []const u8, + pipe: modal.Normal.PipeBehavior, + save, +}) void { + // Nobody is at the keyboard to answer a command a script wrote to a + // ctl file: the write fails instead (core/ninep/ctl.zig). + if (p.fs.no_prompt) { + p.fs.refused = true; + // A failure like any other: the builtin's announcement goes. + p.fs.failures +%= 1; + return; + } + // Asked for over 9P (Save from an exec on a terminal): a question + // the log says, `ask save path`, answered on the pane's + // ctl with `answer ` or `answer -`; asked again, the one + // already open stands, not a second on top of it. + if (request == .save and p.fs.serving) { + if (pane.prompt == .save) return; + var rec: [32]u8 = undefined; + ctlfs.events.notePath(p, "ask", std.fmt.bufPrint(&rec, "{d} save path", .{pane.serial}) catch unreachable); // a u32 and 10 bytes fit 32 + } + const marker = switch (request) { + .search => |marker| marker, + .save => config.save_marker, + .pipe => |how| pipe: { + // A body is piped only when it is a file that saves; a tag's + // or a header's text is its own. + if (t.what == .body) { + const file = pane.file orelse return; + if (!panes.Output.fileTraits(file.output).saves) return; + } + break :pipe Pipe.pipeMarker(how); + }, + }; + // Save asks for a path, so its answer starts out as the pane's own + // directory for the name to be typed onto. + const dir = if (request == .save) paneDir(pane) else ""; + const slash: []const u8 = if (request == .save and (dir.len == 0 or dir[dir.len - 1] != '/')) "/" else ""; + const answer = std.mem.concat(p.gpa, u8, &.{ marker, dir, slash }) catch |err| return p.reportError(p.view().active, "prompt", err); + // The keyboard comes back to the text answered for; a prompt for + // the body takes it out of a tag or header. + switch (t.what) { + .body => { + pane.focus = .body; + if (p.panes[p.view().active] == pane) tagline.exitHeader(p); + }, + .tag => pane.focus = .tag, + .column, .workspace, .input => {}, + } + // Not closePrompt: an s/S snapshot was taken for this very prompt. + if (pane.input.own) |old| p.gpa.free(old); + pane.prompt = switch (request) { + .search => .search, + .pipe => |how| .{ .pipe = how }, + .save => .save, + }; + pane.prompt_for = t.what; + pane.input = .{ .what = .input, .own = answer, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(answer.len) }; + // Whatever mode the text was in, it is in normal mode once the + // prompt is answered or dropped. + t.mode = .normal; + t.normal.clear(); +} + +/// The text `pane`'s open prompt answers for, if it is still there. +pub fn promptTarget(p: *Pardes, pane: *Pane) ?*Text { + return switch (pane.prompt_for) { + .body => &pane.body, + .tag => &pane.tag, + .column, .workspace => if (tagline.focusedHeader(p)) |h| (if (h.what == pane.prompt_for) h else null) else null, + .input => null, + }; +} + +test { + _ = Pane; + _ = Text; + _ = File; + _ = Output; + _ = Dir; + _ = mini; + _ = @import("Kind.zig"); +} + +test "owned cwd preserves long paths aliases and failed updates" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); + defer p.deinit(); + const pane = p.panes[0].?; + var path: [3072]u8 = @splat('d'); + path[0] = '/'; + for (1..12) |i| path[i * 256] = '/'; + p.setCwd(0, &path); + try std.testing.expectEqualStrings(&path, pane.cwdSlice()); + try std.testing.expect(pane.cwdSlice().ptr != &path); + const original = pane.cwdSlice(); + try pane.setOwnedCwd(original); + try std.testing.expectEqualStrings(&path, pane.cwdSlice()); + // A terminal's directory may be as long as a path is (PATH_MAX): one + // past the effect's buffer goes out of line (spawn_dirs); only one past + // the host's path limit is too long. + const free = p.freeSlot().?; + _ = try p.newShell(free, path[0..]); + try std.testing.expectEqualStrings(&path, p.spawn_dirs[free].?); + try p.removePane(free, null); + while (p.nextEffect()) |_| {} + var too_long: [limits.host_path_cap + 1]u8 = @splat('d'); + too_long[0] = '/'; + try std.testing.expectError(error.PathTooLong, p.newShell(free, &too_long)); + try std.testing.expect(p.panes[free] == null); + const effects = p.effects_len; + exec.saveTo(p, 0, "file.txt"); + try std.testing.expectEqual(effects, p.effects_len); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "path too long") != null); + + const current = pane.cwdSlice(); + allocator.fail_index = allocator.alloc_index; + p.setCwd(0, "/replacement"); + try std.testing.expectEqual(current.ptr, pane.cwdSlice().ptr); + try std.testing.expectEqualStrings(&path, pane.cwdSlice()); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "out of memory") != null); + allocator.fail_index = std.math.maxInt(usize); + p.setCwd(0, "/replacement"); + try std.testing.expectEqualStrings("/replacement", pane.cwdSlice()); + const allocations = allocator.allocations; + p.setCwd(0, "/replacement"); + try std.testing.expectEqual(allocations, allocator.allocations); + pane.clearCwd(); + try std.testing.expect(pane.cwd == .none); + try std.testing.expectEqualStrings("", pane.cwdSlice()); +} + +test "owned cwd close copies are transactional across inherited chains" { + for (0..2) |failed_copy| { + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); + defer p.deinit(); + const parent = try p.setTestFile("body\n"); + p.gpa.free(parent.file.?.path); + parent.file.?.path = try p.gpa.dupe(u8, "/work/project/source.zig"); + p.newScratchBelow(0); + const first_id = p.view().active; + const first = p.panes[first_id].?; + p.newScratchBelow(0); + const second = p.panes[p.view().active].?; + p.newScratchBelow(first_id); + const grandchild = p.panes[p.view().active].?; + p.sync(); + while (p.nextEffect()) |_| {} + p.parkPendingWrite(0, "queued"); + const pending = p.pending_write[0].?.bytes; + const columns = p.view().cols; + const active = p.view().active; + const live_bytes = allocator.allocated_bytes - allocator.freed_bytes; + allocator.fail_index = allocator.alloc_index + failed_copy; + try std.testing.expectError(error.OutOfMemory, p.removePane(0, null)); + try std.testing.expectEqual(parent, p.panes[0].?); + try std.testing.expectEqual(parent, first.cwd.inherited); + try std.testing.expectEqual(parent, second.cwd.inherited); + try std.testing.expectEqual(first, grandchild.cwd.inherited); + try std.testing.expectEqualDeep(columns, p.view().cols); + try std.testing.expectEqual(active, p.view().active); + try std.testing.expectEqual(@as(usize, 0), p.effects_len); + try std.testing.expectEqual(pending.ptr, p.pending_write[0].?.bytes.ptr); + try std.testing.expectEqual(live_bytes, allocator.allocated_bytes - allocator.freed_bytes); + + allocator.fail_index = std.math.maxInt(usize); + try p.removePane(0, null); + try std.testing.expect(p.panes[0] == null); + try std.testing.expect(first.cwd == .owned and second.cwd == .owned); + try std.testing.expectEqual(first, grandchild.cwd.inherited); + try std.testing.expect(first.cwdSlice().ptr != second.cwdSlice().ptr); + try p.removePane(first_id, null); + try std.testing.expect(grandchild.cwd == .owned); + p.sync(); + p.sync(); + try std.testing.expectEqualStrings("/work/project", Pardes.paneDir(second)); + try std.testing.expectEqualStrings("/work/project", Pardes.paneDir(grandchild)); + } +} + +test "owned cwd column close allocates every copy before removing any pane" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(allocator.allocator(), .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + p.setCwd(0, "/first"); + p.setCwd(1, "/second"); + const first_child = try p.newDocPane(3); + const second_child = try p.newDocPane(4); + first_child.cwd = .{ .inherited = p.panes[0].? }; + second_child.cwd = .{ .inherited = p.panes[1].? }; + while (p.nextEffect()) |_| {} + const before = p.panes; + const columns = p.view().cols; + allocator.fail_index = allocator.alloc_index + 1; + try std.testing.expectError(error.OutOfMemory, layout.removeColumn(p, 0)); + for (before, p.panes) |old, current| try std.testing.expectEqual(old, current); + try std.testing.expectEqualDeep(columns, p.view().cols); + try std.testing.expectEqual(@as(usize, 0), p.effects_len); + try std.testing.expect(first_child.cwd == .inherited and second_child.cwd == .inherited); + allocator.fail_index = std.math.maxInt(usize); + try layout.removeColumn(p, 0); + try std.testing.expect(p.panes[0] == null and p.panes[1] == null); + p.sync(); + p.sync(); + try std.testing.expectEqualStrings("/first", first_child.cwdSlice()); + try std.testing.expectEqualStrings("/second", second_child.cwdSlice()); +} + +test "owned cwd EOF failure retains the pane and Del retries its close" { + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); + defer p.deinit(); + p.setCwd(0, "/exited"); + const parent = p.panes[0].?; + p.newScratchBelow(0); + const child = p.panes[p.view().active].?; + p.sync(); + while (p.nextEffect()) |_| {} + allocator.fail_index = allocator.alloc_index; + p.update(.{ .eof = .{ .pane = 0 } }); + try std.testing.expectEqual(parent, p.panes[0].?); + try std.testing.expectEqual(parent, child.cwd.inherited); + try std.testing.expectEqual(Text.Mode.normal, parent.body.mode); + try std.testing.expect(std.mem.indexOf(u8, parent.msg[0..parent.msg_len], "Del retries close") != null); + try std.testing.expectEqual(@as(usize, 0), p.effects_len); + allocator.fail_index = std.math.maxInt(usize); + try std.testing.expect(p.executeBuiltinLine(0, "Del")); + try std.testing.expect(p.panes[0] == null); + p.sync(); + p.sync(); + try std.testing.expectEqualStrings("/exited", child.cwdSlice()); +} + +test "owned cwd restore either copies the directory or preserves the old core" { + // No terminal: the emulator's (1.4) snapshot decode leaks when an allocation + // inside it fails, and this fails every allocation of a Restore in turn + // (what pardes's own load made is freed, core/walk.zig rollback). + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true, .file = "/nonexistent/pardes-owned-cwd" }); + defer p.deinit(); + p.newScratchBelow(0); + const id = p.view().active; + try p.panes[id].?.setOwnedCwd("/retained/terminal/directory"); + try dump.dumpState(p); + const original = p.panes[id].?; + var completed = false; + for (0..256) |failure| { + allocator.has_induced_failure = false; + allocator.fail_index = allocator.alloc_index + failure; + const replacement = dump.restore(p, p.dump_out.?, "test") catch { + try std.testing.expect(allocator.has_induced_failure); + try std.testing.expectEqual(original, p.panes[id].?); + try std.testing.expectEqualStrings("/retained/terminal/directory", original.cwdSlice()); + continue; + }; + defer replacement.deinit(); + try std.testing.expectEqualStrings("/retained/terminal/directory", replacement.panes[id].?.cwdSlice()); + try std.testing.expectEqual(original, p.panes[id].?); + if (!allocator.has_induced_failure) { + completed = true; + break; + } + } + allocator.fail_index = std.math.maxInt(usize); + try std.testing.expect(completed); +} + +test "owned cwd Save promotion releases the former directory" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + p.newScratchBelow(0); + const id = p.view().active; + const pane = p.panes[id].?; + try pane.setOwnedCwd("/old/directory"); + exec.saveTo(p, id, "saved.txt"); + // Named once the write is done (a failed one changes nothing). + try std.testing.expect(pane.file.?.output != null); + while (p.nextEffect()) |effect| p.perform(effect); + try std.testing.expect(pane.cwd == .none); + try std.testing.expect(pane.file.?.output == null); + try std.testing.expectEqualStrings("/old/directory/saved.txt", pane.file.?.path); + try std.testing.expectEqualStrings("/old/directory", Pardes.paneDir(pane)); +} + +test "the Tutor pane is named +Tutor in the session's directory, never a bare path at the root" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const session = "/project/src"; + @memcpy(p.session_dir[0..session.len], session); + p.session_dir_len = session.len; + const tutor = try openTutorView(p, 1); + try std.testing.expectEqualStrings("/project/src/+Tutor", tutor.file.?.path); + // Its bare Save writes no file named +Tutor: it asks for a path. + while (p.nextEffect()) |_| {} + try std.testing.expect(p.executeBuiltinLine(1, "Save")); + try std.testing.expect(tutor.prompt == .save); + while (p.nextEffect()) |e| try std.testing.expect(e != .save_file); +} + +test "New opens an empty scratch below the caller, inheriting its directory" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells + const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + const source: usize = 2; // the right column; active starts in the left + p.setCwd(source, "/tmp/pardes-scratch-dir"); + const source_col = layout.findPane(p, source).?.col; + + try std.testing.expect(p.executeBuiltinLine(source, "New")); + // no shell IO: the scratch is created in-core, focused, below the caller + while (p.nextEffect()) |_| {} + const id = p.view().active; + try std.testing.expect(id != source); + try std.testing.expectEqual(source_col, layout.findPane(p, id).?.col); + const np = p.panes[id].?; + try std.testing.expect(np.file.?.output != null); // an output buffer, empty + try std.testing.expectEqual(@as(usize, 0), np.file.?.content.len); + // its directory is a LIVE link to the opener, not a snapshot taken at New + try std.testing.expectEqualStrings("/tmp/pardes-scratch-dir", Pardes.paneDir(np)); + p.setCwd(source, "/tmp/pardes-moved"); + try std.testing.expectEqualStrings("/tmp/pardes-moved", Pardes.paneDir(np)); + try p.removePane(source, null); + p.sync(); + try std.testing.expect(np.cwd == .owned); + try std.testing.expectEqualStrings("/tmp/pardes-moved", Pardes.paneDir(np)); + p.sync(); + try std.testing.expectEqualStrings("/tmp/pardes-moved", Pardes.paneDir(np)); +} + +test "a prompt chip is a band with its caret, still on the grid, and only the chip swallows a click" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const id = p.view().active; + const pane = p.panes[id].?; + p.sync(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + + // The caret sits AFTER the prompt text the moment the prompt opens, and + // the chip ends at the pane's right edge -- so this is the frame that + // used to put it one column past the pane, off the grid and past what the + // detached wire will encode. + startPrompt(p, pane, &pane.body, .{ .search = "/" }); + _ = try p.render(frame.allocator()); + const r = p.view().rects[id]; + const cursor = p.surface.cursor orelse return error.MissingPromptCursor; + const row = p.bodyTop(pane, r); + try std.testing.expectEqual(@as(u8, 1), pane.notices.len); + try std.testing.expectEqual(row, cursor.y); + try std.testing.expect(cursor.x < r.x + r.w); + try std.testing.expect(cursor.x < p.surface.cols); + // A pixel shell draws the prompt from its band, in the tagline's pitch, + // with the caret right after the marker's last glyph. + const band = for (p.surface.tagLayers()) |*layer| { + if (layer.rows != 0 and layer.kind == .notice) break layer; + } else return error.NoPromptBand; + try std.testing.expectEqual(row, band.viewport.y); + const caret = band.cursor orelse return error.MissingBandCaret; + try std.testing.expect(caret.bar); + try std.testing.expectEqualStrings("/", band.cells[caret.x - 1].grapheme()); + + // The chip covers only its own columns. Left of it is ordinary body, and + // a sweep there still selects. + const left = pane.notices.left[0]; + try std.testing.expect(left > r.x + config.GUTTER + 2); + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = left - 3, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = left - 1, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = left - 1, .row = row } }); + try std.testing.expect(pane.sel[0].state != .none); + try std.testing.expect(pane.sel[0].r0 >= BOX_H); // the body, not the tag + + // Inside it is chrome: mapped as body it would land on Sel row 0, which is + // the TAG row, so a sweep there would highlight the tagline instead. + // The sweep closed the prompt, and its chip with it: open it again. + pane.clearPointerSelection(0); + pane.sel[0] = .{}; + startPrompt(p, pane, &pane.body, .{ .search = "/" }); + p.sync(); + try std.testing.expectEqual(left, pane.notices.left[0]); + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x + r.w - 3, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = r.x + r.w - 2, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = r.x + r.w - 2, .row = row } }); + for (pane.sel) |selection| try std.testing.expect(selection.state == .none); +} + +test "a prompt is typed on its own line in the notice band and leaves the tag row alone" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile("one two\n"); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const tag_before = try std.testing.allocator.dupe(Cell, p.surface.tag_layers[0].cells); + defer std.testing.allocator.free(tag_before); + + // `s` keeps a prompt on the band (a text's `/` is its query pane's + // line 1 now, Query.zig). + p.update(.{ .key = .{ .cp = 's' } }); + p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); + p.update(.{ .key = .{ .cp = Key.left } }); + try std.testing.expect(pane.prompt == .search and pane.focus == .body); + try std.testing.expectEqualStrings(config.select_marker ++ "tw", pane.promptText().?); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + // The tagline is exactly what it was: nothing of the prompt is in it. + try std.testing.expectEqual(tag_before.len, p.surface.tag_layers[0].cells.len); + for (tag_before, p.surface.tag_layers[0].cells) |was, is| try std.testing.expect(was.visuallyEqual(&is)); + try std.testing.expect(p.surface.tag_layers[0].cursor == null); + // The band carries the answer and the caret, one cell back from its end. + const band = for (p.surface.tagLayers()) |*layer| { + if (layer.rows != 0 and layer.kind == .notice) break layer; + } else return error.NoPromptBand; + const caret = band.cursor orelse return error.MissingBandCaret; + try std.testing.expectEqualStrings("t", band.cells[caret.x - 1].grapheme()); + try std.testing.expectEqualStrings("w", band.cells[caret.x].grapheme()); + const grid = p.surface.cursor orelse return error.MissingPromptCursor; + try std.testing.expectEqual(p.bodyTop(pane, p.view().rects[0]), grid.y); + + // Submitting searches for what was typed and gives the prompt its line back. + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(pane.prompt == .none and pane.input.own == null); +} -- cgit v1.3