diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Effect.zig | 2 | ||||
| -rw-r--r-- | src/Pipe.zig | 2 | ||||
| -rw-r--r-- | src/Query.zig | 2 | ||||
| -rw-r--r-- | src/builtins.zig | 12 | ||||
| -rw-r--r-- | src/edit.zig | 4 | ||||
| -rw-r--r-- | src/exec.zig | 4 | ||||
| -rw-r--r-- | src/host_io.zig | 7 | ||||
| -rw-r--r-- | src/keys.zig | 4 | ||||
| -rw-r--r-- | src/look.zig | 4 | ||||
| -rw-r--r-- | src/lsp/Ask.zig | 2 | ||||
| -rw-r--r-- | src/ninep/cols.zig | 11 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 10 | ||||
| -rw-r--r-- | src/ninep/tree.zig | 3 | ||||
| -rw-r--r-- | src/normal.zig | 14 | ||||
| -rw-r--r-- | src/panes.zig | 769 | ||||
| -rw-r--r-- | src/pardes.zig | 796 | ||||
| -rw-r--r-- | src/pdf_view.zig | 10 | ||||
| -rw-r--r-- | src/tagline.zig | 4 | ||||
| -rw-r--r-- | src/terminal.zig | 6 |
19 files changed, 851 insertions, 815 deletions
diff --git a/src/Effect.zig b/src/Effect.zig index f9b0e645..51b7c645 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -539,7 +539,7 @@ test "saves armed in one batch stay with their own panes" { p.setCwd(tty_id, "/tmp/pardes-batch"); p.update(.{ .output = .{ .pane = @intCast(tty_id), .bytes = "shell text\r\n" } }); const file = try p.setTestFile("file text\n"); - const file_id = p.paneIdOf(file) orelse return error.MissingFilePane; + const file_id = panes.paneIdOf(p, file) orelse return error.MissingFilePane; try std.testing.expect(shell.isTerminal()); try std.testing.expect(tty_id != file_id); while (p.nextEffect()) |_| {} diff --git a/src/Pipe.zig b/src/Pipe.zig index 3045d738..05085b9a 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -98,7 +98,7 @@ pub const PendingPipe = struct { pub fn submitPipe(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; - const t = p.promptTarget(pane) orelse return; + const t = panes.promptTarget(p, pane) orelse return; if (t.what == .body) { const f = pane.file orelse return; if (!panes.Output.fileTraits(f.output).saves) return; diff --git a/src/Query.zig b/src/Query.zig index 1524212c..3337a575 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -2045,7 +2045,7 @@ pub fn clampEdit(p: *Pardes, t: *panes.Text, old: []const u8, new: []u8) ?[]u8 { if (rows_same) return new; if (span.head > end or (span.head == end and old_to > end and put.len == 0 and end < old.len)) { t.refused = true; - if (t.pane()) |pane| if (p.paneIdOf(pane)) |id| + if (t.pane()) |pane| if (panes.paneIdOf(p, pane)) |id| p.setMessage(id, "the rows are line 1's: edit the query (Enter keeps them as text)"); return null; } diff --git a/src/builtins.zig b/src/builtins.zig index 398e699d..0ad7d998 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1248,7 +1248,7 @@ pub const Save = struct { // A `+` name is a generated pane's (+Tutor), no file of its own: // a bare Save asks for a path, as a +New scratch's does. if (c.pane.file) |file| if (file.output == null and !std.mem.startsWith(u8, std.fs.path.basename(file.path), "+")) return exec.saveFile(c.p, c.id); - if (c.pane.file != null or c.pane.isTerminal()) c.p.startPrompt(c.pane, &c.pane.body, .save); + if (c.pane.file != null or c.pane.isTerminal()) panes.startPrompt(c.p, c.pane, &c.pane.body, .save); } }; @@ -1550,7 +1550,7 @@ pub const Tutor = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Tutor", error.NoPaneSlots); - _ = c.p.openTutorView(free) catch return; + _ = panes.openTutorView(c.p, free) catch return; exec.placeNew(c.p, c.id, c.id, free, .doc); // a doc like any other } }; @@ -1583,7 +1583,7 @@ pub const Config = struct { if (real != null) return look.lookAt(c.p, c.id, path); // Not there yet: a pane named for it, which Save makes. const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Config", error.NoPaneSlots); - c.p.newScratchFor(c.id, .scratch); + panes.newScratchFor(c.p, c.id, .scratch); if (c.p.panes[free] == null) return; @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, "Config", err); c.p.active = free; @@ -1852,7 +1852,7 @@ pub const Last = struct { } // Nothing on the jumplist to go back to, which is the ordinary case // for a pane that opened beside this one and was never focused. - if (c.p.neighbourPane(c.id)) |next| look.focusPaneLine(c.p, next, .{ .line = 0, .col = 0 }, .keep); + if (panes.neighbourPane(c.p, c.id)) |next| look.focusPaneLine(c.p, next, .{ .line = 0, .col = 0 }, .keep); } }; @@ -1992,7 +1992,7 @@ pub const Rename = struct { pub fn run(c: Ctx) void { const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (a.len > 0) return c.p.lspRequest(c.id, .rename, a); - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.rename_marker }); + panes.startPrompt(c.p, c.pane, &c.pane.body, .{ .search = config.rename_marker }); } }; @@ -2003,7 +2003,7 @@ pub const WsSymbols = struct { pub fn run(c: Ctx) void { const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (a.len > 0) return c.p.lspRequest(c.id, .workspace_symbols, a); - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.symbol_marker }); + panes.startPrompt(c.p, c.pane, &c.pane.body, .{ .search = config.symbol_marker }); } }; diff --git a/src/edit.zig b/src/edit.zig index ec37d0e3..834911f6 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -79,7 +79,7 @@ pub fn pasteRegister(p: *Pardes, t: *Text, how: Paste, count: usize) void { if (name == '+' or name == '*') { if (!normal.multiOnce(p)) return; const pane = t.pane() orelse return; - return clipRequest(p, p.paneIdOf(pane) orelse return, how); + return clipRequest(p, panes.paneIdOf(p, pane) orelse return, how); } const y = registerValue(p, t, name) orelse return; switch (how) { @@ -141,7 +141,7 @@ pub fn applyPaste(p: *Pardes, whole: []const u8) void { n += 1; }; if (n > 0) insertKey(p, &pane.input, .{ .cp = line[0], .text = line[0..n] }); - if (normal.selRegexArmed(pane)) |a| if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); + if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); return; } if (pane.focus == .tag) return pasteInto(p, &pane.tag, bytes); diff --git a/src/exec.zig b/src/exec.zig index 81826271..6ed37624 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -774,7 +774,7 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { p.reportError(from, "exec", error.NoPaneSlots); return null; }; - const pane = p.newCommand(free, dir, line) catch |err| { + const pane = panes.newCommand(p, free, dir, line) catch |err| { p.reportError(from, "exec", err); return null; }; @@ -990,7 +990,7 @@ pub fn runBuiltinFrom(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ? } // No pane at all (the window Delcol emptied): a word runs all the same, // with a stand-in that is no pane (New, Newcol, Exit are what make sense). - const pane = p.panes[id] orelse (if (builtins.registry.scope(b) == .session or p.anyPane() == null) p.standIn() orelse return else return); + const pane = p.panes[id] orelse (if (builtins.registry.scope(b) == .session or panes.anyPane(p) == null) panes.standIn(p) orelse return else return); // A builtin says its own name before it runs, so a tagline click is // legible even when what it did is invisible. Whatever the builtin // then says for itself replaces the announcement. It is the message diff --git a/src/host_io.zig b/src/host_io.zig index 1a328ad5..bbf72d8c 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -9,6 +9,7 @@ const filesystem = @import("fs.zig"); const file_watch = @import("file_watch.zig"); const replica = @import("replica.zig"); const daemon = @import("daemon.zig"); +const panes = @import("panes.zig"); pub const Host = struct { ctx: ?*anyopaque = null, @@ -3282,7 +3283,7 @@ test "a command pane's child is its shell running the one line, and its exit sta defer core.deinit(); while (core.nextEffect()) |_| {} const id = core.freeSlot().?; - _ = try core.newCommand(id, "", "printf 'said '; exit 7"); + _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); while (core.nextEffect()) |_| {} const rcs: Shell.PromptFiles = .{}; const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); @@ -3313,7 +3314,7 @@ test "a command's exit is its process's, told by its watcher, whether or not its .{ .line = "exec </dev/null >/dev/null 2>&1; sleep 0.3; exit 5", .status = 5 }, }) |c| { const id = core.freeSlot().?; - _ = try core.newCommand(id, "", c.line); + _ = try panes.newCommand(core, id, "", c.line); while (core.nextEffect()) |_| {} const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); defer _ = libc.close(child.file.handle); @@ -3353,7 +3354,7 @@ test "a command's background job outlives it and its pty, and Kill stops its who .{ .line = "(sleep 0.4; touch killed) & sleep 5", .kill = true, .made = false }, }) |c| { const id = core.freeSlot().?; - _ = try core.newCommand(id, dir, c.line); + _ = try panes.newCommand(core, id, dir, c.line); while (core.nextEffect()) |_| {} const child = try forkShell(core, id, &rcs, "/bin/sh", dir, 24, 80); if (c.kill) { diff --git a/src/keys.zig b/src/keys.zig index 5673c0ba..ad7d8e83 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -306,7 +306,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { if (header == null and pane.prompt != .none) { if (hit(key, config.search_submit) or hit(key, config.escape)) { const submit = hit(key, config.search_submit); - const target = p.promptTarget(pane); + const target = panes.promptTarget(p, pane); switch (pane.prompt) { .pipe => if (submit) Pipe.submitPipe(p, p.active), .save => if (submit) exec.submitSave(p, p.active), @@ -324,7 +324,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { return; } edit.handleInsert(p, &pane.input, key); - if (normal.selRegexArmed(pane)) |a| if (p.promptTarget(pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode); + if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode); return; } if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key); diff --git a/src/look.zig b/src/look.zig index 0574985b..7b39f113 100644 --- a/src/look.zig +++ b/src/look.zig @@ -540,7 +540,7 @@ pub fn submitSearch(p: *Pardes, id: usize) void { p.registers.put(p.gpa, '/', a.pat, 0, 1, true); p.registers.last_search = '/'; } - return if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); + return if (panes.promptTarget(p, pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); } const armed = pane.promptText() orelse return; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return; @@ -1154,7 +1154,7 @@ fn canonicalLookLocation(p: *Pardes, id: usize, text: []const u8) ?[]const u8 { pub fn pdfLinkLocation(p: *Pardes, pane: *const Pane, link: if (pdf_enabled) pdf.Link else void) ?[]const u8 { if (comptime !pdf_enabled) return null; const state = pane.pdf orelse return null; - const id = p.paneIdOf(pane) orelse return null; + const id = panes.paneIdOf(p, pane) orelse return null; return switch (link.destination) { .none => null, .internal => |dest| if (dest.page < state.document.pages) diff --git a/src/lsp/Ask.zig b/src/lsp/Ask.zig index 5ef63e7e..c658593d 100644 --- a/src/lsp/Ask.zig +++ b/src/lsp/Ask.zig @@ -417,7 +417,7 @@ test "Lspwhy after a Hover asks to explain that hover, in its file at its place, p.lsp_wait = null; // Run from another file's pane: still the hover's file and place. const other = p.freeSlot().?; - _ = try p.openTutorView(other); + _ = try panes.openTutorView(p, other); p.lspRequest(other, .explain, ""); var seen = false; while (p.nextEffect()) |e| if (e == .lsp) { diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index d1ffc3c6..f53bb433 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -8,6 +8,7 @@ const pardes = @import("../pardes.zig"); const Pardes = pardes.Pardes; const tree = @import("tree.zig"); const limits = @import("../memory.zig").limits; +const panes = @import("../panes.zig"); const tagline = pardes.tagline; const layout = pardes.layout; const Text = pardes.panes.Text; @@ -451,11 +452,11 @@ test "New and Term run at /tagexec and a column's exec, with no pane at all too" while (p.ncol > 0) { const first = p.panes[p.col_panes[0][0]].?.serial; _ = th.wr(p, tree.Node.of(first, .ctl), "delete\n"); - if (p.anyPane() == null) break; + if (panes.anyPane(p) == null) break; } - try testing.expect(p.anyPane() == null); + try testing.expect(panes.anyPane(p) == null); try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, line).reply.status); - try testing.expect(p.anyPane() != null); + try testing.expect(panes.anyPane(p) != null); } } @@ -564,7 +565,7 @@ test "a focus write makes its pane's column the active one: layout says so and p defer p.deinit(); const left = p.panes[0].?.serial; p.newColumn(p.active); - p.newScratchFor(p.active, .fs); // fills the new, right column + panes.newScratchFor(p, p.active, .fs); // fills the new, right column p.sync(); try testing.expectEqual(@as(usize, 1), layout.findPane(p, p.active).?.col); var digits: [16]u8 = undefined; @@ -690,7 +691,7 @@ test "a command run from a column's tag gets its pane in that column, not the la const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); p.newColumn(p.active); - p.newScratchFor(p.active, .fs); // fills the new, right column + panes.newScratchFor(p, p.active, .fs); // fills the new, right column p.sync(); const left = layout.columnSerial(p, 0); try testing.expectEqual(tree.Status.ok, th.wr(p, Node.ofCol(left, .exec), "true\n").reply.status); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 4cb4728f..2d733af6 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -210,7 +210,7 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep // scratch made as New makes one (and its column), dropped // unannounced when the look went elsewhere. var scratch: ?usize = null; - if (p.panes[id] == null and serial == null and p.anyPane() == null) { + if (p.panes[id] == null and serial == null and panes.anyPane(p) == null) { if (exec) { p.exec_header = true; defer p.exec_header = false; @@ -218,7 +218,7 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep continue; } const free = p.freeSlot() orelse return Reply.fail(req.tag, E.NOSPC); - p.newScratchFor(id, .scratch); + panes.newScratchFor(p, id, .scratch); if (p.panes[free] == null) return Reply.fail(req.tag, E.NOSPC); p.active = free; id = free; @@ -779,7 +779,7 @@ pub fn writeRoot(p: *Pardes, req: Req) Reply { continue; } // An empty window (no pane at all) still takes its session words. - if (p.panes[p.active] == null and p.anyPane() != null) return Reply.fail(req.tag, E.NOENT); + if (p.panes[p.active] == null and panes.anyPane(p) != null) return Reply.fail(req.tag, E.NOENT); p.fs.session_write = true; defer p.fs.session_write = false; if (runBuiltin(p, req, p.active, line)) |refusal| return refusal; @@ -2257,7 +2257,7 @@ test "with no pane at all, the root look opens its file and the root exec runs i p.session_dir_len = @intCast(session.len); const Empty = struct { fn all(q: *Pardes) !void { - while (q.anyPane()) |k| _ = wr(q, Node.of(q.panes[k].?.serial, .ctl), "delete\n"); + while (panes.anyPane(q)) |k| _ = wr(q, Node.of(q.panes[k].?.serial, .ctl), "delete\n"); } }; try Empty.all(p); @@ -2277,7 +2277,7 @@ test "with no pane at all, the root look opens its file and the root exec runs i try Empty.all(p); try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.exec), "echo hi\n").reply.status); - const made = p.panes[p.anyPane().?].?; + const made = p.panes[panes.anyPane(p).?].?; try testing.expect(made.command != null); try testing.expectEqualStrings(session, made.cwdSlice()); } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 3b8a8581..8c0743bd 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -24,6 +24,7 @@ pub const pty = @import("pty.zig"); pub const sources = @import("sources.zig"); pub const screen = @import("screen.zig"); const daemon = @import("../daemon.zig"); +const panes = @import("../panes.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; @@ -836,7 +837,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { // Refused, the open's err is the one record of it (the // one rule): no msg besides. p.fs.capturing = true; - p.newScratchFor(p.active, .fs); + panes.newScratchFor(p, p.active, .fs); p.fs.capturing = false; p.fs.failure_len = 0; const made = p.panes[slot] orelse return Reply.fail(req.tag, E.NFILE); diff --git a/src/normal.zig b/src/normal.zig index 6a65ee3e..1209fb1e 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -59,7 +59,7 @@ fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode pane.nsel_snap = @intCast(got.n); pane.sel_snap_pri = @intCast(got.pri); pane.sel_snap_expl = t.vsel.active and t.vsel.explicit; - p.startPrompt(pane, t, .{ .search = regexMarker(mode) }); + panes.startPrompt(p, pane, t, .{ .search = regexMarker(mode) }); } fn regexMarker(mode: modal.Normal.RegexMode) []const u8 { @@ -837,17 +837,17 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void { .column, .workspace => tagline.exitHeader(p), .body, .input => tagline.enterTag(p, pane), }, - .pipe_selection => return p.startPrompt(pane, t, .{ .pipe = .replace }), - .pipe_selection_to => return p.startPrompt(pane, t, .{ .pipe = .ignore }), - .insert_output => return p.startPrompt(pane, t, .{ .pipe = .insert }), - .append_output => return p.startPrompt(pane, t, .{ .pipe = .append }), - .keep_pipe => return p.startPrompt(pane, t, .{ .pipe = .keep }), + .pipe_selection => return panes.startPrompt(p, pane, t, .{ .pipe = .replace }), + .pipe_selection_to => return panes.startPrompt(p, pane, t, .{ .pipe = .ignore }), + .insert_output => return panes.startPrompt(p, pane, t, .{ .pipe = .insert }), + .append_output => return panes.startPrompt(p, pane, t, .{ .pipe = .append }), + .keep_pipe => return panes.startPrompt(p, pane, t, .{ .pipe = .keep }), // `/` in a text is its query pane's line 1 (Query.zig); a // terminal's still asks on the notice band. .search => if (pane.file != null and t.what == .body) panes.Query.open(p, p.active, .text, "", true) else - return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), + return panes.startPrompt(p, pane, &pane.body, .{ .search = config.search_marker }), // In a file's text, n and N step its places while they answer for // the register (Places.answersN); else helix's search of the register. .search_next, .search_prev => if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) diff --git a/src/panes.zig b/src/panes.zig index 73a0fc9e..8786de2b 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -3,7 +3,24 @@ const pardes = @import("pardes.zig"); const views = @import("views.zig"); const config = @import("config.zig"); const modal = @import("modal.zig"); -const limits = @import("memory.zig").limits; +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; +const pdf_enabled = Pdf.enabled; /// An owned editable buffer and the absolute surface row of its first line. /// Files use row zero; terminal overlays may begin anywhere in scrollback. @@ -722,3 +739,753 @@ test { _ = Pdf; _ = terminal; } + +// ---- 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 pane.hasPdf(); + 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); + panes.terminal.deinitPendingCommand(pane); + if (pane.command) |line| p.gpa.free(line); + if (pane.shell) |bin| p.gpa.free(bin); + if (pane.image) |*iv| { + iv.deinit(p.image_gpa); + } + if (comptime pdf_enabled) if (pane.pdf) |pv| panes.Pdf.deinitPane(p, pane, pv); + 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; + } + panes.terminal.deinitEmulator(pane, p.gpa); + 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.rects[id] = .{}; + p.panes[id] = pane; + views.installed(p, pane); + panes.terminal.adoptSettings(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.terminal.create(p.gpa, p.screen_w, p.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 {}; + panes.terminal.armShellSpawn(pane); + 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.terminal.create(p.gpa, p.screen_w, p.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.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + p.installPane(id, pane); + return pane; +} + +pub fn newScratch(p: *Pardes, from_id: usize, free: usize, kind: exec.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, <cwd>/+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 exec.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: exec.NewPane) void { + const free = p.freeSlot() orelse return p.reportError(from_id, "New", error.NoPaneSlots); + _ = newScratch(p, from_id, free, kind) catch return; + exec.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.terminal.createDoc(p.gpa, p.screen_w, p.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.fs.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 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.terminal.createDoc(p.gpa, p.screen_w, p.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; + p.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 (comptime pdf_enabled) if (pane.pdf) |pv| + return std.fs.path.dirname(pv.path) orelse "/"; + if (pane.image) |iv| return std.fs.path.dirname(iv.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 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 (p.col_n[f.col] == 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| p.besideColumn(c, p.rects[id]) else null; + layout.removePane(p, id); + p.panes[id] = null; + if (kept) |k| p.store.close(p, k, gainer); + // The finder's last pane takes the column with it. + const finder_gone = if (emptied) |c| p.finder.emptied(p, c) else false; + if (p.active != id) return; + // No pane left: the session is over. + p.active = gainer orelse beside orelse anyPane(p) orelse { + p.quit = true; + return p.emit(.quit); + }; + if (emptied) |c| if (!finder_gone and !p.header_focus) 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.col_n[at.col]; + if (n > 1) return p.col_panes[at.col][(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 (src/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 <serial> save path`, answered on the pane's + // ctl with `answer <path>` 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 ""); + } + 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 return; + // 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.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 "owned cwd preserves long paths aliases and failed updates" { + 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.active; + const first = p.panes[first_id].?; + p.newScratchBelow(0); + const second = p.panes[p.active].?; + p.newScratchBelow(first_id); + const grandchild = p.panes[p.active].?; + p.sync(); + while (p.nextEffect()) |_| {} + p.parkPendingWrite(0, "queued"); + const pending = p.pending_write[0].?.bytes; + const columns = p.col_panes; + const counts = p.col_n; + const active = p.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.col_panes); + try std.testing.expectEqualDeep(counts, p.col_n); + try std.testing.expectEqual(active, p.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" { + 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.col_panes; + const counts = p.col_n; + allocator.fail_index = allocator.alloc_index + 1; + try std.testing.expectError(error.OutOfMemory, p.removeColumn(0)); + for (before, p.panes) |old, current| try std.testing.expectEqual(old, current); + try std.testing.expectEqualDeep(columns, p.col_panes); + try std.testing.expectEqualDeep(counts, p.col_n); + 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 p.removeColumn(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.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: ghostty 1.4's 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, src/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.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.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" { + 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.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.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.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.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); +} diff --git a/src/pardes.zig b/src/pardes.zig index 5add3f68..4e10aa00 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -769,21 +769,6 @@ test "a frame no one watches is not drawn, and is drawn once someone does" { try std.testing.expectEqual(@as(usize, 1), Watch.presents); } -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 p.openTutorView(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 "an empty column shows its theme's empty_col under its tag: acme's white, else the border" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 20 }); defer p.deinit(); @@ -951,10 +936,10 @@ test "a spawn is for the pane it was made for, not whatever took the slot since" // A command pane closed and its slot taken, in one step, before the // effects run: only the second's spawn is performed. const slot = p.freeSlot().?; - _ = try p.newCommand(slot, "", "first"); + _ = try panes.newCommand(p, slot, "", "first"); try p.removePane(slot, null); try std.testing.expectEqual(slot, p.freeSlot().?); - _ = try p.newCommand(slot, "", "second"); + _ = try panes.newCommand(p, slot, "", "second"); while (p.nextEffect()) |effect| p.perform(effect); try std.testing.expectEqual(@as(usize, 1), Count.spawns); try std.testing.expectEqualStrings("second", Count.command[0.."second".len]); @@ -1168,7 +1153,7 @@ test "a REPL bound for a language takes the exec made on a body in it; tags, Exe // A command pane is a REPL while its command runs: done, it is none, // and a done one cannot be bound. A document pane is no terminal. const cmd = p.freeSlot().?; - _ = try p.newCommand(cmd, "", "python3"); + _ = try panes.newCommand(p, cmd, "", "python3"); try std.testing.expect(p.executeBuiltinLine(cmd, "Repl python")); try std.testing.expect(p.panes[cmd].?.repl != null); p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 0 } }); @@ -1341,7 +1326,7 @@ test "a command pane shows how its command ended, and the next command there run p.host = .{ .vtable = &Count.vtable }; try std.testing.expect(p.executeBuiltinLine(0, "Kill make")); try p.removePane(dst, null); - _ = try p.newCommand(dst, "", "other"); + _ = try panes.newCommand(p, dst, "", "other"); while (p.nextEffect()) |effect| if (effect == .signal_pty) p.perform(effect); try std.testing.expectEqual(@as(usize, 0), Count.signals); p.host = host_before; @@ -1354,7 +1339,7 @@ test "image dump restores source bytes renderer choices and exact custom tail" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); - try p.deinitPane(p.panes[0].?); + try panes.deinitPane(p, p.panes[0].?); p.panes[0] = null; const source = "\x00embedded image bytes\xff"; @@ -1455,241 +1440,6 @@ test "the host is asked about a tty only where a command line is about to go" { try std.testing.expectEqual(@as(usize, 1), host.asked); } -test "New opens an empty scratch below the caller, inheriting its directory" { - 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.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 "owned cwd preserves long paths aliases and failed updates" { - 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.active; - const first = p.panes[first_id].?; - p.newScratchBelow(0); - const second = p.panes[p.active].?; - p.newScratchBelow(first_id); - const grandchild = p.panes[p.active].?; - p.sync(); - while (p.nextEffect()) |_| {} - p.parkPendingWrite(0, "queued"); - const pending = p.pending_write[0].?.bytes; - const columns = p.col_panes; - const counts = p.col_n; - const active = p.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.col_panes); - try std.testing.expectEqualDeep(counts, p.col_n); - try std.testing.expectEqual(active, p.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" { - 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.col_panes; - const counts = p.col_n; - allocator.fail_index = allocator.alloc_index + 1; - try std.testing.expectError(error.OutOfMemory, p.removeColumn(0)); - for (before, p.panes) |old, current| try std.testing.expectEqual(old, current); - try std.testing.expectEqualDeep(columns, p.col_panes); - try std.testing.expectEqualDeep(counts, p.col_n); - 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 p.removeColumn(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.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: ghostty 1.4's 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, src/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.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.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 "a host with no methods at all is a complete in-process pardes" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 10 }); @@ -1966,8 +1716,6 @@ pub fn pathUnder(a: []const u8, b: []const u8) bool { return a.len == root.len or a[root.len] == '/'; } -const tutor_text = @embedFile("tutor.txt"); - test "Tab N draws every pane's tab N cells wide and clicks count past it; bare Tab says the width; the ctl read and a Dump keep it" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); @@ -2248,7 +1996,7 @@ test "Newcol refuses an unsplittable restored weight before spawning" { p.col_weight[3] -= 1; for ([_]usize{ 3, 2, 1 }) |id| { const pane = p.panes[id].?; - try p.deinitPane(pane); + try panes.deinitPane(p, pane); layout.removePane(p, id); layout.dropColumn(p, id); p.panes[id] = null; @@ -2414,7 +2162,7 @@ pub const RetiredPanes = struct { current: [2 * MAX_PANES]?*Pane = @splat(null), previous: [2 * MAX_PANES]?*Pane = @splat(null), - fn retire(a: *RetiredPanes, pane: *Pane) void { + pub fn retire(a: *RetiredPanes, pane: *Pane) void { for (&a.current) |*slot| if (slot.* == null) { slot.* = pane; return; @@ -2791,6 +2539,20 @@ pub const Pardes = struct { /// `p.executeBuiltinLine(...)`; it lives with the rest of exec in exec.zig. pub const executeBuiltinLine = exec.executeBuiltinLine; + /// Pane slots, called from everywhere as `p.freeSlot()` and the rest + /// (emitSpawn and installPane by dump.zig); they live with the panes + /// in panes.zig. + pub const emitSpawn = panes.emitSpawn; + pub const installPane = panes.installPane; + pub const newShell = panes.newShell; + pub const newDocPane = panes.newDocPane; + pub const newScratchBelow = panes.newScratchBelow; + pub const freeSlot = panes.freeSlot; + pub const paneBySerial = panes.paneBySerial; + pub const setTestFile = panes.setTestFile; + pub const paneDir = panes.paneDir; + pub const removePane = panes.removePane; + /// A language word's request, called from every word and test as /// `p.lspRequest(...)`; it lives with its answer in lsp/Ask.zig. pub const lspRequest = @import("lsp/Ask.zig").lspRequest; @@ -2914,7 +2676,7 @@ pub const Pardes = struct { // text under the shell. The shell keeps the keyboard. A boot // layout, like .classic's, not a placement. if (p.boot == .tty) { - const np = try p.newScratch(0, 1, .scratch); + const np = try panes.newScratch(p, 0, 1, .scratch); layout.insert(p, 0, 1, 1); layout.splitBelow(p, 0, np); } @@ -3085,13 +2847,13 @@ pub const Pardes = struct { for (p.twin_groups.items) |group| p.gpa.free(group.path); p.twin_groups.deinit(p.gpa); p.fs.batch.bytes.deinit(p.gpa); - if (p.stand_in) |pane| p.teardownPane(pane); + if (p.stand_in) |pane| panes.teardownPane(p, pane); look.cancelLookHover(p); if (p.repl_ask) |ask| p.gpa.free(ask.text); for (0..MAX_PANES) |id| p.dropPendingWrite(id); // The panes, then those retired these last two frames. inline for (.{ &p.panes, &p.retired_panes.previous, &p.retired_panes.current }) |slots| for (slots) |*slot| if (slot.*) |pane| { - p.teardownPane(pane); + panes.teardownPane(p, pane); slot.* = null; }; const gpa = p.gpa; @@ -3181,197 +2943,6 @@ pub const Pardes = struct { return COLBAR_H; } - 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 p.detachCwds(&.{pane}); - p.retirePane(pane); - } - - 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 pane.hasPdf(); - 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. - 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); - panes.terminal.deinitPendingCommand(pane); - if (pane.command) |line| p.gpa.free(line); - if (pane.shell) |bin| p.gpa.free(bin); - if (pane.image) |*iv| { - iv.deinit(p.image_gpa); - } - if (comptime pdf_enabled) if (pane.pdf) |pv| panes.Pdf.deinitPane(p, pane, pv); - 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; - } - panes.terminal.deinitEmulator(pane, p.gpa); - pane.clearCwd(); - pane.fs.deinit(p.gpa); - p.gpa.destroy(pane); - } - - fn reapPanes(p: *Pardes) void { - var reaped = false; - for (&p.retired_panes.previous) |*slot| if (slot.*) |pane| { - p.teardownPane(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.rects[id] = .{}; - p.panes[id] = pane; - views.installed(p, pane); - panes.terminal.adoptSettings(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.terminal.create(p.gpa, p.screen_w, p.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 {}; - panes.terminal.armShellSpawn(pane); - 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.terminal.create(p.gpa, p.screen_w, p.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.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); - p.installPane(id, pane); - return pane; - } - - fn newScratch(p: *Pardes, from_id: usize, free: usize, kind: exec.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, <cwd>/+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 exec.placeNew - /// places it. - pub fn newScratchBelow(p: *Pardes, from_id: usize) void { - p.newScratchFor(from_id, .scratch); - } - - /// A scratch for New (`.scratch`) or 9P's pane/new (`.fs`). - pub fn newScratchFor(p: *Pardes, from_id: usize, kind: exec.NewPane) void { - const free = p.freeSlot() orelse return p.reportError(from_id, "New", error.NoPaneSlots); - _ = p.newScratch(from_id, free, kind) catch return; - exec.placeNew(p, from_id, from_id, free, kind); - } - /// Newcol: an empty column right of the calling pane's, the keyboard /// on its tag, for the next pane made to fill. pub fn newColumn(p: *Pardes, from_id: usize) void { @@ -3457,19 +3028,6 @@ pub const Pardes = struct { return if (layout.findPane(p, id)) |f| f.col else null; } - 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; - } - pub fn emitWrite(p: *Pardes, id: usize, bytes: []const u8) void { var off: usize = 0; // Anything already parked for this pane owns the stream's position, so @@ -3492,7 +3050,7 @@ pub const Pardes = struct { return (p.effects.len - p.effects_len) * effect_write_cap + pending; } - fn parkPendingWrite(p: *Pardes, id: usize, bytes: []const u8) void { + pub fn parkPendingWrite(p: *Pardes, id: usize, bytes: []const u8) void { if (p.pending_write_bytes + bytes.len > limits.pending_write_cap) return; if (p.pending_write[id]) |*pw| { // Compact what the drain already sent before growing: a burst that @@ -3816,15 +3374,9 @@ pub const Pardes = struct { } } - /// 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.terminal.createDoc(p.gpa, p.screen_w, p.screen_h) catch null; - return p.stand_in; - } - /// Drop a pane's parked bytes: its pty is gone, and the slot it occupied /// may be handed to a different pane next frame. - fn dropPendingWrite(p: *Pardes, id: usize) void { + pub fn dropPendingWrite(p: *Pardes, id: usize) void { const pw = p.pending_write[id] orelse return; p.pending_write_bytes -= pw.bytes.len - pw.off; p.gpa.free(pw.bytes); @@ -4305,10 +3857,6 @@ pub const Pardes = struct { } } - pub fn paneIdOf(p: *const Pardes, pane: *const Pane) ?usize { - return std.mem.findScalar(?*const Pane, &p.panes, pane); - } - /// Where pardes started: the directory of what runs from a header. pub fn sessionDir(p: *Pardes) []const u8 { if (p.session_dir_len) |n| return p.session_dir[0..n]; @@ -4331,96 +3879,6 @@ pub const Pardes = struct { return paneDir(p.panes[id] orelse return p.sessionDir()); } - 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 (comptime pdf_enabled) if (pane.pdf) |pv| - return std.fs.path.dirname(pv.path) orelse "/"; - if (pane.image) |iv| return std.fs.path.dirname(iv.path) orelse "/"; - return pane.cwdSlice(); - } - - /// 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 (src/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 <serial> save path`, answered on the pane's - // ctl with `answer <path>` 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 ""); - } - 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 return; - // 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.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, - }; - } - pub const SavePath = Effect.Buf(effect_path_cap); /// What was said of a failure just now on pane `id` is also the waiting @@ -4468,82 +3926,6 @@ pub const Pardes = struct { p.setMessage(p.active, std.fmt.bufPrint(&buf, "WindowOpacity: {s}", .{reason[0..@min(reason.len, 240)]}) catch "WindowOpacity: compositor rejected the request"); } - 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.fs.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 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.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); - errdefer p.gpa.destroy(pane); - try p.deinitPane(p.panes[0].?); - p.panes[0] = null; - pane.file = .{ .path = path, .content = copy, .history = history }; - p.installPane(0, pane); - pane.body.cur_pinned = true; - p.active = 0; - p.sync(); - return pane; - } - - /// 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 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 (p.col_n[f.col] == 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 p.deinitPane(pane); - const gainer = layout.absorbVWeight(p, id, owner orelse to); - const beside = if (emptied) |c| p.besideColumn(c, p.rects[id]) else null; - layout.removePane(p, id); - p.panes[id] = null; - if (kept) |k| p.store.close(p, k, gainer); - // The finder's last pane takes the column with it. - const finder_gone = if (emptied) |c| p.finder.emptied(p, c) else false; - if (p.active != id) return; - // No pane left: the session is over. - p.active = gainer orelse beside orelse p.anyPane() orelse { - p.quit = true; - return p.emit(.quit); - }; - if (emptied) |c| if (!finder_gone and !p.header_focus) tagline.enterHeader(p, c); - } - /// Delcol: close column `col` and every pane in it. pub fn removeColumn(p: *Pardes, col: usize) !void { if (col >= p.ncol) return; @@ -4556,40 +3938,24 @@ pub const Pardes = struct { ids[i] = p.col_panes[col][i]; parents[i] = p.panes[ids[i]].?; } - try p.detachCwds(parents[0..count]); + try panes.detachCwds(p, parents[0..count]); for (ids[0..count], parents[0..count]) |closed, pane| { // Kept for Panes; its column goes, so it comes back as a new pane. if (p.store.keep(p, closed)) |k| p.store.close(p, k, null); - p.retirePane(pane); + panes.retirePane(p, pane); layout.removePane(p, closed); p.panes[closed] = null; } layout.dropColumn(p, col); // The last column gone, the window stays, empty but for the // workspace tag, as acme's does; Newcol starts again from there. - if (p.panes[p.active] == null) p.active = beside orelse p.anyPane() orelse return tagline.enterHeader(p, null); - } - - /// 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.col_n[at.col]; - if (n > 1) return p.col_panes[at.col][(at.idx + 1) % n]; - } - for (p.panes, 0..) |slot, id| { - if (slot != null and id != from) return id; - } - return null; + if (p.panes[p.active] == null) p.active = beside orelse panes.anyPane(p) orelse return tagline.enterHeader(p, null); } /// The pane that takes over the keyboard from column `col`: in the /// column layout.dropColumn gives the width to, the one level with the /// middle of `r` (of the screen without one). Asked while rects hold. - fn besideColumn(p: *const Pardes, col: usize, r: ?Rect) ?usize { + pub fn besideColumn(p: *const Pardes, col: usize, r: ?Rect) ?usize { if (p.ncol < 2) return null; const next = if (col > 0) col - 1 else col + 1; const mid = if (r) |at| at.y + at.h / 2 else p.screen_h / 2; @@ -4602,12 +3968,6 @@ pub const Pardes = struct { return pick; } - /// 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; - } - /// The rows pane `id`'s tag takes at its width, wrapped as `sync` wraps /// it: what a placement must leave it above its body rows. pub fn wantedTagRows(p: *Pardes, id: usize) u16 { @@ -4640,7 +4000,7 @@ pub const Pardes = struct { if (p.header_column != null and p.columnBarHeight() == 0) { tagline.exitHeader(p); } - p.reapPanes(); + panes.reapPanes(p); if (views.several(p)) views.show(p); layout.compute(p); Jump.trackJump(p); @@ -5103,100 +4463,6 @@ test "raw terminal cursor follows its active row only while that row is visible" } } -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.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. - p.startPrompt(pane, &pane.body, .{ .search = "/" }); - _ = try p.render(frame.allocator()); - const r = p.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] = .{}; - p.startPrompt(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.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); -} - test "the bare tty startup opens a text pane under the shell, unfocused" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .boot = .tty }); defer p.deinit(); diff --git a/src/pdf_view.zig b/src/pdf_view.zig index e615521d..10e21a54 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -2364,7 +2364,7 @@ pub fn applyNormal(core: *pardes.Pardes, pane: *pardes.Pane, a: modal.Normal.Act return; }, .command_line => return tagline.enterTag(core, pane), - .search => return core.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), + .search => return panes.startPrompt(core, pane, &pane.body, .{ .search = config.search_marker }), .search_next, .search_prev => return look.lookWalk(core, if (a.role == .search_next) 1 else -1), else => false, }; @@ -2622,7 +2622,7 @@ pub fn sameBytes(core: *pardes.Pardes, pane: *const pardes.Pane) bool { /// can retire the corresponding directory watch before that id is reused. pub fn deinitPane(core: *pardes.Pardes, pane: *pardes.Pane, state: *State) void { if (comptime !enabled) return; - if (core.paneIdOf(pane)) |id| core.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); + if (panes.paneIdOf(core, pane)) |id| core.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); state.deinit(core.pdf_gpa); core.pdf_gpa.destroy(state); pane.pdf = null; @@ -2929,7 +2929,7 @@ pub fn toggleTint(pane: *pardes.Pane) void { pub fn paneViewport(core: *const pardes.Pardes, pane: *const pardes.Pane) ?Viewport { if (comptime !enabled) return null; - const rect = core.rects[core.paneIdOf(pane) orelse return null]; + const rect = core.rects[panes.paneIdOf(core, pane) orelse return null]; const cols = rect.w -| config.GUTTER; const rows = rect.h -| pane.tag_rows; if (cols == 0 or rows == 0) return null; @@ -2967,7 +2967,7 @@ pub fn paneGeometry(core: *const pardes.Pardes, pane: *const pardes.Pane) ?image pub fn pageAtGridRow(core: *const pardes.Pardes, pane: *const pardes.Pane, row: u16) ?usize { if (comptime !enabled) return null; const state = pane.pdf orelse return null; - const rect = core.rects[core.paneIdOf(pane) orelse return null]; + const rect = core.rects[panes.paneIdOf(core, pane) orelse return null]; const body_y = core.bodyTop(pane, rect); if (!state.layout_valid or row < body_y or row >= body_y + (rect.h -| pane.tag_rows)) return null; const document_y = state.document_scroll_y + @as(f64, @floatFromInt( @@ -3023,7 +3023,7 @@ pub fn panePointAtPage( const raster = rasterForPageConst(state, page) orelse return null; if (raster.rgba.len == 0) return null; const placed = placedGeometry(state, raster, view, page) orelse return null; - const rect = core.rects[core.paneIdOf(pane) orelse return null]; + const rect = core.rects[panes.paneIdOf(core, pane) orelse return null]; const body_x = @as(i64, rect.x + config.GUTTER); const body_y = @as(i64, core.bodyTop(pane, rect)); const px = (@as(i64, col) - body_x) * core.cell_pixels.w + core.cell_pixels.w / 2; diff --git a/src/tagline.zig b/src/tagline.zig index 317c1c17..e14feab4 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -313,7 +313,7 @@ pub fn tagWidth(p: *const Pardes, id: usize) usize { pub fn shownTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !Shown { const whole = try tagText(p, arena, pane); - const id = p.paneIdOf(pane) orelse return .{ .text = whole, .soft = &.{} }; + const id = panes.paneIdOf(p, pane) orelse return .{ .text = whole, .soft = &.{} }; return wrapTag(arena, whole, tagWidth(p, id)); } @@ -373,7 +373,7 @@ pub fn draftName(p: *Pardes, pane: *Pane, col: usize) void { /// draft visible on failure so the user can correct it or cancel with Esc. pub fn commitTagName(p: *Pardes, pane: *Pane) bool { if (pane.prompt != .name) return true; - const id = p.paneIdOf(pane) orelse return false; + const id = panes.paneIdOf(p, pane) orelse return false; const name = pane.input.own orelse ""; if (name.len == 0 or name[name.len - 1] == '/' or !std.unicode.utf8ValidateSlice(name)) { p.reportError(id, "name", error.InvalidName); diff --git a/src/terminal.zig b/src/terminal.zig index c041ae22..22371a78 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1079,7 +1079,7 @@ test "a restored command pane comes back finished, its command not run again" { defer p.deinit(); while (p.nextEffect()) |_| {} const cmd = p.freeSlot().?; - _ = try p.newCommand(cmd, "/tmp", "make test"); + _ = try panes.newCommand(p, cmd, "/tmp", "make test"); feedOutput(p, p.panes[cmd].?, "ok\r\n"); p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); try pardes.dump.dumpState(p); @@ -1148,7 +1148,7 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { // A replica's emulator is what the authority's deltas make it; what // pardes keeps over it moves as the authority's ingest told it. if (pardes.tape.screenReplica()) { - if (has_positions and ingestWithPositions(pane, bytes)) if (p.paneIdOf(pane)) |id| p.setMessage(id, positions_lost); + if (has_positions and ingestWithPositions(pane, bytes)) if (panes.paneIdOf(p, pane)) |id| p.setMessage(id, positions_lost); return; } // Sticky bottom, as every other terminal does it: output drags the @@ -1158,7 +1158,7 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { syncPixels(p, pane); if (!has_positions) { ingest(pane, bytes); - } else if (ingestWithPositions(pane, bytes)) if (p.paneIdOf(pane)) |id| p.setMessage(id, positions_lost); + } else if (ingestWithPositions(pane, bytes)) if (panes.paneIdOf(p, pane)) |id| p.setMessage(id, positions_lost); p.shell_rows.markStale(pane); if (pane.body.mode == .tty and at_bottom) followOutput(pane); } |
