diff options
Diffstat (limited to 'src/term')
| -rw-r--r-- | src/term/terminal.zig | 419 |
1 files changed, 59 insertions, 360 deletions
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" { |
