//! 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 is a handle the core holds and never //! looks into; what it knows of it 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 {}; /// How much history there is and where the cursor is, in rows counted from /// the top of the history: `total` rows, the last `len` of them the active /// area (the program's screen). All zero without a terminal. Where a view /// of it stands is the view's, not the terminal's (a `place`: the row its /// top shows, or null on the output; core/panes.zig `scrolled_to`). pub const Grid = struct { total: usize = 0, len: usize = 0, /// The cursor, in cells of the active area. cursor_x: u16 = 0, cursor_y: u16 = 0, /// The program shows the cursor (DECTCEM). cursor_visible: bool = false, /// Its grid's width. 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, /// It is drawing a frame (synchronized output, 2026): what its screen /// shows now is half of one (draw.zig's `Region.held`). sync: 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, nor on the /// line above when a newline in the input began this one (a line taken /// whose command has not started yet). 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, worked out with the /// theme (colors.Chrome, DESIGN.md R1, R14, R15): its page, its text, SGR /// faint's ink on it, and its sixteen, which the filter keys a program's /// colours to as well. `host`: a theme that leaves its page and sixteen to /// the tty (`dark`), drawn in a tty, whose cells then name the tty's own. pub const Ink = struct { fg: [3]u8, bg: [3]u8, dim: [3]u8, ansi: [16][3]u8, host: bool, /// A palette index as the theme draws it: its sixteen, else the index. pub fn palColor(ink: *const Ink, idx: u8) Color { if (!ink.host and idx < 16) return .{ .rgb = ink.ansi[idx] }; return .{ .index = idx }; } }; /// The theme's 256 colours as the filter maps onto them (ghostty's /// generator over its sixteen, page and text), made once a theme and kept /// while it 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, ansi: [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 { /// The view's place (`Grid`): the rows it shows. place: ?usize, 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, /// Its images as glyph art even where pixels could be drawn (the /// pane's Petscii). petscii: bool = false, }; /// 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 }; /// A link (OSC 8) under a cell: its URI (the emulator's bytes: copied before /// the next feed) and the cells `lo..hi` its run takes on that row. pub const Link = struct { uri: []const u8, lo: u16, hi: u16 }; /// 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, 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 }; /// How a kitty image's medium is had (a file, a temporary file, shared /// memory: things of the session's machine): `read(ctx)` is the emulator's /// own read (which deletes a temporary file and unlinks shared memory), /// its bytes `gpa`'s (core/Term.zig `media`). pub const Media = *const fn (ctx: *const anyopaque, read: *const fn (ctx: *const anyopaque) MediumError![]u8, gpa: std.mem.Allocator) MediumError![]u8; /// What ghostty's loader fails a medium's read with. pub const MediumError = error{ OutOfMemory, InvalidData, UnsupportedMedium, DimensionsTooLarge, TemporaryFileNotInTempDir, TemporaryFileNotNamedCorrectly }; /// 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. digest: *const fn (s: *const State, h: *std.hash.Wyhash) 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, /// Its emulator made again from its own snapshot where it is (a join: /// every side does it); the snapshot's hash. reload: *const fn (s: *State) anyerror!u64, /// How every terminal in the process has a kitty image's medium from /// now on (the core's: a recorded answer). media: *const fn (read: Media) void, // ---- output and size ---- /// One read of its program's output (`Told` says where the tracked /// rows went), every view's `places` carried through it (`resize`). feed: *const fn (s: *State, bytes: []const u8, track: []const i32, rows: []i32, erased: []bool, places: []?usize) Told, // A null handle: what a pane without a terminal is told (all zero). grid: *const fn (s: ?*const State) Grid, /// Its grid reflowed, every view's place (`Grid`) carried through it as /// ghostty carries a view of its own: on its row while rows come below, /// up by the rows the history drops above it, at the history's top when /// its own row goes, on the output once it falls into the active area /// or the screen is reset. A function of the bytes and sizes it was /// given: the same places on every side. resize: *const fn (s: *State, cols: u16, rows: u16, places: []?usize) void, 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, last: *?Parts.Coordinate, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8, wheel: *const fn (s: *State, last: *?Parts.Coordinate, 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, /// The cursor keys a click at its row `row` (from the top of its /// history), column `col` of the text shown types at the prompt. 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, /// The rows a view at `place` (`Grid`) shows, as text. viewport: *const fn (s: *State, arena: std.mem.Allocator, cut: bool, place: ?usize) 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, /// 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 link (OSC 8) cell `x` of row `row` (from the top of its history) /// carries; `cut`: `x` and the run counted in the row's text, a /// prompt's own cells cut off (a view out of tty mode). link: *const fn (s: *State, row: i32, x: u16, cut: bool) ?Link, // ---- 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 ---- /// The rows a view at `place` (`Grid`) shows from its row `first`, /// `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, place: ?usize, 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, hasImages: *const fn (s: ?*const State) bool, }; /// `Ops` in its two groups (S1: the emulator's boundary). REPLICATED: what /// every side agrees on by construction, each side's emulator fed the same /// bytes in the tape's order: written only by a step or a load, read by a /// step as the terminal's digest covers it (core/term/terminal.zig /// `digest`), or by a draw. LOCAL: this process's own (its frontend's cell /// size, the pixels and images it draws, its next wake, the module's start /// and its allocator), never what a step's digested state is computed from. /// core/Term.zig's `calls` lists every call of the core's into either, by /// file, with its rule: a new one fails its test until it is listed. pub const replicated = [_][]const u8{ "open", "close", "revive", "digest", "parts", "snapshot", "load", "reload", "media", "feed", "grid", "resize", "replies", "key", "mouse", "wheel", "paste", "modes", "promptMoves", "prompt", "commandOutput", "endOutputHere", "scrollback", "scrollbackLen", "textRows", "link", "viewport", "editRows", "promptCut", "page", "filter", "spanColor", "hasImages", }; pub const local = [_][]const u8{ "start", "stop", "gpa", "due", "cellPixels", "echoCell", "paint", "images" }; comptime { @setEvalBranchQuota(100_000); for (@typeInfo(Ops).@"struct".field_names) |fname| { var n = 0; for (replicated ++ local) |name| { if (std.mem.eql(u8, name, fname)) n += 1; } if (n != 1) @compileError("term.Ops." ++ fname ++ ": in neither group or in both (abi/term.zig `replicated`, `local`): say which, and why"); } for (replicated ++ local) |name| if (!@hasField(Ops, name)) @compileError("term.Ops has no " ++ name); }