//! A terminal pane: its VT emulator, prompt rows, the edit overlay //! typed over shell rows, and the Filter that recolours output to the theme. const panes = @import("../panes.zig"); const std = @import("std"); const plain = @import("plain"); const pardes = @import("../pardes.zig"); const config = @import("../config.zig"); const Pardes = pardes.Pardes; const Surface = pardes.Surface; const modal = @import("../modal.zig"); const tracy = @import("../tracy.zig"); const tagline = @import("../tagline.zig"); const Key = plain.Key; const Pane = panes.Pane; const Term = @import("../Term.zig"); const BodyWalk = @import("../body_layer.zig").BodyWalk; const screen_state = @import("screen_state.zig"); const EditText = panes.EditText; const File = panes.File; const ghostty_vt = @import("ghostty-vt"); const EditBuffer = panes.Text.EditBuffer; const Snapshot = panes.Text.Snapshot; const history_max = panes.Text.history_max; pub const VtSlot = ghostty_vt.Terminal; /// A cell of an emulator's pages, as `getCell` reads it (src/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//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: enum { none, prompt, input, running } = .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: ?struct { seq: u32, status: ?i32 } = 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 emulator as its program has made it, for the replay digest /// (src/walk.zig): the active screen's text, how much history is above /// it and where the view is, the cursor, the answers not yet written. /// Not its pages (their addresses are its own), nor the history's text /// (the screen's was all of it once, and a session's digest is taken /// every step), nor the kitty images, whose media is read off the host: /// a replica's terminal is the authority's screen state from phase 5 /// on (docs/next-daemon.md). pub fn digest(s: *const State, h: *pardes.walk.Hasher) void { // Under screen-state terminals the emulator is the authority's, and // a replica's is what the last delta made it: compared as screens // (test/replicas.zig), not step by step. if (pardes.tape.screenState()) return; s.digestScreen(h, true); } /// `view`: where its view is too (a replica's speculation may move it). pub fn digestScreen(s: *const State, h: *pardes.walk.Hasher, view: bool) void { const screen = s.vt.screens.active; const sb = screen.pages.scrollbar(); const cur = screen.cursor; const offset = if (view) sb.offset else 0; const facts = .{ sb.total, offset, sb.len, cur.x, cur.y, s.vt.modes.get(.cursor_visible), s.vt.screens.active_key, s.reply_dropped }; inline for (facts) |fact| h.update(std.mem.asBytes(&fact)); h.update(s.reply[0..s.reply_len]); var buf: [4096]u8 = undefined; var text: std.Io.Writer.Hashing(pardes.walk.Hasher) = .initHasher(h.*, &buf); if (screen.pages.getBottomRight(.active)) |br| screen.dumpString(&text.writer, .{ .tl = screen.pages.getTopLeft(.active), .br = br, .unwrap = false }) catch unreachable; // a hashing writer never fails text.writer.flush() catch unreachable; // a hashing writer never fails h.* = text.hasher; } /// What the dump keeps of a terminal beside its emulator, by name as /// every dump is (src/walk.zig). const Parts = struct { reply: []const u8 = "", reply_dropped: u32 = 0, mouse_cell: ?ghostty_vt.Coordinate = null, petscii: bool = false, /// The view's top row, counted from the top of the history. view: usize = 0, phase: @FieldType(MarkedHandler, "phase") = .none, started: u32 = 0, prompts: u32 = 0, declined: u32 = 0, continuation: bool = false, lost: bool = false, finished: @FieldType(MarkedHandler, "finished") = null, out_start: ?ghostty_vt.Coordinate = null, out_end: ?ghostty_vt.Coordinate = null, }; fn pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?ghostty_vt.Coordinate { const pin = slot orelse return null; const screen = s.vt.screens.get(.primary) orelse return null; return (screen.pages.pointFromPin(.screen, pin.*) orelse return null).screen; } /// The dump's: ghostty's snapshot of the emulator (both screens, their /// history, styles, links and kitty images), then `Parts`. A sequence /// its program had begun and not ended is not kept: the snapshot is at /// the ground state. pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { const h = &s.stream.handler; const parts: Parts = .{ .reply = s.reply[0..s.reply_len], .reply_dropped = s.reply_dropped, .mouse_cell = s.mouse_cell, .petscii = if (comptime images_enabled) s.images.petscii else false, .view = s.vt.screens.active.pages.scrollbar().offset, .phase = h.phase, .started = h.started, .prompts = h.prompts, .declined = h.declined, .continuation = h.continuation, .lost = h.lost, .finished = h.finished, .out_start = s.pinAt(h.out_start), .out_end = s.pinAt(h.out_end), }; const bytes = try pardes.walk.save(Parts, gpa, &parts); defer gpa.free(bytes); try w.writeAll(std.mem.asBytes(&@as(u64, bytes.len))); try w.writeAll(bytes); // A join's (dump.zig `dumpJoin`): its size alone, an emulator made // afresh there, which its first delta replaces. if (pardes.dump.slim_terminals) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows })); try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground }); } /// What `dumpRead` made, freed: a load that failed after it. pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void { if (comptime images_enabled) s.images.deinit(gpa); s.stream.deinit(); s.vt.deinit(gpa); } /// `dumpWrite`'s back into `out`, a new State, as `create` makes one. pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void { if (bytes.len < 8) return error.EndOfDump; const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump; if (bytes.len - 8 < n) return error.EndOfDump; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const parts = try pardes.walk.load(Parts, arena.allocator(), bytes[8..][0..n], null); var reader: std.Io.Reader = .fixed(bytes[8 + n ..]); if (reader.buffer.len == 4) { const size = std.mem.bytesToValue([2]u16, bytes[8 + n ..][0..4]); out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined }; } else { var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ .max_continuation_bytes = 0, .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, }); defer decoded.deinit(gpa); out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; } if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); }; out.wire(); const reply = parts.reply[0..@min(parts.reply.len, out.reply.len)]; @memcpy(out.reply[0..reply.len], reply); out.reply_len = @intCast(reply.len); out.reply_dropped = parts.reply_dropped; out.mouse_cell = parts.mouse_cell; out.images = if (images_enabled) .{ .petscii = parts.petscii } else {}; const h = &out.stream.handler; h.phase = parts.phase; h.started = parts.started; h.prompts = parts.prompts; h.declined = parts.declined; h.continuation = parts.continuation; h.lost = parts.lost; h.finished = parts.finished; if (out.vt.screens.get(.primary)) |screen| { inline for (.{ .{ "out_start", parts.out_start }, .{ "out_end", parts.out_end } }) |pair| if (pair[1]) |at| { if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null; }; } const screen = out.vt.screens.active; const bottom = screen.pages.scrollbar().offset; screen.scroll(.{ .delta_row = @as(isize, @intCast(parts.view)) - @as(isize, @intCast(bottom)) }); } /// 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(); } }; const GColor = ghostty_vt.color; const FilterPaletteKey = struct { bg: GColor.RGB, fg: GColor.RGB, base: [16]GColor.RGB, }; pub const FilterPalette = LivePalette; const LivePalette = struct { key: ?FilterPaletteKey = null, colors: GColor.Palette = GColor.default, fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { const bg = asGhostRgb(theme.bg orelse theme.tag_bg); const fg = asGhostRgb(theme.fg orelse theme.tag_fg); var base: [16]GColor.RGB = undefined; if (theme.palette) |palette| { for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); } else { const synthesized = [16][3]u8{ theme.bg orelse theme.tag_bg, theme.kw, theme.str, theme.num, theme.box, theme.sel_bg, theme.comment, theme.fg orelse theme.tag_fg, theme.lineno, theme.kw, theme.str, theme.num, theme.scroll_thumb, theme.sel_fg, theme.tag_fg, theme.fg orelse theme.tag_fg, }; for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); } const wanted: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; if (self.key) |old| if (std.meta.eql(old, wanted)) return &self.colors; var seed = GColor.default; for (base, 0..) |rgb, i| seed[i] = rgb; self.colors = GColor.generate256Color(seed, .empty, bg, fg, false); self.key = wanted; return &self.colors; } }; 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, }; } /// 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, track: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool { var marks: [marks_len]u8 = undefined; return screen_state.encode(enc, track, 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, track: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { return screen_state.encodeRows(enc, track, &state.vt, lo, hi, out); } /// What `track` kept of its versions, freed; `state` null when its pane is /// gone with the emulator. pub fn untrack(track: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void { track.deinit(gpa, if (state) |s| &s.vt else null); } /// 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) !screen_state.Replica.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); } const authorityOnly = pardes.tape.authorityOnly; /// 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 (src/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[= 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, track: []const i32, rows: []i32, erased: []bool) Term.Told { if (track.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 (track.len <= room.len) room[0..track.len] else state.gpa.alloc(RowPin, track.len) catch { ingest(state, bytes); @memcpy(rows[0..track.len], track); @memset(erased[0..track.len], false); return .{ .rows = rows[0..track.len], .erased = erased[0..track.len], .cleared = false, .alive = true, .failed = true }; }; defer if (track.len > room.len) state.gpa.free(pins); for (pins, track) |*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..track.len], erased[0..track.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..track.len], .erased = erased[0..track.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 = comptime keys: { var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; for (&keys, 1..) |*slot, n| slot.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); break :keys keys; }; 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. const PromptCut = union(enum) { /// show the row exactly as ghostty dumped it keep, /// show nothing at all blank, /// drop this many leading COLUMNS — the prompt — and keep the rest, which /// is what was typed at it cut: usize, }; 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 many of the bytes `raw` of its row `row` (from the top of the /// history), as the emulator dumps it, are the prompt the row starts with. pub fn promptPrefix(state: ?*State, row: i32, raw: []const u8) usize { if (row < 0) return 0; const s = state orelse return 0; const pin = s.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; if (pin.rowAndCell().row.semantic_prompt == .none) return 0; return switch (promptCut(pin)) { .keep => 0, .blank => raw.len, .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), }; } 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; } /// 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; } // Match surviving edit-buffer rows to their original terminal styles. const EditAnchors = struct { /// the buffer's own text, walked in order: a line the VIEWPORT skipped still /// consumes the row it came from, so the lines below it stay aligned text: []const u8 = &.{}, at: usize = 0, shell: []const []const u8 = &.{}, /// the covered span, absolute grid rows, as `[first, end)` first: usize = 0, end: usize = 0, lines: usize = 0, /// the line `at` names, and the first row still unclaimed idx: usize = 0, cursor: usize = 0, budget: usize = 0, active: bool = false, fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { if (o.rows <= 0 or o.row < 0) return .{}; const first: usize = @intCast(o.row); const screen = pane.terminal.?.vt.screens.active; const total = screen.pages.scrollbar().total; if (first >= total) return .{}; const covered: usize = @intCast(o.rows); const count = @min(covered, total - first); const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; const br = screen.pages.pin(.{ .screen = .{ .x = screen.pages.cols - 1, .y = @intCast(first + count - 1), } }) orelse return .{}; const arena = p.scratch.allocator(); var output: std.Io.Writer.Allocating = .init(arena); screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; const shell = arena.alloc([]const u8, count) catch return .{}; 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; } const lines = std.mem.count(u8, o.text, "\n") + 1; return .{ .text = o.text, .shell = shell, .first = first, .end = first + count, .lines = lines, .cursor = first, .budget = covered + 4 * lines, .active = true, }; } fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { if (!a.active or idx >= a.lines) return null; var found: ?Anchor = null; while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); return found; } fn nextLine(a: *EditAnchors) ?[]const u8 { if (a.at > a.text.len) return null; const rest = a.text[a.at..]; if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { a.at += n + 1; return rest[0..n]; } // The last line has no terminator; one past the end ends the walk. a.at = a.text.len + 1; return rest; } /// Where this line still stands over the grid, if anywhere. fn claim(a: *EditAnchors, line: []const u8) ?Anchor { const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; var k = a.cursor; while (k < end) : (k += 1) { if (a.budget == 0) return null; a.budget -= 1; if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; a.cursor = k + 1; return .{ .row = @intCast(k) }; } if (a.cursor >= a.end) return null; const shell = a.shell[a.cursor - a.first]; var p: usize = 0; while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; var s: usize = 0; const room = @min(line.len, shell.len) - p; while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; if (p + s == 0) return null; if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; const row = a.cursor; if (s > 0 or p >= shell.len) a.cursor += 1; return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; } }; const Anchor = struct { /// the row, absolute while it comes from `EditAnchors`, viewport once /// `recolorAnsi` has subtracted the walk's offset row: i32, prefix: usize = std.math.maxInt(usize), suffix: usize = 0, /// the row's own dumped length — what the suffix is measured from on the /// GRID side, where the edit may have changed the byte count shell_len: usize = 0, fn whole(an: Anchor) bool { return an.prefix == std.math.maxInt(usize); } }; pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { // No emulator, no ANSI cells: the whole pass — and the 256-colour theme // projection behind it — is compiled out. if (pane.terminal == null) return; const body_y = p.bodyTop(pane, r); var filtered_storage: FilteredColors = undefined; const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { const tz_filter = tracy.zone(@src(), "filterInit"); defer tz_filter.end(); filtered_storage = FilteredColors.init(p, &pane.terminal.?.vt); break :blk &filtered_storage; } else null; // DECSCNM, read once: the filtered palette folds it in itself, the raw // path needs it per cell. const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); const pages = &pane.terminal.?.vt.screens.active.pages; const vp_rows: i32 = @intCast(grid(pane.terminal).len); // Which buffer lines the user has not actually changed, so a row swallowed // by a growing buffer keeps the colour it still stands over. var anchors: ?EditAnchors = null; var walk: BodyWalk = .init(pane); var lines = std.mem.splitScalar(u8, body, '\n'); var vr: u16 = 0; while (walk.next()) |row| : (vr += 1) { if (vr >= body_h) break; // Before any early exit below, or the lines fall out of step with rows. const text = lines.next() orelse ""; const anchor: Anchor = switch (row) { .edit => |e| blk: { if (anchors == null) anchors = .init(p, pane, pane.ovl.?); var an = anchors.?.shellRow(e.idx) orelse continue; an.row -= walk.goff; break :blk an; }, .grid => |v| .{ .row = v }, }; const vi = anchor.row; if (vi < 0 or vi >= vp_rows) continue; const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; break :cut switch (promptCut(row_pin)) { .keep => 0, // Blanked end to end: the row shows nothing of the grid, so // projecting the prompt's own colours onto it would be a lie. .blank => continue, .cut => |n| std.math.cast(u16, n) orelse continue, }; }; if (cut > 0 and text.len == 0) continue; var at: usize = 0; var sc: u16 = 0; var gc: u16 = cut; var sb: usize = 0; const mine_from = @min(anchor.prefix, text.len); const mine_to = text.len - @min(anchor.suffix, text.len); var crossed = false; while (at < text.len and sc < tw) { const stop = modal.nextGrapheme(text, at); if (stop <= at) break; const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; if (at >= mine_from and at < mine_to) { sc += span; at = stop; continue; } if (at >= mine_to and !crossed) { crossed = true; const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); while (sb < upto) { const ci = cellAt(pages, row_pin, gc) orelse break; sb += dumpedBytes(row_pin, ci.cell); gc = std.math.add(u16, gc, 1) catch break; } } const want = stop - at; // Consume every cell that contributed to this grapheme. A cluster // ghostty split across several cells is still ONE printed glyph. var covered: usize = 0; var style: ?plain.CellStyle = null; while (covered < want) { const ci = cellAt(pages, row_pin, gc) orelse break; if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) style = cellStyle(p, ci, filtered, scnm); covered += dumpedBytes(row_pin, ci.cell); gc = std.math.add(u16, gc, 1) catch break; // A spacer contributes no bytes; without this the loop would // spin on a row that ends in one. if (covered == 0 and gc >= pane.cols) break; } while (cellAt(pages, row_pin, gc)) |t| { if (t.cell.wide != .spacer_tail) break; gc = std.math.add(u16, gc, 1) catch break; } if (style) |st| for (0..span) |k| { const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); if (cell.default and filtered == null) continue; cell.default = false; cell.style = st; }; sb += covered; sc += span; at = stop; } var tail: ?plain.CellStyle = null; if (anchor.whole() or anchor.suffix > 0) { while (sc < tw) { const ci = cellAt(pages, row_pin, gc) orelse break; gc = std.math.add(u16, gc, 1) catch break; if (ci.cell.wide == .spacer_tail) continue; const cell = s.at(tx + sc, body_y + vr); sc += 1; const style = cellStyle(p, ci, filtered, scnm); tail = style; if (cell.default and filtered == null) continue; cell.default = false; cell.style = style; } if (tail) |style| while (sc < tw) : (sc += 1) { const cell = s.at(tx + sc, body_y + vr); if (cell.default and filtered == null) continue; cell.default = false; cell.style = style; }; } } } /// 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(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) plain.CellStyle { const style = ci.style(); var cs: plain.CellStyle = .{ .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, 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 = palColor(p, 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; } fn asPardesColor(rgb: GColor.RGB) plain.Color { return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; } /// A program's colours mapped to the theme (Filter): a terminal's cells, or /// a +Pager's spans (`vt` null, the program's palette xterm's own). pub const FilteredColors = struct { source: GColor.Palette, target: *const GColor.Palette, theme_bg: GColor.RGB, theme_fg: GColor.RGB, dynamic_bg: ?GColor.RGB, dynamic_fg: ?GColor.RGB, default_bg: GColor.RGB, /// What a foreground too near `default_bg` becomes instead. fallback_fg: GColor.RGB, default_bg_luminance: f64, fg_for_palette: [256]plain.Color = undefined, bg_for_palette: [256]plain.Color = undefined, /// The two answers for a cell that names no colour of its own. fg_default: plain.Color = undefined, bg_default: plain.Color = undefined, cache_rgb: [256]GColor.RGB = undefined, cache_key: [256]u8 = undefined, cache_valid: [256]bool = @splat(false), pub fn init(p: *Pardes, vt: ?*const ghostty_vt.Terminal) FilteredColors { var source = GColor.default; if (vt) |t| { for (&source, 0..) |*rgb, i| rgb.* = t.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; } const theme = p.theme(); var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); var theme_fg = asGhostRgb(theme.fg orelse theme.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: FilteredColors = .{ .source = source, .target = p.tty_filter_palette.get(theme), .theme_bg = theme_bg, .theme_fg = theme_fg, .dynamic_bg = dynamic_bg, .dynamic_fg = dynamic_fg, .default_bg = theme_bg, .fallback_fg = theme_fg, .default_bg_luminance = luminanceOf(theme_bg), }; if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); self.default_bg_luminance = luminanceOf(self.default_bg); if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) self.fallback_fg = self.theme_bg; self.fg_default = asPardesColor(self.legible( if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, )); self.bg_default = asPardesColor(self.default_bg); for (&self.source, 0..) |current, i| { const idx: u8 = @intCast(i); const mapped = self.paletteRgb(idx, current); self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); self.bg_for_palette[idx] = asPardesColor(mapped); } return self; } fn fg(self: *FilteredColors, style: ghostty_vt.Style) plain.Color { return switch (style.fg_color) { .none => self.fg_default, .palette => |idx| self.fg_for_palette[idx], .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ .default = self.dynamic_fg orelse self.theme_fg, .palette = &self.source, .bold = null, })))), }; } fn bg(self: *FilteredColors, 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(self.keyedRgb(style.bg(cell, &self.source).?)); } /// A +Pager span's colour (Term.page), as `fg` and `bg` map a cell's. pub fn spanColor(self: *FilteredColors, 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 = self.keyedRgb(asGhostRgb(rgb)); break :blk asPardesColor(if (is_bg) keyed else self.legible(keyed)); }, }; } fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= config.tty_filter_min_contrast) return rgb; return self.fallback_fg; } fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { if (current.eql(GColor.default[idx])) return self.target[idx]; return self.keyedRgb(current); } fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { return self.target[self.nearestKey(rgb)]; } fn nearestKey(self: *FilteredColors, 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 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] = 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; }; 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); } pub fn palColor(p: *Pardes, idx: u8) plain.Color { if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; return .{ .index = idx }; } fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) plain.Color { return switch (color) { .none => blk: { const t = if (is_bg) p.theme().bg else p.theme().fg; break :blk if (t) |c| .{ .rgb = c } else .default; }, .palette => |idx| palColor(p, 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; } /// Draw the pane's kitty graphics images over its body rows (after the /// rows and their colours: placeholder cells are blanked here). pub fn drawImages(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { if (comptime !images_enabled) return; const state = pane.terminal orelse return; const screen = state.vt.screens.active; cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); // A body taller than this draws its images on the rows that fit. var rows_of: [1024]?u16 = undefined; const vp_rows: usize = @min(grid(state).len, rows_of.len); @memset(rows_of[0..vp_rows], null); var any_placeholder = false; var walk: BodyWalk = .init(pane); var vr: u16 = 0; while (walk.next()) |row| : (vr += 1) { if (vr >= body_h) break; const vi = switch (row) { .grid => |v| v, .edit => continue, }; if (vi < 0 or vi >= vp_rows) continue; const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; const flags = row_pin.rowAndCell().row; // A prompt row outside tty mode is cut or hidden: its columns are // not the grid's. if (pane.body.mode != .tty and flags.semantic_prompt != .none) continue; any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; rows_of[@intCast(vi)] = 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(p, s, &state.vt, @intCast(id), pane.serial, tx, body_y, @min(tw, pane.cols), rows_of[0..vp_rows]); } /// Every byte the core wrote to each pane's pty since the last call, `\n` /// between panes' shares: "0:\n1:\n" for panes that got any. fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 { out.clearRetainingCapacity(); var per: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty); defer for (&per) |*b| b.deinit(p.gpa); while (p.nextEffect()) |effect| { if (effect == .write) try per[effect.write.pane].appendSlice(p.gpa, effect.write.bytes.slice()); } for (per, 0..) |b, id| if (b.items.len > 0) try out.print(p.gpa, "{d}:{s}\n", .{ id, b.items }); return out.items; } /// `a=T` of a 4x2 RGB image, `i=7`, red on the left half, blue on the /// right, with the rest of the control data `extra` (`c=2,r=1` places it /// over two cells). inline fn kittyTransmit(comptime extra: []const u8) []const u8 { return comptime blk: { const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; const pixels = row ++ row; var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined; const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*; break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\"; }; } fn imagePlaces(s: *const Surface) []const plain.Placement { return s.placements.items; } /// `n` line breaks: enough of them push the screen's rows into history. fn lineBreaks(comptime n: usize) [2 * n]u8 { var out: [2 * n]u8 = undefined; for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; return out; } test "replay ownership is terminal-only and construction rolls back on allocation failure" { const Case = struct { fn run(gpa: std.mem.Allocator, terminal: bool) !void { const pane = if (terminal) try panes.createTerminal(gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); defer gpa.destroy(pane); defer if (pane.terminal) |state| close(state, gpa); try std.testing.expectEqual(terminal, pane.terminal != null); } }; try std.testing.expect(@sizeOf(Pane) < 128 * 1024); try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); } test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). const Filling = struct { child: std.mem.Allocator, fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { const self: *@This() = @ptrCast(@alignCast(ctx)); const ptr = self.child.rawAlloc(len, a, ra) orelse return null; @memset(ptr[0..len], 0xAA); return ptr; } fn grow(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { const self: *@This() = @ptrCast(@alignCast(ctx)); return self.child.rawResize(buf, a, n, ra); } fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { const self: *@This() = @ptrCast(@alignCast(ctx)); return self.child.rawRemap(buf, a, n, ra); } fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { const self: *@This() = @ptrCast(@alignCast(ctx)); self.child.rawFree(buf, a, ra); } const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = grow, .remap = remap, .free = free }; }; var filling: Filling = .{ .child = std.testing.allocator }; const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; const pane = try panes.createTerminal(gpa, 40, 12); defer gpa.destroy(pane); defer if (pane.terminal) |state| close(state, gpa); try std.testing.expect(pane.terminal.?.resize_to == null); } test "document construction allocates only the pane and has inert terminal defaults" { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); const allocator = failing.allocator(); const pane = try panes.createDoc(allocator, 40, 12); defer allocator.destroy(pane); defer if (pane.terminal) |state| close(state, allocator); try std.testing.expect(pane.terminal == null); try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); try std.testing.expectEqual(@as(usize, 0), failing.resize_index); try std.testing.expect(!failing.has_induced_failure); try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); try std.testing.expectEqual(Term.Modes{}, modes(pane.terminal)); try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal)); pane.scrollBy(100); pane.followOutput(); pane.resizeGrid(80, 24); try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); try std.testing.expectEqualStrings("", try scrollback(pane.terminal, allocator)); try std.testing.expect(!failing.has_induced_failure); } test "terminal state keeps parser fragments and sends emulator replies through its owner" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; const state = pane.terminal.?; try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); while (p.nextEffect()) |effect| { if (effect == .write) return error.PrematureTerminalReply; } p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); var answers: usize = 0; while (p.nextEffect()) |effect| { if (effect != .write) continue; try std.testing.expectEqual(@as(u8, 0), effect.write.pane); try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); answers += 1; } try std.testing.expectEqual(@as(usize, 1), answers); try std.testing.expectEqual(@as(u16, 0), state.reply_len); } test "a terminal's dump restores the cells it drew, its history and where its view was" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.feedOutput(p, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); for (0..30) |i| { var line: [16]u8 = undefined; pane.feedOutput(p, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); } scroll(pane.terminal.?, -5); const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); defer gpa.free(bytes); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const state = try gpa.create(State); defer gpa.destroy(state); state.* = try pardes.walk.load(State, gpa, bytes, null); defer { state.stream.deinit(); state.vt.deinit(gpa); } try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar()); } test "a restored command pane comes back finished, its command not run again" { if (comptime pardes.isolated) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer p.deinit(); while (p.nextEffect()) |_| {} const cmd = p.freeSlot().?; _ = try panes.newCommand(p, cmd, "/tmp", "make test"); p.panes[cmd].?.feedOutput(p, "ok\r\n"); p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); try pardes.dump.dumpState(p); const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); defer restored.deinit(); var spawns: usize = 0; while (restored.nextEffect()) |effect| switch (effect) { .spawn => spawns += 1, else => {}, }; try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command const again = for (restored.panes) |slot| { if (slot) |pane| if (pane.command != null) break pane; } else return error.CommandPaneLost; try std.testing.expectEqualStrings("make test", again.command.?); try std.testing.expect(again.command_done); try std.testing.expectEqual(@as(?u8, 2), again.command_status); const text = try scrollback(again.terminal, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); } test "a restored terminal keeps its history above a marker and gets a shell where it was" { if (comptime pardes.isolated) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.feedOutput(p, "old output\r\n$ ls\r\n"); try pane.setOwnedCwd("/tmp"); pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash try pardes.dump.dumpState(p); const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); defer restored.deinit(); var spawned = false; while (restored.nextEffect()) |effect| switch (effect) { .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), else => {}, }; try std.testing.expect(spawned); const again = restored.panes[0].?; try std.testing.expectEqualStrings("bash", again.shell.?); try std.testing.expect(again.command == null); try std.testing.expectEqual(.spawn, again.pending_command.wait); const text = try scrollback(again.terminal, gpa); defer gpa.free(text); const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; try std.testing.expect(old_at < mark_at); } test "a position that cannot follow the output for want of memory is said on the message row, and logged" { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[0].?; pane.feedOutput(p, "one\r\ntwo\r\n"); // More positions than the emulator's pins have room for: following them // through the output needs memory, and there is none. try std.testing.expect(pane.body.reserveSels()); for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 }; pane.body.nsel = 8; failing.fail_index = failing.alloc_index; pane.feedOutput(p, "three\r\n"); failing.fail_index = std.math.maxInt(usize); try std.testing.expect(failing.has_induced_failure); try std.testing.expectEqualStrings(panes.positions_lost, pane.msg[0..pane.msg_len]); const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; try std.testing.expectEqualStrings(panes.positions_lost, logged.slice()); } test "raw terminal output needs no position tracking allocations" { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[0].?; pane.body.mode = .tty; pane.feedOutput(p, "warm"); const allocations = failing.alloc_index; failing.fail_index = allocations; const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); pane.feedOutput(p, " output"); try std.testing.expectEqual(allocations, failing.alloc_index); try std.testing.expect(!failing.has_induced_failure); try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); } test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = p.panes[0].?; try std.testing.expect(pane.terminal != null); _ = try pardes.edit.shellRows(p, pane); // A pane's teardown drops its entry; the rows stay until the sweep. p.shell_rows.dropPane(pane); _ = try pardes.edit.shellRows(p, pane); } 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)), ); } } } test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { const testing = std.testing; // Raw index assertions require a theme that inherits the ANSI palette. const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tag_expanded = false; // a one-row tag keeps this small screen's rows p.sync(); try testing.expect(pane.tty_filter); pane.tty_filter = false; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ "\x1b[38;5;196mB" ++ "\x1b[38;2;255;0;0mC" ++ "\x1b[0;48;5;25mD" ++ "\x1b[0;48;2;0;95;175mE" ++ "\x1b[0;1;2;3;4;5;7;8;9mF" ++ "\x1b[0;48;5;25m\x1b[K" ++ "\r\n\x1b[0;38;5;2m界" } }); var frame = std.heap.ArenaAllocator.init(testing.allocator); defer frame.deinit(); const r = p.view().rects[0]; const tx = r.x + config.GUTTER; const body_y = p.bodyTop(pane, r); const raw = try p.render(frame.allocator()); try testing.expectEqual(plain.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); try testing.expectEqual(plain.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); try testing.expectEqual(plain.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); pane.tty_filter = true; _ = frame.reset(.retain_capacity); const filtered = try p.render(frame.allocator()); var expected_cache: FilterPalette = .{}; const expected = expected_cache.get(p.theme()); try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); const attrs = filtered.at(tx + 5, body_y).style; try testing.expect(attrs.bold); try testing.expect(attrs.dim); try testing.expect(attrs.italic); try testing.expect(attrs.blink); try testing.expect(attrs.reverse); try testing.expect(attrs.invisible); try testing.expect(attrs.strikethrough); try testing.expectEqual(.single, attrs.ul); const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); // A filtered terminal never delegates either colour to a backend palette, // including cells which were empty/default before the pass. for (0..r.w - config.GUTTER) |col| { const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); try testing.expect(!cell.default); switch (cell.style.fg) { .rgb => {}, else => return error.FilteredForegroundWasNotRgb, } switch (cell.style.bg) { .rgb => {}, else => return error.FilteredBackgroundWasNotRgb, } } p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); pane.tty_filter = false; pane.tty_filter = true; try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); _ = frame.reset(.retain_capacity); const osc_palette = try p.render(frame.allocator()); try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); // Dynamic default foreground/background colours key every default cell, // including the otherwise blank end of the row. p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ "\x1b]11;#5f5f5f\x1b\\" } }); const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); _ = frame.reset(.retain_capacity); const dynamic = try p.render(frame.allocator()); const edge = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; try testing.expectEqual(asPardesColor(expected[196]), edge.fg); try testing.expectEqual(asPardesColor(expected[59]), edge.bg); const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); _ = frame.reset(.retain_capacity); const reversed = try p.render(frame.allocator()); const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); const reversed_explicit = reversed.at(tx, body_y).style; try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); try testing.expectEqual(plain.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); _ = frame.reset(.retain_capacity); const unreversed = try p.render(frame.allocator()); const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); // The cache is keyed by values, not a theme name. Replacing a custom // theme in place immediately recolours already-rendered indexed cells. p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); var custom = p.theme().*; custom.name = try p.gpa.dupe(u8, "same-name"); custom.palette = null; custom.kw = .{ 1, 2, 3 }; p.custom_theme = custom; _ = frame.reset(.retain_capacity); const custom_first = try p.render(frame.allocator()); try testing.expectEqual(plain.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; _ = frame.reset(.retain_capacity); const custom_second = try p.render(frame.allocator()); try testing.expectEqual(plain.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); } test "terminal Filter keeps extended keys dark-to-light on a light theme" { const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); defer p.deinit(); try std.testing.expectEqualStrings("acme", p.theme().name); var cache: FilterPalette = .{}; const palette = cache.get(p.theme()); try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); } test "terminal Filter preserves exact palette-null light theme default roles" { const testing = std.testing; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); defer p.deinit(); while (p.nextEffect()) |_| {} var light = p.theme().*; light.name = try p.gpa.dupe(u8, "filter-light-defaults"); light.bg = .{ 0xf8, 0xf8, 0xf8 }; light.fg = .{ 0x38, 0x38, 0x38 }; light.palette = null; p.custom_theme = light; const pane = p.panes[0].?; try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); pane.tty_filter = true; var frame = std.heap.ArenaAllocator.init(testing.allocator); defer frame.deinit(); const r = p.view().rects[0]; const tx = r.x + config.GUTTER; const body_y = p.bodyTop(pane, r); const ordinary = try p.render(frame.allocator()); try testing.expectEqual(plain.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); try testing.expectEqual(plain.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); _ = frame.reset(.retain_capacity); const reversed = try p.render(frame.allocator()); try testing.expectEqual(plain.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); try testing.expectEqual(plain.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); } test "terminal Filter maps the default roles before it maps anything else" { const testing = std.testing; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; try testing.expect(pane.tty_filter); // Native dark/light palettes plus legacy helix/dark/acme, including // the null-page fallback that only the legacy dark theme exercises. for (0..9) |t| { p.settings.theme = @intCast(t); const stage_one = FilteredColors.init(p, &pane.terminal.?.vt); // `dark` declares no background of its own, which is exactly why the // resolver reads the tag colours as the fallback rather than `.?`. const theme = p.theme(); try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); // With no OSC 11 in play the mapped page IS that anchor, and the // fallback is the other one: a background never contrasts with itself. try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); } p.settings.theme = 0; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); var moved = FilteredColors.init(p, &pane.terminal.?.vt); try testing.expect(!moved.default_bg.eql(moved.theme_bg)); try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); } test "terminal Filter refuses a foreground that would collapse onto the page" { const testing = std.testing; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; try testing.expect(pane.tty_filter); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ "\x1b[0;30mB" ++ "\x1b[0;31mR" } }); var frame = std.heap.ArenaAllocator.init(testing.allocator); defer frame.deinit(); const r = p.view().rects[0]; const tx = r.x + config.GUTTER; const body_y = p.bodyTop(pane, r); for (0..9) |t| { p.settings.theme = @intCast(t); var fc = FilteredColors.init(p, &pane.terminal.?.vt); const page = asPardesColor(fc.default_bg); const rescued = asPardesColor(fc.fallback_fg); _ = frame.reset(.retain_capacity); const g = try p.render(frame.allocator()); // The colour each of the three would have been given with no floor. const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); const raw_black = fc.paletteRgb(0, GColor.default[0]); const raw_red = fc.paletteRgb(1, GColor.default[1]); for ([_]struct { at: u16, raw: GColor.RGB }{ .{ .at = 0, .raw = raw_white }, .{ .at = 1, .raw = raw_black }, .{ .at = 2, .raw = raw_red }, }) |case| { const cell = g.at(tx + case.at, body_y).style; try testing.expectEqual(page, cell.bg); if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { // Refused: the projection's answer is not painted, the anchor is. try testing.expectEqual(rescued, cell.fg); try testing.expect(!std.meta.eql(cell.fg, cell.bg)); } else { // Cleared the floor, so stage two leaves it exactly alone. try testing.expectEqual(asPardesColor(case.raw), cell.fg); } // Either way a filtered cell delegates neither colour to a backend. switch (cell.fg) { .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= config.tty_filter_min_contrast), else => return error.FilteredForegroundWasNotRgb, } } // At least one of the three has to have been a real collapse, or this // theme proved nothing: white on the light theme, black on the dark. try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); // A saturated red is never the page on any curated theme. try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); } } test "terminal Filter holds every projected foreground off the page" { const testing = std.testing; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; for (0..9) |t| { p.settings.theme = @intCast(t); var fc = FilteredColors.init(p, &pane.terminal.?.vt); var refused: usize = 0; for (fc.target, 0..) |projected, slot| { const ink = fc.legible(projected); try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); if (!ink.eql(projected)) { refused += 1; try testing.expect(ink.eql(fc.fallback_fg)); // Only ever refused for being too near the page. try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); } // The key a background asks for is handed back untouched, including // the one whose value is the page itself. try testing.expect(fc.keyedRgb(GColor.default[slot]).eql(fc.target[fc.nearestKey(GColor.default[slot])])); } // Every curated theme owns at least one collapsing key — that is why // the floor exists — and the floor must not be flattening the palette. try testing.expect(refused > 0); try testing.expect(refused < fc.target.len / 8); } } test "tty ansi colors follow the prompt hug into normal mode" { const testing = std.testing; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); var frame = std.heap.ArenaAllocator.init(testing.allocator); defer frame.deinit(); const r = p.view().rects[0]; const tx = r.x + config.GUTTER; const body_y = p.bodyTop(pane, r); const red: plain.Color = .{ .rgb = p.theme().palette.?[1] }; const blue: plain.Color = .{ .rgb = p.theme().palette.?[4] }; // tty mode projects the emulator's ansi colours cell for cell. pane.body.mode = .tty; p.shell_rows.stale = true; const tty = try p.render(frame.allocator()); try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); pane.body.mode = .normal; p.shell_rows.stale = true; _ = frame.reset(.retain_capacity); const norm = try p.render(frame.allocator()); try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); try testing.expectEqual(red, norm.at(tx, body_y).style.fg); try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); } test "a prompt row hidden end to end paints nothing at all" { const testing = std.testing; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tag_expanded = false; // a 12x8 screen: the body, not the tag p.sync(); pane.tty_filter = false; pane.body.mode = .normal; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); var frame = std.heap.ArenaAllocator.init(testing.allocator); defer frame.deinit(); const r = p.view().rects[0]; const tx = r.x + config.GUTTER; const body_y = p.bodyTop(pane, r); p.shell_rows.stale = true; const s = try p.render(frame.allocator()); try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); try testing.expect(!std.meta.eql(plain.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); } test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 }); defer p.deinit(); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); _ = try p.render(frame.allocator()); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); _ = try ptyWritesByPane(p, &out); p.view().active = 0; // Asking while its pane has the keyboard: told at once that it has. p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1004h" } }); try std.testing.expectEqualStrings("0:\x1b[I\n", try ptyWritesByPane(p, &out)); p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?1004h" } }); try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); // A click into the other pane moves the keyboard: out of one, into the // other. const r = p.view().rects[1]; const at_col = r.x + config.GUTTER + 2; const at_row = p.bodyTop(p.panes[1].?, r) + 1; p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = at_col, .row = at_row } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = at_col, .row = at_row } }); try std.testing.expectEqual(@as(usize, 1), p.view().active); try std.testing.expectEqualStrings("0:\x1b[O\n1:\x1b[I\n", try ptyWritesByPane(p, &out)); // The window: away and back. p.update(.{ .focus = false }); try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); p.update(.{ .focus = false }); try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); p.update(.{ .focus = true }); try std.testing.expectEqualStrings("1:\x1b[I\n", try ptyWritesByPane(p, &out)); // A program that did not ask hears nothing: pane 2. p.view().active = 2; p.update(.tick); try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); } test "a terminal's kitty graphics image is drawn where its program placed it, and a delete takes it away" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); p.view().frontend.native_images = true; p.view().active = 0; p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); const pane = p.panes[0].?; pane.body.mode = .tty; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;5H" ++ kittyTransmit("c=2,r=1") } }); var s = try p.render(frame.allocator()); const places = imagePlaces(s); try std.testing.expectEqual(@as(usize, 1), places.len); const place = places[0]; const r = p.view().rects[0]; const img = pane.terminal.?.vt.screens.active.kitty_images.imageById(7).?; try std.testing.expectEqual(plain.Placement.keyOf(pane.serial, 7, @truncate(img.generation)), place.key); try std.testing.expectEqual(plain.RectCell{ .x = r.x + config.GUTTER + 4, .y = p.bodyTop(pane, r) + 2, .w = 2, .h = 1 }, place.dst); try std.testing.expectEqual(@as(u32, 4), place.raster.w); try std.testing.expectEqual(@as(u32, 2), place.raster.h); try std.testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, place.raster.bytes()[0..4]); try std.testing.expectEqual(plain.RectPx{ .x = 0, .y = 0, .w = 4, .h = 2 }, place.src); try std.testing.expectEqual(plain.RectPx{ .x = 0, .y = 0, .w = 20, .h = 20 }, place.at.?); // Scrolled up by the shell's output, it goes up with the text. p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[24;1H\n\n" } }); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); try std.testing.expectEqual(p.bodyTop(pane, r), imagePlaces(s)[0].dst.y); p.update(.{ .output = .{ .pane = 0, .bytes = "\n" } }); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b_Ga=d,d=A\x1b\\" } }); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); } test "ED 3 takes away a kitty placement whose row it erased: it never comes back at the top" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); p.view().frontend.native_images = true; p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); const pane = p.panes[0].?; pane.body.mode = .tty; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); const storage = &pane.terminal.?.vt.screens.active.kitty_images; try std.testing.expectEqual(@as(usize, 1), storage.placements.count()); // Scrolled into the history, it is not on screen; `clear` (ED 2 then // ED 3) erases that history and the placement with it. p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(40) } }); var s = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[H\x1b[2J\x1b[3J" } }); try std.testing.expectEqual(@as(usize, 0), storage.placements.count()); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); } test "a finished command's output erased by a later ED 3 is not called whole, and no rows stand in for it" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); defer p.deinit(); const pane = p.panes[0].?; const marked = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; p.update(.{ .output = .{ .pane = 0, .bytes = marked ++ "\r\n\x1b]133;C;aid=pardes\x07printed\r\n\x1b]133;D;0;aid=pardes\x07" ++ marked } }); const before = try commandOutput(pane.terminal, gpa, 100); defer gpa.free(before.text); try std.testing.expect(before.whole); try std.testing.expect(std.mem.startsWith(u8, before.text, "printed")); // The command's rows go into the history, and ED 3 erases them: its // pins are `garbage` now (ghostty 1.4), not moved to the screen's top, // where another program's text would be read as its output. p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } }); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); const after = try commandOutput(pane.terminal, gpa, 100); defer gpa.free(after.text); try std.testing.expect(!after.whole); try std.testing.expectEqualStrings("", after.text); } test "a selection whose row ED 3 erased goes; one on the screen stays" { const gpa = std.testing.allocator; for ([_]bool{ true, false }) |in_history| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); defer p.deinit(); const pane = p.panes[0].?; pane.body.mode = .tty; p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } }); pane.body.mode = .normal; const pages = &pane.terminal.?.vt.screens.active.pages; const top: i32 = @intCast(pages.total_rows - pane.rows); const row: i32 = if (in_history) top - 3 else top + 2; pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); try std.testing.expectEqual(!in_history, pane.body.vsel.active); if (!in_history) try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.row); } } test "a virtual kitty placement shows through its placeholder cells, which draw no text" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); p.view().frontend.native_images = true; p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); const pane = p.panes[0].?; pane.body.mode = .tty; // yazi's way: a virtual placement two cells by one, then the two // placeholders, the image's id in their colour, row and column in // their diacritics. p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("U=1,c=2,r=1,q=2") ++ "\x1b[2;3H\x1b[38;2;0;0;7m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}\u{0305}\u{030D}\x1b[39mX" } }); const s = try p.render(frame.allocator()); const places = imagePlaces(s); try std.testing.expectEqual(@as(usize, 1), places.len); const r = p.view().rects[0]; const tx = r.x + config.GUTTER; const y = p.bodyTop(pane, r) + 1; try std.testing.expectEqual(plain.RectCell{ .x = tx + 2, .y = y, .w = 2, .h = 1 }, places[0].dst); try std.testing.expectEqualStrings(" ", s.at(tx + 2, y).grapheme()); try std.testing.expectEqualStrings(" ", s.at(tx + 3, y).grapheme()); try std.testing.expectEqualStrings("X", s.at(tx + 4, y).grapheme()); } test "a terminal's image is a placement whatever the frontend draws, and the Petscii builtin asks for it as glyph art" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); const pane = p.panes[0].?; pane.body.mode = .tty; p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("c=2,r=1") } }); const r = p.view().rects[0]; const tx = r.x + config.GUTTER; const y = p.bodyTop(pane, r); // A frontend that draws no pixels (a tty under no kitty graphics) is // handed the picture all the same, and the cells under it are its. p.view().frontend.native_images = false; var s = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); try std.testing.expect(!imagePlaces(s)[0].art.glyph); try std.testing.expectEqualStrings(" ", s.at(tx, y).grapheme()); try std.testing.expectEqualStrings(" ", s.at(tx + 1, y).grapheme()); // The tag says what that frontend draws, glyph art, as an image pane's does. try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); // The builtin flips the pane to glyph art and back. p.view().frontend.native_images = true; try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); try std.testing.expect(imagePlaces(s)[0].art.glyph); try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); // Dumped and restored, it still asks for glyph art. try pardes.dump.dumpState(p); const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); defer restored.deinit(); try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal)); try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); try std.testing.expect(!imagePlaces(s)[0].art.glyph); } test "a new terminal draws its program's images as pixels, and one without images says nothing of them" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?); // A pane without images says nothing of them. try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null); const id = p.freeSlot().?; const fresh = try p.newShell(id, ""); try std.testing.expectEqual(false, petscii(fresh.terminal).?); } test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); _ = try ptyWritesByPane(p, &out); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[16t" } }); try std.testing.expectEqualStrings("0:\x1b[6;20;10t\n", try ptyWritesByPane(p, &out)); } test "colors.xterm is the palette the emulator starts from, all 256" { for (pardes.colors.xterm, ghostty_vt.color.default) |ours, its| try std.testing.expectEqual(ours, [3]u8{ its.r, its.g, its.b }); }