summaryrefslogtreecommitdiff
path: root/core/term
diff options
context:
space:
mode:
Diffstat (limited to 'core/term')
-rw-r--r--core/term/TerminalImages.zig382
-rw-r--r--core/term/pager.zig363
-rw-r--r--core/term/screen_state.zig1213
-rw-r--r--core/term/term.zig164
-rw-r--r--core/term/terminal.zig1525
5 files changed, 3647 insertions, 0 deletions
diff --git a/core/term/TerminalImages.zig b/core/term/TerminalImages.zig
new file mode 100644
index 00000000..1420d9e3
--- /dev/null
+++ b/core/term/TerminalImages.zig
@@ -0,0 +1,382 @@
+//! A terminal pane's kitty graphics: the images its program sent (yazi's
+//! previews, `kitten icat`) drawn where it placed them. ghostty-vt keeps
+//! the images and placements; this reads them each frame, cuts each one
+//! into the cell rows it covers, clipped to the rows the pane shows, and
+//! hands them on as placements, each at its exact pixels: a frontend draws
+//! them, or draws them as glyph art (Art.zig), as an image pane's.
+//! Both kinds of placement are drawn: one on a cell (`a=T`/`a=p`), which
+//! moves with the text it was put on, and a virtual one (`U=1`) shown
+//! through the U+10EEEE placeholder cells the program prints.
+const std = @import("std");
+const plain = @import("plain");
+const ghostty_vt = @import("ghostty-vt");
+const zstbi = @import("zstbi");
+const wuffs = @import("wuffs");
+
+const TerminalImages = @This();
+const gfx = ghostty_vt.kitty.graphics;
+const PixelRect = plain.RectPx;
+/// Pixels one image may decode to (RGBA, 4 bytes each): checked from its
+/// header before it is decoded.
+const image_decode_pixels: usize = 64 * 1024 * 1024;
+
+/// The bytes ghostty-vt may hold for one screen's images (it evicts the
+/// oldest past this): a 4K picture in RGBA, with room for a second.
+pub const storage_limit = 64 * 1024 * 1024;
+
+/// This pane asks for its images as glyph art even where pixels could be
+/// drawn (the Petscii builtin).
+petscii: bool = false,
+/// Pixels in RGBA for images ghostty-vt holds in another format (RGB,
+/// grey): only for images on screen, dropped the frame they are not.
+converted: std.AutoHashMapUnmanaged(u32, Converted) = .empty,
+/// When the next frame of a playing animation (a=a) is due, in ms on the
+/// core's clock (`Pardes.stepped_ns`): the core wakes for it (nextWake).
+animation_due_ms: ?u64 = null,
+
+const Converted = struct { generation: u64, rgba: []u8, used: bool = true };
+
+/// One image's rectangle in the pane, in pixels from the viewport's top
+/// left corner (above or left of it is negative).
+const Rect = struct { x: i64, y: i64, w: i64, h: i64 };
+
+/// The runs of Kitty placeholder cells between two pins, one row's run at a
+/// time, as ghostty's own `kitty.graphics.unicode.placementIterator` gave
+/// them before it moved into its RenderState, which pardes does not keep.
+const PlaceholderRuns = struct {
+ rows: ghostty_vt.PageList.RowIterator,
+ row: ?ghostty_vt.Pin,
+ /// Where the scan of `row` resumes: a run ended by an incompatible
+ /// placeholder starts the next one there.
+ x: usize = 0,
+
+ fn init(top: ghostty_vt.Pin, bottom: ghostty_vt.Pin) PlaceholderRuns {
+ var rows = top.rowIterator(.right_down, bottom);
+ const row = rows.next();
+ return .{ .rows = rows, .row = row };
+ }
+
+ fn next(self: *PlaceholderRuns) ?gfx.unicode.Placement {
+ while (self.row) |row| {
+ if (!row.rowAndCell().row.kitty_virtual_placeholder) {
+ self.advance();
+ continue;
+ }
+ var run: ?gfx.unicode.IncompletePlacement = null;
+ var first: usize = 0;
+ const cells = row.cells(.all);
+ while (self.x < cells.len) : (self.x += 1) {
+ const cell = &cells[self.x];
+ if (cell.codepoint() != gfx.unicode.placeholder) {
+ if (run) |done| return complete(row, first, done);
+ continue;
+ }
+ const style = row.style(cell);
+ const curr: gfx.unicode.IncompletePlacement = .init(&style, row.grapheme(cell) orelse &.{});
+ if (run) |*prev| {
+ if (!prev.append(&curr)) return complete(row, first, prev.*);
+ } else {
+ run = curr.start();
+ first = self.x;
+ }
+ }
+ self.advance();
+ if (run) |done| return complete(row, first, done);
+ }
+ return null;
+ }
+
+ fn advance(self: *PlaceholderRuns) void {
+ self.row = self.rows.next();
+ self.x = 0;
+ }
+
+ fn complete(row: ghostty_vt.Pin, x: usize, run: gfx.unicode.IncompletePlacement) gfx.unicode.Placement {
+ var pin = row;
+ pin.x = @intCast(x);
+ return .{
+ .pin = pin,
+ .image_id = run.imageId(),
+ .placement_id = run.placement_id orelse 0,
+ .col = run.col.?,
+ .row = run.row.?,
+ .width = run.width,
+ .height = 1,
+ };
+ }
+};
+
+pub fn deinit(ti: *TerminalImages, gpa: std.mem.Allocator) void {
+ var conv = ti.converted.valueIterator();
+ while (conv.next()) |c| gpa.free(c.rgba);
+ ti.converted.deinit(gpa);
+}
+
+/// Accept PNG (`f=100`) as well as raw pixels: ghostty-vt built as a
+/// library decodes none itself. wuffs does it (ghostty's, linked for it).
+pub fn installPngDecoder() void {
+ ghostty_vt.sys.decode_png = &decodePng;
+}
+
+/// The longest side a PNG is kept at: a pane is at most a screenful of
+/// cells, and a multi-thousand-pixel picture only costs its memory.
+const max_dim: u32 = 1280;
+
+/// stb_image_resize has its allocator (`start`): before, a PNG is refused.
+var started = false;
+
+/// Once at startup and exit, with what the resize allocates from.
+pub fn start(gpa: std.mem.Allocator) void {
+ // Refused only when started twice with a resize still alive: PNGs then stay refused.
+ zstbi.init(gpa) catch return;
+ started = true;
+}
+pub fn stop() void {
+ started = false;
+ zstbi.deinit();
+}
+
+fn decodePng(gpa: std.mem.Allocator, bytes: []const u8) ghostty_vt.sys.DecodeError!ghostty_vt.sys.Image {
+ if (!started) return error.InvalidData;
+ // Bounded before decoding: a few KB of PNG can name gigapixels. The
+ // signature, then IHDR first: its length, type, width and height.
+ if (bytes.len < 24 or !std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n") or !std.mem.eql(u8, bytes[12..16], "IHDR")) return error.InvalidData;
+ const w = std.mem.readInt(u32, bytes[16..20], .big);
+ const h = std.mem.readInt(u32, bytes[20..24], .big);
+ if (@as(u64, w) * h > image_decode_pixels) return error.InvalidData;
+ const got = wuffs.png.decode(gpa, bytes) catch return error.InvalidData;
+ if (got.data.len != @as(usize, got.width) * got.height * 4) {
+ gpa.free(got.data);
+ return error.InvalidData;
+ }
+ const longest = @max(got.width, got.height);
+ if (longest <= max_dim) return .{ .width = got.width, .height = got.height, .data = got.data };
+ defer gpa.free(got.data);
+ const img: zstbi.Image = .{ .data = got.data, .width = got.width, .height = got.height, .num_components = 4, .bytes_per_component = 1, .bytes_per_row = got.width * 4, .is_hdr = false };
+ var scaled = img.resize(@intCast(@max(1, @as(u64, got.width) * max_dim / longest)), @intCast(@max(1, @as(u64, got.height) * max_dim / longest))) catch return error.InvalidData;
+ defer scaled.deinit();
+ return .{ .width = scaled.width, .height = scaled.height, .data = gpa.dupe(u8, scaled.data) catch return error.InvalidData };
+}
+
+/// Draw the active screen's images. `rows_of[v]` is the body row the
+/// viewport's row `v` is shown on, if it is shown; `cols` how many of its
+/// columns the body shows, from `tx`.
+pub fn draw(
+ ti: *TerminalImages,
+ gpa: std.mem.Allocator,
+ vt: *ghostty_vt.Terminal,
+ where: plain.term.ImagesAt,
+ rows_of: []const ?u16,
+ out: *std.ArrayList(plain.Placement),
+ frame: []plain.Cell,
+ frame_cols: u16,
+) void {
+ var conv = ti.converted.valueIterator();
+ while (conv.next()) |c| c.used = false;
+ defer ti.prune(gpa);
+
+ const screen = vt.screens.active;
+ const storage = &screen.kitty_images;
+ // Animations step on the core's clock, as this frame shows them; the
+ // shown frame is `renderData()` (a new `generation` each step, which
+ // the caches key on).
+ const now_ms = where.now_ms;
+ ti.animation_due_ms = if (storage.animationTick(vt.io(), now_ms)) |delay| now_ms +| delay else null;
+ const pages = &screen.pages;
+ const top = pages.getTopLeft(.viewport);
+ const bottom = pages.getBottomRight(.viewport) orelse return;
+ const cw: u32 = @max(1, where.cell_w);
+ const ch: u32 = @max(1, where.cell_h);
+ const ctx: Ctx = .{ .ti = ti, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch };
+ // Handed on lowest z first (the storage's order is a hash map's), the
+ // order a shell draws them in; equal z keeps the order they came in.
+ const first = out.items.len;
+ defer std.sort.insertion(plain.Placement, out.items[first..], {}, struct {
+ fn lessThan(_: void, a: plain.Placement, b: plain.Placement) bool {
+ return a.z < b.z;
+ }
+ }.lessThan);
+
+ // Virtual placements: shown through the placeholder cells, one run of
+ // them on a row at a time. The placeholders themselves are not text.
+ var runs: PlaceholderRuns = .init(top, bottom);
+ while (runs.next()) |run| {
+ const at = pages.pointFromPin(.viewport, run.pin) orelse continue;
+ const v = at.viewport.y;
+ if (v >= rows_of.len) continue;
+ const row = rows_of[v] orelse continue;
+ for (@as(usize, at.viewport.x)..@as(usize, at.viewport.x) + run.width) |x| {
+ if (x >= where.cols) break;
+ const cell = &frame[@as(usize, where.body_y + row) * frame_cols + where.tx + x];
+ cell.text[0] = ' ';
+ cell.len = 1;
+ }
+ const img = storage.imageById(run.image_id) orelse continue;
+ const target = storage.placeholderTarget(run.image_id, run.placement_id) orelse continue;
+ const rp = run.renderPlacement(&target.placement, &img, cw, ch) catch continue;
+ if (rp.dest_width == 0 or rp.dest_height == 0 or rp.source_width == 0 or rp.source_height == 0) continue;
+ ctx.place(img, target.placement.z, .{ .x = rp.source_x, .y = rp.source_y, .w = rp.source_width, .h = rp.source_height }, .{
+ .x = @as(i64, at.viewport.x) * cw + rp.offset_x,
+ .y = @as(i64, v) * ch + rp.offset_y,
+ .w = rp.dest_width,
+ .h = rp.dest_height,
+ });
+ }
+
+ // Placements on a cell: they move with the text they were put on, and
+ // go where it goes, above the viewport or off the screen.
+ const origin = pages.pointFromPin(.screen, top) orelse return;
+ var it = storage.placements.iterator();
+ while (it.next()) |entry| {
+ const placed = entry.value_ptr.*;
+ // A placement relative to another (P=/Q=) sits at its chain's root
+ // plus the chain's cell offsets (H=/V=), as ghostty's renderer puts it.
+ var dx: i64 = 0;
+ var dy: i64 = 0;
+ const pin = switch (placed.location) {
+ .pin => |pin| pin,
+ .virtual => continue,
+ .relative => |rel| root: {
+ const chain = storage.resolveChain(rel) orelse continue;
+ dx = chain.horizontal_offset;
+ dy = chain.vertical_offset;
+ break :root switch (chain.root.location) {
+ .pin => |pin| pin,
+ // ponytail: a chain rooted on a virtual placement (shown
+ // through placeholders) is not drawn; ghostty anchors it at
+ // the placeholder run.
+ .virtual, .relative => continue,
+ };
+ },
+ };
+ const img = storage.images.get(entry.key_ptr.image_id) orelse continue;
+ const at = pages.pointFromPin(.screen, pin.*) orelse continue;
+ const size = placed.pixelSize(img, vt);
+ const sx = @min(placed.source_x, img.width);
+ const sy = @min(placed.source_y, img.height);
+ const sw = if (placed.source_width > 0) @min(placed.source_width, img.width - sx) else img.width - sx;
+ const sh = if (placed.source_height > 0) @min(placed.source_height, img.height - sy) else img.height - sy;
+ if (size.width == 0 or size.height == 0 or sw == 0 or sh == 0) continue;
+ ctx.place(img, placed.z, .{ .x = sx, .y = sy, .w = sw, .h = sh }, .{
+ .x = (@as(i64, at.screen.x) + dx) * cw + placed.x_offset,
+ .y = (@as(i64, at.screen.y) - @as(i64, origin.screen.y) + dy) * ch + placed.y_offset,
+ .w = size.width,
+ .h = size.height,
+ });
+ }
+}
+
+const Ctx = struct {
+ ti: *TerminalImages,
+ gpa: std.mem.Allocator,
+ out: *std.ArrayList(plain.Placement),
+ pane: u8,
+ serial: u32,
+ tx: u16,
+ body_y: u16,
+ cols: u16,
+ rows_of: []const ?u16,
+ cw: u32,
+ ch: u32,
+
+ /// Draw `src` of `img` over `dst`, one cell row of it at a time: a row
+ /// is shown, or not, or shown elsewhere, as the body lays it out.
+ fn place(ctx: Ctx, img: gfx.Image, z: i32, src: PixelRect, dst: Rect) void {
+ const cw: i64 = ctx.cw;
+ const ch: i64 = ctx.ch;
+ const x0 = @max(dst.x, 0);
+ const x1 = @min(dst.x + dst.w, @as(i64, ctx.cols) * cw);
+ if (x1 <= x0) return;
+ const rgba = ctx.ti.pixelsOf(ctx.gpa, img) orelse return;
+ const first_row = @divFloor(@max(dst.y, 0), ch);
+ const last_row = @min(@divFloor(dst.y + dst.h - 1, ch), @as(i64, @intCast(ctx.rows_of.len)) - 1);
+ var v = first_row;
+ while (v <= last_row) : (v += 1) {
+ const row = ctx.rows_of[@intCast(v)] orelse continue;
+ const y0 = @max(dst.y, v * ch);
+ const y1 = @min(dst.y + dst.h, (v + 1) * ch);
+ if (y1 <= y0) continue;
+ // The source pixels under this piece, by the same scale.
+ const piece: PixelRect = .{
+ .x = src.x + @as(u32, @intCast(@divFloor((x0 - dst.x) * src.w, dst.w))),
+ .y = src.y + @as(u32, @intCast(@divFloor((y0 - dst.y) * src.h, dst.h))),
+ .w = @max(1, @as(u32, @intCast(@divFloor((x1 - x0) * src.w, dst.w)))),
+ .h = @max(1, @as(u32, @intCast(@divFloor((y1 - y0) * src.h, dst.h)))),
+ };
+ const c0: u16 = @intCast(@divFloor(x0, cw));
+ const c1: u16 = @intCast(@divFloor(x1 + cw - 1, cw));
+ ctx.out.append(ctx.gpa, .{
+ .pane = ctx.pane,
+ .raster = .of(rgba, img.width, img.height),
+ .src = piece,
+ .dst = .{ .x = ctx.tx + c0, .y = ctx.body_y + row, .w = c1 - c0, .h = 1 },
+ .at = .{
+ .x = @intCast(x0 - @as(i64, c0) * cw),
+ .y = @intCast(y0 - v * ch),
+ .w = @intCast(x1 - x0),
+ .h = @intCast(y1 - y0),
+ },
+ .key = plain.Placement.keyOf(ctx.serial, img.id, @truncate(img.generation)),
+ .z = z,
+ .art = .{ .glyph = ctx.ti.petscii },
+ }) catch {};
+ }
+ }
+};
+
+/// The image's pixels as RGBA: its own bytes when it is held so.
+fn pixelsOf(ti: *TerminalImages, gpa: std.mem.Allocator, img: gfx.Image) ?[]const u8 {
+ const n = @as(usize, img.width) * img.height;
+ if (n == 0) return null;
+ const data = img.renderData().bytes() orelse return null;
+ if (img.format == .rgba) return if (data.len == n * 4) data else null;
+ const gop = ti.converted.getOrPut(gpa, img.id) catch return null;
+ if (gop.found_existing) {
+ if (gop.value_ptr.generation == img.generation) {
+ gop.value_ptr.used = true;
+ return gop.value_ptr.rgba;
+ }
+ gpa.free(gop.value_ptr.rgba);
+ _ = ti.converted.remove(img.id);
+ return ti.pixelsOf(gpa, img);
+ }
+ const out = convert(gpa, img, n) orelse {
+ _ = ti.converted.remove(img.id);
+ return null;
+ };
+ gop.value_ptr.* = .{ .generation = img.generation, .rgba = out };
+ return out;
+}
+
+fn convert(gpa: std.mem.Allocator, img: gfx.Image, n: usize) ?[]u8 {
+ const depth: usize = switch (img.format) {
+ .rgb => 3,
+ .gray_alpha => 2,
+ .gray => 1,
+ else => return null,
+ };
+ const data = img.renderData().bytes() orelse return null;
+ if (data.len != n * depth) return null;
+ const out = gpa.alloc(u8, n * 4) catch return null;
+ for (0..n) |i| {
+ const px = data[i * depth ..][0..depth];
+ out[i * 4 ..][0..4].* = switch (depth) {
+ 3 => .{ px[0], px[1], px[2], 255 },
+ 2 => .{ px[0], px[0], px[0], px[1] },
+ else => .{ px[0], px[0], px[0], 255 },
+ };
+ }
+ return out;
+}
+
+/// Drop what this frame did not draw: the caches hold only what is shown.
+fn prune(ti: *TerminalImages, gpa: std.mem.Allocator) void {
+ while (true) {
+ var conv = ti.converted.iterator();
+ const stale = while (conv.next()) |entry| {
+ if (!entry.value_ptr.used) break entry.key_ptr.*;
+ } else break;
+ gpa.free(ti.converted.get(stale).?.rgba);
+ _ = ti.converted.remove(stale);
+ }
+}
diff --git a/core/term/pager.zig b/core/term/pager.zig
new file mode 100644
index 00000000..0cf2ee21
--- /dev/null
+++ b/core/term/pager.zig
@@ -0,0 +1,363 @@
+//! A program's output, paged into a +Pager (`pardes -`): the text it
+//! prints, and its SGR colours as spans over that text. ghostty-vt, which
+//! terminal panes already drive, parses every escape; this keeps what is
+//! printed and how SGR styles it, and drops every other control (cursor
+//! motion, OSC titles and hyperlinks, modes). The spans are display state
+//! of the pane only: no 9P file reads them (File.recolorSyntax draws them).
+const std = @import("std");
+const plain = @import("plain");
+const CellStyle = plain.CellStyle;
+const ghostty_vt = @import("ghostty-vt");
+
+/// Bytes `start..end` of the text, drawn in `style`. A palette colour stays
+/// `.index`, resolved through the theme as it is drawn (terminal.palColor),
+/// and `.default` is the pane's own.
+pub const Span = plain.term.Span;
+
+/// ponytail: past this many spans the rest of a page is plain, rather than
+/// ~100 MB of spans for a 256 MiB coloured log; a packed style if it matters.
+pub const max_spans = 4 << 20;
+
+pub const Page = plain.term.Page;
+
+/// `raw`, a program's output for a terminal, as text and its spans. Both
+/// are `gpa`'s.
+pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Page {
+ var h: Handler = .{ .gpa = gpa };
+ errdefer h.text.deinit(gpa);
+ errdefer h.spans.deinit(gpa);
+ try h.text.ensureTotalCapacity(gpa, raw.len);
+ var stream: ghostty_vt.Stream(*Handler) = .init(.{ .handler = &h });
+ defer stream.deinit();
+ stream.nextSlice(raw);
+ if (h.failed) return error.OutOfMemory;
+ const text = try h.text.toOwnedSlice(gpa);
+ errdefer gpa.free(text);
+ return .{ .text = text, .spans = try h.spans.toOwnedSlice(gpa) };
+}
+
+const Handler = struct {
+ gpa: std.mem.Allocator,
+ text: std.ArrayList(u8) = .empty,
+ spans: std.ArrayList(Span) = .empty,
+ /// What SGR has set so far.
+ style: CellStyle = .{},
+ /// Where the line being printed starts, and its last character.
+ line_start: usize = 0,
+ last: usize = 0,
+ /// A carriage return not yet followed by a newline: the line starts
+ /// over at the next print, as on a terminal, so a progress line keeps
+ /// its last state.
+ cr: bool = false,
+ /// A backspace: the next print strikes over the character before it.
+ bs: bool = false,
+ failed: bool = false,
+
+ const Action = ghostty_vt.StreamAction;
+
+ pub fn vt(h: *Handler, comptime action: Action.Tag, value: Action.Value(action)) void {
+ switch (action) {
+ .print => h.print(value.cp),
+ .print_slice => h.printRun(value.cps),
+ // CSI b repeats the last character, as a terminal draws it;
+ // a terminal stops at its edge, and this at a line's worth.
+ .print_repeat => if (h.text.items.len > h.last) {
+ const cp = std.unicode.utf8Decode(h.text.items[h.last..]) catch return;
+ for (0..@min(value, 1024)) |_| h.print(cp);
+ },
+ .set_attribute => h.attribute(value),
+ .linefeed => {
+ h.append("\n");
+ h.line_start = h.text.items.len;
+ h.last = h.line_start;
+ h.cr = false;
+ h.bs = false;
+ },
+ .carriage_return => h.cr = true,
+ .backspace => h.bs = h.text.items.len > h.line_start,
+ .horizontal_tab => for (0..@min(value, 64)) |_| h.print('\t'),
+ else => {},
+ }
+ }
+
+ pub fn deinit(_: *Handler) void {}
+
+ // ponytail: bytes that are not UTF-8 reach here as U+FFFD (ghostty's
+ // decoder replaces them, as a terminal shows them); a raw-byte pass
+ // through the stream if a +Pager must keep them.
+ fn print(h: *Handler, cp: u21) void {
+ // A control a terminal acts on and never draws: ghostty's fast path
+ // hands those past 0x0f (CAN, DEL, the C1 set) on as printed text.
+ // A tab is HT's, printed here.
+ if ((cp < 0x20 and cp != '\t') or (cp >= 0x7f and cp < 0xa0)) return;
+ if (h.cr) {
+ h.text.shrinkRetainingCapacity(h.line_start);
+ h.cut(h.line_start);
+ h.last = h.line_start;
+ h.cr = false;
+ h.bs = false;
+ }
+ var buf: [4]u8 = undefined;
+ const n = std.unicode.utf8Encode(cp, &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable;
+ if (h.bs) {
+ // A man page's overstrike: a character struck over itself is
+ // bold, one struck with `_` (either way round) is underlined;
+ // any other is replaced, as on a terminal.
+ h.bs = false;
+ const prev = h.text.items[h.last..];
+ var struck = h.style;
+ if (std.mem.eql(u8, prev, buf[0..n])) {
+ struck.bold = true;
+ } else if (std.mem.eql(u8, prev, "_")) {
+ h.text.shrinkRetainingCapacity(h.last);
+ h.append(buf[0..n]);
+ struck.ul = .single;
+ } else if (cp == '_') {
+ struck.ul = .single;
+ } else {
+ h.text.shrinkRetainingCapacity(h.last);
+ h.cut(h.last);
+ h.last = h.text.items.len;
+ h.append(buf[0..n]);
+ h.span(h.last, h.style);
+ return;
+ }
+ h.cut(h.last);
+ h.span(h.last, struck);
+ return;
+ }
+ h.last = h.text.items.len;
+ h.append(buf[0..n]);
+ h.span(h.last, h.style);
+ }
+
+ /// A run of printed characters (most of a page): the first as `print`
+ /// takes it, a pending return or backspace and all, the rest straight
+ /// on, as one span. A 256 MiB page goes through here.
+ fn printRun(h: *Handler, cps: []const u32) void {
+ if (cps.len == 0) return;
+ h.print(@intCast(cps[0]));
+ const rest = cps[1..];
+ if (rest.len == 0) return;
+ var need: usize = 0;
+ for (rest) |cp| need += if (cp < 0x80) 1 else std.unicode.utf8CodepointSequenceLength(@intCast(cp)) catch 3;
+ h.text.ensureUnusedCapacity(h.gpa, need) catch {
+ h.failed = true;
+ return;
+ };
+ const from = h.text.items.len;
+ for (rest) |cp| {
+ if (cp < 0x20 or (cp >= 0x7f and cp < 0xa0)) continue;
+ h.last = h.text.items.len;
+ if (cp < 0x80) {
+ h.text.appendAssumeCapacity(@intCast(cp));
+ continue;
+ }
+ var buf: [4]u8 = undefined;
+ const n = std.unicode.utf8Encode(@intCast(cp), &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable;
+ h.text.appendSliceAssumeCapacity(buf[0..n]);
+ }
+ h.span(from, h.style);
+ }
+
+ fn append(h: *Handler, bytes: []const u8) void {
+ h.text.appendSlice(h.gpa, bytes) catch {
+ h.failed = true;
+ };
+ }
+
+ /// `from` to the text's end drawn in `style`: the span before it goes
+ /// on when it ends there in the same style.
+ fn span(h: *Handler, from: usize, style: CellStyle) void {
+ if (std.meta.eql(style, CellStyle{})) return;
+ const end: u32 = @intCast(h.text.items.len);
+ if (h.spans.items.len > 0) {
+ const tail = &h.spans.items[h.spans.items.len - 1];
+ if (tail.end == from and std.meta.eql(tail.style, style)) {
+ tail.end = end;
+ return;
+ }
+ }
+ if (h.spans.items.len >= max_spans) return;
+ h.spans.append(h.gpa, .{ .start = @intCast(from), .end = end, .style = style }) catch {
+ h.failed = true;
+ };
+ }
+
+ /// No span reaches past `at` any more: the text there is gone.
+ fn cut(h: *Handler, at: usize) void {
+ while (h.spans.items.len > 0) {
+ const tail = &h.spans.items[h.spans.items.len - 1];
+ if (tail.end <= at) return;
+ if (tail.start < at) {
+ tail.end = @intCast(at);
+ return;
+ }
+ _ = h.spans.pop();
+ }
+ }
+
+ fn attribute(h: *Handler, attr: ghostty_vt.Attribute) void {
+ const s = &h.style;
+ switch (attr) {
+ .unset => s.* = .{},
+ .bold => s.bold = true,
+ // SGR 22 ends faint as well as bold.
+ .reset_bold => {
+ s.bold = false;
+ s.dim = false;
+ },
+ .faint => s.dim = true,
+ .italic => s.italic = true,
+ .reset_italic => s.italic = false,
+ // SGR's styles in a cell's order (terminal.zig checks it).
+ .underline => |u| s.ul = @enumFromInt(@intFromEnum(u)),
+ .blink => s.blink = true,
+ .reset_blink => s.blink = false,
+ .inverse => s.reverse = true,
+ .reset_inverse => s.reverse = false,
+ .invisible => s.invisible = true,
+ .reset_invisible => s.invisible = false,
+ .strikethrough => s.strikethrough = true,
+ .reset_strikethrough => s.strikethrough = false,
+ .direct_color_fg => |c| s.fg = .{ .rgb = .{ c.r, c.g, c.b } },
+ .direct_color_bg => |c| s.bg = .{ .rgb = .{ c.r, c.g, c.b } },
+ .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @backingInt(name) },
+ .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @backingInt(name) },
+ .@"256_fg" => |i| s.fg = .{ .index = i },
+ .@"256_bg" => |i| s.bg = .{ .index = i },
+ .reset_fg => s.fg = .default,
+ .reset_bg => s.bg = .default,
+ // A cell has no overline and no underline colour to take.
+ .overline, .reset_overline, .underline_color, .@"256_underline_color", .reset_underline_color, .unknown => {},
+ }
+ }
+};
+
+// ---- tests ----
+
+const testing = std.testing;
+
+/// The text `raw` pages to, and its spans as `text[start..end]=style` lines.
+fn expectPage(raw: []const u8, text: []const u8, spans: []const struct { []const u8, CellStyle }) !void {
+ const page = try parse(testing.allocator, raw);
+ defer page.deinit(testing.allocator);
+ try testing.expectEqualStrings(text, page.text);
+ for (spans, 0..) |want, i| {
+ if (i >= page.spans.len) {
+ std.debug.print("missing span {d}: \"{s}\"\n", .{ i, want[0] });
+ return error.TestExpectedEqual;
+ }
+ const got = page.spans[i];
+ try testing.expectEqualStrings(want[0], page.text[got.start..got.end]);
+ try testing.expectEqualDeep(want[1], got.style);
+ }
+ try testing.expectEqual(spans.len, page.spans.len);
+}
+
+test "git log --color: the commit line yellow, the rest plain" {
+ try expectPage(
+ "\x1b[33mcommit 0123abc\x1b[m\x1b[33m (\x1b[m\x1b[1;36mHEAD -> \x1b[m\x1b[1;32mmain\x1b[m\x1b[33m)\x1b[m\nAuthor: a <a@x>\n\n subject\n",
+ "commit 0123abc (HEAD -> main)\nAuthor: a <a@x>\n\n subject\n",
+ &.{
+ .{ "commit 0123abc (", .{ .fg = .{ .index = 3 } } },
+ .{ "HEAD -> ", .{ .fg = .{ .index = 6 }, .bold = true } },
+ .{ "main", .{ .fg = .{ .index = 2 }, .bold = true } },
+ .{ ")", .{ .fg = .{ .index = 3 } } },
+ },
+ );
+}
+
+test "ls --color=always: 01;34 directories and 01;32 executables, reset by 0 and none" {
+ try expectPage(
+ "\x1b[0m\x1b[01;34mdir\x1b[0m\n\x1b[01;32mrun.sh\x1b[0m\nplain.txt\n",
+ "dir\nrun.sh\nplain.txt\n",
+ &.{
+ .{ "dir", .{ .fg = .{ .index = 4 }, .bold = true } },
+ .{ "run.sh", .{ .fg = .{ .index = 2 }, .bold = true } },
+ },
+ );
+}
+
+test "grep --color=always: the match, the file name and the separator, and EL dropped" {
+ try expectPage(
+ "\x1b[35m\x1b[Ka.txt\x1b[m\x1b[K\x1b[36m\x1b[K:\x1b[m\x1b[Kone \x1b[01;31m\x1b[Kfoo\x1b[m\x1b[K two\n",
+ "a.txt:one foo two\n",
+ &.{
+ .{ "a.txt", .{ .fg = .{ .index = 5 } } },
+ .{ ":", .{ .fg = .{ .index = 6 } } },
+ .{ "foo", .{ .fg = .{ .index = 1 }, .bold = true } },
+ },
+ );
+}
+
+test "a man page's overstrike: bold and underline, and a stray backspace" {
+ try expectPage(
+ "N\x08NA\x08AM\x08ME\x08E _\x08u_\x08s x\x08_ a\x08b\x08\n",
+ "NAME us x b\n",
+ &.{
+ .{ "NAME", .{ .bold = true } },
+ .{ "us", .{ .ul = .single } },
+ .{ "x", .{ .ul = .single } },
+ },
+ );
+}
+
+test "truecolor, 256 colours, background, italic, faint, inverse and curly underline" {
+ try expectPage(
+ "\x1b[38;2;255;128;0mo\x1b[48;5;236mb\x1b[0;3;2mi\x1b[7mr\x1b[0;4:3mc\x1b[m.\n",
+ "obirc.\n",
+ &.{
+ .{ "o", .{ .fg = .{ .rgb = .{ 255, 128, 0 } } } },
+ .{ "b", .{ .fg = .{ .rgb = .{ 255, 128, 0 } }, .bg = .{ .index = 236 } } },
+ .{ "i", .{ .italic = true, .dim = true } },
+ .{ "r", .{ .italic = true, .dim = true, .reverse = true } },
+ .{ "c", .{ .ul = .curly } },
+ },
+ );
+}
+
+test "every other escape is dropped, and a stray or broken one loses no text after it" {
+ const cases = [_][2][]const u8{
+ .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" },
+ .{ "\x1b]0;title\x07\x1b[2J\x1b[H\x1b[?1049hdone\n", "done\n" },
+ .{ "\x1b(Bdone", "done" },
+ .{ "plain\ttext\n", "plain\ttext\n" },
+ .{ "a\r\nb\r\n", "a\nb\n" },
+ .{ "10%\r50%\r\x1b[K100%\ndone\n", "100%\ndone\n" },
+ .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" },
+ // Controls ghostty's fast path prints: CAN, FS, DEL and a C1.
+ .{ "x\x18y\x1cz\x7f!\u{85}?\n", "xyz!?\n" },
+ // A broken CSI: its parameter bytes are eaten up to a final byte, as
+ // a terminal eats them; CAN abandons one, and the text goes on.
+ .{ "a\x1b[31;\x18b\x1b[m\n", "ab\n" },
+ // An unknown SGR changes nothing; an ESC at the very end is dropped.
+ .{ "\x1b[99mz\x1b", "z" },
+ };
+ for (cases) |c| try expectPage(c[0], c[1], &.{});
+}
+
+test "bytes that are not UTF-8 page as U+FFFD, the text around them kept" {
+ try expectPage("caf\xe9 \xff\xfe ok\n", "caf\u{fffd} \u{fffd}\u{fffd} ok\n", &.{});
+}
+
+test "a carriage return's rewrite takes the spans of what it rewrote with it" {
+ try expectPage("\x1b[31m10%\r\x1b[32m100%\x1b[m\n", "100%\n", &.{.{ "100%", .{ .fg = .{ .index = 2 } } }});
+}
+
+test "colon colours, an 8-bit CSI, REP, CHT, CNL, a colour short of its values and UTF-8 cut short" {
+ try expectPage("\x1b[38:2::1:2:3mx\x1b[48:5:7my\x1b[m", "xy", &.{
+ .{ "x", .{ .fg = .{ .rgb = .{ 1, 2, 3 } } } },
+ .{ "y", .{ .fg = .{ .rgb = .{ 1, 2, 3 } }, .bg = .{ .index = 7 } } },
+ });
+ // 0x9b in text is a stray byte, U+FFFD; in a sequence (after ESC
+ // here) it is CSI; as UTF-8 (C2 9B) it is a C1 control, dropped.
+ try expectPage("x\x9b\x1b\x9b31mr\xc2\x9b32mg", "x\u{fffd}r32mg", &.{.{ "r32mg", .{ .fg = .{ .index = 1 } } }});
+ // REP and CHT go on along the line; CNL returns, and `d` starts it over.
+ try expectPage("ab\x1b[3b\x1b[2Ic\n", "abbbb\t\tc\n", &.{});
+ try expectPage("ab\x1b[Ed\n", "d\n", &.{});
+ // 38;5 with no index: 38 is unknown and 5 is blink.
+ try expectPage("\x1b[38;5mx", "x", &.{.{ "x", .{ .blink = true } }});
+ try expectPage("ok\xe2\x82", "ok", &.{});
+ try expectPage("\xe2\x82x", "\u{fffd}x", &.{});
+}
diff --git a/core/term/screen_state.zig b/core/term/screen_state.zig
new file mode 100644
index 00000000..ec72a841
--- /dev/null
+++ b/core/term/screen_state.zig
@@ -0,0 +1,1213 @@
+//! Screen-state terminals (docs/next-daemon.md, "Terminals cross as
+//! authoritative screen state", phase 5). A replica is sent a terminal's
+//! state, never its pty's bytes, so a `cat` of a gigabyte costs it screens.
+//!
+//! The authority encodes a delta for one peer: a header (the cursor, the
+//! active area's first row as an absolute row, the history's extent), the
+//! content address of the terminal-wide state, the content address of each
+//! row of the active area, and the blobs behind the addresses the peer does
+//! not hold. Both kinds of blob are ghostty's own snapshot records, so they
+//! cross exactly: the terminal-wide state is a TERMINAL record (modes,
+//! colours, title, tab stops...), and a row is the PAGE record of a one-row
+//! page (its styles, graphemes, hyperlinks, wide cells, wrap and prompt
+//! marks). A row's address is a hash of what the row shows, not of its blob,
+//! whose style ids are its source page's. An unchanged row costs 8 bytes.
+//!
+//! Each state the authority sends is a version of its terminal (`Track`),
+//! made once whatever the number of peers. A peer's next delta is against
+//! the version it was last sent: the stream is ordered and loses nothing,
+//! so the peer has that one by the time it applies the next. Several are
+//! in flight (`bound`); acknowledgements free their room, and a peer at the
+//! bound gets nothing until one comes, then the newest version, the ones
+//! between skipped. Peers at the same base are sent the same bytes. A
+//! replica holds the blobs of the state it applied last and no others; a
+//! delta against another (one lost) is refused, and the peer started afresh.
+//!
+//! The replica writes each delta into a ghostty Terminal, which a replica's
+//! terminal pane draws as a local one (core/term/terminal.zig reads only that).
+//! Rows that scroll off its active area go into its history, made what the
+//! authority's are by the delta's tail (their addresses, up to a screen of
+//! them). Older ones it never saw, or saw before they last changed, are
+//! holes there, fetched by absolute row on demand (`encodeRows`,
+//! `applyRows`).
+const std = @import("std");
+const vt = @import("ghostty-vt");
+const plain = @import("plain");
+const snapshot = vt.snapshot;
+pub const Terminal = vt.Terminal;
+const Page = vt.page.Page;
+const Row = vt.page.Row;
+const Pin = vt.Pin;
+const Screen = vt.Screen;
+
+// ponytail: 64 bits: two of a million distinct rows collide about once in
+// 4*10^7 sessions; phase 6's cache, shared across sessions, wants 128.
+pub const Hash = u64;
+
+/// What a row shows, hashed: its wrap and prompt flags, and each of its
+/// first `cols` cells up to the last one that is not blank, with its style,
+/// grapheme and hyperlink by value. Not the page's style or hyperlink ids,
+/// nor its derived flags. Its width is in it: a blob is a row that wide.
+/// (A page can be wider than its terminal: ghostty narrows them lazily.)
+pub fn rowHash(page: *Page, row: *Row, cols: u16) Hash {
+ var h = std.hash.Wyhash.init(0);
+ h.update(&.{rowFlags(row)});
+ h.update(std.mem.asBytes(&cols));
+ const all = page.getCells(row);
+ const cells = all[0..@min(cols, all.len)];
+ var n = cells.len;
+ while (n > 0 and @as(u64, @bitCast(cells[n - 1])) == 0) n -= 1;
+ for (cells[0..n]) |*c| {
+ var word = c.*;
+ word.style_id = 0;
+ h.update(std.mem.asBytes(&@as(u64, @bitCast(word))));
+ if (c.style_id != 0) h.update(std.mem.asBytes(&page.styles.get(page.memory, c.style_id).hash()));
+ if (c.hasGrapheme()) h.update(std.mem.sliceAsBytes(page.lookupGrapheme(c).?));
+ if (c.hyperlink) if (page.lookupHyperlink(c)) |id|
+ h.update(std.mem.asBytes(&page.hyperlink_set.get(page.memory, id).hash(page.memory)));
+ }
+ return h.final();
+}
+
+fn rowFlags(row: *const Row) u8 {
+ return @as(u8, @intFromBool(row.wrap)) | @as(u8, @intFromBool(row.wrap_continuation)) << 1 |
+ @as(u8, @backingInt(row.semantic_prompt)) << 2;
+}
+
+/// The authority's absolute row numbers for one terminal: its primary
+/// screen's active area starts at `top`, and a row `d` above it in its
+/// history is `top - d`. Kept by a tracked pin at the last active top, so
+/// it counts the rows scrolled since. A resize renumbers (`epoch`).
+pub const Rows = struct {
+ pin: ?*Pin = null,
+ top: u64 = 0,
+ epoch: u32 = 0,
+ cols: u16 = 0,
+ rows: u16 = 0,
+
+ pub fn update(n: *Rows, t: *Terminal) !void {
+ const pages = &t.screens.get(.primary).?.pages;
+ const top = pages.getTopLeft(.active);
+ const y = pages.pointFromPin(.screen, top).?.screen.y;
+ if (n.pin) |p| {
+ if (t.cols != n.cols or t.rows != n.rows) n.epoch +%= 1;
+ // The last top was pruned away: every row the peer has is
+ // older than the oldest row here.
+ const was: ?u32 = if (p.garbage) null else if (pages.pointFromPin(.screen, p.*)) |pt| pt.screen.y else null;
+ n.top += if (was) |w| y -| w else @as(u64, y) + t.rows;
+ // A reflow (a resize to fewer columns) puts more rows above the
+ // last top than ever scrolled past it: numbered from here, the
+ // history's oldest row is still row 0 or later. A resize
+ // renumbers anyway (`epoch`), so no peer holds the old numbers.
+ n.top = @max(n.top, y);
+ p.* = top;
+ } else {
+ n.pin = try pages.trackPin(top);
+ n.top = y;
+ }
+ n.cols = t.cols;
+ n.rows = t.rows;
+ }
+
+ pub fn deinit(n: *Rows, t: *Terminal) void {
+ if (n.pin) |p| t.screens.get(.primary).?.pages.untrackPin(p);
+ n.* = .{};
+ }
+
+ /// The pin of absolute row `abs`, if the terminal still has it.
+ fn pinAt(n: *const Rows, t: *Terminal, abs: u64) ?Pin {
+ return pinOf(&t.screens.get(.primary).?.pages, n.top, abs);
+ }
+};
+
+fn pinOf(pages: *const vt.PageList, top: u64, abs: u64) ?Pin {
+ if (abs >= top) return pages.pin(.{ .active = .{ .y = std.math.cast(u32, abs - top) orelse return null } });
+ const d = std.math.cast(usize, top - abs) orelse return null;
+ return pages.getTopLeft(.active).up(d);
+}
+
+/// The authority's scratch: a one-row page each blob is copied into
+/// (fresh, so the blob holds that row's styles alone) and encoded from.
+pub const Encoder = struct {
+ gpa: std.mem.Allocator,
+ scratch: ?Page = null,
+ blob: std.Io.Writer.Allocating,
+ /// The rows a delta sends a blob for, and the addresses it lists once.
+ needed: std.ArrayList(struct { pin: Pin, hash: Hash }) = .empty,
+ listed: std.AutoHashMapUnmanaged(Hash, void) = .empty,
+ tail: std.ArrayList(Pin) = .empty,
+
+ pub fn init(gpa: std.mem.Allocator) Encoder {
+ return .{ .gpa = gpa, .blob = .init(gpa) };
+ }
+
+ pub fn deinit(e: *Encoder) void {
+ if (e.scratch) |*s| s.deinit();
+ e.blob.deinit();
+ e.needed.deinit(e.gpa);
+ e.listed.deinit(e.gpa);
+ e.tail.deinit(e.gpa);
+ }
+
+ /// The PAGE record of `row` alone, its first `cols` cells.
+ fn rowBlob(e: *Encoder, page: *Page, row: *Row, cols: u16, w: *std.Io.Writer) !void {
+ var cap: vt.page.Capacity = if (e.scratch) |s| s.capacity else .{ .cols = cols, .rows = 1, .styles = 64 };
+ if (cap.cols != cols) cap = .{ .cols = cols, .rows = 1, .styles = 64 };
+ for (0..16) |_| {
+ const s = try scratchPage(&e.scratch, cap);
+ s.cloneRowFrom(page, s.getRow(0), row) catch {
+ // Room for this row: everything doubled until it fits.
+ cap.styles *|= 2;
+ cap.grapheme_bytes *|= 2;
+ cap.hyperlink_bytes *|= 2;
+ cap.string_bytes *|= 2;
+ continue;
+ };
+ break;
+ } else return error.RowTooBig;
+ var rw: snapshot.record.Writer = .init(e.gpa, w);
+ defer rw.deinit();
+ try snapshot.page.encode(&e.scratch.?, &rw);
+ }
+};
+
+/// `slot`'s one-row scratch page, ready for `cap`: reused when it has that
+/// capacity, else made again.
+fn scratchPage(slot: *?Page, cap: vt.page.Capacity) !*Page {
+ if (slot.*) |*s| {
+ if (std.meta.eql(s.capacity, cap)) {
+ s.reinit();
+ return s;
+ }
+ s.deinit();
+ slot.* = null;
+ }
+ slot.* = try Page.init(cap);
+ return &slot.*.?;
+}
+
+/// Holes older than a history's oldest row are gone with it.
+fn clampHoles(holes: *std.ArrayList([2]u64), oldest: u64) void {
+ var i: usize = 0;
+ while (i < holes.items.len) {
+ const hole = &holes.items[i];
+ hole[0] = @max(hole[0], oldest);
+ if (hole[0] >= hole[1]) _ = holes.orderedRemove(i) else i += 1;
+ }
+}
+
+/// Deltas a peer may have in flight. At 207 ms and 60 frames a second about
+/// 13 are; past the bound a peer gets nothing until an acknowledgement, and
+/// then the newest state, the ones between skipped.
+pub const bound = plain.term.flight_bound;
+
+/// What a peer holds once it has a version: the addresses of its active
+/// rows and its meta. A delta against it sends no blob for these.
+const Known = struct {
+ version: u32,
+ epoch: u32,
+ top: u64,
+ addrs: std.AutoHashMapUnmanaged(Hash, void) = .empty,
+};
+
+/// One terminal as the authority numbers it, for all of its peers: each
+/// state it sends is a version, made once whatever the number of peers.
+pub const Track = struct {
+ rows: Rows = .{},
+ version: u32 = 0,
+ /// The emulator's change count the newest version was made at, and its
+ /// history's rows.
+ changes: u32 = 0,
+ history: u64 = 0,
+ /// The newest version: its active rows (pins, good while the emulator
+ /// is unchanged) and their addresses, and its meta.
+ pins: std.ArrayList(Pin) = .empty,
+ hashes: std.ArrayList(Hash) = .empty,
+ meta: std.Io.Writer.Allocating,
+ meta_hash: Hash = 0,
+ /// The newest versions, oldest first: the bases a peer's next delta may
+ /// have. A peer whose base has gone starts afresh.
+ known: std.ArrayList(Known) = .empty,
+ /// The last delta encoded, for the next peer at the same base.
+ cache: std.Io.Writer.Allocating,
+ cache_base: u32 = 0,
+ cache_version: u32 = 0,
+
+ const kept = bound + 8;
+
+ pub fn init(gpa: std.mem.Allocator) Track {
+ return .{ .meta = .init(gpa), .cache = .init(gpa) };
+ }
+
+ /// `t` is the terminal, or null when it is gone already (with its pins).
+ pub fn deinit(tr: *Track, gpa: std.mem.Allocator, t: ?*Terminal) void {
+ if (t) |term| tr.rows.deinit(term);
+ tr.pins.deinit(gpa);
+ tr.hashes.deinit(gpa);
+ tr.meta.deinit();
+ for (tr.known.items) |*k| k.addrs.deinit(gpa);
+ tr.known.deinit(gpa);
+ tr.cache.deinit();
+ }
+
+ fn find(tr: *const Track, version: u32) ?*const Known {
+ if (version == 0) return null;
+ for (tr.known.items) |*k| if (k.version == version) return if (k.epoch == tr.rows.epoch) k else null;
+ return null;
+ }
+
+ /// A version of `t` as it is now.
+ fn advance(tr: *Track, gpa: std.mem.Allocator, t: *Terminal, changes: u32) !void {
+ try tr.rows.update(t);
+ tr.version +%= 1;
+ if (tr.version == 0) tr.version = 1;
+ tr.changes = changes;
+ const primary = &t.screens.get(.primary).?.pages;
+ tr.history = primary.total_rows - primary.rows;
+ tr.meta.clearRetainingCapacity();
+ {
+ var rw: snapshot.record.Writer = .init(gpa, &tr.meta.writer);
+ defer rw.deinit();
+ try snapshot.terminal.encode(t, &rw);
+ }
+ tr.meta_hash = std.hash.Wyhash.hash(0, tr.meta.written());
+ tr.pins.clearRetainingCapacity();
+ tr.hashes.clearRetainingCapacity();
+ var it = t.screens.active.pages.rowIterator(.right_down, .{ .active = .{} }, null);
+ while (it.next()) |p| {
+ try tr.pins.append(gpa, p);
+ try tr.hashes.append(gpa, rowHash(p.node.page(), p.rowAndCell().row, t.cols));
+ }
+ if (tr.known.items.len == kept) {
+ tr.known.items[0].addrs.deinit(gpa);
+ _ = tr.known.orderedRemove(0);
+ }
+ var k: Known = .{ .version = tr.version, .epoch = tr.rows.epoch, .top = tr.rows.top };
+ errdefer k.addrs.deinit(gpa);
+ try k.addrs.ensureTotalCapacity(gpa, @intCast(tr.hashes.items.len + 1));
+ for (tr.hashes.items) |h| k.addrs.putAssumeCapacity(h, {});
+ k.addrs.putAssumeCapacity(tr.meta_hash, {});
+ try tr.known.append(gpa, k);
+ }
+};
+
+/// What the authority knows of one peer of one terminal: a plain record
+/// both sides name (abi/term.zig), the core keeping one a peer.
+pub const Peer = plain.term.Peer;
+
+/// Its replica's holes once it applies a delta to `tr`'s newest version
+/// against `base`, as Replica.apply makes them.
+fn noteSent(peer: *Peer, gpa: std.mem.Allocator, tr: *const Track, base: ?*const Known, rows: u16) !void {
+ const top = tr.rows.top;
+ const history = tr.history;
+ if (base) |b| {
+ if (top > peer.top) {
+ const tail = @min(top -| b.top, rows, history);
+ if (top - peer.top >= @as(u64, rows) + history) {
+ peer.holes.clearRetainingCapacity();
+ if (history > tail) try peer.holes.append(gpa, .{ top - history, top - tail });
+ } else if (top - tail > peer.top) try peer.holes.append(gpa, .{ peer.top, top - tail });
+ }
+ } else {
+ peer.holes.clearRetainingCapacity();
+ if (history > 0) try peer.holes.append(gpa, .{ top - history, top });
+ }
+ peer.top = top;
+ clampHoles(&peer.holes, top -| history);
+}
+
+/// The delta's fixed header: u32 seq, u32 base (0: none, the replica
+/// starts afresh), u8 flags, u32 epoch, u64 meta, u16 cursor x and y, u8
+/// cursor style, u8 pending wrap, u8 the cursor's semantic content, the
+/// kitty keyboard flags, u64 top, u64 history rows, u64 the viewport's top
+/// as an absolute row (all ones: following the active area), u16 and the
+/// caller's extra bytes; then u16 rows and a u64 per active row, u16 and a
+/// u64 per row of the tail (those that scrolled off the active area since
+/// the base, up to a screen of them, oldest first), and a u16 blob count
+/// and each blob as u64 hash, u32 length, bytes.
+const flag_reset: u8 = 1;
+const KittyFlags = @FieldType(Screen, "kitty_keyboard");
+const following = std.math.maxInt(u64);
+
+/// The delta that takes `peer` from what it was last sent to `t` as it is,
+/// onto `out`; false (nothing written) when it has that already, or has
+/// `bound` in flight. `changes` counts the emulator's writes (a new count
+/// is a new version); `extra` rides along (the caller's own state of the
+/// terminal), the same for every peer of one version. A peer at the same
+/// base as the last one encoded is sent the same bytes.
+pub fn encode(e: *Encoder, tr: *Track, peer: *Peer, t: *Terminal, changes: u32, extra: []const u8, out: *std.Io.Writer) !bool {
+ if (tr.version == 0 or changes != tr.changes) try tr.advance(e.gpa, t, changes);
+ if (peer.sent == tr.version or peer.n == bound) return false;
+ const base = tr.find(peer.sent);
+ const base_version = if (base) |b| b.version else 0;
+ if (tr.cache_version != tr.version or tr.cache_base != base_version) {
+ tr.cache.clearRetainingCapacity();
+ try write(e, tr, base, t, extra, &tr.cache.writer);
+ tr.cache_version = tr.version;
+ tr.cache_base = base_version;
+ }
+ try out.writeAll(tr.cache.written());
+ try noteSent(peer, e.gpa, tr, base, t.rows);
+ peer.sent = tr.version;
+ peer.flight[peer.n] = tr.version;
+ peer.n += 1;
+ return true;
+}
+
+fn write(e: *Encoder, tr: *Track, base: ?*const Known, t: *Terminal, extra: []const u8, out: *std.Io.Writer) !void {
+ const gpa = e.gpa;
+ const reset = base == null;
+ const screen = t.screens.active;
+ const pages = &t.screens.get(.primary).?.pages;
+ const history = pages.total_rows - pages.rows;
+ const top = tr.rows.top;
+ try out.writeInt(u32, tr.version, .little);
+ try out.writeInt(u32, if (base) |b| b.version else 0, .little);
+ try out.writeByte(if (reset) flag_reset else 0);
+ try out.writeInt(u32, tr.rows.epoch, .little);
+ try out.writeInt(u64, tr.meta_hash, .little);
+ try out.writeInt(u16, screen.cursor.x, .little);
+ try out.writeInt(u16, screen.cursor.y, .little);
+ try out.writeByte(@backingInt(screen.cursor.cursor_style));
+ try out.writeByte(@intFromBool(screen.cursor.pending_wrap));
+ try out.writeByte(@backingInt(screen.cursor.semantic_content));
+ // ponytail: raw bytes, as the hello refuses a peer of another build.
+ try out.writeAll(std.mem.asBytes(&screen.kitty_keyboard));
+ try out.writeInt(u64, top, .little);
+ try out.writeInt(u64, history, .little);
+ try out.writeInt(u64, if (pages.viewport == .active) following else top - history + pages.scrollbar().offset, .little);
+ try out.writeInt(u16, @intCast(extra.len), .little);
+ try out.writeAll(extra);
+
+ // The active rows, then the tail: what scrolled off since the base,
+ // which may have changed after it was sent.
+ e.listed.clearRetainingCapacity();
+ e.needed.clearRetainingCapacity();
+ const tail: u16 = if (base) |b| @intCast(@min(top -| b.top, t.rows, history)) else 0;
+ e.tail.clearRetainingCapacity();
+ for (0..tail) |j| try e.tail.append(gpa, pages.getTopLeft(.active).up(tail - j).?);
+ try out.writeInt(u16, @intCast(tr.pins.items.len), .little);
+ for (tr.pins.items, tr.hashes.items) |p, h| {
+ try out.writeInt(u64, h, .little);
+ try needBlob(e, base, p, h);
+ }
+ try out.writeInt(u16, tail, .little);
+ for (e.tail.items) |p| {
+ const h = rowHash(p.node.page(), p.rowAndCell().row, t.cols);
+ try out.writeInt(u64, h, .little);
+ try needBlob(e, base, p, h);
+ }
+ const meta_new = if (base) |b| !b.addrs.contains(tr.meta_hash) else true;
+ try out.writeInt(u16, @intCast(e.needed.items.len + @intFromBool(meta_new)), .little);
+ if (meta_new) {
+ try out.writeInt(u64, tr.meta_hash, .little);
+ try out.writeInt(u32, @intCast(tr.meta.written().len), .little);
+ try out.writeAll(tr.meta.written());
+ }
+ for (e.needed.items) |need| {
+ e.blob.clearRetainingCapacity();
+ try e.rowBlob(need.pin.node.page(), need.pin.rowAndCell().row, t.cols, &e.blob.writer);
+ try out.writeInt(u64, need.hash, .little);
+ try out.writeInt(u32, @intCast(e.blob.written().len), .little);
+ try out.writeAll(e.blob.written());
+ }
+}
+
+/// A blob goes for an address the base does not hold, once.
+fn needBlob(e: *Encoder, base: ?*const Known, p: Pin, h: Hash) !void {
+ if ((try e.listed.getOrPut(e.gpa, h)).found_existing) return;
+ if (base) |b| if (b.addrs.contains(h)) return;
+ try e.needed.append(e.gpa, .{ .pin = p, .hash = h });
+}
+
+/// The primary screen's rows `[lo, hi)` the authority still has, for a
+/// replica that holds them as holes: u32 epoch, u32 blobs, each u64 hash,
+/// u32 length, bytes, then u32 rows, each u64 row and u64 hash. A blob goes
+/// once a message (a flood's rows are one).
+// ponytail: blobs once a message, not once a peer: phase 6's content cache.
+pub fn encodeRows(e: *Encoder, tr: *Track, t: *Terminal, lo: u64, hi: u64, out: *std.Io.Writer) !void {
+ try tr.rows.update(t);
+ var blobs: std.Io.Writer.Allocating = .init(e.gpa);
+ defer blobs.deinit();
+ var rows: std.Io.Writer.Allocating = .init(e.gpa);
+ defer rows.deinit();
+ e.listed.clearRetainingCapacity();
+ var nblobs: u32 = 0;
+ var nrows: u32 = 0;
+ var abs = lo;
+ // The active area is the deltas'.
+ while (abs < @min(hi, tr.rows.top)) : (abs += 1) {
+ const p = tr.rows.pinAt(t, abs) orelse continue;
+ const h = rowHash(p.node.page(), p.rowAndCell().row, t.cols);
+ try rows.writer.writeInt(u64, abs, .little);
+ try rows.writer.writeInt(u64, h, .little);
+ nrows += 1;
+ if ((try e.listed.getOrPut(e.gpa, h)).found_existing) continue;
+ e.blob.clearRetainingCapacity();
+ try e.rowBlob(p.node.page(), p.rowAndCell().row, t.cols, &e.blob.writer);
+ try blobs.writer.writeInt(u64, h, .little);
+ try blobs.writer.writeInt(u32, @intCast(e.blob.written().len), .little);
+ try blobs.writer.writeAll(e.blob.written());
+ nblobs += 1;
+ }
+ try out.writeInt(u32, tr.rows.epoch, .little);
+ try out.writeInt(u32, nblobs, .little);
+ try out.writeAll(blobs.written());
+ try out.writeInt(u32, nrows, .little);
+ try out.writeAll(rows.written());
+}
+
+/// A replica's terminal: what it was sent, written into a ghostty Terminal.
+pub const Replica = struct {
+ seq: u32 = 0,
+ epoch: u32 = 0,
+ meta: Hash = 0,
+ top: u64 = 0,
+ /// The address of each active row as the Terminal holds it, a list per
+ /// screen (primary, alternate).
+ held: [2]std.ArrayList(Hash) = .{ .empty, .empty },
+ /// The blobs of the last state applied: what the authority takes it to
+ /// hold. Owned copies.
+ blobs: std.AutoHashMapUnmanaged(Hash, []u8) = .empty,
+ /// History rows it cannot vouch for (written blank, or seen before
+ /// they last changed), `[lo, hi)` absolute, oldest first.
+ holes: std.ArrayList([2]u64) = .empty,
+ /// The one-row page each row blob is decoded into.
+ scratch: ?Page = null,
+
+ pub fn deinit(r: *Replica, gpa: std.mem.Allocator) void {
+ for (&r.held) |*h| h.deinit(gpa);
+ var it = r.blobs.valueIterator();
+ while (it.next()) |b| gpa.free(b.*);
+ r.blobs.deinit(gpa);
+ r.holes.deinit(gpa);
+ if (r.scratch) |*s| s.deinit();
+ }
+
+ pub const Applied = plain.term.Applied;
+
+ /// Write one delta into `t`: the seq to acknowledge, and the caller's
+ /// extra bytes (borrowed from `bytes`). error.BaseMismatch: the delta
+ /// is against a state this replica does not have (one was lost, or it
+ /// started afresh), so `t` is as it was and it must be sent a reset.
+ pub fn apply(r: *Replica, gpa: std.mem.Allocator, io: std.Io, t: *Terminal, bytes: []const u8) !Applied {
+ var in: std.Io.Reader = .fixed(bytes);
+ const seq = try in.takeInt(u32, .little);
+ const base = try in.takeInt(u32, .little);
+ const flags = try in.takeByte();
+ const reset = flags & flag_reset != 0;
+ if (!reset and base != r.seq) return error.BaseMismatch;
+ const epoch = try in.takeInt(u32, .little);
+ const meta = try in.takeInt(u64, .little);
+ const cx = try in.takeInt(u16, .little);
+ const cy = try in.takeInt(u16, .little);
+ const style = try in.takeByte();
+ const wrap = try in.takeByte();
+ const semantic = try in.takeByte();
+ var kitty: KittyFlags = undefined;
+ @memcpy(std.mem.asBytes(&kitty), try in.take(@sizeOf(KittyFlags)));
+ const top = try in.takeInt(u64, .little);
+ const history = try in.takeInt(u64, .little);
+ const viewport = try in.takeInt(u64, .little);
+ const extra = try in.take(try in.takeInt(u16, .little));
+ const nrows = try in.takeInt(u16, .little);
+ const hashes = try in.take(@as(usize, nrows) * 8);
+ const tail = try in.takeInt(u16, .little);
+ const tails = try in.take(@as(usize, tail) * 8);
+ // The delta's blobs, borrowed from `bytes` while it applies.
+ var fresh: std.AutoHashMapUnmanaged(Hash, []const u8) = .empty;
+ defer fresh.deinit(gpa);
+ for (0..try in.takeInt(u16, .little)) |_| {
+ const h = try in.takeInt(u64, .little);
+ try fresh.put(gpa, h, try in.take(try in.takeInt(u32, .little)));
+ }
+ const blobOf = struct {
+ fn of(rr: *Replica, f: *const std.AutoHashMapUnmanaged(Hash, []const u8), h: Hash) ![]const u8 {
+ if (f.get(h)) |b| return b;
+ if (rr.blobs.get(h)) |b| return b;
+ return error.MissingBlob;
+ }
+ }.of;
+
+ if (reset or meta != r.meta) {
+ var reader: std.Io.Reader = .fixed(try blobOf(r, &fresh, meta));
+ var next = try snapshot.terminal.decode(&reader, try snapshot.record.nextHeader(&reader), io, gpa);
+ if (reset) {
+ std.mem.swap(Terminal, t, &next);
+ next.deinit(gpa);
+ for (&r.held) |*h| h.clearRetainingCapacity();
+ r.holes.clearRetainingCapacity();
+ r.top = top;
+ r.epoch = epoch;
+ // The authority's history, blank, to be fetched. Its own
+ // limit is the authority's row count (below), not bytes:
+ // its pages may pack rows otherwise.
+ const primary = t.screens.get(.primary).?;
+ primary.pages.setMaxBytes(null);
+ try scrollUp(primary, history);
+ if (history > 0) try r.holes.append(gpa, .{ top -| history, top });
+ } else {
+ defer next.deinit(gpa);
+ try takeMeta(t, &next, io, gpa);
+ }
+ r.meta = meta;
+ }
+ if (epoch != r.epoch) return error.Renumbered;
+
+ // The primary screen scrolled `top - r.top` rows since the last
+ // delta: as many go up into the history here (no more than its
+ // history holds and the screen), each beyond the tail a hole.
+ const primary = t.screens.get(.primary).?;
+ if (top > r.top) {
+ const k = top - r.top;
+ const held = &r.held[0];
+ if (k >= @as(u64, t.rows) + history) {
+ // A flood: nothing held here is in this state. The rows stay
+ // where they are, renumbered: the active ones written below,
+ // the tail too, the rest holes (blanked when they come into
+ // view, `blank`), not grown and trimmed by the thousand. As
+ // many more as the history is longer there, grown blank.
+ const have = primary.pages.total_rows - primary.pages.rows;
+ if (have < history) try scrollUp(primary, history - have);
+ held.clearRetainingCapacity();
+ try held.appendNTimes(gpa, unknown, t.rows);
+ r.holes.clearRetainingCapacity();
+ if (history > tail) try r.holes.append(gpa, .{ top - history, top - tail });
+ } else {
+ try scrollUp(primary, @min(k, @as(u64, t.rows) + history));
+ if (k >= held.items.len) held.clearRetainingCapacity() else {
+ std.mem.copyForwards(Hash, held.items, held.items[@intCast(k)..]);
+ held.shrinkRetainingCapacity(held.items.len - @as(usize, @intCast(k)));
+ }
+ if (top - tail > r.top) try r.holes.append(gpa, .{ r.top, top - tail });
+ }
+ r.top = top;
+ }
+ // The history as long as the authority's (it prunes a page at a
+ // time, and an ED 3 takes it all): row numbers and the scrollbar
+ // say the same on both. ponytail: one pruned shorter than that
+ // (its pages packed otherwise) stays shorter.
+ const have = primary.pages.total_rows - primary.pages.rows;
+ if (have > history) primary.pages.eraseHistory(.{ .history = .{ .y = @intCast(have - history - 1) } });
+ r.trimHoles(primary);
+ for (0..tail) |j| {
+ const p = pinOf(&primary.pages, top, top - tail + j) orelse continue;
+ const h = std.mem.readInt(u64, tails[j * 8 ..][0..8], .little);
+ if (rowHash(p.node.page(), p.rowAndCell().row, t.cols) != h) try r.writeRow(gpa, primary, p, try blobOf(r, &fresh, h));
+ }
+
+ const screen = t.screens.active;
+ const held = &r.held[@backingInt(t.screens.active_key)];
+ const blank_row = blankHash(t.cols);
+ while (held.items.len < nrows) try held.append(gpa, blank_row);
+ held.shrinkRetainingCapacity(nrows);
+ for (0..nrows) |y| {
+ const h = std.mem.readInt(u64, hashes[y * 8 ..][0..8], .little);
+ if (h == held.items[y]) continue;
+ try r.writeRow(gpa, screen, screen.pages.pin(.{ .active = .{ .y = @intCast(y) } }).?, try blobOf(r, &fresh, h));
+ held.items[y] = h;
+ }
+ screen.cursorReload();
+ screen.cursorAbsolute(@min(cx, t.cols - 1), @min(cy, t.rows - 1));
+ screen.cursor.cursor_style = @fromBackingInt(@intCast(style));
+ screen.cursor.pending_wrap = wrap != 0;
+ screen.cursor.semantic_content = @fromBackingInt(@intCast(semantic));
+ screen.kitty_keyboard = kitty;
+ const oldest = r.top -| (primary.pages.total_rows - primary.pages.rows);
+ primary.pages.scroll(if (viewport == following) .active else .{ .row = @intCast(viewport -| oldest) });
+
+ // Hold the blobs of this state, and no others.
+ var keep: std.AutoHashMapUnmanaged(Hash, []u8) = .empty;
+ errdefer keep.deinit(gpa);
+ try keep.ensureTotalCapacity(gpa, nrows + tail + 1);
+ for (0..nrows + tail + 1) |i| {
+ const h = if (i == nrows + tail) meta else if (i < nrows)
+ std.mem.readInt(u64, hashes[i * 8 ..][0..8], .little)
+ else
+ std.mem.readInt(u64, tails[(i - nrows) * 8 ..][0..8], .little);
+ if (keep.contains(h)) continue;
+ const b = if (r.blobs.fetchRemove(h)) |kv| kv.value else try gpa.dupe(u8, try blobOf(r, &fresh, h));
+ keep.putAssumeCapacity(h, b);
+ }
+ var old = r.blobs.valueIterator();
+ while (old.next()) |b| gpa.free(b.*);
+ r.blobs.deinit(gpa);
+ r.blobs = keep;
+ r.seq = seq;
+ return .{ .seq = seq, .extra = extra };
+ }
+
+ /// The holes in `[lo, hi)` blank: until their rows come, a hole shows
+ /// nothing rather than what that row held before a flood renumbered it.
+ pub fn blank(r: *const Replica, t: *Terminal, lo: u64, hi: u64) void {
+ const primary = t.screens.get(.primary).?;
+ const oldest = r.top -| (primary.pages.total_rows - primary.pages.rows);
+ for (r.holes.items) |hole| {
+ const a = @max(lo, hole[0], oldest);
+ const b = @min(hi, hole[1], r.top);
+ if (a >= b) continue;
+ primary.clearRows(.{ .screen = .{ .y = @intCast(a - oldest) } }, .{ .screen = .{ .y = @intCast(b - 1 - oldest) } }, false);
+ }
+ }
+
+ /// The holes in `[lo, hi)`: the rows to fetch before showing them.
+ pub fn missing(r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void {
+ for (r.holes.items) |hole| {
+ const a = @max(lo, hole[0]);
+ const b = @min(hi, hole[1]);
+ if (a < b) try out.append(gpa, .{ a, b });
+ }
+ }
+
+ /// The absolute row the viewport of `t`'s primary screen starts at, and
+ /// how many it shows.
+ pub fn shown(r: *const Replica, t: *Terminal) [2]u64 {
+ const pages = &t.screens.get(.primary).?.pages;
+ const sb = pages.scrollbar();
+ const oldest = r.top -| (pages.total_rows - pages.rows);
+ return .{ oldest + sb.offset, oldest + sb.offset + sb.len };
+ }
+
+ /// Write fetched history rows (`encodeRows`) into `t`.
+ pub fn applyRows(r: *Replica, gpa: std.mem.Allocator, t: *Terminal, bytes: []const u8) !void {
+ var in: std.Io.Reader = .fixed(bytes);
+ if (try in.takeInt(u32, .little) != r.epoch) return; // numbered before a resize
+ const primary = t.screens.get(.primary).?;
+ var blobs: std.AutoHashMapUnmanaged(Hash, []const u8) = .empty;
+ defer blobs.deinit(gpa);
+ for (0..try in.takeInt(u32, .little)) |_| {
+ const h = try in.takeInt(u64, .little);
+ try blobs.put(gpa, h, try in.take(try in.takeInt(u32, .little)));
+ }
+ for (0..try in.takeInt(u32, .little)) |_| {
+ const abs = try in.takeInt(u64, .little);
+ const blob = blobs.get(try in.takeInt(u64, .little)) orelse return error.MissingBlob;
+ // Only a hole is written: a row the replica holds is the
+ // authority's already, and newer than what this fetch saw.
+ if (abs >= r.top or !r.inHole(abs)) continue;
+ const p = pinOf(&primary.pages, r.top, abs) orelse continue;
+ try r.writeRow(gpa, primary, p, blob);
+ try r.fill(gpa, abs);
+ }
+ }
+
+ fn inHole(r: *const Replica, abs: u64) bool {
+ for (r.holes.items) |hole| if (abs >= hole[0] and abs < hole[1]) return true;
+ return false;
+ }
+
+ /// Row `abs` is written: out of the holes.
+ fn fill(r: *Replica, gpa: std.mem.Allocator, abs: u64) !void {
+ for (r.holes.items, 0..) |*hole, i| {
+ if (abs < hole[0] or abs >= hole[1]) continue;
+ if (abs == hole[0]) hole[0] += 1 else if (abs + 1 == hole[1]) hole[1] -= 1 else {
+ try r.holes.insert(gpa, i + 1, .{ abs + 1, hole[1] });
+ r.holes.items[i][1] = abs;
+ }
+ if (r.holes.items[i][0] == r.holes.items[i][1]) _ = r.holes.orderedRemove(i);
+ return;
+ }
+ }
+
+ fn trimHoles(r: *Replica, primary: *Screen) void {
+ clampHoles(&r.holes, r.top -| (primary.pages.total_rows - primary.pages.rows));
+ }
+
+ fn writeRow(r: *Replica, gpa: std.mem.Allocator, screen: *Screen, p: Pin, blob: []const u8) !void {
+ var reader: std.Io.Reader = .fixed(blob);
+ var dec: snapshot.page.Decoder = undefined;
+ try dec.init(&reader, try snapshot.record.nextHeader(&reader));
+ const src = try scratchPage(&r.scratch, dec.capacity());
+ try dec.decode(src, gpa);
+ if (src.size.cols != screen.pages.cols) return error.BadRow;
+ _ = screen.clonePartialRowGrowCapacity(p.node, p.y, src, src.getRow(0), 0, src.size.cols);
+ }
+};
+
+/// `k` blank rows onto the bottom of a screen's active area, its top `k`
+/// going up into the history, as `k` linefeeds at the bottom would. A
+/// flood's thousands are grown a row at a time without the cursor (the
+/// page list's fast path, a counter), which is put back after.
+fn scrollUp(screen: *Screen, k: u64) !void {
+ if (k == 0) return;
+ screen.cursorAbsolute(0, screen.pages.rows - 1);
+ if (k <= screen.pages.rows or screen.no_scrollback or screen.cursor.style_id != 0) {
+ for (0..@intCast(k)) |_| try screen.cursorDownScroll();
+ return;
+ }
+ for (0..@intCast(k)) |_| _ = try screen.pages.grow();
+ screen.cursorReload();
+}
+
+/// No row's address: what a row whose content is not known is held as.
+const unknown: Hash = std.math.maxInt(Hash);
+
+/// `rowHash` of a row never written.
+fn blankHash(cols: u16) Hash {
+ var h = std.hash.Wyhash.init(0);
+ h.update(&.{0});
+ h.update(std.mem.asBytes(&cols));
+ return h.final();
+}
+
+/// The terminal-wide state of `next` (a decoded TERMINAL record) into `t`,
+/// whose screens and pages stay: what `snapshot.terminal.decode` sets.
+fn takeMeta(t: *Terminal, next: *Terminal, io: std.Io, gpa: std.mem.Allocator) !void {
+ if (t.cols != next.cols or t.rows != next.rows) try t.resize(gpa, .{ .cols = next.cols, .rows = next.rows });
+ t.width_px = next.width_px;
+ t.height_px = next.height_px;
+ t.scrolling_region = next.scrolling_region;
+ t.status_display = next.status_display;
+ t.previous_char = next.previous_char;
+ t.cursor = next.cursor;
+ t.modes = next.modes;
+ t.flags.shell_redraws_prompt = next.flags.shell_redraws_prompt;
+ t.flags.modify_other_keys_2 = next.flags.modify_other_keys_2;
+ t.flags.mouse_event = next.flags.mouse_event;
+ t.flags.mouse_format = next.flags.mouse_format;
+ t.flags.mouse_shift_capture = next.flags.mouse_shift_capture;
+ t.flags.password_input = next.flags.password_input;
+ t.mouse_shape = next.mouse_shape;
+ t.colors = next.colors;
+ try t.setPwd(next.getPwd() orelse "");
+ try t.setTitle(next.getTitle() orelse "");
+ std.mem.swap(@TypeOf(t.tabstops), &t.tabstops, &next.tabstops);
+ const key = next.screens.active_key;
+ if (key != t.screens.active_key) {
+ if (t.screens.get(key) == null) _ = try t.screens.getInit(io, gpa, key, .{ .cols = t.cols, .rows = t.rows, .max_scrollback_bytes = 0 });
+ t.screens.switchTo(key);
+ }
+}
+
+// ---- checks: a replica against its authority, cell for cell ----
+
+/// What a row shows, written out value by value (not `rowHash`'s walk):
+/// its flags, then each cell's word without its page's ids, its style, its
+/// grapheme and its hyperlink's URI.
+fn dumpRow(page: *Page, row: *Row, cols: u16, w: *std.Io.Writer) !void {
+ try w.print("{d}:", .{rowFlags(row)});
+ const all = page.getCells(row);
+ for (all[0..@min(cols, all.len)]) |*c| {
+ var word = c.*;
+ word.style_id = 0;
+ try w.print(" {x}", .{@as(u64, @bitCast(word))});
+ if (c.style_id != 0) try snapshot.style.encode(page.styles.get(page.memory, c.style_id).*, w);
+ if (c.hasGrapheme()) for (page.lookupGrapheme(c).?) |cp| try w.print("+{x}", .{cp});
+ if (c.hyperlink) if (page.lookupHyperlink(c)) |id| try w.print("@{s}", .{page.hyperlink_set.get(page.memory, id).uri.slice(page.memory)});
+ }
+ try w.writeByte('\n');
+}
+
+/// The state a replica must match: the terminal-wide state, the cursor,
+/// the history's extent and the viewport, the active screen's rows.
+pub fn dumpScreen(t: *Terminal, w: *std.Io.Writer) !void {
+ const screen = t.screens.active;
+ const sb = t.screens.get(.primary).?.pages.scrollbar();
+ try w.print("{d}x{d} {s} cursor {d},{d} {s} {} {s} title {s} pwd {s} scrollbar {d} {d} {d}\n", .{
+ t.cols, t.rows, @tagName(t.screens.active_key),
+ screen.cursor.x, screen.cursor.y, @tagName(screen.cursor.cursor_style),
+ screen.cursor.pending_wrap, @tagName(screen.cursor.semantic_content), t.getTitle() orelse "",
+ t.getPwd() orelse "", sb.total, sb.offset,
+ sb.len,
+ });
+ try w.writeAll(std.mem.asBytes(&t.modes.values));
+ try w.writeAll(std.mem.asBytes(&screen.kitty_keyboard));
+ try w.print(" mouse {s} {s} {s}\n", .{ @tagName(t.flags.mouse_event), @tagName(t.flags.mouse_format), @tagName(t.mouse_shape) });
+ for (t.colors.palette.current) |c| try w.print("{x}{x}{x}", .{ c.r, c.g, c.b });
+ try w.writeByte('\n');
+ var it = screen.pages.rowIterator(.right_down, .{ .active = .{} }, null);
+ while (it.next()) |p| try dumpRow(p.node.page(), p.rowAndCell().row, t.cols, w);
+}
+
+/// An authority and its replica, fed one stream of pty bytes, the deltas
+/// and fetches between them at random: a delta encoded at a random step
+/// (so the states between are skipped), several in flight and each landing
+/// a random number of steps later, in order, one lost now and then (the
+/// replica refuses the next and is started afresh), random resizes of the
+/// authority, random fetches of holes. After each delta, the replica's
+/// screen is the authority's as it was encoded, and every history row it
+/// holds outside its holes is what the authority holds at that absolute
+/// row.
+pub const Soak = struct {
+ gpa: std.mem.Allocator,
+ io: std.Io,
+ a: *Terminal,
+ stream: vt.TerminalStream,
+ track: Track,
+ enc: Encoder,
+ peer: Peer = .{},
+ /// The authority's writes, as terminal.State counts them.
+ changes: u32 = 0,
+ b: *Terminal,
+ rep: Replica = .{},
+ prng: std.Random.DefaultPrng,
+ /// The deltas in flight, oldest first, each with the authority's dump
+ /// when it was encoded and the step it lands at.
+ flight: std.ArrayList(struct { delta: []u8, expect: []u8, at: u64 }) = .empty,
+ got: std.Io.Writer.Allocating,
+ now: u64 = 0,
+ resizes: bool = true,
+ drops: bool = true,
+ /// The replica refused a delta and the authority started it afresh:
+ /// what was in flight before is refused too.
+ refused: bool = false,
+ stats: struct { deltas: u64 = 0, bytes: u64 = 0, fetched: u64 = 0, history_checked: u64 = 0, lost: u64 = 0, refused: u64 = 0, most_in_flight: u64 = 0 } = .{},
+
+ pub fn init(gpa: std.mem.Allocator, io: std.Io, cols: u16, rows: u16, scrollback: usize, seed: u64) !*Soak {
+ const s = try gpa.create(Soak);
+ errdefer gpa.destroy(s);
+ const a = try gpa.create(Terminal);
+ a.* = try Terminal.init(io, gpa, .{ .cols = cols, .rows = rows, .max_scrollback_bytes = scrollback });
+ const b = try gpa.create(Terminal);
+ // Room to spare: its pages may pack rows otherwise, and it keeps the
+ // authority's history to the row.
+ b.* = try Terminal.init(io, gpa, .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 2 * scrollback });
+ s.* = .{
+ .gpa = gpa,
+ .io = io,
+ .a = a,
+ .stream = a.vtStream(),
+ .track = .init(gpa),
+ .enc = .init(gpa),
+ .b = b,
+ .prng = .init(seed),
+ .got = .init(gpa),
+ };
+ return s;
+ }
+
+ pub fn deinit(s: *Soak) void {
+ const gpa = s.gpa;
+ s.stream.deinit();
+ s.track.deinit(gpa, s.a);
+ s.a.deinit(gpa);
+ gpa.destroy(s.a);
+ s.b.deinit(gpa);
+ gpa.destroy(s.b);
+ s.enc.deinit();
+ s.peer.deinit(gpa);
+ s.rep.deinit(gpa);
+ for (s.flight.items) |f| {
+ gpa.free(f.delta);
+ gpa.free(f.expect);
+ }
+ s.flight.deinit(gpa);
+ s.got.deinit();
+ gpa.destroy(s);
+ }
+
+ /// `bytes` into the authority in random pieces, a step after each.
+ pub fn feed(s: *Soak, bytes: []const u8) !void {
+ var at: usize = 0;
+ const random = s.prng.random();
+ while (at < bytes.len) {
+ const n = @min(bytes.len - at, 1 + random.uintLessThan(usize, 512));
+ s.stream.nextSlice(bytes[at..][0..n]);
+ s.changes +%= 1;
+ at += n;
+ try s.step();
+ }
+ }
+
+ pub fn step(s: *Soak) !void {
+ const random = s.prng.random();
+ s.now += 1;
+ if (s.resizes and random.uintLessThan(u32, 200) == 0) {
+ try s.a.resize(s.gpa, .{ .cols = 10 + random.uintLessThan(u16, 200), .rows = 3 + random.uintLessThan(u16, 60) });
+ s.changes +%= 1;
+ }
+ // A frame now and then; the states between are skipped.
+ if (random.boolean()) try s.send(s.now + random.uintLessThan(u64, 12));
+ while (s.flight.items.len > 0 and s.flight.items[0].at <= s.now) try s.land();
+ if (random.uintLessThan(u32, 8) == 0) try s.fetch();
+ }
+
+ /// A delta, if the peer is owed one, sent to land at step `at`.
+ fn send(s: *Soak, at: u64) !void {
+ var d: std.Io.Writer.Allocating = .init(s.gpa);
+ defer d.deinit();
+ if (!try encode(&s.enc, &s.track, &s.peer, s.a, s.changes, "extra", &d.writer)) return;
+ var expect: std.Io.Writer.Allocating = .init(s.gpa);
+ defer expect.deinit();
+ try dumpScreen(s.a, &expect.writer);
+ const last = if (s.flight.items.len > 0) s.flight.items[s.flight.items.len - 1].at else 0;
+ try s.flight.append(s.gpa, .{ .delta = try d.toOwnedSlice(), .expect = try expect.toOwnedSlice(), .at = @max(at, last) });
+ s.stats.deltas += 1;
+ s.stats.bytes += s.flight.items[s.flight.items.len - 1].delta.len;
+ s.stats.most_in_flight = @max(s.stats.most_in_flight, s.flight.items.len);
+ }
+
+ /// The oldest delta in flight applied (or lost), acknowledged, checked.
+ fn land(s: *Soak) !void {
+ const f = s.flight.orderedRemove(0);
+ defer s.gpa.free(f.delta);
+ defer s.gpa.free(f.expect);
+ if (s.drops and s.prng.random().uintLessThan(u32, 50) == 0) {
+ s.stats.lost += 1;
+ return;
+ }
+ const applied = s.rep.apply(s.gpa, s.io, s.b, f.delta) catch |err| switch (err) {
+ error.BaseMismatch => {
+ // Asked once: the authority starts it afresh.
+ if (!s.refused) s.peer.reset();
+ s.refused = true;
+ s.stats.refused += 1;
+ return;
+ },
+ else => return err,
+ };
+ s.refused = false;
+ if (!std.mem.eql(u8, applied.extra, "extra")) return error.ExtraLost;
+ s.peer.ack(applied.seq);
+ s.got.clearRetainingCapacity();
+ try dumpScreen(s.b, &s.got.writer);
+ if (!std.mem.eql(u8, f.expect, s.got.written())) {
+ reportDiff(f.expect, s.got.written());
+ return error.ReplicaDiffers;
+ }
+ try s.checkHistory();
+ }
+
+ /// Everything in flight landed, then a last delta of the end, until the
+ /// replica holds it: what the replica shows at quiescence.
+ fn settle(s: *Soak) !void {
+ s.drops = false;
+ for (0..4) |_| {
+ while (s.flight.items.len > 0) try s.land();
+ try s.send(0);
+ if (s.flight.items.len == 0) return;
+ }
+ return error.NeverSettled;
+ }
+
+ /// Every history row the replica holds, outside its holes and inside
+ /// what the authority still has, is the authority's (rows in history
+ /// never change; a resize renumbers and starts the replica afresh).
+ fn checkHistory(s: *Soak) !void {
+ // Numbered as of now: the authority may have scrolled on since.
+ try s.track.rows.update(s.a);
+ if (s.rep.epoch != s.track.rows.epoch) return;
+ const pages = &s.b.screens.get(.primary).?.pages;
+ const have = pages.total_rows - pages.rows;
+ var ra: std.Io.Writer.Allocating = .init(s.gpa);
+ defer ra.deinit();
+ var rb: std.Io.Writer.Allocating = .init(s.gpa);
+ defer rb.deinit();
+ var d: u64 = 1;
+ while (d <= have) : (d += 1 + d / 8) {
+ const abs = s.rep.top - d;
+ if (s.rep.inHole(abs)) continue;
+ const pb = pinOf(pages, s.rep.top, abs) orelse continue;
+ const pa = s.track.rows.pinAt(s.a, abs) orelse continue;
+ ra.clearRetainingCapacity();
+ rb.clearRetainingCapacity();
+ try dumpRow(pa.node.page(), pa.rowAndCell().row, s.a.cols, &ra.writer);
+ try dumpRow(pb.node.page(), pb.rowAndCell().row, s.b.cols, &rb.writer);
+ if (!std.mem.eql(u8, ra.written(), rb.written())) {
+ std.debug.print("history row {d} ({d} above the top) differs\n", .{ abs, d });
+ reportDiff(ra.written(), rb.written());
+ return error.ReplicaHistoryDiffers;
+ }
+ s.stats.history_checked += 1;
+ }
+ }
+
+ /// Some holes fetched from the authority, as a replica scrolled back.
+ fn fetch(s: *Soak) !void {
+ if (s.rep.holes.items.len == 0) return;
+ const random = s.prng.random();
+ const hole = s.rep.holes.items[random.uintLessThan(usize, s.rep.holes.items.len)];
+ const lo = hole[0] + random.uintLessThan(u64, hole[1] - hole[0]);
+ const hi = @min(hole[1], lo + 1 + random.uintLessThan(u64, 80));
+ s.rep.blank(s.b, lo, hi);
+ var out: std.Io.Writer.Allocating = .init(s.gpa);
+ defer out.deinit();
+ try encodeRows(&s.enc, &s.track, s.a, lo, hi, &out.writer);
+ try s.rep.applyRows(s.gpa, s.b, out.written());
+ s.stats.fetched += hi - lo;
+ try s.checkHistory();
+ }
+};
+
+fn reportDiff(want: []const u8, got: []const u8) void {
+ var wl = std.mem.splitScalar(u8, want, '\n');
+ var gl = std.mem.splitScalar(u8, got, '\n');
+ var line: usize = 0;
+ while (true) : (line += 1) {
+ const a = wl.next();
+ const b = gl.next();
+ if (a == null and b == null) return;
+ if (a != null and b != null and std.mem.eql(u8, a.?, b.?)) continue;
+ std.debug.print("line {d} differs:\n authority {s}\n replica {s}\n", .{ line, a orelse "(none)", b orelse "(none)" });
+ return;
+ }
+}
+
+/// Drive one stream through a soak, then settle: the replica's screen at
+/// quiescence is the authority's.
+pub fn soak(gpa: std.mem.Allocator, io: std.Io, bytes: []const u8, cols: u16, rows: u16, scrollback: usize, seed: u64, resizes: bool) !@FieldType(Soak, "stats") {
+ const s = try Soak.init(gpa, io, cols, rows, scrollback, seed);
+ defer s.deinit();
+ s.resizes = resizes;
+ try s.feed(bytes);
+ try s.settle();
+ return s.stats;
+}
+
+const testing = std.testing;
+
+/// A shell's: prompts marked (OSC 133), colours of the three kinds, wide
+/// and combined graphemes, hyperlinks, tabs, a title and a directory, long
+/// lines that wrap, and a clear (ED2, ED3) now and then.
+pub fn shellStream(gpa: std.mem.Allocator) ![]u8 {
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ errdefer out.deinit();
+ const w = &out.writer;
+ try w.writeAll("\x1b]0;a shell\x07\x1b]7;file://host/home/someone\x07");
+ for (0..400) |i| {
+ try w.print("\x1b]133;A\x07$ \x1b]133;B\x07ls -l {d}\r\n\x1b]133;C\x07", .{i});
+ try w.print("\x1b[1;31mred\x1b[0m \x1b[4;38;5;{d}m256\x1b[0m \x1b[38;2;{d};100;200;48;5;17mtrue\x1b[0m 漢字 e\u{301} 👩\u{200d}💻 ", .{ i % 256, i % 256 });
+ try w.print("\x1b]8;;https://example.com/{d}\x07link\x1b]8;;\x07\tx\r\n", .{i});
+ if (i % 7 == 0) {
+ for (0..12) |_| try w.writeAll("a long line that wraps ");
+ try w.writeAll("\r\n");
+ }
+ try w.writeAll("\x1b]133;D;0\x07");
+ if (i % 97 == 96) try w.writeAll("\x1b[H\x1b[2J\x1b[3J");
+ if (i % 50 == 0) try w.print("\x1b]2;title {d}\x07\x1b]4;1;rgb:{x:0>2}/20/30\x07", .{ i, i % 256 });
+ }
+ return out.toOwnedSlice();
+}
+
+/// A full-screen program's: the alternate screen and its modes, a status
+/// line, a scrolling region scrolled both ways, lines inserted and
+/// deleted, cursor shapes, the kitty keyboard pushed and popped.
+pub fn tuiStream(gpa: std.mem.Allocator) ![]u8 {
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ errdefer out.deinit();
+ const w = &out.writer;
+ try w.writeAll("before the program\r\n\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h\x1b[?2004h\x1b[?1h\x1b[>1u\x1b[4 q\x1b[H\x1b[2J");
+ for (0..300) |f| {
+ try w.print("\x1b[1;1H\x1b[44;97m status {d} \x1b[K\x1b[0m", .{f});
+ try w.print("\x1b[3;18r\x1b[18;1H\r\n\x1b[3{d}mline {d}\x1b[0m", .{ f % 8, f });
+ if (f % 3 == 0) try w.writeAll("\x1b[3;1H\x1bM\x1b[2mreversed in\x1b[0m");
+ if (f % 5 == 0) try w.writeAll("\x1b[6;1H\x1b[2L\x1b[9;1H\x1b[M");
+ try w.writeAll("\x1b[r");
+ try w.print("\x1b[{d};{d}H\x1b[7m*\x1b[0m\x1b[{d}X", .{ 2 + f % 20, 1 + (f * 7) % 70, f % 5 });
+ if (f % 11 == 0) try w.writeAll("\x1b[?25h\x1b[6 q") else if (f % 11 == 5) try w.writeAll("\x1b[?25l\x1b[2 q");
+ }
+ try w.writeAll("\x1b[<u\x1b[?1049l\x1b[?25h\x1b[?1000l\x1b[0 qafter the program\r\n");
+ return out.toOwnedSlice();
+}
+
+pub fn yesStream(gpa: std.mem.Allocator, lines: usize) ![]u8 {
+ const out = try gpa.alloc(u8, lines * 3);
+ for (0..lines) |i| @memcpy(out[i * 3 ..][0..3], "y\r\n");
+ return out;
+}
+
+test "a replica's screen is its authority's, cell for cell, as states are skipped, resized and fetched" {
+ const gpa = testing.allocator;
+ const io = testing.io;
+ const shell = try shellStream(gpa);
+ defer gpa.free(shell);
+ const tui = try tuiStream(gpa);
+ defer gpa.free(tui);
+ const yes = try yesStream(gpa, 30_000);
+ defer gpa.free(yes);
+ var fetched: u64 = 0;
+ var history: u64 = 0;
+ for (0..4) |seed| {
+ // A small scrollback, so it wraps (pruned at its oldest pages).
+ for ([_][]const u8{ shell, tui, yes }) |bytes| {
+ const st = soak(gpa, io, bytes, 80, 24, 64 * 1024, seed, seed != 0) catch |err| {
+ std.debug.print("soak seed {d} stream {d} bytes: {s}\n", .{ seed, bytes.len, @errorName(err) });
+ return err;
+ };
+ try testing.expect(st.deltas > 10);
+ fetched += st.fetched;
+ history += st.history_checked;
+ }
+ }
+ // The holes were fetched, and history rows compared, at all.
+ try testing.expect(fetched > 0 and history > 0);
+}
+
+test "under a flood a delta is a screen of hashes: an unchanged row costs its address alone" {
+ const gpa = testing.allocator;
+ const s = try Soak.init(gpa, testing.io, 200, 60, 1 << 20, 1);
+ defer s.deinit();
+ s.resizes = false;
+ s.drops = false;
+ const yes = try yesStream(gpa, 10_000);
+ defer gpa.free(yes);
+ var last: []u8 = &.{};
+ defer gpa.free(last);
+ for (0..3) |_| {
+ s.stream.nextSlice(yes);
+ s.changes += 1;
+ try s.send(0);
+ try testing.expectEqual(@as(usize, 1), s.flight.items.len);
+ gpa.free(last);
+ last = try gpa.dupe(u8, s.flight.items[0].delta);
+ try s.land();
+ }
+ // The last: 60 rows and the tail's 60, of hashes the replica holds, no
+ // blob; the header and counts around them.
+ const d = last;
+ const at = 4 + 4 + 1 + 4 + 8 + 2 + 2 + 1 + 1 + 1 + @sizeOf(KittyFlags) + 8 + 8 + 8 + 2 + "extra".len;
+ const nrows = std.mem.readInt(u16, d[at..][0..2], .little);
+ const tail = std.mem.readInt(u16, d[at + 2 + nrows * 8 ..][0..2], .little);
+ const blobs = std.mem.readInt(u16, d[at + 4 + (nrows + tail) * 8 ..][0..2], .little);
+ if (d.len >= (nrows + tail) * 8 + 128) std.debug.print("delta {d} bytes: {d} rows, {d} tail, {d} blobs\n", .{ d.len, nrows, tail, blobs });
+ try testing.expectEqual(@as(u16, 0), blobs);
+ try testing.expect(d.len < (nrows + tail) * 8 + 128);
+ try testing.expect(s.rep.holes.items.len > 0);
+}
+
+test "a reflow to fewer columns keeps every history row numbered at or past 0" {
+ const gpa = testing.allocator;
+ const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 3);
+ defer s.deinit();
+ s.resizes = false;
+ s.drops = false;
+ // Lines of 69 columns scrolled into the history, then the screen
+ // narrowed so that each wraps in three: more rows above the last top
+ // than ever scrolled past it (a window client's font, 2026-10-30: the
+ // session's peer started afresh at `top - history`, which overflowed).
+ var line: [80]u8 = undefined;
+ for (0..200) |i| {
+ s.stream.nextSlice(try std.fmt.bufPrint(&line, "{d:0>4} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n", .{i}));
+ s.changes += 1;
+ }
+ try s.send(0);
+ try s.land();
+ try s.a.resize(gpa, .{ .cols = 30, .rows = 24 });
+ s.changes += 1;
+ try s.send(0);
+ try s.land();
+ try s.settle();
+ try testing.expect(s.track.rows.top >= s.track.history);
+}
+
+test "several deltas in flight land in order, and a peer at the bound waits for an acknowledgement" {
+ const gpa = testing.allocator;
+ const s = try Soak.init(gpa, testing.io, 80, 24, 1 << 20, 2);
+ defer s.deinit();
+ s.resizes = false;
+ s.drops = false;
+ var line: [64]u8 = undefined;
+ for (0..bound + 5) |i| {
+ s.stream.nextSlice(try std.fmt.bufPrint(&line, "line {d}\r\n", .{i}));
+ s.changes += 1;
+ try s.send(1000);
+ }
+ // The bound's worth went; the rest wait, and are skipped.
+ try testing.expectEqual(@as(usize, bound), s.flight.items.len);
+ try s.land();
+ try s.send(1000);
+ try testing.expectEqual(@as(usize, bound), s.flight.items.len);
+ try s.settle();
+ try testing.expectEqual(@as(u64, 0), s.stats.refused);
+}
+
diff --git a/core/term/term.zig b/core/term/term.zig
new file mode 100644
index 00000000..6e36816a
--- /dev/null
+++ b/core/term/term.zig
@@ -0,0 +1,164 @@
+//! The terminal, a module of its own (docs/next-terminal.md, Phase 1):
+//! ghostty-vt's emulator and what pardes keeps beside it (terminal.zig),
+//! the screen state its replicas are sent (screen_state.zig), the kitty
+//! images it draws (TerminalImages.zig) and the pager's parse (pager.zig).
+//! It imports std, ghostty-vt, wuffs, zstbi and `plain`, never the core:
+//! the core reaches it through `ops` (core/Term.zig), the records of
+//! abi/term.zig in and out.
+const std = @import("std");
+const plain = @import("plain");
+const iface = plain.term;
+const terminal_ = @import("terminal.zig");
+const pager = @import("pager.zig");
+const screen_state_ = @import("screen_state.zig");
+const TerminalImages = terminal_.TerminalImages;
+
+/// The screen state replicas are sent, its streams and soak (test/replicas.zig).
+pub const screen_state = screen_state_;
+/// The emulator itself, for the tests that read it through a core
+/// (test/terminal.zig).
+pub const terminal = terminal_;
+
+pub const ops: iface.Ops = .{
+ .open = cast(iface.Ops, "open", terminal_.open),
+ .close = cast(iface.Ops, "close", terminal_.close),
+ .due = cast(iface.Ops, "due", terminal_.due),
+ .revive = cast(iface.Ops, "revive", terminal_.revive),
+ .start = TerminalImages.start,
+ .stop = TerminalImages.stop,
+ .gpa = cast(iface.Ops, "gpa", terminal_.gpaOf),
+ .digest = cast(iface.Ops, "digest", terminal_.digest),
+ .parts = cast(iface.Ops, "parts", terminal_.parts),
+ .snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot),
+ .load = cast(iface.Ops, "load", terminal_.load),
+ .feed = cast(iface.Ops, "feed", terminal_.feed),
+ .grid = cast(iface.Ops, "grid", terminal_.grid),
+ .viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo),
+ .scroll = cast(iface.Ops, "scroll", terminal_.scroll),
+ .follow = cast(iface.Ops, "follow", terminal_.follow),
+ .resize = cast(iface.Ops, "resize", terminal_.resize),
+ .resizeDeferred = cast(iface.Ops, "resizeDeferred", terminal_.resizeDeferred),
+ .cellPixels = cast(iface.Ops, "cellPixels", terminal_.cellPixels),
+ .replies = cast(iface.Ops, "replies", terminal_.replies),
+ .key = cast(iface.Ops, "key", terminal_.key),
+ .mouse = cast(iface.Ops, "mouse", terminal_.mouse),
+ .wheel = cast(iface.Ops, "wheel", terminal_.wheel),
+ .paste = cast(iface.Ops, "paste", terminal_.paste),
+ .modes = cast(iface.Ops, "modes", terminal_.modes),
+ .promptMoves = cast(iface.Ops, "promptMoves", terminal_.promptMoves),
+ .prompt = cast(iface.Ops, "prompt", terminal_.prompt),
+ .commandOutput = cast(iface.Ops, "commandOutput", terminal_.commandOutput),
+ .endOutputHere = cast(iface.Ops, "endOutputHere", terminal_.endOutputHere),
+ .scrollback = cast(iface.Ops, "scrollback", terminal_.scrollback),
+ .scrollbackLen = cast(iface.Ops, "scrollbackLen", terminal_.scrollbackLen),
+ .textRows = cast(iface.Ops, "textRows", terminal_.textRows),
+ .viewport = cast(iface.Ops, "viewport", terminal_.viewport),
+ .editRows = cast(iface.Ops, "editRows", terminal_.editRows),
+ .promptCut = cast(iface.Ops, "promptCut", terminal_.promptCutAt),
+ .markRead = cast(iface.Ops, "markRead", terminal_.markRead),
+ .echoCell = cast(iface.Ops, "echoCell", terminal_.echoCell),
+ .page = pager.parse,
+ .filter = terminal_.pagerFilter,
+ .spanColor = terminal_.spanColor,
+ .paint = cast(iface.Ops, "paint", terminal_.paint),
+ .images = cast(iface.Ops, "images", terminal_.images),
+ .petscii = cast(iface.Ops, "petscii", terminal_.petscii),
+ .togglePetscii = cast(iface.Ops, "togglePetscii", terminal_.togglePetscii),
+ .hasImages = cast(iface.Ops, "hasImages", terminal_.hasImages),
+ .encoder = cast(iface.Ops, "encoder", terminal_.encoder),
+ .encoderFree = cast(iface.Ops, "encoderFree", terminal_.encoderFree),
+ .track = cast(iface.Ops, "track", terminal_.track),
+ .untrack = cast(iface.Ops, "untrack", terminal_.untrack),
+ .encode = cast(iface.Ops, "encode", terminal_.encode),
+ .encodeRows = cast(iface.Ops, "encodeRows", terminal_.encodeRows),
+ .wasRead = cast(iface.Ops, "wasRead", terminal_.wasRead),
+ .clearRead = cast(iface.Ops, "clearRead", terminal_.clearRead),
+ .replica = cast(iface.Ops, "replica", terminal_.replica),
+ .replicaFree = cast(iface.Ops, "replicaFree", terminal_.replicaFree),
+ .replicaTop = cast(iface.Ops, "replicaTop", terminal_.replicaTop),
+ .missing = cast(iface.Ops, "missing", terminal_.missing),
+ .apply = cast(iface.Ops, "apply", terminal_.apply),
+ .applyRows = cast(iface.Ops, "applyRows", terminal_.applyRows),
+ .shown = cast(iface.Ops, "shown", terminal_.shown),
+ .blank = cast(iface.Ops, "blank", terminal_.blank),
+ .dumpScreen = cast(iface.Ops, "dumpScreen", terminal_.dumpScreen),
+};
+
+/// The term's handle types as the interface names them, and the module's
+/// own behind each: a pointer to one is a pointer to the other.
+const handles = .{
+ .{ iface.State, terminal_.State },
+ .{ iface.Encoder, screen_state_.Encoder },
+ .{ iface.Track, screen_state_.Track },
+ .{ iface.Replica, screen_state_.Replica },
+};
+
+/// The interface's handle for one of this module's own types, or the type
+/// itself.
+fn handleOf(comptime T: type) type {
+ inline for (handles) |pair| if (T == pair[1]) return pair[0];
+ return switch (@typeInfo(T)) {
+ .pointer => |p| if (p.size != .one) T else if (p.attrs.@"const") *const handleOf(p.child) else *handleOf(p.child),
+ .optional => |o| ?handleOf(o.child),
+ else => T,
+ };
+}
+
+/// Every error of `Have` is one of `Want`'s (anyerror holds them all).
+fn within(comptime Have: type, comptime Want: type) bool {
+ const want = @typeInfo(Want).error_set.error_names orelse return true;
+ const have = @typeInfo(Have).error_set.error_names orelse return false;
+ outer: for (have) |h| {
+ for (want) |w| if (std.mem.eql(u8, h, w)) continue :outer;
+ return false;
+ }
+ return true;
+}
+
+/// The errors of result `H` that result `W` has not, named.
+fn missingFrom(comptime H: type, comptime W: type) []const u8 {
+ if (@typeInfo(H) != .error_union or @typeInfo(W) != .error_union) return "";
+ const want = @typeInfo(@typeInfo(W).error_union.error_set).error_set.error_names orelse return "";
+ const have = @typeInfo(@typeInfo(H).error_union.error_set).error_set.error_names orelse return " (anyerror)";
+ var out: []const u8 = ": not";
+ outer: for (have) |h| {
+ for (want) |w| if (std.mem.eql(u8, h, w)) continue :outer;
+ out = out ++ " " ++ h;
+ }
+ return out;
+}
+
+/// `f`, one of this module's own entries, as the `Ops` field `name`: the
+/// same function, its handles the interface's opaque ones. Refused at
+/// compile time unless every parameter and the result match but for them.
+fn cast(comptime O: type, comptime name: []const u8, comptime f: anytype) @FieldType(O, name) {
+ @setEvalBranchQuota(100_000);
+ const Want = @typeInfo(@FieldType(O, name)).pointer.child;
+ const want = @typeInfo(Want).@"fn";
+ const have = @typeInfo(@TypeOf(f)).@"fn";
+ if (want.param_types.len != have.param_types.len) @compileError(name ++ ": not as many parameters as Ops says");
+ inline for (want.param_types, have.param_types, 0..) |w, h, i| {
+ if (w.? != handleOf(h.?)) @compileError(std.fmt.comptimePrint("{s}: parameter {d} is {s}, Ops says {s}", .{ name, i, @typeName(h.?), @typeName(w.?) }));
+ }
+ // A narrower error set is the same function pointer: an error is its
+ // number whatever set names it.
+ const W = want.return_type.?;
+ const H = have.return_type.?;
+ const same_result = switch (@typeInfo(W)) {
+ // Ops says anyerror: any error set of the same payload.
+ .error_union => |we| switch (@typeInfo(H)) {
+ .error_union => |he| we.payload == handleOf(he.payload) and within(he.error_set, we.error_set),
+ else => false,
+ },
+ else => W == handleOf(H),
+ };
+ if (!same_result) @compileError(name ++ ": returns " ++ @typeName(H) ++ ", Ops says " ++ @typeName(W) ++ missingFrom(H, W));
+ return @ptrCast(&f);
+}
+
+test {
+ _ = &ops;
+ _ = terminal_;
+ _ = pager;
+ _ = screen_state_;
+}
diff --git a/core/term/terminal.zig b/core/term/terminal.zig
new file mode 100644
index 00000000..d328748e
--- /dev/null
+++ b/core/term/terminal.zig
@@ -0,0 +1,1525 @@
+//! A terminal: its VT emulator, the OSC 133 cycle its shell marks, its
+//! text, its view as cells, and the Filter that recolours output to the
+//! theme. The core reaches it through core/term/term.zig's `ops`.
+const std = @import("std");
+const plain = @import("plain");
+const Key = plain.Key;
+const Term = plain.term;
+const screen_state = @import("screen_state.zig");
+
+const ghostty_vt = @import("ghostty-vt");
+const Ink = plain.term.Ink;
+const FilterPalette = plain.term.FilterPalette;
+const Filter = plain.term.Filter;
+const Painted = plain.term.Painted;
+const PaintedRow = plain.term.PaintedRow;
+const ImagesAt = plain.term.ImagesAt;
+const PromptCut = plain.term.PromptCut;
+
+pub const VtSlot = ghostty_vt.Terminal;
+/// A cell of an emulator's pages, as `getCell` reads it (core/term/echo.zig).
+pub const PageCell = ghostty_vt.PageList.Cell;
+/// Kitty graphics: a program's images are placements, as a kind's are.
+pub const images_enabled = true;
+pub const TerminalImages = if (images_enabled) @import("TerminalImages.zig") else void;
+pub const StreamSlot = ghostty_vt.Stream(MarkedHandler);
+
+/// The `aid` pardes's injected bash and fish marks carry (host_io.zig).
+pub const prompt_aid = "pardes";
+
+/// ghostty's handler, plus where the shell is in its command cycle as
+/// its OSC 133 marks tell it: ghostty parses D's exit status and drops
+/// it, and /pane/<n>/pty/run waits on exactly that. Only marks carrying
+/// pardes's own `aid` move it, so fish's native marks, a nested shell's
+/// and a stray `133;D` in some file being printed all pass it by.
+pub const MarkedHandler = struct {
+ inner: ghostty_vt.TerminalStream.Handler,
+ phase: Term.Prompt.Phase = .none,
+ /// Counts commands started (C at the input phase).
+ started: u32 = 0,
+ /// Counts prompts drawn (B), so a line the shell refused without
+ /// running (a fish syntax error: no C, no D, a new prompt) shows.
+ prompts: u32 = 0,
+ /// D marks outside a running command: the shell handled a line
+ /// without starting it (bash on a syntax error prints no C).
+ declined: u32 = 0,
+ /// The newest prompt continues an unfinished line (bash's PS2, marked
+ /// `k=c`): the shell still holds the start of the command.
+ continuation: bool = false,
+ /// Where the newest command's output began (its C) and ended (its
+ /// D) on the primary screen, pinned so scrolling keeps them.
+ out_start: ?*ghostty_vt.Pin = null,
+ out_end: ?*ghostty_vt.Pin = null,
+ /// The running command's output was erased under it -- a clear, ED 3,
+ /// a reset -- so the pins no longer span what it printed. ED 3 flags a
+ /// pin on an erased history row `garbage` (ghostty 1.4), but `pinTop`
+ /// re-pins the start at the screen's top, so the flag is gone with the
+ /// old pin: this remembers it, as it does for a reset or a pin that
+ /// could not be made.
+ lost: bool = false,
+
+ /// The newest command to end: which one, and its status if given.
+ finished: ?Term.Prompt.Finished = null,
+
+ const Action = ghostty_vt.TerminalStream.Action;
+
+ /// Move one of the output pins to the cursor. Only the primary screen
+ /// is pinned: a command's own full-screen display is not its output.
+ fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void {
+ const screen = self.inner.terminal.screens.get(.primary) orelse return;
+ if (slot.*) |old| screen.pages.untrackPin(old);
+ slot.* = null;
+ if (!now or self.inner.terminal.screens.active_key != .primary) return;
+ slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null;
+ }
+
+ pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void {
+ if (comptime action == .semantic_prompt) mark: {
+ const aid = value.readOption(.aid) orelse break :mark;
+ if (!std.mem.eql(u8, aid, prompt_aid)) break :mark;
+ switch (value.action) {
+ .fresh_line_new_prompt => {
+ self.phase = .prompt;
+ self.continuation = value.readOption(.prompt_kind) == .continuation;
+ },
+ .end_prompt_start_input => {
+ self.phase = .input;
+ self.prompts +%= 1;
+ },
+ // bash's DEBUG trap also fires on its own PROMPT_COMMAND,
+ // outside the input phase; only a C that ends input counts
+ .end_input_start_output => if (self.phase == .input) {
+ self.phase = .running;
+ self.started +%= 1;
+ self.lost = false;
+ self.pinCursor(&self.out_start, true);
+ self.pinCursor(&self.out_end, false);
+ },
+ .end_command => if (self.phase == .running) {
+ self.phase = .none;
+ self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) };
+ self.pinCursor(&self.out_end, true);
+ } else {
+ self.declined +%= 1;
+ },
+ else => {},
+ }
+ }
+ if (comptime action == .erase_display_complete or action == .erase_display_scrollback or
+ action == .erase_display_scroll_complete or action == .full_reset)
+ {
+ self.inner.vt(action, value);
+ // A `clear` under a running command: its output is what it
+ // prints from here, the screen's top, not lost. Only what the
+ // scrollback later loses is (the pin goes `garbage`).
+ if (self.phase == .running) self.pinTop(&self.out_start);
+ return;
+ }
+ self.inner.vt(action, value);
+ }
+
+ /// Pins `slot` to the primary screen's top-left; lost when it cannot be.
+ fn pinTop(self: *@This(), slot: *?*ghostty_vt.Pin) void {
+ const screen = self.inner.terminal.screens.get(.primary) orelse return;
+ if (slot.*) |old| screen.pages.untrackPin(old);
+ slot.* = null;
+ if (self.inner.terminal.screens.active_key != .primary) {
+ self.lost = true;
+ return;
+ }
+ const top = screen.pages.pin(.{ .active = .{} }) orelse {
+ self.lost = true;
+ return;
+ };
+ slot.* = screen.pages.trackPin(top) catch null;
+ if (slot.* == null) self.lost = true;
+ }
+
+ pub fn deinit(self: *@This()) void {
+ self.inner.deinit();
+ }
+};
+
+fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void {
+ const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal));
+ const room = state.reply.len - state.reply_len;
+ // A cut answer is worse than none: the program would read the start of
+ // a sequence and wait, or misparse what follows.
+ if (data.len > room) {
+ state.reply_dropped +|= 1;
+ return;
+ }
+ @memcpy(state.reply[state.reply_len..][0..data.len], data);
+ state.reply_len += @intCast(data.len);
+}
+
+fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes {
+ return .{};
+}
+
+/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a
+/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked.
+fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size {
+ const t = handler.terminal;
+ if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null;
+ return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows };
+}
+
+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, ...)
+ /// from one read of its output, written to its pty after it. Room for
+ /// a read's worth of kitty answers (yazi or `kitten icat` asking about
+ /// a batch of images in one write); an answer that does not fit whole
+ /// is dropped whole, never cut short (`reply_dropped` counts them).
+ reply: [4096]u8 = undefined,
+ reply_len: u16 = 0,
+ reply_dropped: u32 = 0,
+ /// The grid cell the program last heard the mouse at, so motion is
+ /// reported once per cell.
+ mouse_cell: ?ghostty_vt.Coordinate = null,
+ /// 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 stream over the emulator, its answers to the program and its
+ /// size reports routed here, PNG decoded: what `create` and a dump's
+ /// load both do once the emulator is in place.
+ fn wire(s: *State) void {
+ s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa });
+ s.stream.handler.inner.effects.write_pty = ptyReport;
+ s.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs;
+ s.stream.handler.inner.effects.size = ptySize;
+ if (comptime images_enabled) TerminalImages.installPngDecoder();
+ }
+};
+
+/// The emulator as its program has made it, for the replay digest (the
+/// core's Term.State.digest, core/walk.zig): the active screen's text, how
+/// much history is above it and, with `view`, 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.
+pub fn digest(s: *const State, h: *std.hash.Wyhash, view: bool) void {
+ 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(std.hash.Wyhash) = .initHasher(h.*, &buf);
+ if (screen.pages.getBottomRight(.active)) |br|
+ screen.dumpString(&text.writer, .{ .tl = screen.pages.getTopLeft(.active), .br = br, .unwrap = false }) catch unreachable; // a hashing writer never fails
+ text.writer.flush() catch unreachable; // a hashing writer never fails
+ h.* = text.hasher;
+ }
+
+fn pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?Term.Parts.Coordinate {
+ const pin = slot orelse return null;
+ const screen = s.vt.screens.get(.primary) orelse return null;
+ const at = (screen.pages.pointFromPin(.screen, pin.*) orelse return null).screen;
+ return .{ .x = at.x, .y = at.y };
+}
+
+fn coordinate(at: ?Term.Parts.Coordinate) ?ghostty_vt.Coordinate {
+ const c = at orelse return null;
+ return .{ .x = c.x, .y = c.y };
+}
+
+/// What the dump keeps of it beside its emulator (the core's
+/// Term.State.dumpWrite writes it by name, as every dump is).
+pub fn parts(s: *const State) Term.Parts {
+ const h = &s.stream.handler;
+ return .{
+ .reply = s.reply[0..s.reply_len],
+ .reply_dropped = s.reply_dropped,
+ .mouse_cell = if (s.mouse_cell) |c| .{ .x = c.x, .y = c.y } else null,
+ .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 = pinAt(s, h.out_start),
+ .out_end = pinAt(s, h.out_end),
+ };
+}
+
+/// Its emulator as the dump keeps it: ghostty's snapshot (both screens,
+/// their history, styles, links and kitty images). A sequence its program
+/// had begun and not ended is not kept: the snapshot is at the ground
+/// state. `slim`, a join's dump (dump.zig `dumpJoin`): its size alone, an
+/// emulator made afresh there, which its first delta replaces.
+pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) !void {
+ if (slim) 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 });
+}
+
+/// `snapshot`'s bytes and `parts` back into a new terminal, as `open`
+/// makes one.
+pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) !*State {
+ const out = try gpa.create(State);
+ errdefer gpa.destroy(out);
+ var reader: std.Io.Reader = .fixed(bytes);
+ if (reader.buffer.len == 4) {
+ const size = std.mem.bytesToValue([2]u16, bytes[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 }) |which| {
+ if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir());
+ };
+ out.wire();
+ const reply = saved.reply[0..@min(saved.reply.len, out.reply.len)];
+ @memcpy(out.reply[0..reply.len], reply);
+ out.reply_len = @intCast(reply.len);
+ out.reply_dropped = saved.reply_dropped;
+ out.mouse_cell = coordinate(saved.mouse_cell);
+ out.images = if (images_enabled) .{ .petscii = saved.petscii } else {};
+ const h = &out.stream.handler;
+ h.phase = saved.phase;
+ h.started = saved.started;
+ h.prompts = saved.prompts;
+ h.declined = saved.declined;
+ h.continuation = saved.continuation;
+ h.lost = saved.lost;
+ h.finished = saved.finished;
+ if (out.vt.screens.get(.primary)) |screen| {
+ inline for (.{ .{ "out_start", saved.out_start }, .{ "out_end", saved.out_end } }) |pair| if (coordinate(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(saved.view)) - @as(isize, @intCast(bottom)) });
+ return out;
+}
+
+/// The allocator it was opened with, its own from then on.
+pub fn gpaOf(s: *const State) std.mem.Allocator {
+ return s.gpa;
+}
+
+const GColor = ghostty_vt.color;
+
+// Projected colors below this contrast use the theme's more legible anchor.
+pub const min_contrast: f64 = 1.5;
+
+/// The theme's 256 colours as the filter maps onto them (ghostty's
+/// `generate256Color` over the theme's sixteen), made again only when the
+/// theme's are not the ones `cache` was made of.
+pub fn filterPalette(cache: *FilterPalette, ink: *const Ink) *const [256][3]u8 {
+ const wanted: FilterPalette.Key = .{ .bg = ink.bg orelse ink.tag_bg, .fg = ink.fg orelse ink.tag_fg, .base = ink.base };
+ if (cache.key) |old| if (std.meta.eql(old, wanted)) return &cache.colors;
+ var seed = GColor.default;
+ for (ink.base, 0..) |rgb, i| seed[i] = asGhostRgb(rgb);
+ const colors = GColor.generate256Color(seed, .empty, asGhostRgb(wanted.bg), asGhostRgb(wanted.fg), false);
+ for (&cache.colors, colors) |*dst, src| dst.* = asTriple(src);
+ cache.key = wanted;
+ return &cache.colors;
+}
+
+pub fn asGhostRgb(rgb: [3]u8) GColor.RGB {
+ return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] };
+}
+
+/// Where a kitty client puts its temporary files: `$TMPDIR`, else /tmp
+/// (which ghostty accepts whatever this says). The environment block lives
+/// as long as the process and pardes never edits it (ChildEnv.exportVar).
+fn tempDir() []const u8 {
+ const dir = std.c.getenv("TMPDIR") orelse return "/tmp";
+ const path = std.mem.span(dir);
+ return if (path.len > 0 and path[0] == '/') path else "/tmp";
+}
+
+pub fn terminalIo() std.Io {
+ return std.Io.Threaded.global_single_threaded.io();
+}
+
+/// Where the view and the cursor are (`Term.Grid`); all zero without an
+/// emulator.
+pub fn grid(state: ?*const State) Term.Grid {
+ const s = state orelse return .{};
+ const screen = s.vt.screens.active;
+ const sb = screen.pages.scrollbar();
+ return .{
+ .total = sb.total,
+ .offset = sb.offset,
+ .len = sb.len,
+ .cursor_x = @intCast(screen.cursor.x),
+ .cursor_y = @intCast(screen.cursor.y),
+ .cursor_visible = s.vt.modes.get(.cursor_visible),
+ .view = if (screen.pages.viewport == .active) null else sb.offset,
+ .cols = screen.pages.cols,
+ };
+}
+
+/// 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 {
+ const m = &state.stream.handler;
+ var w: std.Io.Writer = .fixed(buf);
+ w.writeByte(@backingInt(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 (bytes.len != marks_len) return;
+ const m = &state.stream.handler;
+ m.phase = @fromBackingInt(@intCast(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 };
+}
+
+// ---- its replicas: the screen state they are sent (screen_state.zig) ----
+
+/// What `peer` is owed of it, a delta against what it was sent (with the
+/// marks of its prompt cycle), onto `out`; false when it has it already.
+pub fn encode(state: *State, enc: *screen_state.Encoder, tr: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool {
+ var marks: [marks_len]u8 = undefined;
+ return screen_state.encode(enc, tr, peer, &state.vt, state.changes, marksOf(state, &marks), out);
+}
+
+/// Its rows `lo` to `hi` (absolute), as a replica holding them as holes
+/// is sent them.
+pub fn encodeRows(state: *State, enc: *screen_state.Encoder, tr: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void {
+ return screen_state.encodeRows(enc, tr, &state.vt, lo, hi, out);
+}
+
+/// What a session's authority keeps to encode its terminals for its
+/// peers, and what it keeps of one terminal for them: made and freed.
+pub fn encoder(gpa: std.mem.Allocator) !*screen_state.Encoder {
+ const e = try gpa.create(screen_state.Encoder);
+ e.* = .init(gpa);
+ return e;
+}
+
+pub fn encoderFree(e: *screen_state.Encoder) void {
+ const gpa = e.gpa;
+ e.deinit();
+ gpa.destroy(e);
+}
+
+pub fn track(gpa: std.mem.Allocator) !*screen_state.Track {
+ const t = try gpa.create(screen_state.Track);
+ t.* = .init(gpa);
+ return t;
+}
+
+/// A replica's side of one terminal: made, freed, where its active area
+/// begins, and the history rows `lo..hi` it does not hold.
+pub fn replica(gpa: std.mem.Allocator) !*screen_state.Replica {
+ const r = try gpa.create(screen_state.Replica);
+ r.* = .{};
+ return r;
+}
+
+pub fn replicaFree(r: *screen_state.Replica, gpa: std.mem.Allocator) void {
+ r.deinit(gpa);
+ gpa.destroy(r);
+}
+
+pub fn replicaTop(r: *const screen_state.Replica) u64 {
+ return r.top;
+}
+
+pub fn missing(r: *const screen_state.Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void {
+ return r.missing(lo, hi, out, gpa);
+}
+
+/// What `track` kept of its versions, freed; `state` null when its pane is
+/// gone with the emulator.
+/// A peer's track of it let go, and freed (`state` null: it is gone).
+pub fn untrack(t: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void {
+ t.deinit(gpa, if (state) |s| &s.vt else null);
+ gpa.destroy(t);
+}
+
+/// Whether a step read its rows since `clearRead` (`markRead`).
+pub fn wasRead(state: *const State) bool {
+ return state.read;
+}
+
+pub fn clearRead(state: *State) void {
+ state.read = false;
+}
+
+/// A replica's terminal takes its authority's delta (and the marks riding
+/// it); error.BaseMismatch when it is against a state not held here.
+pub fn apply(state: *State, rep: *screen_state.Replica, bytes: []const u8) !Term.Applied {
+ const applied = try rep.apply(state.gpa, terminalIo(), &state.vt, bytes);
+ takeMarks(state, applied.extra);
+ return applied;
+}
+
+/// ...and rows it asked for.
+pub fn applyRows(state: *State, rep: *screen_state.Replica, bytes: []const u8) !void {
+ return rep.applyRows(state.gpa, &state.vt, bytes);
+}
+
+/// The absolute rows its view shows on a replica.
+pub fn shown(state: *State, rep: *const screen_state.Replica) [2]u64 {
+ return rep.shown(&state.vt);
+}
+
+/// Its screen as text, every row's cells and flags (the replica tests
+/// compare an authority's and a replica's).
+pub fn dumpScreen(state: *State, w: *std.Io.Writer) !void {
+ return screen_state.dumpScreen(&state.vt, w);
+}
+
+/// Rows `lo` to `hi` shown blank on a replica until they come.
+pub fn blank(state: *State, rep: *const screen_state.Replica, lo: u64, hi: u64) void {
+ rep.blank(&state.vt, lo, hi);
+}
+
+/// Its view to row `at` of its history (from the top), or onto its output.
+pub fn viewTo(state: *State, at: ?usize) void {
+ state.vt.screens.active.scroll(if (at) |row| .{ .row = row } else .active);
+}
+
+/// Its view moved by `delta` rows (negative scrolls back).
+pub fn scroll(state: *State, delta: i32) void {
+ state.vt.screens.active.scroll(.{ .delta_row = delta });
+ state.changes +%= 1;
+}
+
+/// Its view back onto the output.
+pub fn follow(state: *State) void {
+ const moved = state.vt.screens.active.pages.viewport != .active;
+ state.vt.screens.active.scroll(.active);
+ state.changes +%= @intFromBool(moved);
+}
+
+/// Its grid reflowed to `cols` by `rows`, now or, `later`, when
+/// `resizeDeferred` is called. A failed reflow keeps the grid it had
+/// rather than dropping a scrollback; the next resize retries with the
+/// same numbers.
+pub fn resize(state: *State, cols: u16, rows: u16, later: bool) void {
+ if (later) {
+ state.resize_to = .{ .cols = cols, .rows = rows };
+ return;
+ }
+ state.changes +%= 1;
+ state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {};
+}
+
+/// The size `resize` left for later, made; whether there was one.
+pub fn resizeDeferred(state: *State) bool {
+ const size = state.resize_to orelse return false;
+ state.resize_to = null;
+ state.changes +%= 1;
+ state.vt.resize(state.gpa, .{ .cols = size.cols, .rows = size.rows }) catch {};
+ return true;
+}
+
+/// The emulator's size in pixels follows the core's cells: kitty graphics
+/// placements are sized by it, and CSI 14/16 t report it.
+pub fn cellPixels(state: *State, w: u32, h: u32) void {
+ if (comptime !images_enabled) return;
+ const vt = &state.vt;
+ vt.width_px = @as(u32, vt.cols) * w;
+ vt.height_px = @as(u32, vt.rows) * h;
+}
+
+/// What it answered its program (a cursor report, its attributes) since
+/// the last call, to be written to its pty behind whatever is queued
+/// there; valid until it is fed again.
+pub fn replies(state: *State) []const u8 {
+ defer state.reply_len = 0;
+ return state.reply[0..state.reply_len];
+}
+
+/// The modes its program set that the core decides by (`Term.Modes`).
+pub fn modes(state: ?*const State) Term.Modes {
+ const s = state orelse return .{};
+ const alternate = s.vt.screens.active_key == .alternate;
+ const mouse_event = s.vt.flags.mouse_event != .none;
+ return .{
+ .mouse = mouse_event,
+ .all_motion = s.vt.flags.mouse_event == .any,
+ // On the alternate screen, which has no scrollback, alternate
+ // scroll (DECSET 1007, on unless turned off) asks for arrow keys.
+ .wheel = mouse_event or (alternate and s.vt.modes.get(.mouse_alternate_scroll)),
+ .focus = s.vt.modes.get(.focus_event),
+ .bracketed_paste = s.vt.modes.get(.bracketed_paste),
+ .alternate = alternate,
+ };
+}
+
+/// A paste as xterm makes one (ghostty's encoder): the control bytes a
+/// paste could smuggle a command in by (ESC, so no ESC[201~ can end
+/// 2004's brackets early, NUL, ^C and the rest of xterm's list) become
+/// spaces, then the text goes inside the brackets when the program set
+/// 2004, else with its newlines as Returns. `text` is rewritten in place.
+pub fn paste(state: ?*const State, text: []u8) [3][]const u8 {
+ return ghostty_vt.input.encodePaste(text, .{ .bracketed = modes(state).bracketed_paste });
+}
+
+/// One mouse event for the program, as xterm reports it (ctlseqs; ghostty's
+/// encoder): the tracking mode it set (1000 clicks, 1002 drags, 1003 all
+/// motion) decides whether it hears of it, the format it set (1006 SGR,
+/// 1015 urxvt, 1005 UTF-8, else X10) how, modifiers as shift+4, meta+8,
+/// ctrl+16. `col`,`row` are the 0-based grid cell; a drag that left the
+/// grid is reported clamped to its edge, motion only when the cell
+/// changed. Empty when the program does not hear of it.
+pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 {
+ const input = ghostty_vt.input;
+ var writer = std.Io.Writer.fixed(buf);
+ var opts: input.MouseEncodeOptions = .{
+ .event = state.vt.flags.mouse_event,
+ .format = state.vt.flags.mouse_format,
+ .size = .{
+ .screen = .{ .width = state.vt.cols, .height = state.vt.rows },
+ .cell = .{ .width = 1, .height = 1 },
+ .padding = .{},
+ },
+ .any_button_pressed = any_pressed,
+ .last_cell = &state.mouse_cell,
+ };
+ // A release is always reported; the rest only over the grid, or held.
+ if (action == .release) opts.any_button_pressed = true;
+ input.encodeMouse(&writer, .{
+ .action = switch (action) {
+ .press => .press,
+ .release => .release,
+ .motion => .motion,
+ },
+ .button = if (button) |b| switch (b) {
+ .left => .left,
+ .middle => .middle,
+ .right => .right,
+ .wheel_up => .four,
+ .wheel_down => .five,
+ .wheel_left => .six,
+ .wheel_right => .seven,
+ } else null,
+ .mods = .{ .shift = mods.shift, .alt = mods.alt, .ctrl = mods.ctrl },
+ .pos = .{ .x = @as(f32, @floatFromInt(col)) + 0.5, .y = @as(f32, @floatFromInt(row)) + 0.5 },
+ }, opts) catch return &.{}; // no report rather than half of one
+ return writer.buffered();
+}
+
+/// The bytes a wheel turn at grid cell `col`,`row` (0-based) sends the
+/// program: its mouse report while it tracks the mouse, else, on the
+/// alternate screen, an arrow key in the cursor keys' mode (none for a
+/// sideways turn). Null when the wheel is not the program's (`Modes.wheel`).
+pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 {
+ const now = modes(state);
+ if (!now.wheel) return null;
+ const m = &state.vt.modes;
+ if (!now.mouse) return switch (turn) {
+ .wheel_up => if (m.get(.cursor_keys)) "\x1bOA" else "\x1b[A",
+ .wheel_down => if (m.get(.cursor_keys)) "\x1bOB" else "\x1b[B",
+ else => null,
+ };
+ return mouse(state, buf, .press, turn, mods, col, row, false);
+}
+
+/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body
+/// 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 scrollback(state: ?*State, gpa: std.mem.Allocator) ![]const u8 {
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ errdefer out.deinit();
+ try writeBody(state, &out.writer);
+ return out.toOwnedSlice();
+}
+
+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 };
+ try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true });
+ if (both.count > 0 and both.final != '\n') try w.writeByte('\n');
+}
+
+/// Passes bytes through, remembering how many and the last one.
+const TeeWriter = struct {
+ a: *std.Io.Writer,
+ count: usize = 0,
+ final: u8 = 0,
+ writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} },
+
+ fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize {
+ const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w));
+ var n: usize = 0;
+ for (data[0 .. data.len - 1]) |bytes| {
+ try t.a.writeAll(bytes);
+ t.note(bytes);
+ n += bytes.len;
+ }
+ const pattern = data[data.len - 1];
+ for (0..splat) |_| {
+ try t.a.writeAll(pattern);
+ t.note(pattern);
+ n += pattern.len;
+ }
+ return n;
+ }
+
+ fn note(t: *TeeWriter, bytes: []const u8) void {
+ if (bytes.len == 0) return;
+ t.count += bytes.len;
+ t.final = bytes[bytes.len - 1];
+ }
+};
+
+/// 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);
+ writeBody(state, &counting.writer) catch unreachable; // a discarding writer never fails
+ return @intCast(counting.fullCount());
+}
+
+/// Its emulator and what it holds, freed; its kitty images' caches were
+/// `gpa`'s.
+pub fn close(state: *State, gpa: std.mem.Allocator) void {
+ if (comptime images_enabled) state.images.deinit(gpa);
+ state.stream.deinit();
+ const own = state.gpa;
+ state.vt.deinit(own);
+ own.destroy(state);
+}
+
+/// A terminal pane's emulator, `cols` by `rows`, as `open` 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,
+ .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0,
+ // Every kitty medium, as ghostty and kitty take them: a file (t=f),
+ // a temporary file it then deletes (t=t, in the temp directory and
+ // named as one) and shared memory (t=s), beside direct data. libghostty
+ // 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 if (@FieldType(ghostty_vt.Terminal.Options, "kitty_image_loading_limits") == void) {} else .direct,
+ });
+}
+
+/// A new emulator, `cols` by `rows`, allocated with `gpa`, its own from
+/// then on (`State.gpa`).
+pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State {
+ const state = try gpa.create(State);
+ errdefer gpa.destroy(state);
+ // Every other field its default, never what the heap had: a digest
+ // reads them, and two replicas must agree (core/replica.zig).
+ state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows), .stream = undefined };
+ state.wire();
+ return state;
+}
+
+/// 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";
+
+/// 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) and
+/// its history marked off from what the new shell prints.
+pub fn revive(state: *State) void {
+ // 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 (state.vt.screens.active_key == .alternate) ingest(state, "\x1b[?1049l");
+ ingest(state, "\x1b[?1l\x1b>\x1b[?25h\x1b[?7h\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[<u");
+ ingest(state, restored_banner);
+}
+
+/// Feed the emulator. Live output and restoration share this byte path,
+/// then apply different views.
+fn ingest(state: *State, bytes: []const u8) void {
+ state.stream.nextSlice(bytes);
+ state.changes +%= 1;
+}
+
+const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 };
+
+fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin {
+ 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;
+ var node = pages.pages.last.?;
+ while (left >= node.rows()) {
+ left -= node.rows();
+ node = node.prev.?;
+ }
+ const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch {
+ failed.* = true;
+ return .{};
+ };
+ return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) };
+}
+
+fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 {
+ const pin = row.pin orelse return row.offset;
+ const alive = pages orelse return 0;
+ if (pin.garbage) return 0;
+ var after: usize = 0;
+ var node = alive.pages.last;
+ while (node) |item| : (node = item.prev) {
+ if (item == pin.node)
+ return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset;
+ after += item.rows();
+ }
+ return 0;
+}
+
+/// One read of its program's output. `track` are rows (absolute, from the
+/// top of the history) the core keeps positions on; each is told in
+/// `rows` where it is after the read and in `erased` whether the program
+/// erased it (a negative row passes through untouched). With nothing
+/// tracked the read is parsed and nothing more.
+pub fn feed(state: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Term.Told {
+ if (tracked.len == 0) {
+ ingest(state, bytes);
+ return .{ .rows = rows[0..0], .erased = erased[0..0], .cleared = false, .alive = true, .failed = false };
+ }
+ const screens = &state.vt.screens;
+ const active = screens.active_key;
+ const generation = screens.generation(active);
+ const pages = &screens.active.pages;
+ var failed = false;
+ var room: [512]RowPin = undefined;
+ const pins = if (tracked.len <= room.len) room[0..tracked.len] else state.gpa.alloc(RowPin, tracked.len) catch {
+ ingest(state, bytes);
+ @memcpy(rows[0..tracked.len], tracked);
+ @memset(erased[0..tracked.len], false);
+ return .{ .rows = rows[0..tracked.len], .erased = erased[0..tracked.len], .cleared = false, .alive = true, .failed = true };
+ };
+ defer if (tracked.len > room.len) state.gpa.free(pins);
+ for (pins, tracked) |*pin, row| pin.* = trackRow(pages, row, &failed);
+ // Whether the program cleared the screen (ED 2, a switch of screens);
+ // pardes reads the flag nowhere else.
+ state.vt.flags.dirty.clear = false;
+ ingest(state, bytes);
+ const cleared = state.vt.flags.dirty.clear;
+ // RIS can destroy the alternate screen and every pin it owned.
+ const alive: ?*ghostty_vt.PageList = if (screens.generation(active) == generation) pages else null;
+ for (pins, rows[0..tracked.len], erased[0..tracked.len]) |pin, *row, *gone| {
+ row.* = pinnedRow(alive, pin);
+ gone.* = alive != null and pin.pin != null and pin.pin.?.garbage;
+ if (alive) |owner| if (pin.pin) |held| owner.untrackPin(held);
+ }
+ return .{ .rows = rows[0..tracked.len], .erased = erased[0..tracked.len], .cleared = cleared, .alive = alive != null, .failed = failed };
+}
+
+/// Where the shell is in its command cycle (`Term.Prompt`); all zero
+/// without an emulator.
+pub fn prompt(state: ?*State) Term.Prompt {
+ const s = state orelse return .{};
+ const marks = &s.stream.handler;
+ const cursor = &s.vt.screens.active.cursor;
+ // At a prompt's input: on the alternate screen too, where a program
+ // killed there (htop, `sig KILL`) left the emulator and the shell then
+ // drew its prompt, marks and all. A full-screen program draws no
+ // prompt marks.
+ const ready = cursor.semantic_content == .input;
+ // Nothing typed on its line: no input left of the cursor and none
+ // under it (text typed and then Ctrl-A'd starts at the cursor).
+ // Nothing further right counts: that is where fish draws a right
+ // prompt, and fish suggests nothing on an empty line.
+ const empty = ready and empty: {
+ const row = cursor.page_pin.cells(.all);
+ for (row[0..@min(cursor.x + 1, row.len)]) |cell|
+ if (cell.semantic_content == .input and !cell.isEmpty()) break :empty false;
+ break :empty true;
+ };
+ return .{
+ .phase = switch (marks.phase) {
+ .none => .none,
+ .prompt => .prompt,
+ .input => .input,
+ .running => .running,
+ },
+ .started = marks.started,
+ .prompts = marks.prompts,
+ .declined = marks.declined,
+ .continuation = marks.continuation,
+ .finished = if (marks.finished) |f| .{ .seq = f.seq, .status = f.status } else null,
+ .input_ready = ready,
+ .input_empty = empty,
+ .at_prompt = s.vt.cursorIsAtPrompt(),
+ };
+}
+
+/// What the newest finished command printed: the screen text between its
+/// C and D marks, read from at most `max_rows` rows above its end, so a
+/// command that printed the whole history costs no more than its tail.
+/// The shell exited in the middle of a command (its `exit 3`): no end mark
+/// will come, so the command's output ends where the cursor is.
+pub fn endOutputHere(state: *State) void {
+ const marks = &state.stream.handler;
+ if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true);
+}
+
+pub fn commandOutput(state: ?*State, gpa: std.mem.Allocator, max_rows: usize) !Term.CommandOutput {
+ // Unless there is text to read, whether the nothing it printed is the
+ // whole of it.
+ const whole = printed: {
+ const s = state orelse break :printed true;
+ const marks = &s.stream.handler;
+ const start = marks.out_start orelse break :printed false;
+ const end = marks.out_end orelse break :printed false;
+ const screen = s.vt.screens.get(.primary) orelse break :printed false;
+ if (end.garbage) break :printed false;
+ var whole = !marks.lost and !start.garbage;
+ // Nothing printed: the whole of it.
+ if (start.eql(end.*)) break :printed whole;
+ // D is where the next prompt begins: the output ends a cell before.
+ // An end at the very top, or before the start, is output a redraw
+ // moved (a prompt drawn over it in a window two rows high): how
+ // much is not known, so it is not called whole.
+ const last = end.leftWrap(1) orelse break :printed false;
+ if (last.before(start.*)) break :printed false;
+ var from = start.*;
+ if (last.up(max_rows)) |floor| if (from.before(floor)) {
+ from = floor;
+ from.x = 0;
+ whole = false;
+ };
+ return .{
+ .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }),
+ .whole = whole,
+ };
+ };
+ return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = whole };
+}
+
+/// One key for its program, as the program's keyboard protocol and modes
+/// ask for it, written to `out`.
+pub fn key(state: *State, k: Key, out: *std.Io.Writer) !void {
+ const input = ghostty_vt.input;
+ const function_keys = [Key.f25 - Key.f1 + 1]input.Key{ .f1, .f2, .f3, .f4, .f5, .f6, .f7, .f8, .f9, .f10, .f11, .f12, .f13, .f14, .f15, .f16, .f17, .f18, .f19, .f20, .f21, .f22, .f23, .f24, .f25 };
+ const physical: input.Key = switch (k.cp) {
+ Key.enter => .enter,
+ Key.backspace => .backspace,
+ Key.tab => .tab,
+ Key.escape => .escape,
+ Key.up => .arrow_up,
+ Key.down => .arrow_down,
+ Key.left => .arrow_left,
+ Key.right => .arrow_right,
+ Key.home => .home,
+ Key.end => .end,
+ Key.page_up => .page_up,
+ Key.page_down => .page_down,
+ Key.delete => .delete,
+ Key.insert => .insert,
+ Key.print_screen => .print_screen,
+ Key.scroll_lock => .scroll_lock,
+ Key.pause => .pause,
+ Key.menu => .context_menu,
+ Key.f1...Key.f25 => function_keys[k.cp - Key.f1],
+ else => if (k.cp < 128) input.Key.fromASCII(@intCast(k.cp)) orelse .unidentified else .unidentified,
+ };
+ var utf8: [4]u8 = undefined;
+ const text_cp = if (k.shift and k.cp >= 'a' and k.cp <= 'z') k.cp - 'a' + 'A' else k.cp;
+ // A key with no text of its own types its code point only when that
+ // is a character: the kitty keyboard protocol numbers function and
+ // modifier keys in the private use area (F3 is U+E016), and a shell
+ // was typed those as junk.
+ const text = if (k.text.len > 0) k.text else if (k.cp >= 32 and k.cp < Key.up and k.cp != Key.backspace and !(k.cp >= 0xE000 and k.cp <= 0xF8FF))
+ utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return]
+ else
+ "";
+ try input.encodeKey(out, .{
+ .key = physical,
+ .mods = .{ .ctrl = k.ctrl, .alt = k.alt, .shift = k.shift },
+ .consumed_mods = .{ .shift = k.text.len > 0 and k.shift },
+ .utf8 = text,
+ .unshifted_codepoint = if (k.cp >= 'A' and k.cp <= 'Z') k.cp - 'A' + 'a' else if (k.cp < Key.up) k.cp else 0,
+ }, options: {
+ var opts = input.KeyEncodeOptions.fromTerminal(&state.vt);
+ // fromTerminal cannot know this one and says so, defaulting to
+ // "option is not alt" — right for an app that lets macOS do the
+ // unicode translation and hands the encoder the composed text.
+ // Every pardes shell resolves the modifier itself and hands the
+ // core the BASE key with the alt bit and no text at all (see
+ // PardesView.keyDown, and app.mjs doing the same with the same
+ // two bits), so by the time this runs alt already means alt.
+ // Left at the default, a macOS build drops the ESC prefix on
+ // the floor and forwards Alt-n to the child as a bare `n`.
+ opts.macos_option_as_alt = .true;
+ break :options opts;
+ });
+}
+
+/// How many cells left or right of the cursor a click on viewport row
+/// `row`, column `col` of the text shown (the prompt cut off) is, at the
+/// prompt the cursor is at: what moves the shell's cursor there. Null
+/// when the cursor is at no prompt, or the click is before the prompt.
+pub fn promptMoves(state: *State, row: i32, col: i32) ?Term.Moves {
+ if (!state.vt.cursorIsAtPrompt() or row < 0) return null;
+ const screen = state.vt.screens.active;
+ var grid_col: i32 = @max(0, col);
+ if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(row) } })) |row_pin| {
+ if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) {
+ .cut => |cols| grid_col += @intCast(cols),
+ .keep, .blank => {},
+ };
+ }
+ const click_pin = screen.pages.pin(.{
+ .viewport = .{ .x = @intCast(grid_col), .y = @intCast(row) },
+ }) orelse return null;
+ const cursor_pin = screen.cursor.page_pin.*;
+ var prompts = cursor_pin.promptIterator(.left_up, null);
+ const prompt_pin = prompts.next() orelse return null;
+ if (click_pin.before(prompt_pin)) return null;
+ const moves = screen.promptClickMove(click_pin);
+ return .{ .left = moves.left, .right = moves.right };
+}
+
+/// 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.
+fn promptCut(pin: ghostty_vt.Pin) PromptCut {
+ const cells = pin.cells(.all);
+ var cols: usize = 0;
+ while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1;
+ // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or
+ // a repaint that has moved on. Nothing here is the prompt, so hide nothing.
+ if (cols == 0) return .keep;
+ // ...and all prompt, nothing typed yet: the row is chrome end to end.
+ if (cols >= cells.len) return .blank;
+ return .{ .cut = cols };
+}
+
+/// How much of its row `row` (from the top of the history) the prompt it
+/// starts with is; null for a row no prompt starts (the core measures the
+/// cut columns in the row's text, Term.promptPrefix).
+pub fn promptCutAt(state: *State, row: i32) ?PromptCut {
+ if (row < 0) return null;
+ const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return null;
+ if (pin.rowAndCell().row.semantic_prompt == .none) return null;
+ return promptCut(pin);
+}
+
+/// What a predicted echo reads of cell `x`, `y` of its active area
+/// (core/echo.zig): null off it.
+pub fn echoCell(state: *const State, x: u16, y: u16) ?Term.EchoCell {
+ if (y >= state.vt.rows) return null;
+ const ci = state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return null;
+ return .{ .cp = ci.cell.codepoint(), .input = ci.cell.semantic_content == .input, .style = ci.cell.style_id };
+}
+
+fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 {
+ const cols = switch (promptCut(pin)) {
+ .keep => return raw,
+ .blank => return "",
+ .cut => |n| n,
+ };
+ const cells = pin.cells(.all);
+ var at: usize = 0;
+ var col: usize = 0;
+ while (col < cols and at < raw.len) {
+ const cell = &cells[col];
+ at = @min(raw.len, at + dumpedBytes(pin, cell));
+ // the tail cell of a wide glyph spells nothing of its own
+ col += if (cell.wide == .wide) @as(usize, 2) else 1;
+ }
+ return std.mem.trimEnd(u8, raw[at..], " \t");
+}
+
+fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize {
+ switch (cell.wide) {
+ .spacer_head, .spacer_tail => return 0,
+ .narrow, .wide => {},
+ }
+ var n: usize = switch (cell.content_tag) {
+ .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength(
+ cell.codepoint(),
+ ) catch 1,
+ // A cell carrying only a colour still spells one blank in the dump.
+ else => 1,
+ };
+ if (cell.content_tag == .codepoint_grapheme) {
+ if (pin.grapheme(cell)) |extra| for (extra) |cp| {
+ n += std.unicode.utf8CodepointSequenceLength(cp) catch 1;
+ };
+ }
+ return n;
+}
+
+/// Its rows `first` and the `count` after it (from the top of its
+/// history) as text, a prompt's own cells cut off the rows it starts:
+/// `arena`'s. An edit copy's rows as they were (core/ansi.zig).
+pub fn editRows(state: *State, arena: std.mem.Allocator, first: usize, count: usize) ![]const []const u8 {
+ const screen = state.vt.screens.active;
+ const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return error.NoRow;
+ const br = screen.pages.pin(.{ .screen = .{
+ .x = screen.pages.cols - 1,
+ .y = @intCast(first + count - 1),
+ } }) orelse return error.NoRow;
+ var output: std.Io.Writer.Allocating = .init(arena);
+ try screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false });
+ const shell = try arena.alloc([]const u8, count);
+ var raw = std.mem.splitScalar(u8, output.written(), '\n');
+ var pins = tl.rowIterator(.right_down, br);
+ for (shell) |*row| {
+ const text = raw.next() orelse "";
+ row.* = if (pins.next()) |pin|
+ if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text
+ else
+ text;
+ }
+ return shell;
+}
+
+/// 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;
+}
+
+/// 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 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);
+ errdefer alloc.free(text);
+ var at: usize = 0;
+ var n: usize = 0;
+ var it = std.mem.splitScalar(u8, full, '\n');
+ while (it.next()) |raw| {
+ const kept = if (pit.next()) |pin|
+ if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw
+ else
+ raw;
+ if (n > 0) {
+ text[at] = '\n';
+ at += 1;
+ }
+ @memcpy(text[at..][0..kept.len], kept);
+ lines[n] = text[at..][0..kept.len];
+ at += kept.len;
+ n += 1;
+ }
+ text[at] = '\n';
+ at += 1;
+ lines[n] = text[at..][0..0];
+ n += 1;
+ std.debug.assert(n == n_rows);
+ return .{ .text_alloc = text, .text = text[0..at], .rows = lines };
+}
+
+/// 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
+ ln
+ else
+ ln;
+ n += 1;
+ }
+ std.debug.assert(n == vp.len);
+ return vp;
+}
+
+/// Its view's rows as cells, for the core's paint (Term.paint, the core's
+/// core/ansi.zig): `rows.len` rows from the view's row `first`, `cols`
+/// cells each into `cells`, each its style in the theme's colours (through
+/// the filter when `filtered`), the bytes it spells in the view's text and
+/// its width; each row whether a prompt starts it, and how much of it that
+/// is.
+pub fn paint(state: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void {
+ var filter_storage: Filter = undefined;
+ const filter: ?*Filter = if (filtered) blk: {
+ filter_storage = filterOf(ink, palette, &state.vt);
+ break :blk &filter_storage;
+ } else null;
+ // DECSCNM, read once: the filtered palette folds it in itself, the raw
+ // path needs it per cell.
+ const scnm = state.vt.modes.get(.reverse_colors);
+ const pages = &state.vt.screens.active.pages;
+ for (rows, 0..) |*row, vi| {
+ row.* = .{ .prompt = null, .placeholder = false, .len = 0 };
+ const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(first + vi) } }) orelse continue;
+ const flags = row_pin.rowAndCell().row;
+ if (flags.semantic_prompt != .none) row.prompt = promptCut(row_pin);
+ row.placeholder = flags.kitty_virtual_placeholder;
+ const out = cells[vi * cols ..][0..cols];
+ var x: u16 = 0;
+ while (x < cols) : (x += 1) {
+ const ci = cellAt(pages, row_pin, x) orelse break;
+ out[x] = .{
+ .style = cellStyle(ink, ci, filter, scnm),
+ .bytes = @intCast(@min(dumpedBytes(row_pin, ci.cell), std.math.maxInt(u16))),
+ .wide = switch (ci.cell.wide) {
+ .narrow => .narrow,
+ .wide => .wide,
+ .spacer_tail => .spacer_tail,
+ .spacer_head => .spacer_head,
+ },
+ };
+ }
+ row.len = x;
+ }
+}
+
+/// 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 };
+}
+
+// A cell's underline styles are SGR's, in SGR's order (`off` its `none`): a
+// cast takes one to the other (cellStyle, and pager.zig's attribute).
+comptime {
+ for (@typeInfo(@FieldType(plain.CellStyle, "ul")).@"enum".field_names, 0..) |name, i|
+ if (@backingInt(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's");
+}
+
+fn cellStyle(ink: *const Ink, ci: ghostty_vt.PageList.Cell, filtered: ?*Filter, scnm: bool) plain.CellStyle {
+ const style = ci.style();
+ var cs: plain.CellStyle = .{
+ .fg = if (filtered) |colors| filterFg(colors, style) else ghostColor(ink, style.fg_color, scnm),
+ .bg = if (filtered) |colors| filterBg(colors, style, ci.cell) else ghostColor(ink, style.bg_color, !scnm),
+ .bold = style.flags.bold,
+ .dim = style.flags.faint,
+ .italic = style.flags.italic,
+ .blink = style.flags.blink,
+ .reverse = style.flags.inverse,
+ .invisible = style.flags.invisible,
+ .strikethrough = style.flags.strikethrough,
+ .ul = @fromBackingInt(@intCast(@backingInt(style.flags.underline))),
+ };
+ if (filtered == null) switch (ci.cell.content_tag) {
+ .bg_color_palette => cs.bg = ink.palColor(ci.cell.content.color_palette.data),
+ .bg_color_rgb => {
+ const rgb = ci.cell.content.color_rgb;
+ cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } };
+ },
+ else => {},
+ };
+ return cs;
+}
+
+pub fn asPardesColor(rgb: GColor.RGB) plain.Color {
+ return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } };
+}
+
+fn asTriple(rgb: GColor.RGB) [3]u8 {
+ return .{ rgb.r, rgb.g, rgb.b };
+}
+
+/// A program's colours mapped to the theme (Term.Filter): for a terminal's
+/// cells (`vt`), or a +Pager's spans (`vt` null, the program's palette
+/// xterm's own).
+pub fn filterOf(ink: *const Ink, palette: *FilterPalette, vt: ?*const ghostty_vt.Terminal) Filter {
+ var source = GColor.default;
+ if (vt) |t| {
+ for (&source, 0..) |*rgb, i|
+ rgb.* = t.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*;
+ }
+ var theme_bg = asGhostRgb(ink.bg orelse ink.tag_bg);
+ var theme_fg = asGhostRgb(ink.fg orelse ink.tag_fg);
+ var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null;
+ var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null;
+ if (vt != null and vt.?.modes.get(.reverse_colors)) {
+ std.mem.swap(GColor.RGB, &theme_bg, &theme_fg);
+ std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg);
+ }
+ var self: Filter = .{
+ .target = filterPalette(palette, ink),
+ .theme_bg = asTriple(theme_bg),
+ .theme_fg = asTriple(theme_fg),
+ .default_bg = asTriple(theme_bg),
+ .fallback_fg = asTriple(theme_fg),
+ .default_bg_luminance = luminanceOf(theme_bg),
+ .fg_for_palette = undefined,
+ .bg_for_palette = undefined,
+ .fg_default = undefined,
+ .bg_default = undefined,
+ };
+ var default_bg = theme_bg;
+ if (dynamic_bg) |rgb| default_bg = keyedRgb(&self, rgb);
+ self.default_bg = asTriple(default_bg);
+ self.default_bg_luminance = luminanceOf(default_bg);
+ if (theme_bg.contrast(default_bg) > theme_fg.contrast(default_bg))
+ self.fallback_fg = asTriple(theme_bg);
+
+ self.fg_default = asPardesColor(legible(&self, if (dynamic_fg) |rgb| keyedRgb(&self, rgb) else theme_fg));
+ self.bg_default = asPardesColor(default_bg);
+ for (&source, 0..) |current, i| {
+ const idx: u8 = @intCast(i);
+ const mapped = paletteRgb(&self, idx, current);
+ self.fg_for_palette[idx] = asPardesColor(legible(&self, mapped));
+ self.bg_for_palette[idx] = asPardesColor(mapped);
+ }
+ return self;
+}
+
+/// The filter a +Pager's spans are drawn through (Term.filter).
+pub fn pagerFilter(ink: *const Ink, palette: *FilterPalette) Filter {
+ return filterOf(ink, palette, null);
+}
+
+fn filterFg(self: *Filter, style: ghostty_vt.Style) plain.Color {
+ return switch (style.fg_color) {
+ .none => self.fg_default,
+ .palette => |idx| self.fg_for_palette[idx],
+ .rgb => |rgb| asPardesColor(legible(self, keyedRgb(self, rgb))),
+ };
+}
+
+fn filterBg(self: *Filter, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) plain.Color {
+ switch (cell.content_tag) {
+ .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data],
+ .bg_color_rgb => {},
+ else => switch (style.bg_color) {
+ .none => return self.bg_default,
+ .palette => |idx| return self.bg_for_palette[idx],
+ .rgb => {},
+ },
+ }
+ // Truecolour, from either the cell or its style.
+ return asPardesColor(keyedRgb(self, style.bg(cell, &GColor.default).?));
+}
+
+/// A +Pager span's colour (Term.page), as `filterFg` and `filterBg` map a
+/// cell's.
+pub fn spanColor(self: *Filter, color: plain.Color, is_bg: bool) plain.Color {
+ return switch (color) {
+ .default => color,
+ .index => |idx| if (is_bg) self.bg_for_palette[idx] else self.fg_for_palette[idx],
+ .rgb => |rgb| blk: {
+ const keyed = keyedRgb(self, asGhostRgb(rgb));
+ break :blk asPardesColor(if (is_bg) keyed else legible(self, keyed));
+ },
+ };
+}
+
+pub fn legible(self: *const Filter, rgb: GColor.RGB) GColor.RGB {
+ if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >=
+ min_contrast) return rgb;
+ return asGhostRgb(self.fallback_fg);
+}
+
+pub fn paletteRgb(self: *Filter, idx: u8, current: GColor.RGB) GColor.RGB {
+ if (current.eql(GColor.default[idx])) return asGhostRgb(self.target[idx]);
+ return keyedRgb(self, current);
+}
+
+pub fn keyedRgb(self: *Filter, rgb: GColor.RGB) GColor.RGB {
+ return asGhostRgb(self.target[nearestKey(self, rgb)]);
+}
+
+pub fn nearestKey(self: *Filter, rgb: GColor.RGB) u8 {
+ const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b;
+ const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24);
+ if (self.cache_valid[slot] and asGhostRgb(self.cache_rgb[slot]).eql(rgb))
+ return self.cache_key[slot];
+
+ var best: u8 = 0;
+ var best_distance: u32 = std.math.maxInt(u32);
+ for (GColor.default, 0..) |candidate, i| {
+ const distance = colorDistance(rgb, candidate);
+ // Strict comparison makes duplicate-colour ties stable at the
+ // lowest canonical xterm key.
+ if (distance < best_distance) {
+ best_distance = distance;
+ best = @intCast(i);
+ }
+ }
+ self.cache_rgb[slot] = asTriple(rgb);
+ self.cache_key[slot] = best;
+ self.cache_valid[slot] = true;
+ return best;
+}
+
+const channel_luminance: [256]f64 = blk: {
+ @setEvalBranchQuota(20000);
+ var table: [256]f64 = undefined;
+ for (&table, 0..) |*slot, c| {
+ const normalized: f64 = @as(f64, @floatFromInt(c)) / 255;
+ slot.* = if (normalized <= 0.03928)
+ normalized / 12.92
+ else
+ std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4);
+ }
+ break :blk table;
+};
+
+pub fn luminanceOf(rgb: GColor.RGB) f64 {
+ return 0.2126 * channel_luminance[rgb.r] +
+ 0.7152 * channel_luminance[rgb.g] +
+ 0.0722 * channel_luminance[rgb.b];
+}
+
+/// ghostty's `RGB.contrast` with both luminances already in hand.
+fn contrastOf(a_luminance: f64, b_luminance: f64) f64 {
+ const lighter = @max(a_luminance, b_luminance);
+ const darker = @min(a_luminance, b_luminance);
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 {
+ const dr = @as(i32, a.r) - @as(i32, b.r);
+ const dg = @as(i32, a.g) - @as(i32, b.g);
+ const db = @as(i32, a.b) - @as(i32, b.b);
+ return @intCast(dr * dr + dg * dg + db * db);
+}
+
+fn ghostColor(ink: *const Ink, color: ghostty_vt.Style.Color, is_bg: bool) plain.Color {
+ return switch (color) {
+ .none => blk: {
+ const t = if (is_bg) ink.bg else ink.fg;
+ break :blk if (t) |c| .{ .rgb = c } else .default;
+ },
+ .palette => |idx| ink.palColor(idx),
+ .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } },
+ };
+}
+
+/// 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.
+pub fn due(state: *const State) ?u64 {
+ if (comptime !images_enabled) return null;
+ return state.images.animation_due_ms;
+}
+
+/// The Petscii builtin on a terminal: its kitty graphics as glyph art,
+/// or back to pixels where the shell draws pixels.
+pub fn togglePetscii(state: *State) void {
+ if (comptime !images_enabled) return;
+ state.images.petscii = !state.images.petscii;
+}
+
+/// Whether the pane draws its kitty graphics as glyph art by choice; null
+/// for a pane with no emulator.
+pub fn petscii(maybe: ?*const State) ?bool {
+ if (comptime !images_enabled) return null;
+ const state = maybe orelse return null;
+ return state.images.petscii;
+}
+
+/// Whether the screen showing holds any kitty graphics image.
+pub fn hasImages(maybe: ?*const State) bool {
+ if (comptime !images_enabled) return false;
+ const state = maybe orelse return false;
+ return state.vt.screens.active.kitty_images.images.count() > 0;
+}
+
+/// Its kitty graphics over the body's rows, as placements appended to
+/// `out` (after the rows and their colours: placeholder cells are blanked
+/// in `frame`, `frame_cols` wide). `at.rows_of` maps its view's rows to
+/// the body's; a prompt row outside tty mode is cut or hidden, its columns
+/// not the grid's, and shows none.
+pub fn images(state: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void {
+ if (comptime !images_enabled) return;
+ const screen = state.vt.screens.active;
+ var rows_of: [1024]?u16 = undefined;
+ const vp_rows = @min(at.rows_of.len, rows_of.len);
+ var any_placeholder = false;
+ for (rows_of[0..vp_rows], at.rows_of[0..vp_rows], 0..) |*slot, body_row, vi| {
+ slot.* = null;
+ const vr = body_row orelse continue;
+ const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue;
+ const flags = row_pin.rowAndCell().row;
+ if (!at.tty_mode and flags.semantic_prompt != .none) continue;
+ any_placeholder = any_placeholder or flags.kitty_virtual_placeholder;
+ slot.* = vr;
+ }
+ // Nothing to draw, no placeholder to blank and nothing cached to let
+ // go: the common case costs the rows' flags.
+ if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return;
+ state.images.draw(gpa, &state.vt, at, rows_of[0..vp_rows], out, frame, frame_cols);
+}
+
+test "the luminance table answers exactly what ghostty computes" {
+ for (0..256) |i| {
+ const c: u8 = @intCast(i);
+ const grey: GColor.RGB = .{ .r = c, .g = c, .b = c };
+ try std.testing.expectEqual(grey.luminance(), luminanceOf(grey));
+ }
+ // Channel weights are asymmetric, so a grey ramp alone would not catch a
+ // transposed coefficient. The palette is what the tables enumerate.
+ for (GColor.default) |candidate| {
+ try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate));
+ for (GColor.default) |page| {
+ try std.testing.expectEqual(
+ candidate.contrast(page),
+ contrastOf(luminanceOf(candidate), luminanceOf(page)),
+ );
+ }
+ }
+}