//! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the //! entries (`Ops`) a terminal module gives the core, and the records they //! take and give. A terminal's state, its replicas' encoder and tracks are //! handles the core holds and never looks into; what it knows of them it is //! told here, as numbers, bytes, text and cells. core/term/term.zig is the //! one implementation (ghostty-vt behind it); core/Term.zig is the core's //! side of it. const std = @import("std"); const plain = @import("plain.zig"); const Color = plain.Color; const CellStyle = plain.CellStyle; /// A terminal: its emulator, its parse and what is kept beside it. pub const State = opaque {}; /// What a session's authority keeps to encode its terminals for its peers /// (one for all of them), and what it keeps of one terminal for them. pub const Encoder = opaque {}; pub const Track = opaque {}; /// A replica's side of one terminal: what it was sent. pub const Replica = opaque {}; /// Where the view and the cursor are, in rows counted from the top of the /// history: `total` rows, the view's top at `offset`, `len` of them shown. /// All zero without a terminal. pub const Grid = struct { total: usize = 0, offset: usize = 0, len: usize = 0, /// The cursor, in cells of the active area (the history's last `len` /// rows). cursor_x: u16 = 0, cursor_y: u16 = 0, /// The program shows the cursor (DECTCEM). cursor_visible: bool = false, /// The view's top row while it is scrolled to one, null while it /// follows the output. view: ?usize = null, /// Its grid's width (a pane's may differ while a resize is deferred). cols: u16 = 0, }; /// What a `feed` told the rows the core keeps positions on: each tracked /// row where it is after the read, whether the program erased it, whether /// it cleared the screen, whether the pages the rows were on lived through /// it (a reset can take them) and whether a row could not be followed (no /// memory for its pin). Taped: a screen-state replica, which feeds /// nothing, is told its authority's. pub const Told = struct { rows: []const i32, erased: []const bool, cleared: bool, alive: bool, failed: bool }; pub const MouseMods = struct { shift: bool = false, alt: bool = false, ctrl: bool = false }; pub const MouseButton = enum { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right }; pub const MouseAction = enum { press, release, motion }; /// Cursor-key presses: so many left, so many right. pub const Moves = struct { left: usize = 0, right: usize = 0 }; /// The modes a program set that the core decides by. pub const Modes = struct { /// It tracks the mouse itself (1000, 1002, 1003). mouse: bool = false, /// ...every move of it (1003). all_motion: bool = false, /// A wheel over it is its own: it tracks the mouse, or it is on the /// alternate screen with alternate scroll (1007). wheel: bool = false, /// It wants to hear focus in and out (1004). focus: bool = false, /// It wants its pastes bracketed (2004). bracketed_paste: bool = false, /// It has the alternate screen (1049). alternate: bool = false, }; /// Where a shell is in its command cycle, as pardes's own OSC 133 marks /// tell it (marks carrying its `aid` alone: a nested shell's pass it by), /// and what is at its cursor. All zero without a terminal. pub const Prompt = struct { phase: Phase = .none, /// Commands started (C at the input phase), prompts drawn (B), and D /// marks outside a running command (a line the shell handled without /// starting it). started: u32 = 0, prompts: u32 = 0, declined: u32 = 0, /// The newest prompt continues an unfinished line (bash's PS2). continuation: bool = false, /// The newest command to end: which one, and its status if given. finished: ?Finished = null, /// The cursor is at a prompt's input, on either screen. input_ready: bool = false, /// ...and nothing is typed on its line up to the cursor. input_empty: bool = false, /// The cursor is on a prompt's row or at its input, on the primary /// screen. at_prompt: bool = false, pub const Phase = enum { none, prompt, input, running }; pub const Finished = struct { seq: u32, status: ?i32 }; }; /// What a command printed. `text` is the caller's. pub const CommandOutput = struct { text: [:0]const u8, /// Whether `text` starts where the command did. It does not when that /// start is not there to read: cut off by the rows asked for, scrolled /// out of the history or erased from it (ED 3), erased under it while /// it ran, or never marked (a C or D on the alternate screen). whole: bool, }; /// A terminal's rows as text: `rows` slices into `text`, which is a prefix /// of `text_alloc` (a prompt cut off shortens the join), the last row the /// empty one after the cursor's. pub const Rows = struct { text_alloc: []u8, text: []const u8, rows: [][]const u8, }; /// How much of a row the prompt it starts with is. pub const PromptCut = union(enum) { /// no prompt: the row as the emulator dumps it keep, /// all prompt, nothing typed yet: show nothing of it blank, /// this many leading COLUMNS are the prompt; the rest is what was typed /// at it cut: usize, }; /// A program's output, as a terminal reads it, paged (`pardes -`, a /// /pager write): its printed text and its SGR colours as spans over it. pub const Page = struct { text: []u8, spans: []Span, pub fn deinit(page: Page, gpa: std.mem.Allocator) void { gpa.free(page.text); gpa.free(page.spans); } }; /// Bytes `start..end` of a page's text, drawn in `style`. pub const Span = struct { start: u32, end: u32, style: CellStyle }; // ---- its colours on the body ---- /// A theme's colours as a terminal's paint takes them. pub const Ink = struct { fg: ?[3]u8, bg: ?[3]u8, tag_fg: [3]u8, tag_bg: [3]u8, /// The theme's own sixteen, when it has them. palette: ?[16][3]u8, /// The sixteen the filter keys a program's colours to: `palette`, else /// made of the theme's roles. base: [16][3]u8, /// A palette index as the theme draws it: its own sixteen, else the /// index. pub fn palColor(ink: *const Ink, idx: u8) Color { if (ink.palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; return .{ .index = idx }; } }; /// The theme's 256 colours as the filter maps onto them, kept while the /// theme is the same (`Pardes.tty_filter_palette`). pub const FilterPalette = struct { key: ?Key = null, colors: [256][3]u8 = undefined, pub const Key = struct { bg: [3]u8, fg: [3]u8, base: [16][3]u8 }; }; /// A program's colours mapped to the theme, once a frame: what a +Pager's /// spans are drawn through (`spanColor`), as a terminal's cells are. pub const Filter = struct { target: *const [256][3]u8, /// The theme's page and ink, and the page a program's colours are /// drawn on (its OSC 11, keyed to the theme, else the theme's). theme_bg: [3]u8, theme_fg: [3]u8, default_bg: [3]u8, /// What a foreground too near the page's background becomes instead. fallback_fg: [3]u8, default_bg_luminance: f64, fg_for_palette: [256]Color, bg_for_palette: [256]Color, /// The two answers for a cell that names no colour of its own. fg_default: Color, bg_default: Color, cache_rgb: [256][3]u8 = undefined, cache_key: [256]u8 = undefined, cache_valid: [256]bool = @splat(false), }; /// One cell of a terminal's view as its paint gives it: its style (its /// colours the theme's already), the bytes it spells in the view's text, /// and whether it is half of a wide one. pub const Painted = struct { style: CellStyle, bytes: u16, wide: enum(u2) { narrow, wide, spacer_tail, spacer_head }, }; /// One row of a terminal's view as its paint gives it. pub const PaintedRow = struct { /// The shell marked it a prompt's: how much of it the prompt is. prompt: ?PromptCut, /// It holds kitty placeholder cells. placeholder: bool, /// Its cells given, from its first: the grid's past them are none. len: u16, }; /// Where a terminal's kitty images go, as the body lays out its rows: /// `rows_of[v]` is the body row its view's row `v` shows on, null for one /// not shown. pub const ImagesAt = struct { pane: u8, serial: u32, tx: u16, body_y: u16, cols: u16, rows_of: []const ?u16, /// The pane shows its terminal's rows as they are (tty mode): a prompt /// row is the grid's then, and its images show. tty_mode: bool, /// The core's clock (animations step on it), and a cell's size in /// pixels. now_ms: u64, cell_w: u32, cell_h: u32, }; /// What a predicted echo reads of a cell: its codepoint, whether the shell /// marked it input, and its style's identity. pub const EchoCell = struct { cp: u21, input: bool, style: u32 }; // ---- its replicas ---- /// Deltas a peer may have in flight. At 207 ms and 60 frames a second about /// 13 are; past the bound a peer gets nothing until an acknowledgement, and /// then the newest state, the ones between skipped. pub const flight_bound = 32; /// What the authority knows of one peer of one terminal. pub const Peer = struct { /// The version last sent, which the next delta is against; 0: none, so /// the next starts the replica afresh. sent: u32 = 0, /// The versions in flight, oldest first. flight: [flight_bound]u32 = undefined, n: u8 = 0, /// The history rows its replica holds as holes, absolute, as the /// replica keeps them (Replica.apply's rule, from what it was sent): /// what `fill` sends before a step reads them. top: u64 = 0, holes: std.ArrayListUnmanaged([2]u64) = .empty, pub fn deinit(peer: *Peer, gpa: std.mem.Allocator) void { peer.holes.deinit(gpa); } /// Every version up to `seq` has landed. pub fn ack(peer: *Peer, seq: u32) void { var i: u8 = 0; while (i < peer.n and peer.flight[i] <= seq) i += 1; std.mem.copyForwards(u32, peer.flight[0 .. peer.n - i], peer.flight[i..peer.n]); peer.n -= i; } /// Start the peer afresh: it lost its state, or never had one. pub fn reset(peer: *Peer) void { var holes = peer.holes; holes.clearRetainingCapacity(); peer.* = .{ .holes = holes }; } }; /// A delta applied: its version, and what its authority sent beside it. pub const Applied = struct { seq: u32, extra: []const u8 }; /// What the dump keeps of a terminal beside its emulator, by name as every /// dump is (core/walk.zig, through the core's `Term.State`). pub const Parts = struct { reply: []const u8 = "", reply_dropped: u32 = 0, mouse_cell: ?Coordinate = null, petscii: bool = false, /// The view's top row, counted from the top of the history. view: usize = 0, phase: Prompt.Phase = .none, started: u32 = 0, prompts: u32 = 0, declined: u32 = 0, continuation: bool = false, lost: bool = false, finished: ?Prompt.Finished = null, out_start: ?Coordinate = null, out_end: ?Coordinate = null, /// A cell's place on a screen (ghostty's `Coordinate`, as it dumps). pub const Coordinate = extern struct { x: u16 = 0, y: u32 = 0 }; }; /// What reading its text can fail with. pub const TextError = error{ OutOfMemory, WriteFailed, UnknownPoint }; /// The entries, as `term.ops` gives them. An error set named here is what /// the core's callers name (the tape's `Failure` reads `open`'s, the text /// readers' are edit.zig's); `anyerror` where the core only passes one on /// or reports it. Each takes the handles above /// (none is made without a terminal module: the core asks `Term.ops` /// first). pub const Ops = struct { // ---- lifecycle ---- /// A new terminal, `cols` by `rows`, allocated with `gpa` (its own from /// then on). open: *const fn (gpa: std.mem.Allocator, cols: u16, rows: u16) error{ OutOfMemory, InvalidValue }!*State, /// It and what it holds, freed. close: *const fn (s: *State) void, /// When its next kitty animation frame is due (ms on the core's clock), /// as its last drawn frame left it; null when nothing plays. due: *const fn (s: *const State) ?u64, /// Loaded from a dump without its shell: its program's modes reset, its /// history marked off from what the next shell prints. revive: *const fn (s: *State) void, /// The PNG resize workers kitty images are decoded with, started and /// stopped with the host. start: *const fn (gpa: std.mem.Allocator) void, stop: *const fn () void, /// The allocator it was opened with. gpa: *const fn (s: *const State) std.mem.Allocator, // ---- the dump and the digest (`Term.State`'s walk hooks) ---- /// Its screen into the replay digest (`view`: where its view is too). digest: *const fn (s: *const State, h: *std.hash.Wyhash, view: bool) void, /// What the dump keeps of it beside its emulator. parts: *const fn (s: *const State) Parts, /// Its emulator as the dump keeps it (ghostty's snapshot); `slim`: its /// size alone (a join's dump, its first delta replaces it). snapshot: *const fn (s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) anyerror!void, /// `snapshot`'s bytes and `parts` back into a new terminal. load: *const fn (gpa: std.mem.Allocator, snapshot: []const u8, parts: *const Parts) anyerror!*State, // ---- output and view ---- /// One read of its program's output (`Told` says where the tracked /// rows went). feed: *const fn (s: *State, bytes: []const u8, track: []const i32, rows: []i32, erased: []bool) Told, // A null handle: what a pane without a terminal is told (all zero). grid: *const fn (s: ?*const State) Grid, viewTo: *const fn (s: *State, at: ?usize) void, scroll: *const fn (s: *State, delta: i32) void, follow: *const fn (s: *State) void, resize: *const fn (s: *State, cols: u16, rows: u16, later: bool) void, resizeDeferred: *const fn (s: *State) bool, cellPixels: *const fn (s: *State, w: u32, h: u32) void, replies: *const fn (s: *State) []const u8, // ---- input ---- key: *const fn (s: *State, k: plain.Key, out: *std.Io.Writer) error{WriteFailed}!void, mouse: *const fn (s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8, wheel: *const fn (s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8, paste: *const fn (s: ?*const State, text: []u8) [3][]const u8, modes: *const fn (s: ?*const State) Modes, promptMoves: *const fn (s: *State, row: i32, col: i32) ?Moves, // ---- prompt and commands ---- prompt: *const fn (s: ?*State) Prompt, commandOutput: *const fn (s: ?*State, gpa: std.mem.Allocator, max_rows: usize) error{OutOfMemory}!CommandOutput, endOutputHere: *const fn (s: *State) void, // ---- text ---- scrollback: *const fn (s: ?*State, gpa: std.mem.Allocator) error{ OutOfMemory, WriteFailed }![]const u8, scrollbackLen: *const fn (s: ?*State) usize, textRows: *const fn (s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) TextError!Rows, viewport: *const fn (s: *State, arena: std.mem.Allocator, cut: bool) TextError![]const []const u8, /// Its rows `first` and the `count` after it (from the top of its /// history) as text, a prompt's own cells cut off: `arena`'s. editRows: *const fn (s: *State, arena: std.mem.Allocator, first: usize, count: usize) (TextError || error{ NoRow })![]const []const u8, /// How much of its row `row` (from the top of its history) the prompt /// it starts with is; null for a row no prompt starts. promptCut: *const fn (s: *State, row: i32) ?PromptCut, markRead: *const fn (s: *State) void, /// What a predicted echo reads of cell `x`, `y` of its active area. echoCell: *const fn (s: *const State, x: u16, y: u16) ?EchoCell, // ---- the pager ---- /// `raw`, a program's output, as a terminal reads it: its text and its /// SGR spans, every other control dropped. `gpa`'s. page: *const fn (gpa: std.mem.Allocator, raw: []const u8) error{OutOfMemory}!Page, /// The filter a +Pager's spans are drawn through (`spanColor`). filter: *const fn (ink: *const Ink, palette: *FilterPalette) Filter, spanColor: *const fn (f: *Filter, color: Color, is_bg: bool) Color, // ---- draw ---- /// Its view's rows, `rows.len` of them, `cols` cells each, into /// `cells`: each cell's style in the theme's colours (through the /// filter when `filtered`), its bytes and width. paint: *const fn (s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void, /// Its kitty images over the body's rows, appended to `out` (`gpa`'s; /// what it keeps to draw them is its own allocator's), and their /// placeholder cells blanked in `frame` (`frame_cols` wide). images: *const fn (s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void, petscii: *const fn (s: ?*const State) ?bool, togglePetscii: *const fn (s: *State) void, hasImages: *const fn (s: ?*const State) bool, // ---- its replicas ---- encoder: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Encoder, encoderFree: *const fn (e: *Encoder) void, track: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Track, /// A peer's track of it let go (`s` null: it is gone). untrack: *const fn (t: *Track, gpa: std.mem.Allocator, s: ?*State) void, /// What a peer is owed of it, a delta against what the peer was sent. encode: *const fn (s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) anyerror!bool, /// Rows of it a replica holds as holes. encodeRows: *const fn (s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) anyerror!void, wasRead: *const fn (s: *const State) bool, clearRead: *const fn (s: *State) void, replica: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Replica, replicaFree: *const fn (r: *Replica, gpa: std.mem.Allocator) void, /// The absolute row its replica's active area begins at. replicaTop: *const fn (r: *const Replica) u64, /// History rows `lo..hi` it does not hold. missing: *const fn (r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) error{OutOfMemory}!void, apply: *const fn (s: *State, r: *Replica, bytes: []const u8) anyerror!Applied, applyRows: *const fn (s: *State, r: *Replica, bytes: []const u8) anyerror!void, shown: *const fn (s: *State, r: *const Replica) [2]u64, blank: *const fn (s: *State, r: *const Replica, lo: u64, hi: u64) void, dumpScreen: *const fn (s: *State, w: *std.Io.Writer) error{WriteFailed}!void, };