//! A terminal: its VT emulator, the OSC 133 cycle its shell marks, its //! text, its view as cells, and the Filter that recolours output to the //! theme. The core reaches it through core/term/term.zig's `ops`. const std = @import("std"); const plain = @import("plain"); const Key = plain.Key; const Term = plain.term; const ghostty_vt = @import("ghostty-vt"); const Ink = plain.term.Ink; const FilterPalette = plain.term.FilterPalette; const Filter = plain.term.Filter; const Painted = plain.term.Painted; const PaintedRow = plain.term.PaintedRow; const ImagesAt = plain.term.ImagesAt; const PromptCut = plain.term.PromptCut; pub const VtSlot = ghostty_vt.Terminal; /// A cell of an emulator's pages, as `getCell` reads it (core/term/echo.zig). pub const PageCell = ghostty_vt.PageList.Cell; /// Kitty graphics: a program's images are placements, as a kind's are. pub const images_enabled = true; pub const TerminalImages = if (images_enabled) @import("TerminalImages.zig") else void; pub const StreamSlot = ghostty_vt.Stream(MarkedHandler); /// The `aid` pardes's injected bash and fish marks carry (host_io.zig). pub const prompt_aid = "pardes"; /// ghostty's handler, plus where the shell is in its command cycle as /// its OSC 133 marks tell it: ghostty parses D's exit status and drops /// it, and /pane//pty/run waits on exactly that. Only marks carrying /// pardes's own `aid` move it, so fish's native marks, a nested shell's /// and a stray `133;D` in some file being printed all pass it by. pub const MarkedHandler = struct { inner: ghostty_vt.TerminalStream.Handler, phase: Term.Prompt.Phase = .none, /// Counts commands started (C at the input phase). started: u32 = 0, /// Counts prompts drawn (B), so a line the shell refused without /// running (a fish syntax error: no C, no D, a new prompt) shows. prompts: u32 = 0, /// D marks outside a running command: the shell handled a line /// without starting it (bash on a syntax error prints no C). declined: u32 = 0, /// The newest prompt continues an unfinished line (bash's PS2, marked /// `k=c`): the shell still holds the start of the command. continuation: bool = false, /// Where the newest command's output began (its C) and ended (its /// D) on the primary screen, pinned so scrolling keeps them. out_start: ?*ghostty_vt.Pin = null, out_end: ?*ghostty_vt.Pin = null, /// The running command's output was erased under it -- a clear, ED 3, /// a reset -- so the pins no longer span what it printed. ED 3 flags a /// pin on an erased history row `garbage` (ghostty 1.4), but `pinTop` /// re-pins the start at the screen's top, so the flag is gone with the /// old pin: this remembers it, as it does for a reset or a pin that /// could not be made. lost: bool = false, /// The newest command to end: which one, and its status if given. finished: ?Term.Prompt.Finished = null, const Action = ghostty_vt.TerminalStream.Action; /// Move one of the output pins to the cursor. Only the primary screen /// is pinned: a command's own full-screen display is not its output. fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { const screen = self.inner.terminal.screens.get(.primary) orelse return; if (slot.*) |old| screen.pages.untrackPin(old); slot.* = null; if (!now or self.inner.terminal.screens.active_key != .primary) return; slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; } pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { if (comptime action == .semantic_prompt) mark: { const aid = value.readOption(.aid) orelse break :mark; if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; switch (value.action) { .fresh_line_new_prompt => { self.phase = .prompt; self.continuation = value.readOption(.prompt_kind) == .continuation; }, .end_prompt_start_input => { self.phase = .input; self.prompts +%= 1; }, // bash's DEBUG trap also fires on its own PROMPT_COMMAND, // outside the input phase; only a C that ends input counts .end_input_start_output => if (self.phase == .input) { self.phase = .running; self.started +%= 1; self.lost = false; self.pinCursor(&self.out_start, true); self.pinCursor(&self.out_end, false); }, .end_command => if (self.phase == .running) { self.phase = .none; self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; self.pinCursor(&self.out_end, true); } else { self.declined +%= 1; }, else => {}, } } if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .erase_display_scroll_complete or action == .full_reset) { self.inner.vt(action, value); // A `clear` under a running command: its output is what it // prints from here, the screen's top, not lost. Only what the // scrollback later loses is (the pin goes `garbage`). if (self.phase == .running) self.pinTop(&self.out_start); return; } self.inner.vt(action, value); } /// Pins `slot` to the primary screen's top-left; lost when it cannot be. fn pinTop(self: *@This(), slot: *?*ghostty_vt.Pin) void { const screen = self.inner.terminal.screens.get(.primary) orelse return; if (slot.*) |old| screen.pages.untrackPin(old); slot.* = null; if (self.inner.terminal.screens.active_key != .primary) { self.lost = true; return; } const top = screen.pages.pin(.{ .active = .{} }) orelse { self.lost = true; return; }; slot.* = screen.pages.trackPin(top) catch null; if (slot.* == null) self.lost = true; } pub fn deinit(self: *@This()) void { self.inner.deinit(); } }; fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); const room = state.reply.len - state.reply_len; // A cut answer is worse than none: the program would read the start of // a sequence and wait, or misparse what follows. if (data.len > room) { state.reply_dropped +|= 1; return; } @memcpy(state.reply[state.reply_len..][0..data.len], data); state.reply_len += @intCast(data.len); } fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { return .{}; } /// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a /// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { const t = handler.terminal; if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; } pub const State = struct { /// What the emulator and this struct are allocated with: the core's, /// but on a screen-state replica the C heap (`emulator_gpa`), outside /// its rollback epoch: written by deltas while a copy is held, no part /// of it is ever a copy's to save or put back. gpa: std.mem.Allocator, vt: VtSlot, stream: StreamSlot, /// The emulator's answers to its program (DSR, DA, kitty graphics, ...) /// from one read of its output, written to its pty after it. Room for /// a read's worth of kitty answers (yazi or `kitten icat` asking about /// a batch of images in one write); an answer that does not fit whole /// is dropped whole, never cut short (`reply_dropped` counts them). reply: [4096]u8 = undefined, reply_len: u16 = 0, reply_dropped: u32 = 0, /// The kitty graphics its program placed, as drawn (TerminalImages.zig). images: TerminalImages = if (images_enabled) .{} else {}, /// 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. False when the stream's /// keeper of a sequence in flight had no room (ghostty goes on without /// it, swallowing the error): `open` and `load` refuse the terminal then, /// as at any allocation that fails. fn wire(s: *State) bool { s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa, .continuation_max_bytes = continuation_max }); 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(); return s.stream.continuation.?.bytes.capacity > 0; } }; /// The emulator as its program has made it, for the replay digest (the /// core's Term.State.digest, core/walk.zig): the active screen's text, how /// much history is above it, 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. Where a /// view stands is the view's (the core digests it with the pane). pub fn digest(s: *const State, h: *std.hash.Wyhash) void { const screen = s.vt.screens.active; const sb = screen.pages.scrollbar(); const cur = screen.cursor; // Everything a step reads of it (abi/term.zig `replicated`): its // size and the cursor, its modes (the alternate screen, the // mouse's, focus reports, bracketed paste: `modes`), whether it // holds a kitty image (the tag says so: tagline.zig), the reply // buffer, the OSC 133 cycle (`prompt`), the active area's text. Not // the history's text, only its length (a step's read of it: not // covered; core/Term.zig `calls`). const Modes = @TypeOf(s.vt.modes.values); const mode_bits: @Int(.unsigned, @bitSizeOf(Modes)) = @bitCast(s.vt.modes.values); const modes_word: @Int(.unsigned, (@bitSizeOf(Modes) + 7) / 8 * 8) = mode_bits; const mouse_flags: [2]u8 = .{ @intCast(@intFromEnum(s.vt.flags.mouse_event)), @intCast(@intFromEnum(s.vt.flags.mouse_format)) }; const facts = .{ s.vt.cols, s.vt.rows, sb.total, sb.len, cur.x, cur.y, modes_word, s.vt.screens.active_key, mouse_flags, s.reply_dropped, hasImages(s) }; inline for (facts) |fact| h.update(std.mem.asBytes(&fact)); h.update(s.reply[0..s.reply_len]); var marks: [marks_len]u8 = undefined; h.update(marksOf(s, &marks)); var buf: [4096]u8 = undefined; var text: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(h.*, &buf); if (screen.pages.getBottomRight(.active)) |br| screen.dumpString(&text.writer, .{ .tl = screen.pages.getTopLeft(.active), .br = br, .unwrap = false }) catch unreachable; // a hashing writer never fails text.writer.flush() catch unreachable; // a hashing writer never fails h.* = text.hasher; } fn pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?Term.Parts.Coordinate { const pin = slot orelse return null; const screen = s.vt.screens.get(.primary) orelse return null; const at = (screen.pages.pointFromPin(.screen, pin.*) orelse return null).screen; return .{ .x = at.x, .y = at.y }; } fn coordinate(at: ?Term.Parts.Coordinate) ?ghostty_vt.Coordinate { const c = at orelse return null; return .{ .x = c.x, .y = c.y }; } /// What the dump keeps of it beside its emulator (the core's /// Term.State.dumpWrite writes it by name, as every dump is). pub fn parts(s: *const State) Term.Parts { const h = &s.stream.handler; return .{ .reply = s.reply[0..s.reply_len], .reply_dropped = s.reply_dropped, .phase = h.phase, .started = h.started, .prompts = h.prompts, .declined = h.declined, .continuation = h.continuation, .lost = h.lost, .finished = h.finished, .out_start = pinAt(s, h.out_start), .out_end = pinAt(s, h.out_end), }; } /// The most bytes of a sequence its program began and has not ended (a /// CSI, an OSC, a UTF-8 codepoint, a kitty graphics chunk: 4 KiB of payload) /// that its stream keeps, so a snapshot taken between any two reads carries /// it (`snapshot`). Past it the sequence is lost at a cut, as every one was /// before. pub const continuation_max = 64 * 1024; /// Its emulator as the dump keeps it: ghostty's snapshot (both screens, /// their history, styles, links and kitty images), and the sequence its /// program had begun and not ended, which `load` feeds again. `slim`, a /// join's dump under screen state (dump.zig `dumpJoin`): its size alone, an /// emulator made afresh there, which its first delta replaces. pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) !void { if (slim) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows })); var held: std.Io.Writer.Allocating = .init(gpa); defer held.deinit(); s.stream.writeContinuation(&held.writer) catch |err| switch (err) { // Longer than it keeps: lost, as at the ground state. error.ContinuationUnavailable, error.ContinuationDisabled => held.clearRetainingCapacity(), error.WriteFailed => return error.OutOfMemory, }; const continuation: ghostty_vt.snapshot.Continuation = if (held.written().len > 0) .{ .bytes = held.written() } else .ground; try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = continuation }); } /// `snapshot`'s bytes decoded, the emulator not yet at its address. fn decode(gpa: std.mem.Allocator, bytes: []const u8) !ghostty_vt.snapshot.Decoded { if (bytes.len == 4) { const size = std.mem.bytesToValue([2]u16, bytes[0..4]); return .{ .terminal = try emulator(gpa, @max(1, size[0]), @max(1, size[1]), scrollback_max), .continuation = .ground, .history_rows = .{} }; } var reader: std.Io.Reader = .fixed(bytes); return ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ .max_continuation_bytes = continuation_max, .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, }); } /// `snapshot`'s bytes and `parts` back into a new terminal, as `open` /// makes one. pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) !*State { const out = try gpa.create(State); errdefer gpa.destroy(out); var decoded = try decode(gpa, bytes); defer decoded.deinit(gpa); out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; if (!install(out, decoded.continuation, saved)) { out.stream.deinit(); out.vt.deinit(gpa); return error.OutOfMemory; } return out; } /// Its emulator made again from its own snapshot, where it is, what pardes /// keeps beside it kept: what a replica and its session do at a join, so /// that both, and the joiner loaded from the session's, hold the same pages /// (ghostty cuts rows into pages, and prunes whole ones, by its history, /// which a snapshot does not carry). The snapshot's hash, which every side /// compares; on an error it is as it was. pub fn reload(s: *State) !u64 { const gpa = s.gpa; var bytes: std.Io.Writer.Allocating = .init(gpa); defer bytes.deinit(); try snapshot(s, gpa, &bytes.writer, false); var decoded = try decode(gpa, bytes.written()); defer decoded.deinit(gpa); var saved = parts(s); var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined; @memcpy(reply[0..saved.reply.len], saved.reply); saved.reply = reply[0..saved.reply.len]; if (comptime images_enabled) s.images.deinit(gpa); s.stream.deinit(); s.vt.deinit(gpa); s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; // Short of room for its sequence in flight it goes on without it (lost // at the next cut), as ghostty's stream does: not worth a terminal. _ = install(s, decoded.continuation, &saved); return joinHash(bytes.written()); } /// What a join compares of a snapshot (`reload`): every record of it but /// its kitty images' (tags 8 to 10, which ghostty's framing makes optional: /// snapshot/record.zig, a u16 tag, a u32 length, a u32 CRC and the payload, /// after a 10-byte envelope): an animation's current frame is stepped by /// each side's own draws, and no digest reads an image. fn joinHash(bytes: []const u8) u64 { const envelope = 10; const head = 10; var h: std.hash.Wyhash = .init(0); h.update(bytes[0..@min(bytes.len, envelope)]); var at: usize = envelope; while (at + head <= bytes.len) { const tag = std.mem.readInt(u16, bytes[at..][0..2], .little); const end = @min(bytes.len, at + head + std.mem.readInt(u32, bytes[at + 2 ..][0..4], .little)); if (tag < 8 or tag > 10) h.update(bytes[at..end]); at = end; } return h.final(); } /// A decoded emulator at its address made a terminal: its stream wired, /// the sequence in flight fed again, what pardes kept beside it put back; /// whether its stream had all the room it wanted (`wire`). fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *const Term.Parts) bool { if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); }; const whole = out.wire(); switch (continuation) { .ground => {}, .bytes => |bytes| out.stream.nextSlice(bytes), } const reply = saved.reply[0..@min(saved.reply.len, out.reply.len)]; @memcpy(out.reply[0..reply.len], reply); out.reply_len = @intCast(reply.len); out.reply_dropped = saved.reply_dropped; const h = &out.stream.handler; h.phase = saved.phase; h.started = saved.started; h.prompts = saved.prompts; h.declined = saved.declined; h.continuation = saved.continuation; h.lost = saved.lost; h.finished = saved.finished; if (out.vt.screens.get(.primary)) |screen| { inline for (.{ .{ "out_start", saved.out_start }, .{ "out_end", saved.out_end } }) |pair| if (coordinate(pair[1])) |at| { if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null; }; } return whole; } /// How every terminal's kitty loader has a medium's bytes from now on /// (ghostty's `read_medium`, build/patches.zig). pub fn media(read: Term.Media) void { if (comptime images_enabled) ghostty_vt.kitty.graphics.LoadingImage.read_medium = read; } /// The allocator it was opened with, its own from then on. pub fn gpaOf(s: *const State) std.mem.Allocator { return s.gpa; } const GColor = ghostty_vt.color; // Projected colors below this contrast use the theme's more legible anchor. pub const min_contrast: f64 = 1.5; /// The theme's 256 colours as the filter maps onto them (ghostty's /// `generate256Color` over the theme's sixteen), made again only when the /// theme's are not the ones `cache` was made of. pub fn filterPalette(cache: *FilterPalette, ink: *const Ink) *const [256][3]u8 { const wanted: FilterPalette.Key = .{ .bg = ink.bg, .fg = ink.fg, .ansi = ink.ansi }; if (cache.key) |old| if (std.meta.eql(old, wanted)) return &cache.colors; var seed = GColor.default; for (ink.ansi, 0..) |rgb, i| seed[i] = asGhostRgb(rgb); const colors = GColor.generate256Color(seed, .empty, asGhostRgb(wanted.bg), asGhostRgb(wanted.fg), false); for (&cache.colors, colors) |*dst, src| dst.* = asTriple(src); cache.key = wanted; return &cache.colors; } pub fn asGhostRgb(rgb: [3]u8) GColor.RGB { return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; } /// Where a kitty client puts its temporary files: `$TMPDIR`, else /tmp /// (which ghostty accepts whatever this says). The environment block lives /// as long as the process and pardes never edits it (ChildEnv.exportVar). fn tempDir() []const u8 { const dir = std.c.getenv("TMPDIR") orelse return "/tmp"; const path = std.mem.span(dir); return if (path.len > 0 and path[0] == '/') path else "/tmp"; } pub fn terminalIo() std.Io { return std.Io.Threaded.global_single_threaded.io(); } /// How much history there is and where the cursor is (`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, .len = sb.len, .cursor_x = @intCast(screen.cursor.x), .cursor_y = @intCast(screen.cursor.y), .cursor_visible = s.vt.modes.get(.cursor_visible), .cols = screen.pages.cols, }; } /// The first and last rows a view at `place` shows (`Term.Grid`: a row of /// the history from its top; null, or one the active area holds: the /// active area). Ghostty's own viewport is never moved: it is the active /// area's. fn shown(pages: *ghostty_vt.PageList, place: ?usize) struct { top: ghostty_vt.Pin, bottom: ghostty_vt.Pin } { const active = pages.getTopLeft(.active); const last = pages.getBottomRight(.active) orelse active; const sb = pages.scrollbar(); const row = place orelse return .{ .top = active, .bottom = last }; const above = (sb.total - sb.len) -| row; if (above == 0) return .{ .top = active, .bottom = last }; const top = active.up(above) orelse pages.getTopLeft(.screen); var bottom = top.down(sb.len - 1) orelse last; bottom.x = bottom.node.cols() - 1; return .{ .top = top, .bottom = bottom }; } /// Each view's place (`Term.Grid`) held through a write of the emulator, /// as ghostty holds a view of its own (`carried` after it): pinned to its /// row of the primary screen, the only one with a history. One the active /// area holds is on the output (null). const Carry = struct { pages: *ghostty_vt.PageList, generation: usize, pins: [max_places]?*ghostty_vt.Pin = @splat(null), /// The core's views (core/views.zig `max`), with room. const max_places = 8; }; fn carry(state: *State, places: []?usize) Carry { const screens = &state.vt.screens; const pages = &screens.get(.primary).?.pages; var c: Carry = .{ .pages = pages, .generation = screens.generation(.primary) }; std.debug.assert(places.len <= Carry.max_places); const bottom = pages.total_rows - pages.rows; for (places, c.pins[0..places.len]) |*place, *pin| { const row = place.* orelse continue; if (row >= bottom) { place.* = null; continue; } const at = pages.pin(.{ .screen = .{ .y = @intCast(row) } }) orelse { place.* = null; continue; }; // No room to follow it: on the output, as at a reset. pin.* = pages.trackPin(at) catch null; if (pin.* == null) place.* = null; } return c; } /// `carry`'s places where the write left their rows: the history's top /// for one whose row it dropped or erased, the output for one in the /// active area now or on a screen made again. fn carried(state: *State, c: Carry, places: []?usize) void { const alive = state.vt.screens.generation(.primary) == c.generation; const bottom = c.pages.total_rows - c.pages.rows; for (places, c.pins[0..places.len]) |*place, held| { const pin = held orelse continue; if (!alive) { place.* = null; continue; } const row: usize = @intCast(pinnedRow(c.pages, .{ .pin = pin })); c.pages.untrackPin(pin); place.* = if (row >= bottom) null else row; } } /// What pardes made of a terminal's stream that its emulator does not hold /// (the OSC 133 cycle, MarkedHandler), as bytes its digest holds: 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). const marks_len = 1 + 4 * 3 + 2 + 4 + 4; 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(); } /// What a row shows, written out value by value: its flags, then each /// cell's word without its page's ids, its style, its grapheme and its /// hyperlink's URI. fn dumpRow(page: *ghostty_vt.page.Page, row: *ghostty_vt.page.Row, cols: u16, w: *std.Io.Writer) !void { try w.print("{d}:", .{@as(u8, @intFromBool(row.wrap)) | @as(u8, @intFromBool(row.wrap_continuation)) << 1 | @as(u8, @backingInt(row.semantic_prompt)) << 2}); const all = page.getCells(row); for (all[0..@min(cols, all.len)]) |*c| { var word = c.*; word.style_id = 0; try w.print(" {x}", .{@as(u64, @bitCast(word))}); if (c.style_id != 0) try ghostty_vt.snapshot.style.encode(page.styles.get(page.memory, c.style_id).*, w); if (c.hasGrapheme()) for (page.lookupGrapheme(c).?) |cp| try w.print("+{x}", .{cp}); if (c.hyperlink) if (page.lookupHyperlink(c)) |id| try w.print("@{s}", .{page.hyperlink_set.get(page.memory, id).uri.slice(page.memory)}); } try w.writeByte('\n'); } /// What an emulator shows, cell for cell: the terminal-wide state, the /// cursor, the history's extent and the viewport, the active screen's rows /// (test/replicas.zig compares a client's terminal with its session's by it). pub fn dumpScreen(t: *ghostty_vt.Terminal, w: *std.Io.Writer) !void { const screen = t.screens.active; const sb = t.screens.get(.primary).?.pages.scrollbar(); try w.print("{d}x{d} {s} cursor {d},{d} {s} {} {s} title {s} pwd {s} scrollbar {d} {d} {d}\n", .{ t.cols, t.rows, @tagName(t.screens.active_key), screen.cursor.x, screen.cursor.y, @tagName(screen.cursor.cursor_style), screen.cursor.pending_wrap, @tagName(screen.cursor.semantic_content), t.getTitle() orelse "", t.getPwd() orelse "", sb.total, sb.offset, sb.len, }); try w.writeAll(std.mem.asBytes(&t.modes.values)); try w.writeAll(std.mem.asBytes(&screen.kitty_keyboard)); try w.print(" mouse {s} {s} {s}\n", .{ @tagName(t.flags.mouse_event), @tagName(t.flags.mouse_format), @tagName(t.mouse_shape) }); for (t.colors.palette.current) |c| try w.print("{x}{x}{x}", .{ c.r, c.g, c.b }); try w.writeByte('\n'); var it = screen.pages.rowIterator(.right_down, .{ .active = .{} }, null); while (it.next()) |p| try dumpRow(p.node.page(), p.rowAndCell().row, t.cols, w); } /// Its grid reflowed to `cols` by `rows`, every view's place carried /// through it (`carry`: a row's first cell, so a place is a row again after /// every reflow, whatever a widening joined). 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, places: []?usize) void { const held: ?Carry = if (places.len == 0) null else carry(state, places); defer if (held) |c| carried(state, c, places); state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {}; } /// 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, .sync = s.vt.modes.get(.synchronized_output), }; } /// 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 from `last`, the cell it last heard of (its pane's, which a /// rollback puts back). Empty when the program does not hear of it. pub fn mouse(state: *State, last: *?Term.Parts.Coordinate, 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 cell = coordinate(last.*); defer last.* = if (cell) |c| .{ .x = c.x, .y = c.y } else null; 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 = &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, last: *?Term.Parts.Coordinate, 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, last, 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. pub fn close(state: *State) void { const own = state.gpa; if (comptime images_enabled) state.images.deinit(own); state.stream.deinit(); state.vt.deinit(own); own.destroy(state); } /// A terminal pane's emulator, `cols` by `rows`, as `open` makes one. /// How much history a terminal keeps, in bytes of ghostty's pages. const scrollback_max = 16 * 1024 * 1024; fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16, history: usize) !ghostty_vt.Terminal { return ghostty_vt.Terminal.init(terminalIo(), gpa, .{ .cols = cols, .rows = rows, .max_scrollback_bytes = history, .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 { return openKeeping(gpa, cols, rows, scrollback_max); } /// `open`, keeping `history` bytes of history (the tests below fill a /// smaller one). fn openKeeping(gpa: std.mem.Allocator, cols: u16, rows: u16, history: usize) !*State { const state = try gpa.create(State); errdefer gpa.destroy(state); // Every other field its default, never what the heap had: a digest // reads them, and two replicas must agree (core/replica.zig). state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows, history), .stream = undefined }; if (!state.wire()) { state.stream.deinit(); state.vt.deinit(gpa); return error.OutOfMemory; } 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). Every view's /// place is carried through it as `resize` carries them. With nothing /// tracked and no view off the output the read is parsed and nothing more. pub fn feed(state: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool, places: []?usize) Term.Told { const carrying: ?Carry = if (places.len == 0) null else carry(state, places); defer if (carrying) |c| carried(state, c, places); if (tracked.len == 0) { ingest(state, bytes); return .{ .rows = rows[0..0], .erased = erased[0..0], .cleared = false, .alive = true, .failed = false }; } const screens = &state.vt.screens; const active = screens.active_key; const generation = screens.generation(active); const pages = &screens.active.pages; var failed = false; var room: [512]RowPin = undefined; const pins = if (tracked.len <= room.len) room[0..tracked.len] else state.gpa.alloc(RowPin, tracked.len) catch { ingest(state, bytes); @memcpy(rows[0..tracked.len], tracked); @memset(erased[0..tracked.len], false); return .{ .rows = rows[0..tracked.len], .erased = erased[0..tracked.len], .cleared = false, .alive = true, .failed = true }; }; defer if (tracked.len > room.len) state.gpa.free(pins); for (pins, tracked) |*pin, row| pin.* = trackRow(pages, row, &failed); // Whether the program cleared the screen (ED 2, a switch of screens); // pardes reads the flag nowhere else. state.vt.flags.dirty.clear = false; ingest(state, bytes); const cleared = state.vt.flags.dirty.clear; // RIS can destroy the alternate screen and every pin it owned. const alive: ?*ghostty_vt.PageList = if (screens.generation(active) == generation) pages else null; for (pins, rows[0..tracked.len], erased[0..tracked.len]) |pin, *row, *gone| { row.* = pinnedRow(alive, pin); gone.* = alive != null and pin.pin != null and pin.pin.?.garbage; if (alive) |owner| if (pin.pin) |held| owner.untrackPin(held); } return .{ .rows = rows[0..tracked.len], .erased = erased[0..tracked.len], .cleared = cleared, .alive = alive != null, .failed = failed }; } /// Where the shell is in its command cycle (`Term.Prompt`); all zero /// without an emulator. pub fn prompt(state: ?*State) Term.Prompt { const s = state orelse return .{}; const marks = &s.stream.handler; const cursor = &s.vt.screens.active.cursor; // At a prompt's input: on the alternate screen too, where a program // killed there (htop, `sig KILL`) left the emulator and the shell then // drew its prompt, marks and all. A full-screen program draws no // prompt marks. const ready = cursor.semantic_content == .input; // Nothing typed on its line: no input left of the cursor and none // under it (text typed and then Ctrl-A'd starts at the cursor). // Nothing further right counts: that is where fish draws a right // prompt, and fish suggests nothing on an empty line. const empty = ready and empty: { var prompted = false; 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; prompted = prompted or cell.semantic_content == .prompt; } // A row with no prompt on it, begun by a newline in the input: the // line above was taken, its Enter echoed and the command's C still // to come (bash writes them apart), so it is typed still. if (!prompted and cursor.page_row.semantic_prompt == .prompt_continuation) if (cursor.page_pin.up(1)) |above| { for (above.cells(.all)) |cell| if (cell.semantic_content == .input and !cell.isEmpty()) break :empty false; }; break :empty true; }; return .{ .phase = switch (marks.phase) { .none => .none, .prompt => .prompt, .input => .input, .running => .running, }, .started = marks.started, .prompts = marks.prompts, .declined = marks.declined, .continuation = marks.continuation, .finished = if (marks.finished) |f| .{ .seq = f.seq, .status = f.status } else null, .input_ready = ready, .input_empty = empty, .at_prompt = s.vt.cursorIsAtPrompt(), }; } /// What the newest finished command printed: the screen text between its /// C and D marks, read from at most `max_rows` rows above its end, so a /// command that printed the whole history costs no more than its tail. /// The shell exited in the middle of a command (its `exit 3`): no end mark /// will come, so the command's output ends where the cursor is. pub fn endOutputHere(state: *State) void { const marks = &state.stream.handler; if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); } pub fn commandOutput(state: ?*State, gpa: std.mem.Allocator, max_rows: usize) !Term.CommandOutput { // Unless there is text to read, whether the nothing it printed is the // whole of it. const whole = printed: { const s = state orelse break :printed true; const marks = &s.stream.handler; const start = marks.out_start orelse break :printed false; const end = marks.out_end orelse break :printed false; const screen = s.vt.screens.get(.primary) orelse break :printed false; if (end.garbage) break :printed false; var whole = !marks.lost and !start.garbage; // Nothing printed: the whole of it. if (start.eql(end.*)) break :printed whole; // D is where the next prompt begins: the output ends a cell before. // An end at the very top, or before the start, is output a redraw // moved (a prompt drawn over it in a window two rows high): how // much is not known, so it is not called whole. const last = end.leftWrap(1) orelse break :printed false; if (last.before(start.*)) break :printed false; var from = start.*; if (last.up(max_rows)) |floor| if (from.before(floor)) { from = floor; from.x = 0; whole = false; }; return .{ .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), .whole = whole, }; }; return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = whole }; } /// One key for its program, as the program's keyboard protocol and modes /// ask for it, written to `out`. pub fn key(state: *State, k: Key, out: *std.Io.Writer) !void { const input = ghostty_vt.input; const function_keys = [Key.f25 - Key.f1 + 1]input.Key{ .f1, .f2, .f3, .f4, .f5, .f6, .f7, .f8, .f9, .f10, .f11, .f12, .f13, .f14, .f15, .f16, .f17, .f18, .f19, .f20, .f21, .f22, .f23, .f24, .f25 }; const physical: input.Key = switch (k.cp) { Key.enter => .enter, Key.backspace => .backspace, Key.tab => .tab, Key.escape => .escape, Key.up => .arrow_up, Key.down => .arrow_down, Key.left => .arrow_left, Key.right => .arrow_right, Key.home => .home, Key.end => .end, Key.page_up => .page_up, Key.page_down => .page_down, Key.delete => .delete, Key.insert => .insert, Key.print_screen => .print_screen, Key.scroll_lock => .scroll_lock, Key.pause => .pause, Key.menu => .context_menu, Key.f1...Key.f25 => function_keys[k.cp - Key.f1], else => if (k.cp < 128) input.Key.fromASCII(@intCast(k.cp)) orelse .unidentified else .unidentified, }; var utf8: [4]u8 = undefined; const text_cp = if (k.shift and k.cp >= 'a' and k.cp <= 'z') k.cp - 'a' + 'A' else k.cp; // A key with no text of its own types its code point only when that // is a character: the kitty keyboard protocol numbers function and // modifier keys in the private use area (F3 is U+E016), and a shell // was typed those as junk. const text = if (k.text.len > 0) k.text else if (k.cp >= 32 and k.cp < Key.up and k.cp != Key.backspace and !(k.cp >= 0xE000 and k.cp <= 0xF8FF)) utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] else ""; try input.encodeKey(out, .{ .key = physical, .mods = .{ .ctrl = k.ctrl, .alt = k.alt, .shift = k.shift }, .consumed_mods = .{ .shift = k.text.len > 0 and k.shift }, .utf8 = text, .unshifted_codepoint = if (k.cp >= 'A' and k.cp <= 'Z') k.cp - 'A' + 'a' else if (k.cp < Key.up) k.cp else 0, }, options: { var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); // fromTerminal cannot know this one and says so, defaulting to // "option is not alt" — right for an app that lets macOS do the // unicode translation and hands the encoder the composed text. // Every pardes shell resolves the modifier itself and hands the // core the BASE key with the alt bit and no text at all (see // PardesView.keyDown, and app.mjs doing the same with the same // two bits), so by the time this runs alt already means alt. // Left at the default, a macOS build drops the ESC prefix on // the floor and forwards Alt-n to the child as a bare `n`. opts.macos_option_as_alt = .true; break :options opts; }); } /// How many cells left or right of the cursor a click on row `row` (from /// the top of the history), 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(.{ .screen = .{ .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(.{ .screen = .{ .x = @intCast(grid_col), .y = @intCast(row) }, }) orelse return null; const cursor_pin = screen.cursor.page_pin.*; var prompts = cursor_pin.promptIterator(.left_up, null); const prompt_pin = prompts.next() orelse return null; if (click_pin.before(prompt_pin)) return null; const moves = screen.promptClickMove(click_pin); return .{ .left = moves.left, .right = moves.right }; } /// What LEAVING raw tty mode does to one prompt row, decided from its cells /// alone: OSC 133 prompt cells are hidden in normal mode, what was typed at /// them stays. fn promptCut(pin: ghostty_vt.Pin) PromptCut { const cells = pin.cells(.all); var cols: usize = 0; while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or // a repaint that has moved on. Nothing here is the prompt, so hide nothing. if (cols == 0) return .keep; // ...and all prompt, nothing typed yet: the row is chrome end to end. if (cols >= cells.len) return .blank; return .{ .cut = cols }; } /// How much of its row `row` (from the top of the history) the prompt it /// starts with is; null for a row no prompt starts (the core measures the /// cut columns in the row's text, Term.promptPrefix). pub fn promptCutAt(state: *State, row: i32) ?PromptCut { if (row < 0) return null; const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return null; if (pin.rowAndCell().row.semantic_prompt == .none) return null; return promptCut(pin); } /// What a predicted echo reads of cell `x`, `y` of its active area /// (core/echo.zig): null off it. pub fn echoCell(state: *const State, x: u16, y: u16) ?Term.EchoCell { if (y >= state.vt.rows) return null; const ci = state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return null; return .{ .cp = ci.cell.codepoint(), .input = ci.cell.semantic_content == .input, .style = ci.cell.style_id }; } /// The link (OSC 8) cell `x` of row `row` (from the top of the history) /// carries, and the cells its run takes on that row; `cut`: counted in the /// row's text, its prompt's own cells cut off (promptCut). pub fn link(state: *State, row: i32, x: u16, cut: bool) ?Term.Link { if (row < 0) return null; const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return null; const shift: usize = if (!cut or pin.rowAndCell().row.semantic_prompt == .none) 0 else switch (promptCut(pin)) { .keep => 0, .blank => return null, .cut => |n| n, }; const cells = pin.cells(.all); const at = @as(usize, x) + shift; if (at >= cells.len) return null; const page = pin.node.page(); if (!cells[at].hyperlink) return null; const id = page.lookupHyperlink(&cells[at]) orelse return null; var lo = at; while (lo > shift and sameLink(page, &cells[lo - 1], id)) lo -= 1; var hi = at + 1; while (hi < cells.len and sameLink(page, &cells[hi], id)) hi += 1; const uri = page.hyperlink_set.get(page.memory, id).uri.slice(page.memory); return .{ .uri = uri, .lo = @intCast(lo - shift), .hi = @intCast(hi - shift) }; } fn sameLink(page: *const ghostty_vt.page.Page, cell: *const ghostty_vt.page.Cell, id: anytype) bool { if (!cell.hyperlink) return false; return (page.lookupHyperlink(cell) orelse return false) == id; } fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { const cols = switch (promptCut(pin)) { .keep => return raw, .blank => return "", .cut => |n| n, }; const cells = pin.cells(.all); var at: usize = 0; var col: usize = 0; while (col < cols and at < raw.len) { const cell = &cells[col]; at = @min(raw.len, at + dumpedBytes(pin, cell)); // the tail cell of a wide glyph spells nothing of its own col += if (cell.wide == .wide) @as(usize, 2) else 1; } return std.mem.trimEnd(u8, raw[at..], " \t"); } fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { switch (cell.wide) { .spacer_head, .spacer_tail => return 0, .narrow, .wide => {}, } var n: usize = switch (cell.content_tag) { .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( cell.codepoint(), ) catch 1, // A cell carrying only a colour still spells one blank in the dump. else => 1, }; if (cell.content_tag == .codepoint_grapheme) { if (pin.grapheme(cell)) |extra| for (extra) |cp| { n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; }; } return n; } /// Its rows `first` and the `count` after it (from the top of its /// history) as text, a prompt's own cells cut off the rows it starts: /// `arena`'s. An edit copy's rows as they were (core/ansi.zig). pub fn editRows(state: *State, arena: std.mem.Allocator, first: usize, count: usize) ![]const []const u8 { const screen = state.vt.screens.active; const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return error.NoRow; const br = screen.pages.pin(.{ .screen = .{ .x = screen.pages.cols - 1, .y = @intCast(first + count - 1), } }) orelse return error.NoRow; var output: std.Io.Writer.Allocating = .init(arena); try screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }); const shell = try arena.alloc([]const u8, count); var raw = std.mem.splitScalar(u8, output.written(), '\n'); var pins = tl.rowIterator(.right_down, br); for (shell) |*row| { const text = raw.next() orelse ""; row.* = if (pins.next()) |pin| if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text else text; } return shell; } /// 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 a view at `place` 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, place: ?usize) ![]const []const u8 { const screen = state.vt.screens.active; const rows = shown(&screen.pages, place); var rows_out: std.Io.Writer.Allocating = .init(arena); try screen.dumpString(&rows_out.writer, .{ .tl = rows.top, .br = rows.bottom, .unwrap = false }); const raw = try rows_out.toOwnedSlice(); var prompts = rows.top.rowIterator(.right_down, rows.bottom); 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; } /// The rows of a view at `place` as cells, for the core's paint /// (Term.paint, the core's core/ansi.zig): `rows.len` rows from the view's /// row `first`, `cols` cells each into `cells`, each its style in the /// theme's colours (through the filter when `filtered`), the bytes it /// spells in the view's text and its width; each row whether a prompt /// starts it, and how much of it that is. pub fn paint(state: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, place: ?usize, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void { var filter_storage: Filter = undefined; const filter: ?*Filter = if (filtered) blk: { filter_storage = filterOf(ink, palette, &state.vt); break :blk &filter_storage; } else null; // DECSCNM, read once: the filtered palette folds it in itself, the raw // path needs it per cell. const scnm = state.vt.modes.get(.reverse_colors); const pages = &state.vt.screens.active.pages; const top = shown(pages, place).top; for (rows, 0..) |*row, vi| { row.* = .{ .prompt = null, .placeholder = false, .len = 0 }; const row_pin = top.down(first + vi) orelse continue; const flags = row_pin.rowAndCell().row; if (flags.semantic_prompt != .none) row.prompt = promptCut(row_pin); row.placeholder = flags.kitty_virtual_placeholder; const out = cells[vi * cols ..][0..cols]; var x: u16 = 0; while (x < cols) : (x += 1) { const ci = cellAt(pages, row_pin, x) orelse break; out[x] = .{ .style = cellStyle(ink, ci, filter, scnm), .bytes = @intCast(@min(dumpedBytes(row_pin, ci.cell), std.math.maxInt(u16))), .wide = switch (ci.cell.wide) { .narrow => .narrow, .wide => .wide, .spacer_tail => .spacer_tail, .spacer_head => .spacer_head, }, }; } row.len = x; } } /// The cell at column `x` of the row `row` pins, as `pages.getCell` reads /// it, without walking from the viewport's top down to the row again: that /// walk, once a cell, was most of a terminal's paint (once getCell was no /// longer inlined, a frame of a 120x40 shell took 75 µs more). fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghostty_vt.PageList.Cell { if (x >= pages.cols or x >= row.node.cols()) return null; const rac = row.node.page().getRowAndCell(x, row.y); return .{ .node = row.node, .row = rac.row, .cell = rac.cell, .row_idx = row.y, .col_idx = x }; } // A cell's underline styles are SGR's, in SGR's order (`off` its `none`): a // cast takes one to the other (cellStyle, and pager.zig's attribute). comptime { for (@typeInfo(@FieldType(plain.CellStyle, "ul")).@"enum".field_names, 0..) |name, i| if (@backingInt(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's"); } fn cellStyle(ink: *const Ink, ci: ghostty_vt.PageList.Cell, filtered: ?*Filter, scnm: bool) plain.CellStyle { const style = ci.style(); var cs: plain.CellStyle = .{ .fg = if (filtered) |colors| filterFg(colors, style) else ghostColor(ink, style.fg_color, scnm), .bg = if (filtered) |colors| filterBg(colors, style, ci.cell) else ghostColor(ink, style.bg_color, !scnm), .bold = style.flags.bold, .dim = style.flags.faint, .italic = style.flags.italic, .blink = style.flags.blink, .reverse = style.flags.inverse, .invisible = style.flags.invisible, .strikethrough = style.flags.strikethrough, .ul = @fromBackingInt(@intCast(@backingInt(style.flags.underline))), }; if (filtered == null) switch (ci.cell.content_tag) { .bg_color_palette => cs.bg = ink.palColor(ci.cell.content.color_palette.data), .bg_color_rgb => { const rgb = ci.cell.content.color_rgb; cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; }, else => {}, }; // SGR faint on the page's text is the page's dim ink (DESIGN.md R15): // toward the page, so as faint on a light theme as on a dark one. if (cs.dim and std.meta.eql(cs.fg, plain.Color{ .rgb = ink.fg })) { cs.fg = .{ .rgb = ink.dim }; cs.dim = false; } return cs; } pub fn asPardesColor(rgb: GColor.RGB) plain.Color { return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; } fn asTriple(rgb: GColor.RGB) [3]u8 { return .{ rgb.r, rgb.g, rgb.b }; } /// A program's colours mapped to the theme (Term.Filter): for a terminal's /// cells (`vt`), or a +Pager's spans (`vt` null, the program's palette /// xterm's own). pub fn filterOf(ink: *const Ink, palette: *FilterPalette, vt: ?*const ghostty_vt.Terminal) Filter { var source = GColor.default; if (vt) |t| { for (&source, 0..) |*rgb, i| rgb.* = t.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; } var theme_bg = asGhostRgb(ink.bg); var theme_fg = asGhostRgb(ink.fg); var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null; var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null; if (vt != null and vt.?.modes.get(.reverse_colors)) { std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); } var self: Filter = .{ .target = filterPalette(palette, ink), .theme_bg = asTriple(theme_bg), .theme_fg = asTriple(theme_fg), .default_bg = asTriple(theme_bg), .fallback_fg = asTriple(theme_fg), .default_bg_luminance = luminanceOf(theme_bg), .fg_for_palette = undefined, .bg_for_palette = undefined, .fg_default = undefined, .bg_default = undefined, }; var default_bg = theme_bg; if (dynamic_bg) |rgb| default_bg = keyedRgb(&self, rgb); self.default_bg = asTriple(default_bg); self.default_bg_luminance = luminanceOf(default_bg); if (theme_bg.contrast(default_bg) > theme_fg.contrast(default_bg)) self.fallback_fg = asTriple(theme_bg); self.fg_default = asPardesColor(legible(&self, if (dynamic_fg) |rgb| keyedRgb(&self, rgb) else theme_fg)); self.bg_default = asPardesColor(default_bg); for (&source, 0..) |current, i| { const idx: u8 = @intCast(i); const mapped = paletteRgb(&self, idx, current); self.fg_for_palette[idx] = asPardesColor(legible(&self, mapped)); self.bg_for_palette[idx] = asPardesColor(mapped); } return self; } /// The filter a +Pager's spans are drawn through (Term.filter). pub fn pagerFilter(ink: *const Ink, palette: *FilterPalette) Filter { return filterOf(ink, palette, null); } fn filterFg(self: *Filter, style: ghostty_vt.Style) plain.Color { return switch (style.fg_color) { .none => self.fg_default, .palette => |idx| self.fg_for_palette[idx], .rgb => |rgb| asPardesColor(legible(self, keyedRgb(self, rgb))), }; } fn filterBg(self: *Filter, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) plain.Color { switch (cell.content_tag) { .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], .bg_color_rgb => {}, else => switch (style.bg_color) { .none => return self.bg_default, .palette => |idx| return self.bg_for_palette[idx], .rgb => {}, }, } // Truecolour, from either the cell or its style. return asPardesColor(keyedRgb(self, style.bg(cell, &GColor.default).?)); } /// A +Pager span's colour (Term.page), as `filterFg` and `filterBg` map a /// cell's. pub fn spanColor(self: *Filter, color: plain.Color, is_bg: bool) plain.Color { return switch (color) { .default => color, .index => |idx| if (is_bg) self.bg_for_palette[idx] else self.fg_for_palette[idx], .rgb => |rgb| blk: { const keyed = keyedRgb(self, asGhostRgb(rgb)); break :blk asPardesColor(if (is_bg) keyed else legible(self, keyed)); }, }; } pub fn legible(self: *const Filter, rgb: GColor.RGB) GColor.RGB { if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= min_contrast) return rgb; return asGhostRgb(self.fallback_fg); } pub fn paletteRgb(self: *Filter, idx: u8, current: GColor.RGB) GColor.RGB { if (current.eql(GColor.default[idx])) return asGhostRgb(self.target[idx]); return keyedRgb(self, current); } pub fn keyedRgb(self: *Filter, rgb: GColor.RGB) GColor.RGB { return asGhostRgb(self.target[nearestKey(self, rgb)]); } pub fn nearestKey(self: *Filter, rgb: GColor.RGB) u8 { const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); if (self.cache_valid[slot] and asGhostRgb(self.cache_rgb[slot]).eql(rgb)) return self.cache_key[slot]; var best: u8 = 0; var best_distance: u32 = std.math.maxInt(u32); for (GColor.default, 0..) |candidate, i| { const distance = colorDistance(rgb, candidate); // Strict comparison makes duplicate-colour ties stable at the // lowest canonical xterm key. if (distance < best_distance) { best_distance = distance; best = @intCast(i); } } self.cache_rgb[slot] = asTriple(rgb); self.cache_key[slot] = best; self.cache_valid[slot] = true; return best; } const channel_luminance: [256]f64 = blk: { @setEvalBranchQuota(20000); var table: [256]f64 = undefined; for (&table, 0..) |*slot, c| { const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; slot.* = if (normalized <= 0.03928) normalized / 12.92 else std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); } break :blk table; }; pub fn luminanceOf(rgb: GColor.RGB) f64 { return 0.2126 * channel_luminance[rgb.r] + 0.7152 * channel_luminance[rgb.g] + 0.0722 * channel_luminance[rgb.b]; } /// ghostty's `RGB.contrast` with both luminances already in hand. fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { const lighter = @max(a_luminance, b_luminance); const darker = @min(a_luminance, b_luminance); return (lighter + 0.05) / (darker + 0.05); } fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { const dr = @as(i32, a.r) - @as(i32, b.r); const dg = @as(i32, a.g) - @as(i32, b.g); const db = @as(i32, a.b) - @as(i32, b.b); return @intCast(dr * dr + dg * dg + db * db); } fn ghostColor(ink: *const Ink, color: ghostty_vt.Style.Color, is_bg: bool) plain.Color { return switch (color) { .none => if (ink.host) .default else .{ .rgb = if (is_bg) ink.bg else ink.fg }, .palette => |idx| ink.palColor(idx), .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, }; } /// When the pane's next kitty animation frame is due (ms on the core's /// clock), as its last drawn frame left it; null when nothing plays. pub fn due(state: *const State) ?u64 { if (comptime !images_enabled) return null; return state.images.animation_due_ms; } /// Whether the screen showing holds any kitty graphics image. pub fn hasImages(maybe: ?*const State) bool { if (comptime !images_enabled) return false; const state = maybe orelse return false; return state.vt.screens.active.kitty_images.images.count() > 0; } /// Its kitty graphics over the body's rows, as placements appended to /// `out` (after the rows and their colours: placeholder cells are blanked /// in `frame`, `frame_cols` wide). `at.rows_of` maps its view's rows to /// the body's; a prompt row outside tty mode is cut or hidden, its columns /// not the grid's, and shows none. pub fn images(state: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void { if (comptime !images_enabled) return; const screen = state.vt.screens.active; const view = shown(&screen.pages, at.place); var rows_of: [1024]?u16 = undefined; const vp_rows = @min(at.rows_of.len, rows_of.len); var any_placeholder = false; for (rows_of[0..vp_rows], at.rows_of[0..vp_rows], 0..) |*slot, body_row, vi| { slot.* = null; const vr = body_row orelse continue; const row_pin = view.top.down(vi) orelse continue; const flags = row_pin.rowAndCell().row; if (!at.tty_mode and flags.semantic_prompt != .none) continue; any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; slot.* = vr; } // Nothing to draw, no placeholder to blank and nothing cached to let // go: the common case costs the rows' flags. if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return; state.images.draw(state.gpa, gpa, &state.vt, at, view.top, view.bottom, rows_of[0..vp_rows], out, frame, frame_cols); } test "a view's place at the history's cap: it keeps showing its line while output drops the rows above it, and goes to the top once its own row is dropped; on the output it follows" { const gpa = std.testing.allocator; const s = try open(gpa, 20, 4); defer close(s); // The history at its least (whole pages are dropped past it), filled // to it: a line no longer grows it. s.vt.screens.active.pages.setMaxBytes(1); var line: [32]u8 = undefined; var n: usize = 0; while (true) : (n += 1) { const before = grid(s).total; ingest(s, try std.fmt.bufPrint(&line, "line-{d}\r\n", .{n})); if (before > grid(s).len and grid(s).total <= before) break; } // A page dropped: the next page is the newest. Fed into it past a // screenful, so its own rows reach into the history. for (0..100) |_| { ingest(s, try std.fmt.bufPrint(&line, "line-{d}\r\n", .{n})); n += 1; } var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); // One view on the history's last row (in that newest page), one on the // output. const at = grid(s).total - grid(s).len - 1; var places = [_]?usize{ at, null }; const was = (try viewport(s, arena.allocator(), false, places[0]))[0]; // Fed a line at a time until the history drops the page above it. while (places[0].? == at) : (n += 1) { _ = feed(s, try std.fmt.bufPrint(&line, "line-{d}\r\n", .{n}), &.{}, &.{}, &.{}, &places); try std.testing.expectEqual(@as(?usize, null), places[1]); } // Moved up by the rows dropped, on the same line. try std.testing.expect(places[0].? < at); try std.testing.expectEqualStrings(was, (try viewport(s, arena.allocator(), false, places[0]))[0]); // Fed until its own row is dropped: the history's top. while (places[0].? > 0) : (n += 1) _ = feed(s, try std.fmt.bufPrint(&line, "line-{d}\r\n", .{n}), &.{}, &.{}, &.{}, &places); try std.testing.expectEqual(@as(?usize, 0), places[0]); try std.testing.expectEqual(@as(?usize, null), places[1]); } test "a view's place is carried through output, the history's cap and reflows as ghostty carries a view of its own, a row's first cell each time (a fuzz)" { var seed: u64 = 0; while (seed < 300) : (seed += 1) _ = try carryFuzz(std.testing.allocator, seed); } test "a scrolled-back view stays on its line through a narrowing that grows the rows, where ghostty's own went to the output in the middle of the resize (the carry's fuzz, seed 1956)" { // 44x3, the view on row 23 (the active area 24-26), resized to 21x6: // ghostty grows the rows first (the active area 21-26 takes the view's // row: to the output), then reflows (the line on rows 46-47 of 55, the // active area 49-54). Its history is all there: the view stays on it. try std.testing.expectEqual(@as(usize, 1), try carryFuzz(std.testing.allocator, 1956)); } /// One run of the carry's fuzz: 80 random reads of output (lines 0-150 /// long, wrapped), resizes and scrolls of two emulators alike, a view's /// place carried in one (`feed`, `resize`) and ghostty's own view in the /// other (the oracle): its view put at its row's first cell after a reflow /// (a widening can leave ghostty's mid-row: pardes-term-join-6), and at the /// output when it reaches the active area. Where ghostty's view went to the /// output only in the MIDDLE of a resize and its row is in the history /// again after it (ghostty grows the rows before a narrowing's reflow, /// PageList.resizeWithoutReflow, and checks before a widening's growth, /// PageList.resizeCols: an order of its own, nothing under the view gone), /// the view stays on its line (pardes-term-join-11): the oracle is put back /// on the row a pin of its own was carried to through the resize, and the /// run counts it. How many it put back. fn carryFuzz(gpa: std.mem.Allocator, seed: u64) !usize { var prng: std.Random.DefaultPrng = .init(seed); const rnd = prng.random(); var cols: u16 = rnd.intRangeAtMost(u16, 20, 60); var rows: u16 = rnd.intRangeAtMost(u16, 2, 6); const ours = try open(gpa, cols, rows); defer close(ours); const oracle = try open(gpa, cols, rows); defer close(oracle); const capped = rnd.boolean(); for ([_]*State{ ours, oracle }) |s| if (capped) s.vt.screens.active.pages.setMaxBytes(1); const pages = &oracle.vt.screens.active.pages; var places = [_]?usize{null}; var line: [200]u8 = undefined; var kept: usize = 0; for (0..80) |_| { switch (rnd.uintLessThan(u8, 4)) { 0, 1 => for (0..rnd.intRangeAtMost(usize, 1, 400)) |i| { const len = rnd.intRangeAtMost(usize, 0, 150); for (line[0..len], 0..) |*c, j| c.* = 'a' + @as(u8, @intCast((i + j) % 26)); _ = feed(ours, line[0..len], &.{}, &.{}, &.{}, &places); _ = feed(ours, "\r\n", &.{}, &.{}, &.{}, &places); ingest(oracle, line[0..len]); ingest(oracle, "\r\n"); }, 2 => { if (rnd.boolean()) cols = rnd.intRangeAtMost(u16, 20, 60); rows = rnd.intRangeAtMost(u16, 2, 6); resize(ours, cols, rows, &places); const held: ?*ghostty_vt.Pin = if (pages.viewport == .pin) pages.trackPin(pages.viewport_pin.*) catch null else null; oracle.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; if (pages.viewport == .pin) pages.viewport_pin.x = 0; if (held) |pin| { defer pages.untrackPin(pin); const row: usize = @intCast(pinnedRow(pages, .{ .pin = pin })); if (pages.viewport == .active and !pin.garbage and row < pages.total_rows - pages.rows) { pages.scroll(.{ .row = row }); kept += 1; } } }, else => { const sb = ours.vt.screens.active.pages.scrollbar(); const to = rnd.uintLessThan(usize, sb.total); places[0] = if (to >= sb.total - sb.len) null else to; oracle.vt.screens.active.scroll(.{ .row = to }); }, } const sb = pages.scrollbar(); if (sb.offset >= sb.total - sb.len) pages.scroll(.active); const want: ?usize = if (pages.viewport == .active) null else pages.scrollbar().offset; if (want != places[0]) { std.debug.print("seed {d}: carried {?d}, ghostty's own {?d}\n", .{ seed, places[0], want }); return error.TestExpectedEqual; } } return kept; } 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)), ); } } } /// Its snapshot as the dump writes it, `gpa`'s (the tests below). fn snapshotOf(gpa: std.mem.Allocator, s: *const State) ![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); try snapshot(s, gpa, &out.writer, false); return out.toOwnedSlice(); } /// Two terminals as a replica compares them: their snapshots' bytes, what /// pardes keeps beside the emulator, and the digest. fn expectSame(gpa: std.mem.Allocator, a: *const State, b: *const State) !void { const x = try snapshotOf(gpa, a); defer gpa.free(x); const y = try snapshotOf(gpa, b); defer gpa.free(y); try std.testing.expectEqualSlices(u8, x, y); var ma: [marks_len]u8 = undefined; var mb: [marks_len]u8 = undefined; try std.testing.expectEqualSlices(u8, marksOf(a, &ma), marksOf(b, &mb)); try std.testing.expectEqualSlices(u8, a.reply[0..a.reply_len], b.reply[0..b.reply_len]); var ha: std.hash.Wyhash = .init(0); var hb: std.hash.Wyhash = .init(0); digest(a, &ha); digest(b, &hb); try std.testing.expectEqual(ha.final(), hb.final()); } test "a snapshot taken inside a sequence carries it: over pardes's own handler the load continues as the terminal fed whole" { // ghostty promises the continuation for its standard handler; pardes's // MarkedHandler wraps it (OSC 133 marks, erases): cut at every byte of // a CSI, an OSC (a link, pardes's own marks), a UTF-8 codepoint, a // kitty graphics payload (APC) and a device query. const gpa = std.testing.allocator; const streams = [_][]const u8{ "a\x1b[38;2;10;20;30mcolour\x1b[0m b", "\x1b]8;;https://example.com/x\x1b\\link\x1b]8;;\x1b\\ c", "x\u{1F469}\u{200D}\u{1F4BB}y \u{6F22}\u{5B57} \u{E9}", "\x1b_Ga=T,i=7,f=24,s=1,v=1;AAAA\x1b\\ after", "\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07ls\r\n\x1b]133;C;aid=pardes\x07out\r\n\x1b]133;D;0;aid=pardes\x07", "q\x1b[6n\x1b[c\x1b[16t z", }; for (streams) |stream| for (1..stream.len) |cut| { const whole = try open(gpa, 24, 5); defer close(whole); whole.stream.nextSlice(stream[0..cut]); whole.stream.nextSlice(stream[cut..]); const cutting = try open(gpa, 24, 5); defer close(cutting); cutting.stream.nextSlice(stream[0..cut]); const bytes = try snapshotOf(gpa, cutting); defer gpa.free(bytes); const loaded = try load(gpa, bytes, &parts(cutting)); defer close(loaded); loaded.stream.nextSlice(stream[cut..]); expectSame(gpa, whole, loaded) catch |err| { std.debug.print("cut at byte {d} of {f}\n", .{ cut, std.ascii.hexEscape(stream, .lower) }); return err; }; }; } /// What the join tests below stream: plain text, a build's log, and heavy /// colour and links (a truecolour a cell, a link a word, marks piled on /// letters, wide characters: what runs a page out of room for styles, /// links and graphemes), `lines` of it, no clear. const Corpus = enum { text, logs, heavy }; fn corpus(gpa: std.mem.Allocator, which: Corpus, lines: usize) ![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); const w = &out.writer; var prng: std.Random.DefaultPrng = .init(@as(u64, @intFromEnum(which)) + 11); const random = prng.random(); const words = [_][]const u8{ "the", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog", "./core/replica.zig:1234:", "error:", "expected", "\u{6F22}\u{5B57}", "na\u{EF}ve" }; for (0..lines) |i| switch (which) { .text => { for (0..random.uintLessThan(usize, 18)) |_| try w.print("{s} ", .{words[random.uintLessThan(usize, words.len)]}); try w.print("{d}\r\n", .{i}); }, .logs => try w.print("[{d:>3}%] \x1b[32mBuilding CXX object\x1b[0m src/CMakeFiles/core.dir/module_{d}.cpp.o{s}\r\n", .{ i * 100 / lines, i, if (i % 9 == 0) " \x1b[1;33mwarning:\x1b[0m unused variable" else "" }), .heavy => switch (i % 3) { 0 => { for (0..100) |x| try w.print("\x1b[38;2;{d};{d};{d}m{c}", .{ (i * 7 + x * 3) % 256, (i * 13 + x * 5) % 256, (x * 11 + i) % 256, @as(u8, @intCast(97 + (x + i) % 26)) }); try w.writeAll("\x1b[0m\r\n"); }, 1 => { for (0..18) |x| try w.print("\x1b]8;;https://example.com/{d}/{d}\x1b\\w{d}\x1b]8;;\x1b\\ ", .{ i, x, x }); try w.writeAll("\r\n"); }, else => { for (0..40) |x| { try w.writeByte(@intCast(97 + (x + i) % 26)); for (0..1 + x % 6) |j| try w.print("{u}", .{@as(u21, @intCast(0x300 + (x * 3 + j + i) % 0x6f))}); } try w.writeAll(" \u{6F22}\u{5B57}\u{6F22}\u{5B57} \u{1F469}\u{200D}\u{1F4BB}\r\n"); }, }, }; return out.toOwnedSlice(); } /// `bytes[from..to]` fed in reads of 4 KiB, and two reflows on the way /// at `stops` (to a little over half the width and three rows taller, then /// back), as the join tests' every side takes them. fn feedReflowing(s: *State, bytes: []const u8, from: usize, to: usize, stops: [2]usize) void { const cols = s.vt.cols; const rows = s.vt.rows; var at = from; while (at < to) { if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3, &.{}); if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3, &.{}); var end = @min(to, at + 4096); for (stops) |stop| if (at < stop and stop < end) { end = stop; }; s.stream.nextSlice(bytes[at..end]); at = end; } } fn sameSnapshot(gpa: std.mem.Allocator, a: *const State, b: *const State) !bool { const x = try snapshotOf(gpa, a); defer gpa.free(x); const y = try snapshotOf(gpa, b); defer gpa.free(y); return std.mem.eql(u8, x, y); } test "a join at a cut: every side reloaded from its own snapshot holds the same terminal as the joiner, after more bytes and after two reflows; a joiner nobody reloaded for with heavy colour does not" { // The sizing pass's join check (reports/pardes-term-bytes.md, section 2) // in the tree: a scrollback past its limit (pruned a page at a time, // by the history of its pages), cut at a random read boundary, often // inside a sequence. const gpa = std.testing.allocator; var prng: std.Random.DefaultPrng = .init(29); const random = prng.random(); var heavy_apart: usize = 0; for ([_]Corpus{ .text, .logs, .heavy }, [_]usize{ 6000, 6000, 3000 }) |which, lines| { const bytes = try corpus(gpa, which, lines); defer gpa.free(bytes); for (0..2) |_| { const cut = bytes.len / 3 + random.uintLessThan(usize, bytes.len / 3); const mid = cut + (bytes.len - cut) / 2; const stops: [2]usize = .{ mid + (bytes.len - mid) / 3, mid + 2 * (bytes.len - mid) / 3 }; // The session, and a replica that was there from the start. const session = try openKeeping(gpa, 120, 40, 1 << 20); defer close(session); const there = try openKeeping(gpa, 120, 40, 1 << 20); defer close(there); feedReflowing(session, bytes, 0, cut, stops); feedReflowing(there, bytes, 0, cut, stops); // The same join made without the reload: the session as it // would go on, and a joiner loaded from its snapshot. const lineage = try openKeeping(gpa, 120, 40, 1 << 20); defer close(lineage); feedReflowing(lineage, bytes, 0, cut, stops); const before = try snapshotOf(gpa, session); defer gpa.free(before); const unreloaded = try load(gpa, before, &parts(session)); defer close(unreloaded); // The join as it is made: every side reloads, the joiner loads // the session's snapshot taken after (the join's dump). const hash = try reload(session); try std.testing.expectEqual(hash, try reload(there)); try std.testing.expectEqual(hash, joinHash(before)); const after = try snapshotOf(gpa, session); defer gpa.free(after); const joiner = try load(gpa, after, &parts(session)); defer close(joiner); for ([_]*State{ session, there, joiner, unreloaded, lineage }) |s| feedReflowing(s, bytes, cut, mid, stops); try expectSame(gpa, session, there); try expectSame(gpa, session, joiner); if (!try sameSnapshot(gpa, lineage, unreloaded)) heavy_apart += @intFromBool(which == .heavy); for ([_]*State{ session, there, joiner }) |s| feedReflowing(s, bytes, mid, bytes.len, stops); try expectSame(gpa, session, there); try expectSame(gpa, session, joiner); } } // The fault the reload mends is real: a joiner nobody reloaded for is // another terminal once heavy colour has pruned pages cut otherwise. try std.testing.expectEqual(2, heavy_apart); } test "wide characters filling a scrollback past its limit, reflowed: its snapshot loads to the same snapshot and hash, and goes on as the same terminal through more bytes and reflows" { // The soak's `cat` (test/replicas.zig): source lines, one in a few // hundred with wide characters (CJK, box drawing, ambiguous symbols), // a full scrollback pruned a page at a time, reflowed at odd widths // where a wide character meets the right edge. const gpa = std.testing.allocator; var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); const wide = " try writeText(notes, \"# Fallback faces and rules\\n\\n| name | glyphs |\\n|------|--------|\\n| cjk | \u{754C}\u{9762}\u{5B57} |\\n| sym | \u{222E} \u{2260} \u{2605} |\\n\\n\u{250C}\u{2500}\u{2500}\u{252C}\u{2500}\u{2500}\u{2510}\\n\u{2502} a\u{2502} b\u{2502}\\n\u{2514}\u{2500}\u{2500}\u{2534}\u{2500}\u{2500}\u{2518}\\n\");"; for (0..30000) |i| { if (i % 7 == 3) try out.writer.print("{s}\r\n", .{wide}) else try out.writer.print("{s} {d}\r\n", .{ " const line = std.fmt.bufPrint(&buf, \"{d}\", .{i}) catch continue;"[0 .. 8 + i % 60], i }); } const bytes = out.written(); const stops: [2]usize = .{ bytes.len / 3, 2 * bytes.len / 3 }; const first = try openKeeping(gpa, 121, 40, 1 << 20); defer close(first); feedReflowing(first, bytes, 0, bytes.len / 2, stops); const snap = try snapshotOf(gpa, first); defer gpa.free(snap); const loaded = try load(gpa, snap, &parts(first)); defer close(loaded); const again = try snapshotOf(gpa, loaded); defer gpa.free(again); try std.testing.expectEqualSlices(u8, snap, again); try std.testing.expectEqual(joinHash(snap), try reload(first)); try expectSame(gpa, first, loaded); feedReflowing(first, bytes, bytes.len / 2, bytes.len, stops); feedReflowing(loaded, bytes, bytes.len / 2, bytes.len, stops); try expectSame(gpa, first, loaded); }