diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 00:38:41 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | 26929e67111e843db4ad27abb4f1341cf396158c (patch) | |
| tree | 8540497ac35231593742c17fb6df03ec0a16a76f | |
| parent | 1d382a3ed42788e82301d0ce2a16ebc35c79046c (diff) | |
| download | pardes-26929e67111e843db4ad27abb4f1341cf396158c.tar.gz pardes-26929e67111e843db4ad27abb4f1341cf396158c.zip | |
Term: text through the interface, the editing of the copy back to the core: Term.scrollback and Term.scrollbackLen are its whole history as plain text (its body, Save), Term.textRows its rows as text with a prompt's own cells cut off (a plain Term.Rows), Term.viewport the rows its view shows, Term.promptPrefix how many bytes of a row are its prompt and Term.markRead says a step read them; the editing of the copy of a terminal's rows is the core's again, in edit.zig beside the text it edits: shellRows and the rows' cache (edit.RowsCache, edit.drawing), terminalLines (the rows with the copy spliced in), and in edit.zig's own flatSurface, editText, setEditText, pushUndo and undoStep the terminal's arms written out where they were dispatched to terminal.zig; the body's walk over the rows and the copy (BodyWalk) is body_layer.zig's, beside the bodyText it makes; screenTextAlloc, screenTextLen, cursorLines, flatSurface, editText, setEditText, pushUndo, undoStep and bodyText leave terminal.zig; nothing else changes
| -rw-r--r-- | src/Core.zig | 16 | ||||
| -rw-r--r-- | src/Effect.zig | 2 | ||||
| -rw-r--r-- | src/File.zig | 2 | ||||
| -rw-r--r-- | src/Term.zig | 29 | ||||
| -rw-r--r-- | src/body_layer.zig | 105 | ||||
| -rw-r--r-- | src/draw.zig | 4 | ||||
| -rw-r--r-- | src/dump.zig | 3 | ||||
| -rw-r--r-- | src/edit.zig | 217 | ||||
| -rw-r--r-- | src/exec.zig | 2 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 2 | ||||
| -rw-r--r-- | src/ninep/pane.zig | 4 | ||||
| -rw-r--r-- | src/ninep/screen.zig | 4 | ||||
| -rw-r--r-- | src/replica.zig | 12 | ||||
| -rw-r--r-- | src/term/terminal.zig | 419 | ||||
| -rw-r--r-- | src/tui/tui.zig | 2 | ||||
| -rw-r--r-- | test/kitty.zig | 7 | ||||
| -rw-r--r-- | test/panes.zig | 14 | ||||
| -rw-r--r-- | test/perf.zig | 2 |
18 files changed, 434 insertions, 412 deletions
diff --git a/src/Core.zig b/src/Core.zig index 55848aa9..62f54416 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -389,8 +389,8 @@ scratch: std.heap.ArenaAllocator, /// that still own their loop pass their own arena to `render` instead. frame_arena: std.heap.ArenaAllocator, /// the terminal motion surface, memoized against the pane it was built -/// for — see panes.terminal.RowsCache for the lifetime rule -shell_rows: pardes.panes.terminal.RowsCache = .{}, +/// for — see edit.RowsCache for the lifetime rule +shell_rows: pardes.edit.RowsCache = .{}, /// Finished command panes' output, and whether it is a diff /// (File.DiffOutput). diff_output: pardes.panes.File.DiffOutput = .{}, @@ -2741,7 +2741,7 @@ test "a command of several lines keeps its tag one row, and its echo does not st _ = exec.execute(p, 1, two); while (p.nextEffect()) |_| {} _ = try p.render(frame.allocator()); - const body = try pardes.panes.terminal.screenTextAlloc(pane, gpa); + const body = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(body); try std.testing.expect(std.mem.indexOf(u8, body, "% def greet(name):\n return name") != null); } @@ -3080,7 +3080,7 @@ test "a command pane shows how its command ended, and the next command there run const pane = p.panes[dst].?; // Its first command is echoed as every later one is. { - const first = try pardes.panes.terminal.screenTextAlloc(pane, gpa); + const first = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(first); try std.testing.expect(std.mem.startsWith(u8, first, "% make -j8")); } @@ -3120,7 +3120,7 @@ test "a command pane shows how its command ended, and the next command there run respawned = true; }; try std.testing.expect(respawned); - const body = try pardes.panes.terminal.screenTextAlloc(pane, gpa); + const body = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(body); const said = std.mem.indexOf(u8, body, "compiled") orelse return error.OutputLost; const ended = std.mem.indexOf(u8, body, "exit 2") orelse return error.ExitLost; @@ -3932,14 +3932,14 @@ test "leaving tty hides the prompt and keeps the command typed at it" { const rowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const rows = pardes.panes.terminal.shellRows(pp, pane) catch return null; + const rows = pardes.edit.shellRows(pp, pane) catch return null; for (rows) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; } }.at; const bodyRowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const body = pardes.panes.terminal.bodyText(pp.scratch.allocator(), pane) catch return null; + const body = @import("body_layer.zig").bodyText(pp.scratch.allocator(), pane) catch return null; var it = std.mem.splitScalar(u8, body, '\n'); while (it.next()) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; @@ -3994,7 +3994,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" p.shell_rows.stale = true; // The command shows LEFT-HUGGED, so its column 3 is the '3'... - const rows = try pardes.panes.terminal.shellRows(p, sp); + const rows = try pardes.edit.shellRows(p, sp); var row: i32 = 0; const at = for (rows, 0..) |r, i| { if (std.mem.indexOf(u8, r, "0123456789") != null) break i; diff --git a/src/Effect.zig b/src/Effect.zig index 2af28dd7..e161d1db 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -164,7 +164,7 @@ pub fn perform(p: *Pardes, e: Effect) void { return; } if (!pane.isTerminal()) return; - const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch |err| return p.reportError(st.pane, "Save", err); + const text = pardes.Term.scrollback(pane.terminal, p.gpa) catch |err| return p.reportError(st.pane, "Save", err); defer p.gpa.free(text); if (writeChecked(p, st.pane, st.serial, st.path.slice(), text, 0)) |still| ctlfs.events.noteLogAs(p, .save, still, st.path.slice()); diff --git a/src/File.zig b/src/File.zig index bedf8ada..962737d4 100644 --- a/src/File.zig +++ b/src/File.zig @@ -2101,7 +2101,7 @@ pub const DiffOutput = struct { e.used = o.clock; return if (e.is_diff) e.rows else null; }; - const shown = terminal.shellRows(p, pane) catch return null; + const shown = pardes.edit.shellRows(p, pane) catch return null; const is_diff = diff.looksLikeDiff(shown); var total: usize = 0; if (is_diff) for (shown) |row| { diff --git a/src/Term.zig b/src/Term.zig index ba0a2307..160ed01e 100644 --- a/src/Term.zig +++ b/src/Term.zig @@ -166,3 +166,32 @@ pub const CommandOutput = struct { /// it ran, or never marked (a C or D on the alternate screen). whole: bool, }; + +// ---- text ---- + +/// Its whole scrollback as plain text, logical lines (rows it wrapped +/// joined again), ending in a newline: what its body reads and Save +/// writes. The caller's. +pub const scrollback = terminal.scrollback; +/// How long `scrollback` would be, counted without keeping it. +pub const scrollbackLen = terminal.scrollbackLen; +/// Its rows from the top of its history as text, a prompt's own cells cut +/// off (`Rows`). +pub const textRows = terminal.textRows; +/// The rows its view shows as text, prompts cut off or not. +pub const viewport = terminal.viewport; +/// How many bytes of one of its rows, as `viewport` and `textRows` give it +/// uncut, are the prompt it starts with. +pub const promptPrefix = terminal.promptPrefix; +/// A step read its rows: its replicas must hold them for the step's +/// replay. +pub const markRead = terminal.markRead; + +/// A terminal's rows as text: `rows` slices into `text`, which is a prefix +/// of `text_alloc` (a prompt cut off shortens the join), the last row the +/// empty one after the cursor's. +pub const Rows = struct { + text_alloc: []u8, + text: []const u8, + rows: [][]const u8, +}; diff --git a/src/body_layer.zig b/src/body_layer.zig index a8d09c66..2df619ba 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -50,7 +50,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ lo -|= row.prompt_bytes; hi -|= row.prompt_bytes; } else if (!row.raw_terminal and raw) { - const prefix = panes.terminal.promptPrefixBytes(pane, source_row, line); + const prefix = panes.Term.promptPrefix(pane.terminal, source_row, line); lo += prefix; hi += prefix; } @@ -79,7 +79,7 @@ fn pastView(pane: *Pane, body: []const u8, line: i32, row: i32, at: i32, col: i3 fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { if (pane.isTerminal()) return paintTerminalSelection(p, s, pane, r, rows, bg, fg); - const terminal_lines = if (pane.file == null) panes.terminal.cursorLines(p, pane) catch return else &.{}; + const terminal_lines = if (pane.file == null) edit.terminalLines(p, pane) catch return else &.{}; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; const body_y = p.bodyTop(pane, r); @@ -546,5 +546,104 @@ pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { return buf; } if (pane.file) |*f| return panes.File.bodyText(arena, pane, f); - return panes.terminal.bodyText(arena, pane); + // A terminal's: the rows its view shows (outside raw mode its prompts + // cut off), the edit copy's lines over the rows the copy covers. + const vp: []const []const u8 = if (pane.terminal) |state| try panes.Term.viewport(state, arena, pane.body.mode != .tty) else &.{}; + const len = fillBody(null, pane, vp); + const out = try arena.alloc(u8, len); + const filled = fillBody(out, pane, vp); + std.debug.assert(filled == out.len); + return out; +} + +pub const BodyRow = union(enum) { + grid: i32, + edit: struct { line: []const u8, idx: usize }, +}; + +/// A terminal pane's body rows, top down: a row of its emulator's view +/// (`grid`, its viewport row), or a line of the edit copy standing in for +/// the rows it covers (`edit`). +pub const BodyWalk = struct { + pane: *Pane, + goff: i32, + g: i32, + /// the buffer can start above the viewport: drop the lines scrolled past + skip: usize, + n: usize = 0, + lines: ?std.mem.SplitIterator(u8, .scalar) = null, + covered: i32 = 0, + line_idx: usize = 0, + + pub fn init(pane: *Pane) BodyWalk { + const off = pane.scroll(); + const goff: i32 = @intCast(panes.Term.grid(pane.terminal).offset); + return .{ + .pane = pane, + .goff = goff, + .g = if (pane.body.mode == .tty) goff + pane.pan else pane.gridRow(off), + .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, + }; + } + + pub fn next(w: *BodyWalk) ?BodyRow { + while (w.n < w.pane.rows) { + if (w.lines) |*it| { + if (it.next()) |line| { + const idx = w.line_idx; + w.line_idx += 1; + // Lines scrolled off the top still count: the index names a + // line of the BUFFER, not of the visible body. + if (w.skip > 0) { + w.skip -= 1; + continue; + } + w.n += 1; + return .{ .edit = .{ .line = line, .idx = idx } }; + } + // The buffer stands in for `rows` shell rows however many lines + // it actually spelled, which is the whole slide. + w.g += w.covered; + w.skip = 0; + w.lines = null; + continue; + } + if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { + w.lines = std.mem.splitScalar(u8, o.text, '\n'); + w.covered = o.rows; + w.line_idx = 0; + continue; + }; + const vi = w.g - w.goff; + w.g += 1; + w.n += 1; + return .{ .grid = vi }; + } + return null; + } +}; + +/// Run the terminal body row walk. A null destination counts bytes; a slice +/// fills the exact allocation made from that count. +fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { + var walk: BodyWalk = .init(pane); + var written: usize = 0; + var first = true; + while (walk.next()) |row| { + if (!first) { + if (dst) |out| out[written] = '\n'; + written += 1; + } + first = false; + const bytes = switch (row) { + .edit => |e| e.line, + .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) + viewport[@intCast(vi)] + else + "", + }; + if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); + written += bytes.len; + } + return written; } diff --git a/src/draw.zig b/src/draw.zig index a779d588..238f459a 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -259,8 +259,8 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { const v = p.view(); const taped = pardes.tape.enter(p, .render); defer pardes.tape.leave(p, taped); - panes.terminal.drawing = true; - defer panes.terminal.drawing = false; + edit.drawing = true; + defer edit.drawing = false; panes.File.refreshHighlights(p); const s = &p.surface; const ncells = @as(usize, v.screen_w) * v.screen_h; diff --git a/src/dump.zig b/src/dump.zig index 075bb8cc..38be263d 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -998,7 +998,6 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and test "a loaded terminal's history stays above its banner, the cursor where it was" { if (comptime isolated) return error.SkipZigTest; const gpa = std.testing.allocator; - const term = pardes.panes.terminal; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -1011,7 +1010,7 @@ test "a loaded terminal's history stays above its banner, the cursor where it wa try std.testing.expectEqual([2]u16{ before.cursor_x, before.cursor_y }, [2]u16{ after.cursor_x, after.cursor_y }); const q = try initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); defer q.deinit(); - const text = try term.screenTextAlloc(q.panes[0].?, gpa); + const text = try pardes.Term.scrollback(q.panes[0].?.terminal, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "one\ntwo\n") != null); try std.testing.expect(std.mem.indexOf(u8, text, "two").? < std.mem.indexOf(u8, text, "restored history").?); diff --git a/src/edit.zig b/src/edit.zig index 3881020a..5b94c0d8 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -222,7 +222,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { // Refresh the source map before translating the rendered rectangle. const raw = pane.isTerminal() and pane.body.mode == .tty; const body = try body_layer.bodyText(p.scratch.allocator(), pane); - const terminal_lines = if (pane.file == null and !raw) try panes.terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null and !raw) try terminalLines(p, pane) else &.{}; const first = @max(0, @min(gesture.r0, gesture.r1) - pane.tag_rows); const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - pane.tag_rows); @@ -260,7 +260,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { .hi = if (right < prefix) lo else if (cols.hi == null) end else @min(end, modal.nextGrapheme(line, at)), .to_edge = cols.hi == null, .raw_terminal = raw, - .prompt_bytes = if (raw) panes.terminal.promptPrefixBytes(pane, source.line, line) else 0, + .prompt_bytes = if (raw) panes.Term.promptPrefix(pane.terminal, source.line, line) else 0, }; } pane.next_pointer_selection += 1; @@ -275,7 +275,7 @@ pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { const arena = p.scratch.allocator(); if (pane.rawPointerText(sl)) |text| return arena.dupe(u8, text); if (pane.pointerSelection(sl)) |rows| { - const terminal_lines = if (pane.file == null) try panes.terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null) try terminalLines(p, pane) else &.{}; var total: usize = rows.len -| 1; for (rows) |row| { const line = pointerSourceLine(pane, terminal_lines, row.row); @@ -386,7 +386,7 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) Error![]const []const u8 { const pane = t.pane() orelse return &.{}; if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); if (pane.addon != null) return &.{}; - return panes.terminal.cursorLines(p, pane); + return terminalLines(p, pane); } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { @@ -418,6 +418,111 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); } +// ---- a terminal's rows, and the copy of them an edit makes ---- + +/// Set while a frame is drawn: what it reads is no step's. +pub var drawing = false; + +/// A terminal's rows as text (`Term.rows`), kept for one pane until its +/// grid moves. Returned slices remain valid until the next cache rebuild +/// or reset. +pub const RowsCache = struct { + /// whose grid this describes; null = the slot is free + pane: ?*const Pane = null, + /// the rows joined by '\n' — `flatSurface` hands this back verbatim + /// instead of rebuilding the join on every keystroke + text: []const u8 = &.{}, + /// slices INTO `text`, absolute grid rows from 0 + rows: [][]const u8 = &.{}, + /// `text` is a prefix of this: blanking a prompt row shortens the join, + /// and the slack is not worth a second allocation to reclaim + text_alloc: []u8 = &.{}, + stale: bool = false, + + pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.text_alloc.len > 0) gpa.free(c.text_alloc); + if (c.rows.len > 0) gpa.free(c.rows); + c.* = .{}; + } + + /// Free a stale entry. Called at the top of `update`, and nowhere else. + pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.stale) c.reset(gpa); + } + + /// `pane`'s grid moved: the entry no longer describes it. + pub fn markStale(c: *RowsCache, pane: *const Pane) void { + if (c.pane == pane) c.stale = true; + } + + pub fn dropPane(c: *RowsCache, pane: *const Pane) void { + if (c.pane != pane) return; + c.pane = null; + c.stale = true; + } +}; + +const empty_grid = [1][]const u8{""}; + +/// A terminal pane's rows from the top of its history (`Term.rows`), kept +/// in `Pardes.shell_rows` while its grid holds still. +pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { + const state = pane.terminal orelse return &empty_grid; + pardes.tape.touchTerminal(); + // A step's read whether the rows are kept or made: a client that came + // since holds them as holes, and is sent them (Screens.fill). + if (!drawing) panes.Term.markRead(state); + const c = &p.shell_rows; + if (!c.stale and c.pane == pane) return c.rows; + // Another pane's rows, or a dropped pane's still waiting for the step's + // sweep (dropPane keeps them, as they may still be borrowed): this + // step's rows are scratch, and nothing in the slot is written over. + if (c.pane != null or c.text_alloc.len > 0 or c.rows.len > 0) { + c.stale = true; + return (try panes.Term.textRows(state, p.scratch.allocator(), p.scratch.allocator())).rows; + } + const built = try panes.Term.textRows(state, p.gpa, p.scratch.allocator()); + c.* = .{ + .pane = pane, + .text = built.text, + .rows = built.rows, + .text_alloc = built.text_alloc, + }; + return c.rows; +} + +/// The full modal motion surface: shell history with the live edit overlay +/// spliced into the rows it covers. +pub fn terminalLines(p: *Pardes, pane: *Pane) ![]const []const u8 { + const rows = try shellRows(p, pane); + if (pane.ovl == null) return rows; + var last = rows.len; + if (pane.ovl) |overlay| + last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); + var count = last; + if (pane.ovl) |overlay| { + if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) + count = count - @min( + @as(usize, @intCast(overlay.rows)), + last - @as(usize, @intCast(overlay.row)), + ) + @max(1, modal.lineCount(overlay.text)); + } + const lines = try p.scratch.allocator().alloc([]const u8, count); + var n: usize = 0; + var grid_row: usize = 0; + while (grid_row < last) : (grid_row += 1) { + if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { + var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); + while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; + grid_row += @intCast(overlay.rows - 1); + continue; + }; + lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; + n += 1; + } + return lines[0..n]; +} + pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 { switch (t.what) { .body => {}, @@ -429,8 +534,25 @@ pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 { const pane = t.pane() orelse return ""; if (pane.file) |f| return f.content; if (pane.addon != null) return ""; - const lines = try panes.terminal.cursorLines(p, pane); - return panes.terminal.flatSurface(p, pane, lines); + const lines = try terminalLines(p, pane); + // The kept rows' own join when the lines are them (no edit copy), not + // made again on every keystroke; a join of them in scratch else. + const cache = &p.shell_rows; + if (!cache.stale and cache.pane == pane and + lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; + var total: usize = if (lines.len > 0) lines.len - 1 else 0; + for (lines) |line| total += line.len; + const text = try p.scratch.allocator().alloc(u8, total); + var at: usize = 0; + for (lines, 0..) |line, i| { + if (i > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..line.len], line); + at += line.len; + } + return text; } pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { @@ -455,7 +577,71 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditT const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.addon != null) return null; - return panes.terminal.editText(p, pane, lo, hi, col); + // A terminal's: its edit copy (`Pane.ovl`), made from the rows `lo` to + // `hi` or widened over them, with one exact allocation; the rows are + // scratch-owned or borrowed, only the joined text is kept. + const want_lo = @max(0, @min(lo, hi)); + const want_hi = @max(want_lo, @max(lo, hi)); + const fresh = pane.ovl == null; + const old: Text.EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; + const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); + const up = old.row - want_lo; + const down = want_hi - (old.row + lines - 1); + const extending = fresh or up > 0 or down > 0; + var row0 = old.row; + var covered = old.rows; + var text = old.text; + var owned = false; + if (extending) { + const rows = try shellRows(p, pane); + row0 = old.row - @max(0, up); + covered = old.rows + @max(0, up) + @max(0, down); + const up_len: usize = @intCast(@max(0, up)); + const down_len: usize = @intCast(@max(0, down)); + const parts = try p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len); + for (parts[0..up_len], 0..) |*part, i| { + const src = @as(usize, @intCast(row0)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + const middle: usize = @intCast(old.row); + parts[up_len] = if (fresh) + (if (middle < rows.len) rows[middle] else "") + else + old.text; + for (parts[up_len + 1 ..], 0..) |*part, i| { + const src = @as(usize, @intCast(old.row + old.rows)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + text = try std.mem.join(p.gpa, "\n", parts); + owned = true; + } + + const row: usize = @intCast(@max(0, want_lo - row0)); + const line_len: i32 = @intCast(modal.lineSlice(text, row).len); + if (col > line_len) { + const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { + if (owned) p.gpa.free(text); + return null; + }; + @memset(spaces, ' '); + const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { + if (owned) p.gpa.free(text); + return null; + }; + if (owned) p.gpa.free(text); + text = padded; + owned = true; + } + if (owned) { + if (pane.ovl) |overlay| p.gpa.free(overlay.text); + pane.ovl = .{ .row = row0, .rows = covered, .text = text }; + } + // A terminal's text is its program's: edited here it is a copy, to run + // with Tab or B2, gone when the program draws again. Said at its first + // edit, so it never looks like an edit that was lost. + if (fresh) for (p.panes, 0..) |slot, id| if (slot == pane) + p.setMessage(id, "a copy of the terminal's text: Tab or B2 runs it; what the program draws next replaces it (Ctrl-b types to the program)"); + return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; } fn editTextEol(p: *Pardes, t: *Text, b: Bounds) Error!?panes.EditText { @@ -533,7 +719,14 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp const end = known_end orelse modal.positionAt(new, new.len - found.?.tail); t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; if (pane.file) |*f| return panes.File.setContentSpan(p, f, new, found); - panes.terminal.setEditText(p, pane, new); + // A terminal's edit copy rewritten: the text it replaces freed. + const overlay = if (pane.ovl) |*value| value else return retireEditText(p, new); + for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + } + p.gpa.free(overlay.text); + overlay.text = new; } /// The file whose text `t` edits in place (File.replace), the bytes it puts @@ -1863,7 +2056,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) error{OutOfMemory}!void { } const pane = t.pane() orelse return; if (pane.file != null) return panes.File.pushUndo(p, pane); - return panes.terminal.pushUndo(p, pane); + return pane.body.remember(p.gpa, pane.ovl); } /// Undo (back) or redo one step of the text's history: its file's, its @@ -1873,7 +2066,11 @@ pub fn undoStep(p: *Pardes, t: *Text, back: bool) error{OutOfMemory}!void { if (t.what != .body) return; const pane = t.pane() orelse return; if (pane.file != null) return panes.File.undoStep(p, pane, back); - return panes.terminal.undoStep(p, pane, back); + // A terminal's edit copy, as it was. + const to = (try pane.body.step(p.gpa, pane.ovl, back)) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = to.ovl; + pane.ensureCursorVisible(); } /// Undo or redo an edit of a text's own characters; stepping back past its diff --git a/src/exec.zig b/src/exec.zig index 23c624bd..315f4eee 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -144,7 +144,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l lo -|= span.prompt_bytes; hi -|= span.prompt_bytes; } else if (!span.raw_terminal and raw) { - const prefix = panes.terminal.promptPrefixBytes(pane, row, raw_line); + const prefix = panes.Term.promptPrefix(pane.terminal, row, raw_line); lo += prefix; hi += prefix; } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index a72e7259..2e045a73 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -426,7 +426,7 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: *[pane_text_cap]u8) []const u8 { pane.serial, if (pane_files.tagOf(p, pane)) |tag| tag.len else |_| 0, // a length, as a stat's: none when the tag cannot be made // A terminal's body is its history, read whole on an open's first read. - if (pane.isTerminal()) panes.terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, + if (pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else pane_files.bodyOf(pane).len, // A directory pane is one, as acme's isdir says. @intFromBool(if (pane.file) |f| f.listing != null else false), @intFromBool(pane_files.dirtyOf(pane)), diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3fa45404..13a15206 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -317,7 +317,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pf = &pane.fs; return switch (f) { // A terminal's body reads its screen and history, as text. - .body => if (pane.file == null and pane.isTerminal()) panes.terminal.screenTextLen(pane) else if (kindText(p, pane)) |t| t.len else bodyOf(pane).len, + .body => if (pane.file == null and pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else if (kindText(p, pane)) |t| t.len else bodyOf(pane).len, // What addr selects, generated by each read: no length, as acme's // data and xdata have none. .data, .xdata => 0, @@ -441,7 +441,7 @@ fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // A kind's body is its text (a PDF's, the page shown's): read-only. if (kindText(p, pane)) |text| return tree.window(p, req, text); if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane); - const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch + const text = pardes.Term.scrollback(pane.terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); defer p.gpa.free(text); return tree.window(p, req, text); diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 634ef640..1bfd9b63 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -64,7 +64,7 @@ pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { const snapshot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.snapshot; if (snapshot.* == null) { const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); - snapshot.* = panes.terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); + snapshot.* = pardes.Term.scrollback(terminal.terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); } return tree.window(p, req, snapshot.*.?); } @@ -126,7 +126,7 @@ test "terminal body handles keep one history snapshot across fragmented reads" { const node = Node.of(serialOf(p), .body); p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } }); while (p.nextEffect()) |_| {} - const original = try panes.terminal.screenTextAlloc(p.panes[0].?, gpa); + const original = try pardes.Term.scrollback(p.panes[0].?.terminal, gpa); defer gpa.free(original); const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); try testing.expectEqual(Status.ok, opened.reply.status); diff --git a/src/replica.zig b/src/replica.zig index 9a2c80a7..fa6cfadb 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -3422,7 +3422,7 @@ test "a delta applied under a speculation outlives its rollback: the terminal st try std.testing.expect(r.copy.held); try deliver(a, &screens, peer, r, .flush); // The rows the core keeps, read once under the copy. - _ = try terminal.shellRows(r.core(), r.core().panes[shell].?); + _ = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); } for (sent.items) |m| { r.confirm(try a.take(m)); @@ -3436,7 +3436,7 @@ test "a delta applied under a speculation outlives its rollback: the terminal st // another's unit puts the copy back: the rows it kept are of an older // grid and must not be read. r.confirm(try a.local(.{ .focus = false })); - _ = try terminal.shellRows(r.core(), r.core().panes[shell].?); + _ = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); try key(r, 'x', &sent); for (0..40) |i| a.output(.{ .output = .{ .pane = shell, .bytes = try std.fmt.bufPrint(&line, "last line {d}\r\n", .{i}) } }); r.confirm((try a.pending()).?); @@ -3445,8 +3445,8 @@ test "a delta applied under a speculation outlives its rollback: the terminal st r.confirm(try a.local(.{ .focus = true })); r.settle(); const n = a.core.panes[shell].?.rows; - const back = try terminal.shellRows(r.core(), r.core().panes[shell].?); - const now = try terminal.shellRows(a.core, a.core.panes[shell].?); + const back = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); + const now = try pardes.edit.shellRows(a.core, a.core.panes[shell].?); for (now[now.len - n ..], back[back.len - n ..]) |x, y| try std.testing.expectEqualStrings(x, y); for (sent.items) |m| { r.confirm(try a.take(m)); @@ -3463,8 +3463,8 @@ test "a delta applied under a speculation outlives its rollback: the terminal st try screen_state.dumpScreen(&a.core.panes[shell].?.terminal.?.vt, &dump_a.writer); try screen_state.dumpScreen(&r.core().panes[shell].?.terminal.?.vt, &dump_r.writer); try std.testing.expectEqualStrings(dump_a.written(), dump_r.written()); - const rows_a = try terminal.shellRows(a.core, a.core.panes[shell].?); - const rows_r = try terminal.shellRows(r.core(), r.core().panes[shell].?); + const rows_a = try pardes.edit.shellRows(a.core, a.core.panes[shell].?); + const rows_r = try pardes.edit.shellRows(r.core(), r.core().panes[shell].?); // As many rows (the history is the authority's to the row), the screen's // the same; above it, rows scrolled past more than a screen at once are // holes until fetched. diff --git a/src/term/terminal.zig b/src/term/terminal.zig index 2fe84d0e..2c05cd3c 100644 --- a/src/term/terminal.zig +++ b/src/term/terminal.zig @@ -12,6 +12,7 @@ const tagline = @import("../tagline.zig"); const Key = pardes.Key; const Pane = panes.Pane; const Term = @import("../Term.zig"); +const BodyWalk = @import("../body_layer.zig").BodyWalk; const EditText = panes.EditText; const File = panes.File; @@ -631,15 +632,15 @@ pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: /// reads and `Save` writes out. Logical lines: rows the terminal wrapped /// are joined again (ghostty's wrap flags, as pty/run's output is), and /// the last line ends with a newline. -pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { +pub fn scrollback(state: ?*State, gpa: std.mem.Allocator) ![]const u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); - try writeScreenText(pane, &out.writer); + try writeBody(state, &out.writer); return out.toOwnedSlice(); } -fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { - const state = pane.terminal orelse return; +fn writeBody(maybe: ?*State, w: *std.Io.Writer) !void { + const state = maybe orelse return; const screen = state.vt.screens.active; const br = screen.pages.getBottomRight(.screen) orelse return; var both: TeeWriter = .{ .a = w }; @@ -678,12 +679,12 @@ const TeeWriter = struct { } }; -/// How long `screenTextAlloc` would be, counted without keeping it: the -/// length a terminal's body reads as, which its ctl line reports. -pub fn screenTextLen(pane: *Pane) usize { +/// How long `scrollback` would be, counted without keeping it: the length a +/// terminal's body reads as, which its ctl line reports. +pub fn scrollbackLen(state: ?*State) usize { var buf: [256]u8 = undefined; var counting: std.Io.Writer.Discarding = .init(&buf); - writeScreenText(pane, &counting.writer) catch unreachable; // a discarding writer never fails + writeBody(state, &counting.writer) catch unreachable; // a discarding writer never fails return @intCast(counting.fullCount()); } @@ -989,51 +990,6 @@ pub fn promptMoves(state: *State, row: i32, col: i32) ?Term.Moves { return .{ .left = moves.left, .right = moves.right }; } -// Returned slices remain valid until the next cache rebuild or reset. -pub const RowsCache = struct { - /// whose grid this describes; null = the slot is free - pane: ?*const Pane = null, - /// the rows joined by '\n' — `flatSurface` hands this back verbatim - /// instead of rebuilding the join on every keystroke - text: []const u8 = &.{}, - /// slices INTO `text`, absolute grid rows from 0 - rows: [][]const u8 = &.{}, - /// `text` is a prefix of this: blanking a prompt row shortens the join, - /// and the slack is not worth a second allocation to reclaim - text_alloc: []u8 = &.{}, - stale: bool = false, - - pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.text_alloc.len > 0) gpa.free(c.text_alloc); - if (c.rows.len > 0) gpa.free(c.rows); - c.* = .{}; - } - - /// Free a stale entry. Called at the top of `update`, and nowhere else. - pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.stale) c.reset(gpa); - } - - /// `pane`'s grid moved: the entry no longer describes it. - pub fn markStale(c: *RowsCache, pane: *const Pane) void { - if (c.pane == pane) c.stale = true; - } - - pub fn dropPane(c: *RowsCache, pane: *const Pane) void { - if (c.pane != pane) return; - c.pane = null; - c.stale = true; - } -}; - -const Rows = struct { - text_alloc: []u8, - text: []const u8, - rows: [][]const u8, -}; - -const empty_grid = [1][]const u8{""}; - /// What LEAVING raw tty mode does to one prompt row, decided from its cells /// alone: OSC 133 prompt cells are hidden in normal mode, what was typed at /// them stays. @@ -1059,10 +1015,12 @@ fn promptCut(pin: ghostty_vt.Pin) PromptCut { return .{ .cut = cols }; } -pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { +/// How many of the bytes `raw` of its row `row` (from the top of the +/// history), as the emulator dumps it, are the prompt the row starts with. +pub fn promptPrefix(state: ?*State, row: i32, raw: []const u8) usize { if (row < 0) return 0; - const state = pane.terminal orelse return 0; - const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; + const s = state orelse return 0; + const pin = s.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; if (pin.rowAndCell().row.semantic_prompt == .none) return 0; return switch (promptCut(pin)) { .keep => 0, @@ -1109,176 +1067,24 @@ fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { return n; } -pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { - if (pane.terminal == null) return &empty_grid; - pardes.tape.touchTerminal(); - const c = &p.shell_rows; - if (!c.stale and c.pane == pane) { - // A step's read whether the rows are kept or made: a client that - // came since holds them as holes, and is sent them (Screens.fill). - if (!drawing) pane.terminal.?.read = true; - return c.rows; - } - // Another pane's rows, or a dropped pane's still waiting for the step's - // sweep (dropPane keeps them, as they may still be borrowed): this - // step's rows are scratch, and nothing in the slot is written over. - if (c.pane != null or c.text_alloc.len > 0 or c.rows.len > 0) { - c.stale = true; - return (try buildRows(p.scratch.allocator(), p, pane)).rows; - } - const built = try buildRows(p.gpa, p, pane); - c.* = .{ - .pane = pane, - .text = built.text, - .rows = built.rows, - .text_alloc = built.text_alloc, - }; - return c.rows; +/// A step read its rows (its history too): a replica replaying the step +/// must hold them (`State.read`). +pub fn markRead(state: *State) void { + state.read = true; } -/// The full modal motion surface: shell history with the live edit overlay -/// spliced into the rows it covers. -pub fn cursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { - const rows = try shellRows(p, pane); - if (pane.ovl == null) return rows; - var last = rows.len; - if (pane.ovl) |overlay| - last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); - var count = last; - if (pane.ovl) |overlay| { - if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) - count = count - @min( - @as(usize, @intCast(overlay.rows)), - last - @as(usize, @intCast(overlay.row)), - ) + @max(1, modal.lineCount(overlay.text)); - } - const lines = try p.scratch.allocator().alloc([]const u8, count); - var n: usize = 0; - var grid_row: usize = 0; - while (grid_row < last) : (grid_row += 1) { - if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { - var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); - while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; - grid_row += @intCast(overlay.rows - 1); - continue; - }; - lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; - n += 1; - } - return lines[0..n]; -} - -/// Flatten `cursorLines` without rebuilding the common cached/no-overlay -/// case. Scratch-owned when a join is required. -pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { - const cache = &p.shell_rows; - if (!cache.stale and cache.pane == pane and - lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; - var total: usize = if (lines.len > 0) lines.len - 1 else 0; - for (lines) |line| total += line.len; - const text = try p.scratch.allocator().alloc(u8, total); - var at: usize = 0; - for (lines, 0..) |line, i| { - if (i > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..line.len], line); - at += line.len; - } - return text; -} - -/// Materialize or extend the terminal edit overlay with one exact allocation. -/// Row slices are scratch-owned/borrowed; only the joined text is installed. -pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) error{ OutOfMemory, WriteFailed, UnknownPoint }!?EditText { - const want_lo = @max(0, @min(lo, hi)); - const want_hi = @max(want_lo, @max(lo, hi)); - const fresh = pane.ovl == null; - const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; - const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); - const up = old.row - want_lo; - const down = want_hi - (old.row + lines - 1); - const extending = fresh or up > 0 or down > 0; - var row0 = old.row; - var covered = old.rows; - var text = old.text; - var owned = false; - if (extending) { - const rows = try shellRows(p, pane); - row0 = old.row - @max(0, up); - covered = old.rows + @max(0, up) + @max(0, down); - const up_len: usize = @intCast(@max(0, up)); - const down_len: usize = @intCast(@max(0, down)); - const parts = try p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len); - for (parts[0..up_len], 0..) |*part, i| { - const src = @as(usize, @intCast(row0)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - const middle: usize = @intCast(old.row); - parts[up_len] = if (fresh) - (if (middle < rows.len) rows[middle] else "") - else - old.text; - for (parts[up_len + 1 ..], 0..) |*part, i| { - const src = @as(usize, @intCast(old.row + old.rows)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - text = try std.mem.join(p.gpa, "\n", parts); - owned = true; - } - - const row: usize = @intCast(@max(0, want_lo - row0)); - const line_len: i32 = @intCast(modal.lineSlice(text, row).len); - if (col > line_len) { - const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { - if (owned) p.gpa.free(text); - return null; - }; - @memset(spaces, ' '); - const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { - if (owned) p.gpa.free(text); - return null; - }; - if (owned) p.gpa.free(text); - text = padded; - owned = true; - } - if (owned) { - if (pane.ovl) |overlay| p.gpa.free(overlay.text); - pane.ovl = .{ .row = row0, .rows = covered, .text = text }; - } - // A terminal's text is its program's: edited here it is a copy, to run - // with Tab or B2, gone when the program draws again. Said at its first - // edit, so it never looks like an edit that was lost. - if (fresh) for (p.panes, 0..) |slot, id| if (slot == pane) - p.setMessage(id, "a copy of the terminal's text: Tab or B2 runs it; what the program draws next replaces it (Ctrl-b types to the program)"); - return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; -} - -/// Consume a rewritten overlay, freeing the terminal edit text it replaces. -pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { - const overlay = if (pane.ovl) |*value| value else return pardes.edit.retireEditText(p, new); - for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - } - p.gpa.free(overlay.text); - overlay.text = new; -} - -/// Set while a frame is drawn: what it reads is no step's. -pub var drawing = false; - -fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { - if (!drawing) pane.terminal.?.read = true; - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); - var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); +/// Its rows from the top of its history as text, a prompt's own cells cut +/// off the rows it starts (what typed text stays), joined by '\n' in +/// `text` with `rows` slices into it and one empty row after them, the +/// cursor's: `alloc`'s, the emulator's dump `scratch`'s. +pub fn textRows(state: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) !Term.Rows { + const full = try state.vt.screens.active.dumpStringAlloc(scratch, .{ .screen = .{} }); + var pit = state.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); // split yields one more item than delimiters; the extra final slot is the // cursor row retained below. const n_rows = std.mem.count(u8, full, "\n") + 2; - const rows = try alloc.alloc([]const u8, n_rows); - errdefer alloc.free(rows); + const lines = try alloc.alloc([]const u8, n_rows); + errdefer alloc.free(lines); // Blanking a prompt row only ever SHORTENS it and the retained cursor row // adds one separator, so the dump's length plus one bounds the join. const text = try alloc.alloc(u8, full.len + 1); @@ -1296,140 +1102,44 @@ fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { at += 1; } @memcpy(text[at..][0..shown.len], shown); - rows[n] = text[at..][0..shown.len]; + lines[n] = text[at..][0..shown.len]; at += shown.len; n += 1; } text[at] = '\n'; at += 1; - rows[n] = text[at..][0..0]; + lines[n] = text[at..][0..0]; n += 1; std.debug.assert(n == n_rows); - return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; -} - -pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { - const vp: []const []const u8 = vp: { - const state = pane.terminal orelse break :vp &.{}; - const screen = state.vt.screens.active; - var tl = screen.pages.getTopLeft(.viewport); - tl.x = 0; - const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; - var rows_out: std.Io.Writer.Allocating = .init(arena); - try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); - const raw = try rows_out.toOwnedSlice(); - var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); - const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); - var lines = std.mem.splitScalar(u8, raw, '\n'); - var n: usize = 0; - while (lines.next()) |ln| { - vp[n] = if (pane.body.mode != .tty) - if (prompts.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln - else - ln - else - ln; - n += 1; - } - std.debug.assert(n == vp.len); - break :vp vp; - }; - - const len = fillBody(null, pane, vp); - const out = try arena.alloc(u8, len); - const filled = fillBody(out, pane, vp); - std.debug.assert(filled == out.len); - return out; + return .{ .text_alloc = text, .text = text[0..at], .rows = lines }; } -pub const BodyRow = union(enum) { - grid: i32, - edit: struct { line: []const u8, idx: usize }, -}; - -const BodyWalk = struct { - pane: *Pane, - goff: i32, - g: i32, - /// the buffer can start above the viewport: drop the lines scrolled past - skip: usize, - n: usize = 0, - lines: ?std.mem.SplitIterator(u8, .scalar) = null, - covered: i32 = 0, - line_idx: usize = 0, - - fn init(pane: *Pane) BodyWalk { - const off = pane.scroll(); - const goff: i32 = @intCast(grid(pane.terminal).offset); - return .{ - .pane = pane, - .goff = goff, - .g = if (pane.body.mode == .tty) goff + pane.pan else pane.gridRow(off), - .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, - }; - } - - fn next(w: *BodyWalk) ?BodyRow { - while (w.n < w.pane.rows) { - if (w.lines) |*it| { - if (it.next()) |line| { - const idx = w.line_idx; - w.line_idx += 1; - // Lines scrolled off the top still count: the index names a - // line of the BUFFER, not of the visible body. - if (w.skip > 0) { - w.skip -= 1; - continue; - } - w.n += 1; - return .{ .edit = .{ .line = line, .idx = idx } }; - } - // The buffer stands in for `rows` shell rows however many lines - // it actually spelled, which is the whole slide. - w.g += w.covered; - w.skip = 0; - w.lines = null; - continue; - } - if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { - w.lines = std.mem.splitScalar(u8, o.text, '\n'); - w.covered = o.rows; - w.line_idx = 0; - continue; - }; - const vi = w.g - w.goff; - w.g += 1; - w.n += 1; - return .{ .grid = vi }; - } - return null; - } -}; - -/// Run the terminal body row walk. A null destination counts bytes; a slice -/// fills the exact allocation made from that count. -fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { - var walk: BodyWalk = .init(pane); - var written: usize = 0; - var first = true; - while (walk.next()) |row| { - if (!first) { - if (dst) |out| out[written] = '\n'; - written += 1; - } - first = false; - const bytes = switch (row) { - .edit => |e| e.line, - .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) - viewport[@intCast(vi)] +/// The rows its view shows as text, a prompt's own cells cut off the rows +/// it starts when `cut` (as the core shows them outside raw mode): `arena`'s. +pub fn viewport(state: *State, arena: std.mem.Allocator, cut: bool) ![]const []const u8 { + const screen = state.vt.screens.active; + var tl = screen.pages.getTopLeft(.viewport); + tl.x = 0; + const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; + var rows_out: std.Io.Writer.Allocating = .init(arena); + try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); + const raw = try rows_out.toOwnedSlice(); + var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); + const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); + var lines = std.mem.splitScalar(u8, raw, '\n'); + var n: usize = 0; + while (lines.next()) |ln| { + vp[n] = if (cut) + if (prompts.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln else - "", - }; - if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); - written += bytes.len; + ln + else + ln; + n += 1; } - return written; + std.debug.assert(n == vp.len); + return vp; } // Match surviving edit-buffer rows to their original terminal styles. @@ -1914,17 +1624,6 @@ fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Col }; } -pub fn pushUndo(p: *Pardes, pane: *Pane) error{OutOfMemory}!void { - return pane.body.remember(p.gpa, pane.ovl); -} - -/// Undo (back) or redo one step of the edit overlay. -pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) error{OutOfMemory}!void { - const to = (try pane.body.step(p.gpa, pane.ovl, back)) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = to.ovl; - pane.ensureCursorVisible(); -} /// When the pane's next kitty animation frame is due (ms on the core's /// clock), as its last drawn frame left it; null when nothing plays. @@ -2093,7 +1792,7 @@ test "document construction allocates only the pane and has inert terminal defau pane.followOutput(); pane.resizeGrid(80, 24); try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); - try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); + try std.testing.expectEqualStrings("", try scrollback(pane.terminal, allocator)); try std.testing.expect(!failing.has_induced_failure); } @@ -2172,7 +1871,7 @@ test "a restored command pane comes back finished, its command not run again" { try std.testing.expectEqualStrings("make test", again.command.?); try std.testing.expect(again.command_done); try std.testing.expectEqual(@as(?u8, 2), again.command_status); - const text = try screenTextAlloc(again, gpa); + const text = try scrollback(again.terminal, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); } @@ -2200,7 +1899,7 @@ test "a restored terminal keeps its history above a marker and gets a shell wher try std.testing.expectEqualStrings("bash", again.shell.?); try std.testing.expect(again.command == null); try std.testing.expectEqual(.spawn, again.pending_command.wait); - const text = try screenTextAlloc(again, gpa); + const text = try scrollback(again.terminal, gpa); defer gpa.free(text); const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; @@ -2248,10 +1947,10 @@ test "rows asked for after a pane's cached rows were dropped, before the sweep, defer p.deinit(); const pane = p.panes[0].?; try std.testing.expect(pane.terminal != null); - _ = try shellRows(p, pane); + _ = try pardes.edit.shellRows(p, pane); // A pane's teardown drops its entry; the rows stay until the sweep. p.shell_rows.dropPane(pane); - _ = try shellRows(p, pane); + _ = try pardes.edit.shellRows(p, pane); } test "the luminance table answers exactly what ghostty computes" { diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 8afa8ca8..b66a900f 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -2983,7 +2983,7 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { shell.gens[0] = 2; _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); + const text = try pardes.Term.scrollback(core.panes[0].?.terminal, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); diff --git a/test/kitty.zig b/test/kitty.zig index 4341677e..760d22be 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -19,7 +19,6 @@ const std = @import("std"); const pardes = @import("pardes"); const Pardes = pardes.Pardes; const config = pardes.config; -const terminal = pardes.panes.terminal; const gpa = std.testing.allocator; @@ -309,7 +308,7 @@ test "kitty: text around an APC prints, in the same read and split across reads" var r = try Rig.init(1); defer r.deinit(); r.feedSplit(0, "before" ++ apc("a=t,i=3,f=24,s=4,v=2,q=2", rgb_b64) ++ "after", step); - const text = try terminal.screenTextAlloc(r.pane(0), r.frame.allocator()); + const text = try pardes.Term.scrollback(r.pane(0).terminal, r.frame.allocator()); try std.testing.expect(std.mem.indexOf(u8, text, "beforeafter") != null); try std.testing.expect(r.hasImage(0, 3)); } @@ -643,7 +642,7 @@ test "kitty: an image follows its text when the shell scrolls, resizes and reflo // A narrower pane reflows the text; the image stays on its row. const pane = r.pane(0); pane.resizeGrid(40, pane.rows); - const text = try terminal.screenTextAlloc(pane, r.frame.allocator()); + const text = try pardes.Term.scrollback(pane.terminal, r.frame.allocator()); var row: usize = 0; var lines = std.mem.splitScalar(u8, text, '\n'); while (lines.next()) |line| : (row += 1) if (std.mem.startsWith(u8, line, "marker")) break; @@ -762,7 +761,7 @@ test "kitty: a cancelled (CAN, SUB) APC runs nothing, answers nothing, and the t r.feed(0, "after"); try std.testing.expect(!r.hasImage(0, 60)); try std.testing.expectEqualStrings("", try r.take(0)); - const text = try terminal.screenTextAlloc(r.pane(0), r.frame.allocator()); + const text = try pardes.Term.scrollback(r.pane(0).terminal, r.frame.allocator()); try std.testing.expect(std.mem.indexOf(u8, text, "after") != null); } } diff --git a/test/panes.zig b/test/panes.zig index 301568c1..5562105e 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -1016,7 +1016,7 @@ test "terminal output keeps following new rows after scrollback eviction" { try std.testing.expect(pages.page_size <= pages.limits.max(.bytes)); const sb = pages.scrollbar(); try std.testing.expectEqual(sb.total - pane.rows, sb.offset); - const full = try panes.terminal.screenTextAlloc(pane, gpa); + const full = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(full); var last_buf: [16]u8 = undefined; const last = try std.fmt.bufPrint(&last_buf, "row-{d:0>5}", .{(phase + 1) * 20_000 - 1}); @@ -1080,7 +1080,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { } } try std.testing.expect(removed > 0 and removed < original_row); - const full = try panes.terminal.screenTextAlloc(pane, gpa); + const full = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(full); const row = original_row - @as(i32, @intCast(removed)); try std.testing.expectEqualStrings(last, modal.lineSlice(full, @intCast(row))); @@ -1111,7 +1111,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen pane.body.cur_col = 4; pane.body.cur_pinned = true; pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; - try panes.terminal.pushUndo(p, pane); + try pane.body.remember(p.gpa, pane.ovl); const overlay = pane.ovl.?; pane.body.ed_redo[0] = .{ .ovl = .{ .row = overlay.row, .rows = overlay.rows, .text = try gpa.dupe(u8, overlay.text) }, @@ -1153,7 +1153,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen try std.testing.expectEqualStrings("edit one\nedit two", snapshot.ovl.?.text); } try std.testing.expectEqual(@as(usize, 2), pane.terminal.?.vt.screens.active.pages.countTrackedPins()); - try panes.terminal.undoStep(p, pane, true); + try pardes.edit.undoStep(p, &pane.body, true); try std.testing.expectEqualStrings("edit one\nedit two", pane.ovl.?.text); try std.testing.expectEqual(expected, pane.ovl.?.row); } @@ -1170,7 +1170,7 @@ test "terminal lower scroll regions do not move edits above them" { pane.ovl = .{ .row = 1, .rows = 1, .text = try gpa.dupe(u8, "unsent") }; pane.body.cur_row = 1; pane.body.cur_pinned = true; - try panes.terminal.pushUndo(p, pane); + try pane.body.remember(p.gpa, pane.ovl); const total = pardes.Term.grid(pane.terminal).total; var setup: [64]u8 = undefined; const bytes = try std.fmt.bufPrint(&setup, "\x1b[4;{d}r\x1b[{d};1H", .{ pane.rows, pane.rows }); @@ -1180,7 +1180,7 @@ test "terminal lower scroll regions do not move edits above them" { try std.testing.expectEqual(@as(i32, 1), pane.ovl.?.row); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 1), pane.body.ed_undo[0].ovl.?.row); - const full = try panes.terminal.screenTextAlloc(pane, gpa); + const full = try pardes.Term.scrollback(pane.terminal, gpa); defer gpa.free(full); try std.testing.expect(std.mem.startsWith(u8, full, "top\nsecond\nthird\n")); } @@ -1210,7 +1210,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv pane.ovl = .{ .row = old_row, .rows = 1, .text = try gpa.dupe(u8, "kept edit") }; pane.body.cur_row = old_row; pane.body.cur_pinned = true; - try panes.terminal.pushUndo(p, pane); + try pane.body.remember(p.gpa, pane.ovl); const old_total = pages.total_rows; var buf: [128]u8 = undefined; const bytes = try std.fmt.bufPrint(&buf, "new\r\n\x1b[4;{d}r\x1b[{d};1Hregion\r\n", .{ pane.rows, pane.rows }); diff --git a/test/perf.zig b/test/perf.zig index b8514d26..d9341cad 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -880,7 +880,7 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he pane.body.cur_row = first + 1; pane.body.cur_col = 1; pane.body.vsel = .{ .active = true, .row = first, .col = 0 }; - try pardes.panes.terminal.pushUndo(core, pane); + try pane.body.remember(core.gpa, pane.ovl); core.gpa.free(pane.ovl.?.text); pane.ovl = null; if (pane.body.ed_undo_len != index + 1) return error.TerminalUndoSnapshotFailed; |
