summaryrefslogtreecommitdiff
path: root/src/terminal.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-31 06:28:48 -0300
committerGabriel Schneider <[email protected]>2026-10-31 06:28:48 -0300
commita479792a1ab2b593642d7f648194bfa23ce01dba (patch)
tree96ddee7d879a9084daa07db43b0b7910b072a785 /src/terminal.zig
parente179cc44fe5060c76a5b00c41e53f11209f5acd9 (diff)
parent4c761893e5b3fdae422622cfa02104ab36633045 (diff)
downloadpardes-a479792a1ab2b593642d7f648194bfa23ce01dba.tar.gz
pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.zip
Merge the upstream daemon and replicated client/server refactor
Diffstat (limited to 'src/terminal.zig')
-rw-r--r--src/terminal.zig743
1 files changed, 528 insertions, 215 deletions
diff --git a/src/terminal.zig b/src/terminal.zig
index ce41bd95..86eec32d 100644
--- a/src/terminal.zig
+++ b/src/terminal.zig
@@ -8,7 +8,6 @@ const Pardes = pardes.Pardes;
const Surface = pardes.Surface;
const modal = @import("modal.zig");
const tracy = @import("tracy.zig");
-const dump = @import("dump.zig");
const tagline = @import("tagline.zig");
const Key = pardes.Key;
const Pane = panes.Pane;
@@ -21,6 +20,8 @@ const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {};
pub const history_max = if (enabled) 64 else 8;
pub const VtSlot = if (enabled) ghostty_vt.Terminal else void;
+/// A cell of an emulator's pages, as `getCell` reads it (src/echo.zig).
+pub const PageCell = if (enabled) ghostty_vt.PageList.Cell else void;
/// Kitty graphics are drawn where pixel geometry is (pdf_enabled, as for
/// image panes' native placements).
pub const images_enabled = enabled and pardes.pdf_enabled;
@@ -144,6 +145,11 @@ pub const MarkedHandler = if (enabled) struct {
} else void;
pub const State = struct {
+ /// What the emulator and this struct are allocated with: the core's,
+ /// but on a screen-state replica the C heap (`emulator_gpa`), outside
+ /// its rollback epoch: written by deltas while a copy is held, no part
+ /// of it is ever a copy's to save or put back.
+ gpa: std.mem.Allocator,
vt: VtSlot,
stream: StreamSlot,
/// The emulator's answers to its program (DSR, DA, kitty graphics, ...)
@@ -159,6 +165,176 @@ pub const State = struct {
mouse_cell: if (enabled) ?ghostty_vt.Coordinate else void = if (enabled) null else {},
/// The kitty graphics its program placed, as drawn (TerminalImages.zig).
images: TerminalImages = if (images_enabled) .{} else {},
+ /// Counts the emulator's writes (output, a resize, its view scrolled):
+ /// a new count is a new state for its replicas (screen_state.Track).
+ changes: u32 = 0,
+ /// A step read its rows (its history too): a replica replaying that
+ /// step must hold them, so its authority sends the ones it does not
+ /// before the step's unit (replica.Screens.fill).
+ read: bool = false,
+ /// The size a step gave it, on an authority with screen-state replicas:
+ /// made after the step's unit (`resizeDeferred`), so that the rest of
+ /// the step reads the grid it had, as its replicas' replays do, and the
+ /// rows sent them for it (Screens.fill) are of that grid's numbering.
+ resize_to: ?struct { cols: u16, rows: u16 } = null,
+
+ /// The emulator as its program has made it, for the replay digest
+ /// (src/walk.zig): the active screen's text, how much history is above
+ /// it and where the view is, the cursor, the answers not yet written.
+ /// Not its pages (their addresses are its own), nor the history's text
+ /// (the screen's was all of it once, and a session's digest is taken
+ /// every step), nor the kitty images, whose media is read off the host:
+ /// a replica's terminal is the authority's screen state from phase 5
+ /// on (docs/next-daemon.md).
+ pub fn digest(s: *const State, h: *pardes.walk.Hasher) void {
+ if (comptime !enabled) return;
+ // Under screen-state terminals the emulator is the authority's, and
+ // a replica's is what the last delta made it: compared as screens
+ // (test/replicas.zig), not step by step.
+ if (pardes.tape.screenState()) return;
+ s.digestScreen(h, true);
+ }
+
+ /// `view`: where its view is too (a replica's speculation may move it).
+ pub fn digestScreen(s: *const State, h: *pardes.walk.Hasher, view: bool) void {
+ if (comptime !enabled) return;
+ const screen = s.vt.screens.active;
+ const sb = screen.pages.scrollbar();
+ const cur = screen.cursor;
+ const offset = if (view) sb.offset else 0;
+ const facts = .{ sb.total, offset, sb.len, cur.x, cur.y, s.vt.modes.get(.cursor_visible), s.vt.screens.active_key, s.reply_dropped };
+ inline for (facts) |fact| h.update(std.mem.asBytes(&fact));
+ h.update(s.reply[0..s.reply_len]);
+ var buf: [4096]u8 = undefined;
+ var text: std.Io.Writer.Hashing(pardes.walk.Hasher) = .initHasher(h.*, &buf);
+ if (screen.pages.getBottomRight(.active)) |br|
+ screen.dumpString(&text.writer, .{ .tl = screen.pages.getTopLeft(.active), .br = br, .unwrap = false }) catch {};
+ text.writer.flush() catch {};
+ h.* = text.hasher;
+ }
+
+ /// What the dump keeps of a terminal beside its emulator, by name as
+ /// every dump is (src/walk.zig).
+ const Parts = struct {
+ reply: []const u8 = "",
+ reply_dropped: u32 = 0,
+ mouse_cell: ?ghostty_vt.Coordinate = null,
+ petscii: bool = false,
+ /// The view's top row, counted from the top of the history.
+ view: usize = 0,
+ phase: @FieldType(MarkedHandler, "phase") = .none,
+ started: u32 = 0,
+ prompts: u32 = 0,
+ declined: u32 = 0,
+ continuation: bool = false,
+ lost: bool = false,
+ finished: @FieldType(MarkedHandler, "finished") = null,
+ out_start: ?ghostty_vt.Coordinate = null,
+ out_end: ?ghostty_vt.Coordinate = null,
+ };
+
+ fn pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?ghostty_vt.Coordinate {
+ const pin = slot orelse return null;
+ const screen = s.vt.screens.get(.primary) orelse return null;
+ return (screen.pages.pointFromPin(.screen, pin.*) orelse return null).screen;
+ }
+
+ /// The dump's: ghostty's snapshot of the emulator (both screens, their
+ /// history, styles, links and kitty images), then `Parts`. A sequence
+ /// its program had begun and not ended is not kept: the snapshot is at
+ /// the ground state.
+ pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void {
+ if (comptime !enabled) return;
+ const h = &s.stream.handler;
+ const parts: Parts = .{
+ .reply = s.reply[0..s.reply_len],
+ .reply_dropped = s.reply_dropped,
+ .mouse_cell = s.mouse_cell,
+ .petscii = if (comptime images_enabled) s.images.petscii else false,
+ .view = s.vt.screens.active.pages.scrollbar().offset,
+ .phase = h.phase,
+ .started = h.started,
+ .prompts = h.prompts,
+ .declined = h.declined,
+ .continuation = h.continuation,
+ .lost = h.lost,
+ .finished = h.finished,
+ .out_start = s.pinAt(h.out_start),
+ .out_end = s.pinAt(h.out_end),
+ };
+ const bytes = try pardes.walk.save(Parts, gpa, &parts);
+ defer gpa.free(bytes);
+ try w.writeAll(std.mem.asBytes(&@as(u64, bytes.len)));
+ try w.writeAll(bytes);
+ // A join's (dump.zig `dumpJoin`): its size alone, an emulator made
+ // afresh there, which its first delta replaces.
+ if (pardes.dump.slim_terminals) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows }));
+ try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground });
+ }
+
+ /// What `dumpRead` made, freed: a load that failed after it.
+ pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void {
+ if (comptime !enabled) return;
+ if (comptime images_enabled) s.images.deinit(gpa);
+ s.stream.deinit();
+ s.vt.deinit(gpa);
+ }
+
+ /// `dumpWrite`'s back into `out`, a new State, as `create` makes one.
+ pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void {
+ if (comptime !enabled) {
+ out.* = .{ .vt = {}, .stream = {} };
+ return;
+ }
+ if (bytes.len < 8) return error.EndOfDump;
+ const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump;
+ if (bytes.len - 8 < n) return error.EndOfDump;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const parts = try pardes.walk.load(Parts, arena.allocator(), bytes[8..][0..n], null);
+ var reader: std.Io.Reader = .fixed(bytes[8 + n ..]);
+ if (reader.buffer.len == 4) {
+ const size = std.mem.bytesToValue([2]u16, bytes[8 + n ..][0..4]);
+ out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined };
+ } else {
+ var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{
+ .max_continuation_bytes = 0,
+ .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0,
+ });
+ defer decoded.deinit(gpa);
+ out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined };
+ }
+ if (comptime images_enabled) inline for (.{ .primary, .alternate }) |key| {
+ if (out.vt.screens.get(key)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir());
+ };
+ out.stream = .init(.{ .handler = .{ .inner = out.vt.vtHandler() }, .allocator = gpa });
+ out.stream.handler.inner.effects.write_pty = ptyReport;
+ out.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs;
+ out.stream.handler.inner.effects.size = ptySize;
+ const reply = parts.reply[0..@min(parts.reply.len, out.reply.len)];
+ @memcpy(out.reply[0..reply.len], reply);
+ out.reply_len = @intCast(reply.len);
+ out.reply_dropped = parts.reply_dropped;
+ out.mouse_cell = parts.mouse_cell;
+ out.images = if (images_enabled) .{ .petscii = parts.petscii } else {};
+ if (comptime images_enabled) TerminalImages.installPngDecoder();
+ const h = &out.stream.handler;
+ h.phase = parts.phase;
+ h.started = parts.started;
+ h.prompts = parts.prompts;
+ h.declined = parts.declined;
+ h.continuation = parts.continuation;
+ h.lost = parts.lost;
+ h.finished = parts.finished;
+ if (out.vt.screens.get(.primary)) |screen| {
+ inline for (.{ .{ "out_start", parts.out_start }, .{ "out_end", parts.out_end } }) |pair| if (pair[1]) |at| {
+ if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null;
+ };
+ }
+ const screen = out.vt.screens.active;
+ const bottom = screen.pages.scrollbar().offset;
+ screen.scroll(.{ .delta_row = @as(isize, @intCast(parts.view)) - @as(isize, @intCast(bottom)) });
+ }
};
const GColor = ghostty_vt.color;
@@ -302,7 +478,7 @@ pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void {
pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void {
if (pane.pending_command.wait == .input)
- releasePendingCommand(p, id, pane, promptInputReady(pane));
+ releasePendingCommand(p, id, pane, pardes.tape.value(.prompt, promptInputReady, .{pane}));
}
fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void {
@@ -371,15 +547,118 @@ pub fn visibleCursor(pane: *const Pane) ?GridCursor {
const cur = state.vt.screens.active.cursor;
const sb = scrollbar(pane);
const row = sb.total - sb.len + cur.y;
- if (row < sb.offset or row - sb.offset >= sb.len) return null;
- return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) };
+ if (row < sb.offset + pane.pan or row - sb.offset >= sb.len) return null;
+ return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset - pane.pan) };
+}
+
+/// The rows terminal `pane`'s top is passed over by in a view whose rect
+/// `r` is shorter than it, one that does not size it (Pardes.sizes): as
+/// many as keep its cursor's row in sight, as tmux pans a bigger window in
+/// a smaller client. 0 in the view that sizes it, and in one tall enough.
+pub fn panFor(p: *const Pardes, pane: *const Pane, r: pardes.Rect) u16 {
+ if (comptime !enabled) return 0;
+ if (pane.sized_by == p.view or pane.collapsed or !pane.isTerminal()) return 0;
+ const shown = r.h -| pane.tag_rows;
+ if (shown == 0 or shown >= pane.rows) return 0;
+ const state = pane.terminal orelse return 0;
+ const sb = scrollbar(pane);
+ // The cursor's row in the viewport; past its end (scrolled back), its
+ // last row.
+ const row = sb.total - sb.len + state.vt.screens.active.cursor.y;
+ const at: usize = if (row < sb.offset) 0 else @min(row - sb.offset, pane.rows - 1);
+ return @intCast(@min(pane.rows - shown, (at + 1) -| shown));
+}
+
+/// What pardes made of a terminal's stream that its emulator does not hold
+/// (the OSC 133 cycle, MarkedHandler), for a replica's delta: phase u8,
+/// started, prompts, declined u32, continuation and lost u8, a finished
+/// command's seq u32 and status i32 (all ones: none; i32 min: no status).
+// ponytail: the output pins stay the authority's (its 9P pty/run reads them).
+pub const marks_len = 1 + 4 * 3 + 2 + 4 + 4;
+
+pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 {
+ if (comptime !enabled) return &.{};
+ const m = &state.stream.handler;
+ var w: std.Io.Writer = .fixed(buf);
+ w.writeByte(@intFromEnum(m.phase)) catch unreachable;
+ inline for (.{ m.started, m.prompts, m.declined }) |n| w.writeInt(u32, n, .little) catch unreachable;
+ w.writeAll(&.{ @intFromBool(m.continuation), @intFromBool(m.lost) }) catch unreachable;
+ w.writeInt(u32, if (m.finished) |f| f.seq else std.math.maxInt(u32), .little) catch unreachable;
+ w.writeInt(i32, if (m.finished) |f| f.status orelse std.math.minInt(i32) else 0, .little) catch unreachable;
+ return w.buffered();
+}
+
+/// A replica's terminal takes its authority's marks (`marksOf`).
+pub fn takeMarks(state: *State, bytes: []const u8) void {
+ if (comptime !enabled) return;
+ if (bytes.len != marks_len) return;
+ const m = &state.stream.handler;
+ m.phase = @enumFromInt(bytes[0]);
+ m.started = std.mem.readInt(u32, bytes[1..5], .little);
+ m.prompts = std.mem.readInt(u32, bytes[5..9], .little);
+ m.declined = std.mem.readInt(u32, bytes[9..13], .little);
+ m.continuation = bytes[13] != 0;
+ m.lost = bytes[14] != 0;
+ const seq = std.mem.readInt(u32, bytes[15..19], .little);
+ const status = std.mem.readInt(i32, bytes[19..23], .little);
+ m.finished = if (seq == std.math.maxInt(u32)) null else .{ .seq = seq, .status = if (status == std.math.minInt(i32)) null else status };
+}
+
+/// A screen-state replica's emulators' allocator (`State.gpa`).
+pub const emulator_gpa = std.heap.c_allocator;
+
+/// What a terminal's emulator is made with, by `create` or a pane's load
+/// (dump.loadPane, a closed terminal brought back): `gpa`, but on a screen-
+/// state replica `emulator_gpa`. A hosted build's: the web has no C heap.
+pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator {
+ return if (comptime pardes.hosted) (if (pardes.tape.screenReplica()) emulator_gpa else gpa) else gpa;
+}
+
+/// A replica's speculation leaves an emulator be: it is the authority's
+/// (docs/next-daemon.md, phase 5), so the input waits for its order.
+fn authorityOnly(comptime why: []const u8) bool {
+ if (!pardes.tape.speculating()) return false;
+ pardes.tape.poison(why);
+ return true;
+}
+
+/// A speculation that moves a terminal's view: a screen-state replica's
+/// may (its rollback puts the view back, replica.zig `views`, and a delta
+/// sets it), any other stops (`authorityOnly`).
+fn viewOnly(comptime why: []const u8) bool {
+ if (!pardes.tape.speculating()) return false;
+ if (pardes.tape.screenState()) {
+ pardes.tape.touchTerminal();
+ return false;
+ }
+ pardes.tape.poison(why);
+ return true;
+}
+
+/// Where a terminal's view is: its top row counted from the top of its
+/// history, or null following its output (a replica's rollback copy,
+/// which holds no emulator, keeps it so).
+pub fn viewOf(pane: *const Pane) ?usize {
+ if (comptime !enabled) return null;
+ const state = pane.terminal orelse return null;
+ const pages = &state.vt.screens.active.pages;
+ if (pages.viewport == .active) return null;
+ return pages.scrollbar().offset;
+}
+
+pub fn viewTo(pane: *Pane, at: ?usize) void {
+ if (comptime !enabled) return;
+ const state = pane.terminal orelse return;
+ state.vt.screens.active.scroll(if (at) |row| .{ .row = row } else .active);
}
/// Move the emulator's viewport by `delta` shell rows (negative scrolls back).
pub fn scrollGrid(pane: *Pane, delta: i32) void {
if (comptime !enabled) return;
+ if (viewOnly("scroll a terminal")) return;
const state = pane.terminal orelse return;
state.vt.screens.active.scroll(.{ .delta_row = delta });
+ state.changes +%= 1;
}
/// Is the viewport already showing the last row of output?
@@ -392,20 +671,47 @@ pub fn atBottom(pane: *const Pane) bool {
/// Snap the viewport back onto live output.
pub fn followOutput(pane: *Pane) void {
if (comptime !enabled) return;
+ if (viewOnly("follow a terminal")) return;
const state = pane.terminal orelse return;
+ const moved = state.vt.screens.active.pages.viewport != .active;
state.vt.screens.active.scroll(.active);
+ state.changes +%= @intFromBool(moved);
}
/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping
/// a scrollback; the next resize retries with the same numbers.
pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void {
if (comptime !enabled) return;
+ if (authorityOnly("resize a terminal")) return;
const state = pane.terminal orelse return;
if (cols != pane.cols) for (0..pane.sel.len) |button| {
pane.clearPointerSelection(button);
pane.sel[button].state = .none;
};
- state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {};
+ // A replica's emulator is sized by its authority: the next delta says.
+ if (pardes.tape.screenReplica()) return;
+ // ...and the authority's once the step's unit is out (a client typing
+ // at another size than the last typist's read history rows its replay
+ // held as holes, and the rows came renumbered, 2026-10-30).
+ if (pardes.tape.screenAuthority()) {
+ state.resize_to = .{ .cols = cols, .rows = rows };
+ return;
+ }
+ state.changes +%= 1;
+ _ = gpa;
+ state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {};
+}
+
+/// The sizes steps gave terminals (`resizeGrid`), made: between units, on an
+/// authority with screen-state replicas (replica.Peers.unit).
+pub fn resizeDeferred(p: *Pardes) void {
+ if (comptime !enabled) return;
+ for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| if (state.resize_to) |size| {
+ state.resize_to = null;
+ state.changes +%= 1;
+ p.shell_rows.markStale(pane);
+ state.vt.resize(state.gpa, .{ .cols = size.cols, .rows = size.rows }) catch {};
+ };
}
/// DECSET 2004: the program wants its pastes bracketed.
@@ -601,23 +907,21 @@ pub fn screenTextLen(pane: *Pane) usize {
/// Release the emulator's heap. The Pane allocation itself is the core's.
pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void {
if (comptime !enabled) return;
+ // A pane with none (a file's, a picker's, a preview's) closes in a
+ // speculation as anywhere.
const state = pane.terminal orelse return;
+ if (authorityOnly("close a terminal")) return;
if (comptime images_enabled) state.images.deinit(gpa);
state.stream.deinit();
- state.vt.deinit(gpa);
- gpa.destroy(state);
+ const own = state.gpa;
+ state.vt.deinit(own);
+ own.destroy(state);
pane.terminal = null;
}
-/// Allocate the live emulator half of a terminal pane. Slot ownership, serial
-/// assignment, and spawn effects remain core lifecycle invariants.
-pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane {
- const pane = try createDoc(gpa, cols, rows);
- errdefer gpa.destroy(pane);
- if (comptime !enabled) return pane;
- const state = try gpa.create(State);
- errdefer gpa.destroy(state);
- state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{
+/// A terminal pane's emulator, `cols` by `rows`, as `create` makes one.
+fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal {
+ return ghostty_vt.Terminal.init(terminalIo(), gpa, .{
.cols = cols,
.rows = rows,
.max_scrollback_bytes = 16 * 1024 * 1024,
@@ -628,10 +932,30 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane {
// defaults to direct alone, which `kitten icat` and timg detect and
// fall back from, base64 through the pty. What the program can read
// it could send itself: it runs as the user, under pardes.
- .kitty_image_loading_limits = if (images_enabled) .allWithTempDir(tempDir()) else .direct,
+ .kitty_image_loading_limits = if (images_enabled) .allWithTempDir(tempDir()) else if (@FieldType(ghostty_vt.Terminal.Options, "kitty_image_loading_limits") == void) {} else .direct,
});
- state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa });
+}
+
+/// Allocate the live emulator half of a terminal pane. Slot ownership, serial
+/// assignment, and spawn effects remain core lifecycle invariants.
+pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane {
+ if (authorityOnly("open a terminal")) return error.OutOfMemory;
+ const pane = try createDoc(gpa, cols, rows);
+ errdefer gpa.destroy(pane);
+ if (comptime !enabled) return pane;
+ const own = emulatorGpa(gpa);
+ const state = try own.create(State);
+ errdefer own.destroy(state);
+ state.gpa = own;
+ state.vt = try emulator(own, cols, rows);
+ state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = own });
state.reply_len = 0;
+ state.changes = 0;
+ state.read = false;
+ state.resize_to = null;
+ // Every field its default (create leaves them what the heap had, which
+ // a digest then reads: two replicas must agree, src/replica.zig).
+ state.reply_dropped = 0;
state.mouse_cell = null;
state.images = if (images_enabled) .{} else {};
if (comptime images_enabled) TerminalImages.installPngDecoder();
@@ -656,48 +980,35 @@ pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane {
/// Where a restored terminal's history ends and its new shell begins.
pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n";
-/// Rebuild a dump's terminal emulator from its recorded output. `live`: a
-/// shell will be spawned into it, so the history is marked off from what
-/// that shell prints and the pane waits for it like any new terminal.
-/// Registration and tag/cwd policy stay with the core; raw VT replay and
-/// viewport restoration belong here.
-pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane {
- const terminal = src.terminal.?;
- if (comptime !enabled) {
- const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows));
- errdefer p.gpa.destroy(pane);
- if (terminal.stream.len > 0)
- pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) };
- return pane;
- }
- const bytes = if (terminal.stream_b64.len > 0)
- try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64)
- else
- &.{};
- const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows));
- if (live) {
- if (bytes.len > 0) {
- ingest(pane, bytes);
- ingest(pane, restored_banner);
- }
- followOutput(pane);
- // A view left scrolled back stays on what it was showing: the
- // banner's line breaks scrolled a full screen by that many more.
- if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n"))));
- armShellSpawn(pane);
- } else if (bytes.len > 0) {
- ingest(pane, bytes);
- followOutput(pane);
- if (src.scroll > 0)
- scrollGrid(pane, -@as(i32, @intCast(src.scroll)));
- }
- return pane;
+/// A terminal loaded from a dump, its shell not there, made ready for a new
+/// one: its program's screen modes reset (the old program is gone), its
+/// history marked off from what the new shell prints, and the pane waiting
+/// for it like any new terminal (a line queued for the old one goes to it).
+pub fn reviveShell(pane: *Pane) void {
+ if (comptime !enabled) return;
+ if (pane.terminal == null) return;
+ // The primary screen, keys, cursor and mouse as a shell starts with
+ // them, the cursor where it was (a soft reset, or leaving a primary
+ // screen for itself, would take it home).
+ if (pane.terminal.?.vt.screens.active_key == .alternate) ingest(pane, "\x1b[?1049l");
+ ingest(pane, "\x1b[?1l\x1b>\x1b[?25h\x1b[?7h\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[<u");
+ ingest(pane, restored_banner);
+ // What the old shell was, ran and said is gone with it: the REPL it
+ // ran, the Tty+ word naming it.
+ pane.shell_spoke = false;
+ pane.had_shell = false;
+ pane.shell_failed = false;
+ pane.shell_tail_len = 0;
+ pane.repl = null;
+ pane.sent_command = null;
+ pane.pending_command.wait = .spawn;
}
/// Feed the emulator. Live output and restoration share this byte path,
/// then apply different views.
fn ingest(pane: *Pane, bytes: []const u8) void {
pane.terminal.?.stream.nextSlice(bytes);
+ pane.terminal.?.changes +%= 1;
}
test "replay ownership is terminal-only and construction rolls back on allocation failure" {
@@ -714,6 +1025,40 @@ test "replay ownership is terminal-only and construction rolls back on allocatio
try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true});
}
+test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" {
+ if (comptime !enabled) return error.SkipZigTest;
+ // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field
+ // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30).
+ const Filling = struct {
+ child: std.mem.Allocator,
+ fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ const ptr = self.child.rawAlloc(len, a, ra) orelse return null;
+ @memset(ptr[0..len], 0xAA);
+ return ptr;
+ }
+ fn resize(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ return self.child.rawResize(buf, a, n, ra);
+ }
+ fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ return self.child.rawRemap(buf, a, n, ra);
+ }
+ fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ self.child.rawFree(buf, a, ra);
+ }
+ const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free };
+ };
+ var filling: Filling = .{ .child = std.testing.allocator };
+ const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable };
+ const pane = try create(gpa, 40, 12);
+ defer gpa.destroy(pane);
+ defer deinitEmulator(pane, gpa);
+ try std.testing.expect(pane.terminal.?.resize_to == null);
+}
+
test "document construction allocates only the pane and has inert terminal defaults" {
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 });
const allocator = failing.allocator();
@@ -764,32 +1109,32 @@ test "terminal state keeps parser fragments and sends emulator replies through i
try std.testing.expectEqual(@as(u16, 0), state.reply_len);
}
-test "a terminal stream restores the cells it drew" {
+test "a terminal's dump restores the cells it drew, its history and where its view was" {
if (comptime !enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();
while (p.nextEffect()) |_| {}
const pane = p.panes[0].?;
- const drawn = "\x1b[31mred\x1b[0m\r\ncafé\r\n";
- feedOutput(p, pane, drawn);
- const encoded = try dump.encodeBytes(gpa, drawn);
- defer gpa.free(encoded);
- const restored = try restore(p, .{
- .kind = .terminal,
- .tag = "",
- .body = "",
- .cols = pane.cols,
- .rows = pane.rows,
- .terminal = .{ .stream_b64 = encoded },
- }, false);
- defer gpa.destroy(restored);
- defer deinitEmulator(restored, gpa);
- const before = try screenTextAlloc(pane, gpa);
- defer gpa.free(before);
- const after = try screenTextAlloc(restored, gpa);
- defer gpa.free(after);
- try std.testing.expectEqualStrings(before, after);
+ feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n");
+ for (0..30) |i| {
+ var line: [16]u8 = undefined;
+ feedOutput(p, pane, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable);
+ }
+ scrollGrid(pane, -5);
+ const bytes = try pardes.walk.save(State, gpa, pane.terminal.?);
+ defer gpa.free(bytes);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const state = try gpa.create(State);
+ defer gpa.destroy(state);
+ state.* = try pardes.walk.load(State, gpa, bytes, null);
+ defer {
+ state.stream.deinit();
+ state.vt.deinit(gpa);
+ }
+ try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state));
+ try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar());
}
test "a restored command pane comes back finished, its command not run again" {
@@ -802,8 +1147,8 @@ test "a restored command pane comes back finished, its command not run again" {
_ = try p.newCommand(cmd, "/tmp", "make test");
feedOutput(p, p.panes[cmd].?, "ok\r\n");
p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } });
- try dump.dumpState(p);
- const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?);
+ try pardes.dump.dumpState(p);
+ const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?);
defer restored.deinit();
var spawns: usize = 0;
while (restored.nextEffect()) |effect| switch (effect) {
@@ -832,8 +1177,8 @@ test "a restored terminal keeps its history above a marker and gets a shell wher
feedOutput(p, pane, "old output\r\n$ ls\r\n");
try pane.setOwnedCwd("/tmp");
pane.shell = try gpa.dupe(u8, "bash"); // `Tty bash`: it comes back as bash
- try dump.dumpState(p);
- const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?);
+ try pardes.dump.dumpState(p);
+ const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?);
defer restored.deinit();
var spawned = false;
while (restored.nextEffect()) |effect| switch (effect) {
@@ -858,9 +1203,16 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void {
// There are no pty reads at all without an emulator to parse them into.
if (comptime !enabled) return;
if (pane.terminal == null) return;
+ if (authorityOnly("a terminal's output")) return;
const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or
pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or
pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0;
+ // 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) ingestWithPositions(pane, bytes);
+ return;
+ }
// Sticky bottom, as every other terminal does it: output drags the
// viewport down only when the viewport was already on the last row, so
// a reader scrolled back into the scrollback stays where they scrolled.
@@ -879,7 +1231,9 @@ const PositionPin = struct {
edit_row: ?i32 = null,
};
-fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin {
+fn trackRow(maybe_pages: ?*ghostty_vt.PageList, row: i32, failed: *bool) RowPin {
+ // A screen-state replica's: told by the tape, not its emulator.
+ const pages = maybe_pages orelse return .{ .offset = row };
if (row < 0) return .{ .offset = row };
const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1);
var left = pages.total_rows - 1 - bounded;
@@ -909,7 +1263,7 @@ fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 {
return 0;
}
-fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin {
+fn trackPosition(pages: ?*ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin {
var grid = target.*;
if (overlay) |edit| {
const lines: i32 = @intCast(modal.lineCount(edit.text));
@@ -928,11 +1282,24 @@ fn pointerRowCount(pane: *const Pane) usize {
return count;
}
+/// What an ingest told the positions over it (`ingestWithPositions`): each
+/// tracked row where it is after it (the spans' starts and ends, the
+/// positions, the pointer rows, in that order) and whether the program
+/// erased it, whether the screen was cleared, whether its pages lived and
+/// whether a pin could not be made. Taped: a screen-state replica, which
+/// ingests nothing, is told the authority's.
+pub const Told = struct { rows: []const i32, erased: []const bool, cleared: bool, alive: bool, failed: bool };
+
+fn told(t: Told) Told {
+ return t;
+}
+
fn ingestWithPositions(pane: *Pane, bytes: []const u8) void {
const screens = &pane.terminal.?.vt.screens;
const key = screens.active_key;
const generation = screens.generation(key);
- const pages = &screens.active.pages;
+ const replica = pardes.tape.screenReplica();
+ const pages: ?*ghostty_vt.PageList = if (replica) null else &screens.active.pages;
const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel };
var groups: [history_max * 2 + 1]Group = undefined;
groups[0] = .{
@@ -1014,31 +1381,61 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void {
}
};
} else failed = true;
- // Whether the program cleared the screen (ED 2, a switch of screens);
- // pardes reads the flag nowhere else.
- pane.terminal.?.vt.flags.dirty.clear = false;
- ingest(pane, bytes);
- const cleared = pane.terminal.?.vt.flags.dirty.clear;
- // RIS can destroy the alternate screen and every pin it owned.
- const alive = if (screens.generation(key) == generation) pages else null;
- var moved = false;
- var pointer_rows_lost = alive == null or pointer_positions == null;
- if (pointer_positions) |pins| for (pins) |position| {
- if (alive != null) if (position.row.pin) |pin| {
- if (pin.garbage) pointer_rows_lost = true;
+ var cleared = false;
+ var alive: ?*ghostty_vt.PageList = null;
+ if (!replica) {
+ // Whether the program cleared the screen (ED 2, a switch of
+ // screens); pardes reads the flag nowhere else.
+ pane.terminal.?.vt.flags.dirty.clear = false;
+ ingest(pane, bytes);
+ cleared = pane.terminal.?.vt.flags.dirty.clear;
+ // RIS can destroy the alternate screen and every pin it owned.
+ alive = if (screens.generation(key) == generation) pages else null;
+ }
+ const pointers: []PositionPin = pointer_positions orelse &.{};
+ const n = 2 * nspans + npositions + pointers.len;
+ // On the stack, as the local path never allocated here but for the
+ // pointer's rows.
+ var rows_buf: [512]i32 = undefined;
+ var erased_buf: [512]bool = undefined;
+ const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return;
+ defer if (n > rows_buf.len) pane.gpa.free(rows_after);
+ const erased_after = if (n <= erased_buf.len) erased_buf[0..n] else pane.gpa.alloc(bool, n) catch return;
+ defer if (n > erased_buf.len) pane.gpa.free(erased_after);
+ @memset(rows_after, 0);
+ @memset(erased_after, false);
+ if (!replica) {
+ var k: usize = 0;
+ for (spans[0..nspans]) |span| for ([_]RowPin{ span.start, span.end }) |rp| {
+ rows_after[k] = pinnedRow(alive, rp);
+ erased_after[k] = alive != null and rp.pin != null and rp.pin.?.garbage;
+ k += 1;
+ };
+ for ([_][]PositionPin{ positions[0..npositions], pointers }) |batch| for (batch) |position| {
+ rows_after[k] = pinnedRow(alive, position.row);
+ erased_after[k] = alive != null and position.row.pin != null and position.row.pin.?.garbage;
+ k += 1;
};
+ }
+ const after = pardes.tape.value(.positions, told, .{Told{ .rows = rows_after, .erased = erased_after, .cleared = cleared, .alive = alive != null, .failed = failed }});
+ if (after.rows.len != n or after.erased.len != n) return; // a replica its authority's states apart (diverged)
+ failed = after.failed;
+ const at_position = 2 * nspans;
+ const at_pointer = at_position + npositions;
+ var moved = false;
+ var pointer_rows_lost = !after.alive or pointer_positions == null;
+ for (0..pointers.len) |i| if (after.erased[at_pointer + i]) {
+ pointer_rows_lost = true;
};
// The program cleared the screen, or the rows the live copy stood on are
// gone (pruned, a reset): the copy goes with them, as what the program
// drew next. Kept, ghostty would move its rows to the top of what is
// left, over the program's new text.
- var copy_lost = cleared or alive == null;
- for (spans[0..nspans]) |span| {
- if (span.overlay == overlay) if (span.start.pin) |pin| if (alive != null and pin.garbage) {
- copy_lost = true;
- };
- const start = pinnedRow(alive, span.start);
- const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1);
+ var copy_lost = after.cleared or !after.alive;
+ for (spans[0..nspans], 0..) |span, i| {
+ if (span.overlay == overlay and after.erased[2 * i]) copy_lost = true;
+ const start = after.rows[2 * i];
+ const rows = @max(1, after.rows[2 * i + 1] -| start +| 1);
moved = moved or start != span.overlay.row or rows != span.overlay.rows;
span.overlay.row = start;
span.overlay.rows = rows;
@@ -1050,23 +1447,16 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void {
// The rule above for the copy holds for the selections: one whose row
// is gone (ED 3 erased its history row, which ghostty flags `garbage`)
// goes too, rather than being clamped to the top.
- const erased = struct {
- fn at(owner: ?*ghostty_vt.PageList, all: []const PositionPin, index: usize) bool {
- if (owner == null) return false;
- const pin = all[index].row.pin orelse return false;
- return pin.garbage;
- }
- }.at;
+ const erased = after.erased[at_position..];
const vsel_lost = if (vsel_at) |i|
- erased(alive, positions[0..npositions], i) or (copy_lost and positions[i].edit_row != null)
+ erased[i] or (copy_lost and positions[i].edit_row != null)
else
false;
- const msel_lost = if (msel_at) |i| erased(alive, positions[0..npositions], i) or erased(alive, positions[0..npositions], i + 1) else false;
+ const msel_lost = if (msel_at) |i| erased[i] or erased[i + 1] else false;
var sels_keep: [panes.Text.max_selections]bool = undefined;
- for (0..pane.body.nsel) |i| sels_keep[i] = !(erased(alive, positions[0..npositions], sels_at + 2 * i) or
- erased(alive, positions[0..npositions], sels_at + 2 * i + 1));
- for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| {
- var row = pinnedRow(alive, position.row);
+ for (0..pane.body.nsel) |i| sels_keep[i] = !(erased[sels_at + 2 * i] or erased[sels_at + 2 * i + 1]);
+ for ([_][]PositionPin{ positions[0..npositions], pointers }, [_]usize{ at_position, at_pointer }) |batch, first| for (batch, first..) |position, k| {
+ var row = after.rows[k];
if (position.overlay) |edit| {
if (position.edit_row) |relative| {
row = edit.row +| relative;
@@ -1508,8 +1898,14 @@ fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize {
pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 {
if (comptime !enabled) return &empty_grid;
if (pane.terminal == null) return &empty_grid;
+ pardes.tape.touchTerminal();
const c = &p.shell_rows;
- if (!c.stale and c.pane == pane) return c.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.
@@ -1670,105 +2066,12 @@ pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void {
overlay.text = new;
}
-/// The shell's screen and scrollback (the primary screen, even under a
-/// full-screen program) as VT that replays to what was shown: styled
-/// text, soft-wrapped lines rejoined so they reflow at another width.
-fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 {
- const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{};
- var out: std.Io.Writer.Allocating = .init(arena);
- try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer);
- return out.written();
-}
-/// Serialize terminal-only state; the core supplies shared pane metadata.
-pub fn dumpPane(
- pane: *Pane,
- arena: std.mem.Allocator,
- tag: []const u8,
- body: []const u8,
- scroll: usize,
-) !dump.Pane {
- if (!enabled or pane.terminal == null) {
- const text = if (pane.ovl) |overlay| overlay.text else "";
- return .{
- .kind = .terminal,
- .tag = tag,
- .body = body,
- .scroll = scroll,
- .cols = pane.cols,
- .rows = pane.rows,
- .vweight = pane.vweight,
- .collapsed = pane.collapsed,
- .terminal = .{
- .cwd = try arena.dupe(u8, pane.cwdSlice()),
- .shell = try arena.dupe(u8, pane.shell orelse ""),
- .command = try arena.dupe(u8, pane.command orelse ""),
- .status = pane.command_status,
- .stream = try arena.dupe(u8, text),
- .stream_b64 = &.{},
- .cursor = .{ .col = 0, .row = 0 },
- },
- };
- }
- const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} });
- const extra = if (pane.ovl) |overlay| overlay.text.len else 0;
- const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra));
- var len: usize = 0;
- var lines = std.mem.splitAny(u8, full, "\n");
- var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null);
- var row: i32 = 0;
- var skip: i32 = 0;
- while (lines.next()) |raw| : (row += 1) {
- // Hidden overlay rows still consume prompt pins to keep them aligned.
- const prompt = if (pane.body.mode != .tty) prompts.next() else null;
- if (skip > 0) {
- skip -= 1;
- continue;
- }
- if (row > 0) {
- stream[len] = '\n';
- len += 1;
- }
- if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) {
- @memcpy(stream[len..][0..overlay.text.len], overlay.text);
- len += overlay.text.len;
- skip = overlay.rows - 1;
- continue;
- };
- const shown = if (prompt) |pin|
- if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw
- else
- raw;
- @memcpy(stream[len..][0..shown.len], shown);
- len += shown.len;
- }
- return .{
- .kind = .terminal,
- .tag = tag,
- .body = body,
- .scroll = scroll,
- .cols = pane.cols,
- .rows = pane.rows,
- .vweight = pane.vweight,
- .collapsed = pane.collapsed,
- .terminal = .{
- .cwd = try arena.dupe(u8, pane.cwdSlice()),
- .shell = try arena.dupe(u8, pane.shell orelse ""),
- .command = try arena.dupe(u8, pane.command orelse ""),
- .status = pane.command_status,
- .stream = stream[0..len],
- .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)),
- .stream_is_screen = true,
- .petscii = petscii(pane) orelse false,
- .cursor = .{
- .col = pane.terminal.?.vt.screens.active.cursor.x,
- .row = pane.terminal.?.vt.screens.active.cursor.y,
- },
- },
- };
-}
+/// 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);
// split yields one more item than delimiters; the extra final slot is the
@@ -1862,7 +2165,7 @@ const BodyWalk = struct {
return .{
.pane = pane,
.goff = goff,
- .g = if (pane.body.mode == .tty) goff else pane.gridRow(off),
+ .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,
};
}
@@ -2116,7 +2419,7 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16
crossed = true;
const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len);
while (sb < upto) {
- const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break;
+ const ci = cellAt(pages, row_pin, gc) orelse break;
sb += dumpedBytes(row_pin, ci.cell);
gc = std.math.add(u16, gc, 1) catch break;
}
@@ -2127,7 +2430,7 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16
var covered: usize = 0;
var style: ?pardes.CellStyle = null;
while (covered < want) {
- const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break;
+ const ci = cellAt(pages, row_pin, gc) orelse break;
if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head)
style = cellStyle(p, ci, filtered, scnm);
covered += dumpedBytes(row_pin, ci.cell);
@@ -2136,7 +2439,7 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16
// spin on a row that ends in one.
if (covered == 0 and gc >= pane.cols) break;
}
- while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| {
+ while (cellAt(pages, row_pin, gc)) |t| {
if (t.cell.wide != .spacer_tail) break;
gc = std.math.add(u16, gc, 1) catch break;
}
@@ -2153,7 +2456,7 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16
var tail: ?pardes.CellStyle = null;
if (anchor.whole() or anchor.suffix > 0) {
while (sc < tw) {
- const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break;
+ const ci = cellAt(pages, row_pin, gc) orelse break;
gc = std.math.add(u16, gc, 1) catch break;
if (ci.cell.wide == .spacer_tail) continue;
const cell = s.at(tx + sc, body_y + vr);
@@ -2174,6 +2477,16 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16
}
}
+/// The cell at column `x` of the row `row` pins, as `pages.getCell` reads
+/// it, without walking from the viewport's top down to the row again: that
+/// walk, once a cell, was most of a terminal's paint (once getCell was no
+/// longer inlined, a frame of a 120x40 shell took 75 µs more).
+fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghostty_vt.PageList.Cell {
+ if (x >= pages.cols or x >= row.node.cols()) return null;
+ const rac = row.node.page().getRowAndCell(x, row.y);
+ return .{ .node = row.node, .row = rac.row, .cell = rac.cell, .row_idx = row.y, .col_idx = x };
+}
+
fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle {
const style = ci.style();
var cs: pardes.CellStyle = .{