diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Core.zig | 10 | ||||
| -rw-r--r-- | src/Event.zig | 31 | ||||
| -rw-r--r-- | src/File.zig | 12 | ||||
| -rw-r--r-- | src/Term.zig | 569 | ||||
| -rw-r--r-- | src/ansi.zig | 305 | ||||
| -rw-r--r-- | src/body_layer.zig | 5 | ||||
| -rw-r--r-- | src/config.zig | 3 | ||||
| -rw-r--r-- | src/echo.zig (renamed from src/term/echo.zig) | 63 | ||||
| -rw-r--r-- | src/keys.zig | 2 | ||||
| -rw-r--r-- | src/memory.zig | 3 | ||||
| -rw-r--r-- | src/ninep/pty.zig | 7 | ||||
| -rw-r--r-- | src/pardes.zig | 6 | ||||
| -rw-r--r-- | src/plain/plain.zig | 161 | ||||
| -rw-r--r-- | src/plain/term.zig | 432 | ||||
| -rw-r--r-- | src/replica.zig | 59 | ||||
| -rw-r--r-- | src/surface.zig | 126 | ||||
| -rw-r--r-- | src/term/TerminalImages.zig | 52 | ||||
| -rw-r--r-- | src/term/pager.zig | 16 | ||||
| -rw-r--r-- | src/term/screen_state.zig | 131 | ||||
| -rw-r--r-- | src/term/term.zig | 164 | ||||
| -rw-r--r-- | src/term/terminal.zig | 1937 |
21 files changed, 2007 insertions, 2087 deletions
diff --git a/src/Core.zig b/src/Core.zig index a3ace8f9..ee4420ec 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -372,7 +372,7 @@ surface: Surface = .{}, /// A replica's predicted echo (src/term/echo.zig), drawn over its terminals: /// presentation, its own, in no digest and no rollback copy. Null on a /// session's own core. -echo: ?*pardes.Term.Echo = null, +echo: ?*pardes.Echo = null, /// The live view, `views[live]` (`view()`): whose input the session /// takes now, and whose share of the panes is in their own fields /// (views.zig). `views_open` says which views there are, one a window @@ -2484,6 +2484,7 @@ test "TreeContext command and custom tag survive a workspace round trip" { test "Filter is ordered after Del and toggles only its terminal or +Pager pane" { const testing = std.testing; + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin; const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin; try testing.expectEqual(@backingInt(del) + 1, @backingInt(filter)); @@ -2492,12 +2493,12 @@ test "Filter is ordered after Del and toggles only its terminal or +Pager pane" defer p.deinit(); while (p.nextEffect()) |_| {} const first = p.panes[0].?; - const palette_before = first.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; + const palette_before = pardes.Term.emulatorOf(first.terminal.?).vt.colorForXterm(.{ .palette = 1 }).?; try testing.expect(first.tty_filter); try testing.expect(p.executeBuiltinLine(0, "Filter")); try testing.expect(!first.tty_filter); - try testing.expect(palette_before.eql(first.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); + try testing.expect(palette_before.eql(pardes.Term.emulatorOf(first.terminal.?).vt.colorForXterm(.{ .palette = 1 }).?)); const second_id = p.freeSlot().?; const second = try p.newShell(second_id, ""); @@ -3760,6 +3761,7 @@ test "the bare tty startup opens a text pane under the shell, unfocused" { } test "tty output follows only from the bottom" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); @@ -3919,6 +3921,7 @@ test "pasted bytes still queued at shutdown are freed, not leaked" { } test "leaving tty hides the prompt and keeps the command typed at it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); @@ -3984,6 +3987,7 @@ test "leaving tty hides the prompt and keeps the command typed at it" { } test "entering tty walks the shell cursor to the column clicked past the prompt" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); diff --git a/src/Event.zig b/src/Event.zig index aa93f412..faea73cc 100644 --- a/src/Event.zig +++ b/src/Event.zig @@ -49,36 +49,7 @@ pub const Mouse = struct { amount: f32 = 0, }; -pub const Key = struct { - cp: u21, // codepoint or one of the specials below - text: []const u8 = "", - ctrl: bool = false, - alt: bool = false, - shift: bool = false, - - pub const enter: u21 = 0x0D; - pub const escape: u21 = 0x1B; - pub const tab: u21 = 0x09; - pub const backspace: u21 = 0x7F; - // private-use plane for non-text keys, matching no real codepoint - pub const up: u21 = 0xF0001; - pub const down: u21 = 0xF0002; - pub const left: u21 = 0xF0003; - pub const right: u21 = 0xF0004; - pub const home: u21 = 0xF0005; - pub const end: u21 = 0xF0006; - pub const page_up: u21 = 0xF0007; - pub const page_down: u21 = 0xF0008; - pub const delete: u21 = 0xF0009; - pub const insert: u21 = 0xF000A; - pub const print_screen: u21 = 0xF000B; - pub const scroll_lock: u21 = 0xF000C; - pub const pause: u21 = 0xF000D; - pub const menu: u21 = 0xF000E; - /// F1 to F25, in order: Fn is `f1 + n - 1`. - pub const f1: u21 = 0xF0011; - pub const f25: u21 = f1 + 24; -}; +pub const Key = @import("plain").Key; pub fn hit(key: Key, binding: []const config.Chord) bool { for (binding) |c| { diff --git a/src/File.zig b/src/File.zig index 64614191..d4032171 100644 --- a/src/File.zig +++ b/src/File.zig @@ -13,6 +13,7 @@ const filesystem = @import("fs.zig"); const syntax = @import("syntax.zig"); const diff = @import("diff.zig"); const tracy = @import("tracy.zig"); +const ansi = @import("ansi.zig"); const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); const Colors = @import("colors.zig"); @@ -1831,9 +1832,10 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. // A row whose first byte names a hue (syntax.ground_add, _del): its // grounds, the theme's, worked out once a frame and only for one. var grounds: ?Colors.Grounds = null; + const ink = ansi.inkOf(p.theme()); var filtered_storage: pardes.Term.Filter = undefined; const filtered: ?*pardes.Term.Filter = if (pane.tty_filter and spans.len > 0) blk: { - filtered_storage = .init(p, null); + filtered_storage = pardes.Term.filter(&ink, &p.tty_filter_palette); break :blk &filtered_storage; } else null; // indexed start, same as bodyText — an empty tail simply paints nothing @@ -1957,11 +1959,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. // palette colour through the theme's sixteen and // truecolor as it is. if (filtered) |colors| { - if (st.fg != .default) cell.style.fg = colors.spanColor(st.fg, false); - if (st.bg != .default) cell.style.bg = colors.spanColor(st.bg, true); + if (st.fg != .default) cell.style.fg = pardes.Term.spanColor(colors, st.fg, false); + if (st.bg != .default) cell.style.bg = pardes.Term.spanColor(colors, st.bg, true); } else { - if (st.fg != .default) cell.style.fg = if (st.fg == .index) pardes.Term.palColor(p, st.fg.index) else st.fg; - if (st.bg != .default) cell.style.bg = if (st.bg == .index) pardes.Term.palColor(p, st.bg.index) else st.bg; + if (st.fg != .default) cell.style.fg = if (st.fg == .index) ink.palColor(st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) ink.palColor(st.bg.index) else st.bg; } cell.style.bold = cell.style.bold or st.bold; cell.style.dim = st.dim; diff --git a/src/Term.zig b/src/Term.zig index a21c3d97..8bd6e05b 100644 --- a/src/Term.zig +++ b/src/Term.zig @@ -1,275 +1,448 @@ -//! The terminal as the core sees it (docs/next-terminal.md, Phase 0): the -//! entries the core calls and the plain records they take and give. A -//! terminal pane holds a `*State` the core never looks into: what it knows -//! of one it is told here, as numbers, bytes and text. The emulator -//! (ghostty-vt) and what it brings stay behind this file, in src/term/; -//! this is the one file outside it that names a file inside it (and so -//! the one place Phase 1 turns into the module's registration). +//! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the +//! entries of the terminal module (src/term/, its own module: ghostty-vt, +//! wuffs and zstbi are its, not the core's) and the plain records they take +//! and give (src/plain/term.zig). A terminal pane holds a `*State` the core +//! never looks into: what it knows of one it is told here, as numbers, +//! bytes, text and cells. A core built without the module (a test +//! configuration: core-test) has `ops` null, and no terminal at all. const std = @import("std"); -const terminal = @import("term/terminal.zig"); -const pager = @import("term/pager.zig"); -const echo = @import("term/echo.zig"); -/// The screen state replicas are sent (its encoder, a terminal's versions, -/// what a peer holds, a replica's side), and its streams and soak for the -/// replica tests outside src/. -pub const screen_state = @import("term/screen_state.zig"); +const builtin = @import("builtin"); +const plain = @import("plain"); +const walk = @import("walk.zig"); +const tape = @import("tape.zig"); +const dump = @import("dump.zig"); +const File = @import("File.zig"); +const iface = plain.term; -/// A terminal pane's emulator, its parse and what pardes keeps beside it. -pub const State = terminal.State; +/// The terminal module's entries; null in a core built without it. +pub const ops: ?*const iface.Ops = if (@import("term_options").terminal) &@import("term").ops else null; + +/// What a core without a terminal says, once, where one would have been. +pub const none = "no terminal in this build"; + +pub const Grid = iface.Grid; +pub const Told = iface.Told; +pub const Modes = iface.Modes; +pub const Prompt = iface.Prompt; +pub const CommandOutput = iface.CommandOutput; +pub const Rows = iface.Rows; +pub const Moves = iface.Moves; +pub const MouseMods = iface.MouseMods; +pub const MouseButton = iface.MouseButton; +pub const MouseAction = iface.MouseAction; +pub const Page = iface.Page; +pub const Span = iface.Span; +pub const Ink = iface.Ink; +pub const FilterPalette = iface.FilterPalette; +pub const Filter = iface.Filter; +pub const Painted = iface.Painted; +pub const PaintedRow = iface.PaintedRow; +pub const ImagesAt = iface.ImagesAt; +pub const EchoCell = iface.EchoCell; +pub const Peer = iface.Peer; +pub const Applied = iface.Applied; +pub const Encoder = iface.Encoder; +pub const Track = iface.Track; +pub const Replica = iface.Replica; + +fn the() *const iface.Ops { + return ops orelse unreachable; // no State, Encoder or Replica is made without it +} + +/// A terminal pane's terminal: the module's handle, and the walk's hooks +/// (src/walk.zig) for it: the replay digest, and the dump, which keeps it +/// as it always has (`Parts` by name, then ghostty's snapshot). +pub const State = struct { + impl: *iface.State, + + /// The emulator as its program has made it, for the replay digest. + /// Under screen-state terminals the emulator is the authority's, and a + /// replica's is what the last delta made it: compared as screens + /// (test/replicas.zig), not step by step. + pub fn digest(s: *const State, h: *walk.Hasher) void { + if (tape.screenState()) return; + s.digestScreen(h, true); + } + + /// `view`: where its view is too (a replica's speculation may move it). + pub fn digestScreen(s: *const State, h: *walk.Hasher, view: bool) void { + the().digest(s.impl, h, view); + } + + pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { + const parts = the().parts(s.impl); + const bytes = try walk.save(iface.Parts, gpa, &parts); + defer gpa.free(bytes); + try w.writeAll(std.mem.asBytes(&@as(u64, bytes.len))); + try w.writeAll(bytes); + try the().snapshot(s.impl, gpa, w, dump.slim_terminals); + } + + /// What `dumpRead` made, freed: a load that failed after it. + pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void { + the().close(s.impl, gpa); + } + + pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void { + const o = ops orelse return error.NoTerminal; + if (bytes.len < 8) return error.EndOfDump; + const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump; + if (bytes.len - 8 < n) return error.EndOfDump; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null); + out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) }; + } +}; + +/// The module's own state behind a handle: for a test that reads the +/// emulator itself, in a core with the module (a test in one without skips +/// before it gets here: `ops == null` is known at compile time). +pub fn emulatorOf(s: *State) *@import("term").terminal.State { + return @ptrCast(@alignCast(s.impl)); +} // ---- lifecycle ---- -/// A new emulator, `cols` by `rows`, allocated with `gpa` (its own from -/// then on). -pub const open = terminal.open; -/// Its emulator and what it holds, freed; the kitty images' caches were -/// `gpa`'s. -pub const close = terminal.close; +/// A new terminal, `cols` by `rows`, allocated with `gpa` (its own from +/// then on). Refused in a core without one (a test of one skips). +pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { + const o = ops orelse return if (builtin.is_test) error.SkipZigTest else error.NoTerminal; + const s = try gpa.create(State); + errdefer gpa.destroy(s); + s.* = .{ .impl = try o.open(gpa, cols, rows) }; + return s; +} + +/// It and what it holds, freed; the kitty images' caches were `gpa`'s. +pub fn close(s: *State, gpa: std.mem.Allocator) void { + const own = the().gpa(s.impl); + the().close(s.impl, gpa); + own.destroy(s); +} + /// 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. -pub const due = terminal.due; +pub fn due(s: *const State) ?u64 { + return the().due(s.impl); +} + /// Loaded from a dump without its shell: its program's modes reset, its /// history marked off from what the next shell prints. -pub const revive = terminal.revive; +pub fn revive(s: *State) void { + the().revive(s.impl); +} + /// The PNG resize workers kitty images are decoded with, started and /// stopped with the host. -pub const start = terminal.TerminalImages.start; -pub const stop = terminal.TerminalImages.stop; +pub fn start(gpa: std.mem.Allocator) void { + if (ops) |o| o.start(gpa); +} + +pub fn stop() void { + if (ops) |o| o.stop(); +} // ---- output and view ---- /// One read of its program's output (`Told` says where the tracked rows /// went). -pub const feed = terminal.feed; -/// Where the view and the cursor are (`Grid`). -pub const grid = terminal.grid; +pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told { + return the().feed(s.impl, bytes, tracked, rows, erased); +} + +/// Where the view and the cursor are; all zero without a terminal. +pub fn grid(s: ?*const State) Grid { + const o = ops orelse return .{}; + return o.grid(if (s) |state| state.impl else null); +} + /// Its view to a row of its history, or onto its output (null). -pub const viewTo = terminal.viewTo; +pub fn viewTo(s: *State, at: ?usize) void { + the().viewTo(s.impl, at); +} + /// Its view moved by a number of rows (negative scrolls back). -pub const scroll = terminal.scroll; +pub fn scroll(s: *State, delta: i32) void { + the().scroll(s.impl, delta); +} + /// Its view back onto its output. -pub const follow = terminal.follow; +pub fn follow(s: *State) void { + the().follow(s.impl); +} + /// Its grid reflowed, now or when `resizeDeferred` makes it. -pub const resize = terminal.resize; -pub const resizeDeferred = terminal.resizeDeferred; +pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void { + the().resize(s.impl, cols, rows, later); +} + +pub fn resizeDeferred(s: *State) bool { + return the().resizeDeferred(s.impl); +} + /// Its cells' size in pixels (kitty graphics, CSI 14/16 t). -pub const cellPixels = terminal.cellPixels; +pub fn cellPixels(s: *State, w: u32, h: u32) void { + the().cellPixels(s.impl, w, h); +} + /// What it answered its program since the last call, to be written to its /// pty. -pub const replies = terminal.replies; - -/// 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, -}; - -/// 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 fn replies(s: *State) []const u8 { + return the().replies(s.impl); +} // ---- input ---- /// One key for its program, as the program's keyboard protocol and modes /// ask for it, written out. -pub const key = terminal.key; +pub fn key(s: *State, k: plain.Key, out: *std.Io.Writer) !void { + return the().key(s.impl, k, out); +} + /// One mouse event for its program, as the mode and format it set ask for /// it; empty when the program does not hear of it. -pub const mouse = terminal.mouse; +pub fn mouse(s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { + return the().mouse(s.impl, buf, action, button, mods, col, row, any_pressed); +} + /// A wheel turn for its program; null when the wheel is not the program's. -pub const wheel = terminal.wheel; +pub fn wheel(s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { + return the().wheel(s.impl, buf, turn, col, row, mods); +} + /// A paste as xterm makes one: three parts, the text between the brackets /// when the program set 2004. -pub const paste = terminal.paste; -/// The modes its program set that the core decides by (`Modes`). -pub const modes = terminal.modes; +pub fn paste(s: ?*const State, text: []u8) [3][]const u8 { + const o = ops orelse return .{ "", text, "" }; + return o.paste(if (s) |state| state.impl else null, text); +} + +/// The modes its program set that the core decides by. +pub fn modes(s: ?*const State) Modes { + const o = ops orelse return .{}; + return o.modes(if (s) |state| state.impl else null); +} + /// How far left or right a click on the prompt line moves the shell's /// cursor, at the prompt the cursor is at. -pub const promptMoves = terminal.promptMoves; +pub fn promptMoves(s: *State, row: i32, col: i32) ?Moves { + return the().promptMoves(s.impl, row, col); +} -/// The key a frontend read (Event.zig). -pub const Key = @import("Event.zig").Key; -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 }; +// ---- prompt and commands ---- -/// 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 its shell is in its command cycle; all zero without a terminal. +pub fn prompt(s: ?*State) Prompt { + const o = ops orelse return .{}; + return o.prompt(if (s) |state| state.impl else null); +} -// ---- prompt and commands ---- +/// What the newest finished command printed, read from at most so many +/// rows above its end. +pub fn commandOutput(s: ?*State, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { + const o = ops orelse return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = true }; + return o.commandOutput(if (s) |state| state.impl else null, gpa, max_rows); +} -/// Where its shell is in its command cycle (`Prompt`). -pub const prompt = terminal.prompt; -/// What the newest finished command printed (`CommandOutput`), read from -/// at most so many rows above its end. -pub const commandOutput = terminal.commandOutput; /// The shell exited in the middle of a command: its output ends at the /// cursor. -pub const endOutputHere = terminal.endOutputHere; - -/// 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: enum { none, prompt, input, running } = .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: ?struct { seq: u32, status: ?i32 } = 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, -}; - -/// 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, -}; +pub fn endOutputHere(s: *State) void { + the().endOutputHere(s.impl); +} // ---- text ---- /// Its whole scrollback as plain text, logical lines (rows it wrapped /// joined again), ending in a newline: what its body reads and Save -/// writes. The caller's. -pub const scrollback = terminal.scrollback; +/// writes. The caller's; empty without a terminal. +pub fn scrollback(s: ?*State, gpa: std.mem.Allocator) ![]const u8 { + const o = ops orelse return gpa.dupe(u8, ""); + return o.scrollback(if (s) |state| state.impl else null, gpa); +} + /// How long `scrollback` would be, counted without keeping it. -pub const scrollbackLen = terminal.scrollbackLen; +pub fn scrollbackLen(s: ?*State) usize { + const o = ops orelse return 0; + return o.scrollbackLen(if (s) |state| state.impl else null); +} + /// Its rows from the top of its history as text, a prompt's own cells cut /// off (`Rows`). -pub const textRows = terminal.textRows; +pub fn textRows(s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) iface.TextError!Rows { + return the().textRows(s.impl, alloc, scratch); +} + /// The rows its view shows as text, prompts cut off or not. -pub const viewport = terminal.viewport; +pub fn viewport(s: *State, arena: std.mem.Allocator, cut: bool) iface.TextError![]const []const u8 { + return the().viewport(s.impl, arena, cut); +} + +/// Its rows `first` and the `count` after it as text, prompts cut off (the +/// edit copy's rows, as they were). +pub fn editRows(s: *State, arena: std.mem.Allocator, first: usize, count: usize) ![]const []const u8 { + return the().editRows(s.impl, arena, first, count); +} + /// How many bytes of one of its rows, as `viewport` and `textRows` give it -/// uncut, are the prompt it starts with. -pub const promptPrefix = terminal.promptPrefix; +/// uncut, are the prompt it starts with: the prompt's columns, measured in +/// the row's text as the core measures a display. +pub fn promptPrefix(s: ?*State, row: i32, raw: []const u8) usize { + const state = s orelse return 0; + if (row < 0) return 0; + const cut = the().promptCut(state.impl, row) orelse return 0; + return switch (cut) { + .keep => 0, + .blank => raw.len, + .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), + }; +} + /// A step read its rows: its replicas must hold them for the step's /// replay. -pub const markRead = terminal.markRead; +pub fn markRead(s: *State) void { + the().markRead(s.impl); +} -/// 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, -}; +/// What a predicted echo reads of a cell of its active area. +pub fn echoCell(s: *const State, x: u16, y: u16) ?EchoCell { + return the().echoCell(s.impl, x, y); +} // ---- the pager ---- /// 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 -/// (`Page`), every other control dropped. The emulator's own parse, so a -/// +Pager pages what a terminal pane would print. -pub const page = pager.parse; -pub const Page = pager.Page; -/// Bytes `start..end` of a page's text, drawn in `style`. -pub const Span = pager.Span; +/// /pager write): its printed text and its SGR colours as spans over it, +/// every other control dropped. The emulator's own parse, so a +Pager +/// pages what a terminal pane would print. Without a terminal the bytes +/// are paged as they are: plain text, no colours (nothing in the core +/// parses an escape). +pub fn page(gpa: std.mem.Allocator, raw: []const u8) error{OutOfMemory}!Page { + if (ops) |o| return o.page(gpa, raw); + const text = try gpa.dupe(u8, raw); + errdefer gpa.free(text); + return .{ .text = text, .spans = try gpa.alloc(Span, 0) }; +} + +/// The filter a +Pager's spans are drawn through, and a span's colour +/// through it. +pub fn filter(ink: *const Ink, palette: *FilterPalette) Filter { + return the().filter(ink, palette); +} + +pub fn spanColor(f: *Filter, color: plain.Color, is_bg: bool) plain.Color { + return the().spanColor(f, color, is_bg); +} // ---- draw ---- // -// ponytail: not yet narrowed to plain data (docs/next-terminal.md's draw -// row): these still take the core's Pardes, Surface and Pane, read the -// pane's edit copy and write the surface's cells and placements -// themselves. Phase 1 needs them as a cell hand-over (`paint`) and a -// placement list (`images`) first. +// Plain data both ways: the core hands the theme's colours (`Ink`) and a +// buffer, and is given its view's cells (`Painted`, `PaintedRow`) and its +// images as placements; which of the body's rows they stand under is the +// core's (src/ansi.zig). -/// Its program's colours over the body's rows, through the theme's +/// Its view's rows as cells in the theme's colours, through the theme's /// filter when the pane has it on. -pub const recolor = terminal.recolorAnsi; +pub fn paint(s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, cols: u16, cells: []Painted, rows: []PaintedRow) void { + the().paint(s.impl, ink, palette, filtered, cols, cells, rows); +} + /// Its kitty graphics over the body's rows, as placements. -pub const images = terminal.drawImages; +pub fn images(s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void { + the().images(s.impl, gpa, at, out, frame, frame_cols); +} + /// The Petscii builtin on it: its kitty graphics as glyph art, or back to /// pixels; null for none. -pub const petscii = terminal.petscii; -pub const togglePetscii = terminal.togglePetscii; +pub fn petscii(s: ?*const State) ?bool { + const o = ops orelse return null; + return o.petscii(if (s) |state| state.impl else null); +} + +pub fn togglePetscii(s: *State) void { + the().togglePetscii(s.impl); +} + /// Whether the screen showing holds any kitty graphics image. -pub const hasImages = terminal.hasImages; -/// A program's colours mapped to the theme (Filter): a terminal's cells -/// or a +Pager's spans (`spanColor`). -pub const Filter = terminal.FilteredColors; -/// 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 = terminal.FilterPalette; -/// A palette index as the theme draws it: its own sixteen, else the index. -pub const palColor = terminal.palColor; +pub fn hasImages(s: ?*const State) bool { + const o = ops orelse return false; + return o.hasImages(if (s) |state| state.impl else null); +} // ---- its replicas ---- +pub fn encoder(gpa: std.mem.Allocator) !*Encoder { + return the().encoder(gpa); +} + +pub fn encoderFree(e: *Encoder) void { + the().encoderFree(e); +} + +pub fn track(gpa: std.mem.Allocator) !*Track { + return the().track(gpa); +} + +/// A peer's track of it let go (`s` null: it is gone). +pub fn untrack(t: *Track, gpa: std.mem.Allocator, s: ?*State) void { + the().untrack(t, gpa, if (s) |state| state.impl else null); +} + /// What a peer is owed of it, a delta against what the peer was sent. -pub const encode = terminal.encode; +pub fn encode(s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) !bool { + return the().encode(s.impl, e, t, peer, out); +} + /// Rows of it a replica holds as holes. -pub const encodeRows = terminal.encodeRows; -/// A peer's track of it let go. -pub const untrack = terminal.untrack; +pub fn encodeRows(s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { + return the().encodeRows(s.impl, e, t, lo, hi, out); +} + /// Whether a step read its rows since `clearRead`. -pub const wasRead = terminal.wasRead; -pub const clearRead = terminal.clearRead; +pub fn wasRead(s: *const State) bool { + return the().wasRead(s.impl); +} + +pub fn clearRead(s: *State) void { + the().clearRead(s.impl); +} + +/// A replica's side of one terminal: made, freed, where its active area +/// begins, and the history rows it does not hold. +pub fn replica(gpa: std.mem.Allocator) !*Replica { + return the().replica(gpa); +} + +pub fn replicaFree(r: *Replica, gpa: std.mem.Allocator) void { + the().replicaFree(r, gpa); +} + +pub fn replicaTop(r: *const Replica) u64 { + return the().replicaTop(r); +} + +pub fn missing(r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void { + return the().missing(r, lo, hi, out, gpa); +} + /// A replica's side: a delta applied, rows applied, the rows its view /// shows, rows blank until they come. -pub const apply = terminal.apply; -pub const applyRows = terminal.applyRows; -pub const shown = terminal.shown; -pub const blank = terminal.blank; -pub const dumpScreen = terminal.dumpScreen; -pub const Encoder = screen_state.Encoder; -pub const Track = screen_state.Track; -pub const Peer = screen_state.Peer; -pub const Replica = screen_state.Replica; -/// A replica's keys into a terminal drawn at once, before its authority -/// says (predicted echo). -pub const Echo = echo.Echo; +pub fn apply(s: *State, r: *Replica, bytes: []const u8) !Applied { + return the().apply(s.impl, r, bytes); +} + +pub fn applyRows(s: *State, r: *Replica, bytes: []const u8) !void { + return the().applyRows(s.impl, r, bytes); +} + +pub fn shown(s: *State, r: *const Replica) [2]u64 { + return the().shown(s.impl, r); +} + +pub fn blank(s: *State, r: *const Replica, lo: u64, hi: u64) void { + the().blank(s.impl, r, lo, hi); +} -test { - _ = terminal; - _ = pager; - _ = echo; - _ = screen_state; +pub fn dumpScreen(s: *State, w: *std.Io.Writer) !void { + return the().dumpScreen(s.impl, w); } diff --git a/src/ansi.zig b/src/ansi.zig new file mode 100644 index 00000000..3a3f9d85 --- /dev/null +++ b/src/ansi.zig @@ -0,0 +1,305 @@ +//! A program's colours on a pane's body: a terminal's cells over the rows +//! the body shows (its paint, handed over as plain cells: Term.paint), and +//! its kitty images over them (Term.images). The terminal gives its view's +//! cells in the theme's colours; which of them stand under which of the +//! body's rows, the edit copy's among them, is worked out here. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const modal = @import("modal.zig"); +const tracy = @import("tracy.zig"); +const Term = @import("Term.zig"); +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Surface = pardes.Surface; +const BodyWalk = @import("body_layer.zig").BodyWalk; +const EditBuffer = panes.Text.EditBuffer; + +/// The theme's colours as a terminal's paint takes them. +pub fn inkOf(theme: *const pardes.Theme) Term.Ink { + return .{ + .fg = theme.fg, + .bg = theme.bg, + .tag_fg = theme.tag_fg, + .tag_bg = theme.tag_bg, + .palette = theme.palette, + .base = theme.palette orelse .{ + theme.bg orelse theme.tag_bg, + theme.kw, + theme.str, + theme.num, + theme.box, + theme.sel_bg, + theme.comment, + theme.fg orelse theme.tag_fg, + theme.lineno, + theme.kw, + theme.str, + theme.num, + theme.scroll_thumb, + theme.sel_fg, + theme.tag_fg, + theme.fg orelse theme.tag_fg, + }, + }; +} + +/// Its program's colours over the body's rows, through the theme's filter +/// when the pane has it on. +pub fn recolor(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { + const state = pane.terminal orelse return; + const body_y = p.bodyTop(pane, r); + const g = Term.grid(state); + const cols = g.cols; + const arena = p.scratch.allocator(); + const cells = arena.alloc(Term.Painted, g.len * @as(usize, cols)) catch return; + const rows = arena.alloc(Term.PaintedRow, g.len) catch return; + { + const tz_paint = tracy.zone(@src(), "termPaint"); + defer tz_paint.end(); + const ink = inkOf(p.theme()); + Term.paint(state, &ink, &p.tty_filter_palette, pane.tty_filter, cols, cells, rows); + } + const filtered = pane.tty_filter; + const vp_rows: i32 = @intCast(g.len); + // Which buffer lines the user has not actually changed, so a row swallowed + // by a growing buffer keeps the colour it still stands over. + var anchors: ?EditAnchors = null; + var walk: BodyWalk = .init(pane); + var lines = std.mem.splitScalar(u8, body, '\n'); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + // Before any early exit below, or the lines fall out of step with rows. + const text = lines.next() orelse ""; + const anchor: Anchor = switch (row) { + .edit => |e| blk: { + if (anchors == null) anchors = .init(p, pane, pane.ovl.?); + var an = anchors.?.shellRow(e.idx) orelse continue; + an.row -= walk.goff; + break :blk an; + }, + .grid => |v| .{ .row = v }, + }; + const vi = anchor.row; + if (vi < 0 or vi >= vp_rows) continue; + const prow = rows[@intCast(vi)]; + const grid_row = cells[@as(usize, @intCast(vi)) * cols ..][0..prow.len]; + const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { + const prompt = prow.prompt orelse break :cut 0; + break :cut switch (prompt) { + .keep => 0, + // Blanked end to end: the row shows nothing of the grid, so + // projecting the prompt's own colours onto it would be a lie. + .blank => continue, + .cut => |n| std.math.cast(u16, n) orelse continue, + }; + }; + if (cut > 0 and text.len == 0) continue; + var at: usize = 0; + var sc: u16 = 0; + var gc: u16 = cut; + var sb: usize = 0; + const mine_from = @min(anchor.prefix, text.len); + const mine_to = text.len - @min(anchor.suffix, text.len); + var crossed = false; + while (at < text.len and sc < tw) { + const stop = modal.nextGrapheme(text, at); + if (stop <= at) break; + const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; + if (at >= mine_from and at < mine_to) { + sc += span; + at = stop; + continue; + } + if (at >= mine_to and !crossed) { + crossed = true; + const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); + while (sb < upto) { + if (gc >= grid_row.len) break; + sb += grid_row[gc].bytes; + gc = std.math.add(u16, gc, 1) catch break; + } + } + const want = stop - at; + // Consume every cell that contributed to this grapheme. A cluster + // ghostty split across several cells is still ONE printed glyph. + var covered: usize = 0; + var style: ?pardes.CellStyle = null; + while (covered < want) { + if (gc >= grid_row.len) break; + const c = &grid_row[gc]; + if (style == null and c.wide != .spacer_tail and c.wide != .spacer_head) + style = c.style; + covered += c.bytes; + gc = std.math.add(u16, gc, 1) catch break; + // A spacer contributes no bytes; without this the loop would + // spin on a row that ends in one. + if (covered == 0 and gc >= pane.cols) break; + } + while (gc < grid_row.len and grid_row[gc].wide == .spacer_tail) + gc = std.math.add(u16, gc, 1) catch break; + if (style) |st| for (0..span) |k| { + const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); + if (cell.default and !filtered) continue; + cell.default = false; + cell.style = st; + }; + sb += covered; + sc += span; + at = stop; + } + var tail: ?pardes.CellStyle = null; + if (anchor.whole() or anchor.suffix > 0) { + while (sc < tw) { + if (gc >= grid_row.len) break; + const c = &grid_row[gc]; + gc = std.math.add(u16, gc, 1) catch break; + if (c.wide == .spacer_tail) continue; + const cell = s.at(tx + sc, body_y + vr); + sc += 1; + tail = c.style; + if (cell.default and !filtered) continue; + cell.default = false; + cell.style = c.style; + } + if (tail) |style| while (sc < tw) : (sc += 1) { + const cell = s.at(tx + sc, body_y + vr); + if (cell.default and !filtered) continue; + cell.default = false; + cell.style = style; + }; + } + } +} + +/// Its kitty images over the body's rows, as placements (after the rows +/// and their colours: placeholder cells are blanked by it). +pub fn images(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + const state = pane.terminal orelse return; + Term.cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); + // A body taller than this draws its images on the rows that fit. + var rows_of: [1024]?u16 = undefined; + const vp_rows: usize = @min(Term.grid(state).len, rows_of.len); + @memset(rows_of[0..vp_rows], null); + var walk: BodyWalk = .init(pane); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + const vi = switch (row) { + .grid => |v| v, + .edit => continue, + }; + if (vi < 0 or vi >= vp_rows) continue; + rows_of[@intCast(vi)] = vr; + } + Term.images(state, p.gpa, .{ + .pane = @intCast(id), + .serial = pane.serial, + .tx = tx, + .body_y = body_y, + .cols = @min(tw, pane.cols), + .rows_of = rows_of[0..vp_rows], + .tty_mode = pane.body.mode == .tty, + .now_ms = p.clock.stepped_ns / std.time.ns_per_ms, + .cell_w = @max(1, p.view().cell_pixels.w), + .cell_h = @max(1, p.view().cell_pixels.h), + }, &p.surface.placements, s.cells, s.cols); +} + +// Match surviving edit-buffer rows to their original terminal styles. +const EditAnchors = struct { + /// the buffer's own text, walked in order: a line the VIEWPORT skipped still + /// consumes the row it came from, so the lines below it stay aligned + text: []const u8 = &.{}, + at: usize = 0, + shell: []const []const u8 = &.{}, + /// the covered span, absolute grid rows, as `[first, end)` + first: usize = 0, + end: usize = 0, + lines: usize = 0, + /// the line `at` names, and the first row still unclaimed + idx: usize = 0, + cursor: usize = 0, + budget: usize = 0, + active: bool = false, + + fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { + if (o.rows <= 0 or o.row < 0) return .{}; + const first: usize = @intCast(o.row); + const total = Term.grid(pane.terminal).total; + if (first >= total) return .{}; + const covered: usize = @intCast(o.rows); + const count = @min(covered, total - first); + const shell = Term.editRows(pane.terminal.?, p.scratch.allocator(), first, count) catch return .{}; + const lines = std.mem.count(u8, o.text, "\n") + 1; + return .{ + .text = o.text, + .shell = shell, + .first = first, + .end = first + count, + .lines = lines, + .cursor = first, + .budget = covered + 4 * lines, + .active = true, + }; + } + fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { + if (!a.active or idx >= a.lines) return null; + var found: ?Anchor = null; + while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); + return found; + } + + fn nextLine(a: *EditAnchors) ?[]const u8 { + if (a.at > a.text.len) return null; + const rest = a.text[a.at..]; + if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { + a.at += n + 1; + return rest[0..n]; + } + // The last line has no terminator; one past the end ends the walk. + a.at = a.text.len + 1; + return rest; + } + + /// Where this line still stands over the grid, if anywhere. + fn claim(a: *EditAnchors, line: []const u8) ?Anchor { + const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; + var k = a.cursor; + while (k < end) : (k += 1) { + if (a.budget == 0) return null; + a.budget -= 1; + if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; + a.cursor = k + 1; + return .{ .row = @intCast(k) }; + } + if (a.cursor >= a.end) return null; + const shell = a.shell[a.cursor - a.first]; + var p: usize = 0; + while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; + var s: usize = 0; + const room = @min(line.len, shell.len) - p; + while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; + if (p + s == 0) return null; + if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; + const row = a.cursor; + if (s > 0 or p >= shell.len) a.cursor += 1; + return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; + } +}; + +const Anchor = struct { + /// the row, absolute while it comes from `EditAnchors`, viewport once + /// `recolorAnsi` has subtracted the walk's offset + row: i32, + prefix: usize = std.math.maxInt(usize), + suffix: usize = 0, + /// the row's own dumped length — what the suffix is measured from on the + /// GRID side, where the edit may have changed the byte count + shell_len: usize = 0, + + fn whole(an: Anchor) bool { + return an.prefix == std.math.maxInt(usize); + } +}; diff --git a/src/body_layer.zig b/src/body_layer.zig index 6c0ffcea..abd21090 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -11,6 +11,7 @@ const modal = @import("modal.zig"); const tracy = @import("tracy.zig"); const panes = @import("panes.zig"); const colors = @import("colors.zig"); +const ansi = @import("ansi.zig"); const Color = @import("surface.zig").Color; const CellStyle = @import("surface.zig").CellStyle; const Cell = @import("surface.zig").Cell; @@ -344,11 +345,11 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane pane.places.paint(p, s, pane, r, body_h); panes.Query.paint(p, s, pane, r, body_h); } else if (pane.isTerminal()) { - panes.Term.recolor(p, s, pane, r, tx, tw, body_h, body); + ansi.recolor(p, s, pane, r, tx, tw, body_h, body); panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); } tz_color.end(); - if (pane.isTerminal()) panes.Term.images(p, s, pane, id, tx, tw, body_y, body_h); + if (pane.isTerminal()) ansi.images(p, s, pane, id, tx, tw, body_y, body_h); const sel_btn = buttonTints(th); if (p.look_hover_preview) |preview| { diff --git a/src/config.zig b/src/config.zig index 0568fa26..c7078d8e 100644 --- a/src/config.zig +++ b/src/config.zig @@ -217,9 +217,6 @@ pub const back_out: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; -// Projected colors below this contrast use the theme's more legible anchor. -pub const tty_filter_min_contrast: f64 = 1.5; - // What a pty child is told it is talking to. Every pane is emulated by the // bundled VT, so this describes pardes and never the terminal pardes itself // was launched from — the child inherits the launcher's TERM otherwise, which diff --git a/src/term/echo.zig b/src/echo.zig index a5c65f7e..cf7e9ef8 100644 --- a/src/term/echo.zig +++ b/src/echo.zig @@ -28,8 +28,8 @@ //! prompt or a program that ignores input confirms none, so nothing typed //! there is ever shown. const std = @import("std"); -const pardes = @import("../pardes.zig"); -const terminal = @import("terminal.zig"); +const pardes = @import("pardes.zig"); +const Term = pardes.Term; const Pardes = pardes.Pardes; const Pane = pardes.Pane; const Surface = pardes.Surface; @@ -235,13 +235,11 @@ pub const Echo = struct { /// Whether a key `kind` into terminal `pane` was predicted. fn predict(e: *Echo, pane: *Pane, kind: Kind, seq: u32) bool { const state = pane.terminal orelse return false; - const vt = &state.vt; - const sb = vt.screens.active.pages.scrollbar(); - if (vt.screens.active_key != .primary or sb.offset + sb.len < sb.total or !vt.modes.get(.cursor_visible)) return false; + const g = Term.grid(state); + if (Term.modes(state).alternate or g.offset + g.len < g.total or !g.cursor_visible) return false; const top = e.tops[e.pane]; - const screen = vt.screens.active; - const cur: Cursor = e.cursor orelse .{ .x = @intCast(screen.cursor.x), .row = top + screen.cursor.y, .seq = 0 }; - if (cur.row < top or cur.row - top >= vt.rows or e.n == max) return false; + const cur: Cursor = e.cursor orelse .{ .x = g.cursor_x, .row = top + g.cursor_y, .seq = 0 }; + if (cur.row < top or cur.row - top >= g.len or e.n == max) return false; var next: Cursor = .{ .x = cur.x, .row = cur.row, .seq = seq }; var cell: ?Cell = null; switch (kind) { @@ -251,7 +249,7 @@ pub const Echo = struct { // or a suggestion (fish's) being left: the shell redraws // what is right of it. ponytail: mosh's shift of the rest // would cover bash's middle, and mispredict fish's. - if (cur.x + 1 >= vt.cols) return false; + if (cur.x + 1 >= g.cols) return false; const under = e.cpAt(state, cur.x, cur.row); if (!blank(under) and under != cp) return false; cell = .{ .x = cur.x, .row = cur.row, .cp = cp, .was = under, .seq = seq }; @@ -271,7 +269,7 @@ pub const Echo = struct { // Over typed text only: past its end, fish takes the right // arrow for its suggestion (another colour). .right => { - if (cur.x + 1 >= vt.cols or !e.isText(state, cur.x, cur.row)) return false; + if (cur.x + 1 >= g.cols or !e.isText(state, cur.x, cur.row)) return false; next.x += 1; }, } @@ -298,40 +296,40 @@ pub const Echo = struct { } /// What the screen shows at a cell as predicted so far. - fn cpAt(e: *const Echo, state: *terminal.State, x: u16, row: u64) u21 { + fn cpAt(e: *const Echo, state: *Term.State, x: u16, row: u64) u21 { if (e.mine(x, row)) |have| return have.cp; return e.screenCp(state, x, row); } /// What the screen itself shows there; off its active area, a /// codepoint no key types. - fn screenCp(e: *const Echo, state: *terminal.State, x: u16, row: u64) u21 { - const ci = e.screenCell(state, x, row) orelse return 0x10ffff; - return ci.cell.codepoint(); + fn screenCp(e: *const Echo, state: *Term.State, x: u16, row: u64) u21 { + const c = e.screenCell(state, x, row) orelse return 0x10ffff; + return c.cp; } - fn screenCell(e: *const Echo, state: *terminal.State, x: u16, row: u64) ?terminal.PageCell { + fn screenCell(e: *const Echo, state: *Term.State, x: u16, row: u64) ?Term.EchoCell { const top = e.tops[e.pane]; - if (row < top or row - top >= state.vt.rows) return null; - return state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = @intCast(row - top) } }); + if (row < top or row - top >= Term.grid(state).len) return null; + return Term.echoCell(state, x, @intCast(row - top)); } /// A prompt's input there, or a character predicted. - fn isInput(e: *const Echo, state: *terminal.State, x: u16, row: u64) bool { + fn isInput(e: *const Echo, state: *Term.State, x: u16, row: u64) bool { if (e.mine(x, row)) |have| return !blank(have.cp); - const ci = e.screenCell(state, x, row) orelse return false; - return ci.cell.semantic_content == .input; + const c = e.screenCell(state, x, row) orelse return false; + return c.input; } /// Typed text there: a character predicted, or a prompt's input in the /// colour of the cell before it. - fn isText(e: *const Echo, state: *terminal.State, x: u16, row: u64) bool { + fn isText(e: *const Echo, state: *Term.State, x: u16, row: u64) bool { if (e.mine(x, row)) |have| return !blank(have.cp); - const ci = e.screenCell(state, x, row) orelse return false; - if (ci.cell.semantic_content != .input or blank(ci.cell.codepoint())) return false; + const c = e.screenCell(state, x, row) orelse return false; + if (!c.input or blank(c.cp)) return false; if (x == 0) return true; const before = e.screenCell(state, x - 1, row) orelse return false; - return before.cell.style_id == ci.cell.style_id; + return before.style == c.style; } /// The authority confirmed its client's input `seq`. @@ -384,7 +382,7 @@ pub const Echo = struct { const pane = c.panes[e.pane] orelse return e.drop(); if (pane.serial != e.serial) return e.drop(); const state = pane.terminal orelse return e.drop(); - if (state.vt.screens.active_key != .primary) return e.drop(); + if (Term.modes(state).alternate) return e.drop(); const shown = e.visible(c); var i: usize = 0; while (i < e.n) { @@ -400,8 +398,8 @@ pub const Echo = struct { } e.stats.mispredicted += 1; if (std.c.getenv("PARDES_REPLICA_TRACE") != null) { - const cur = state.vt.screens.active.cursor; - std.debug.print("echo: key {d}'s {u} at {d},{d} not shown ({u} there) {d} ms past due; top {d}, the screen's cursor {d},{d}, acked {d}\n", .{ cell.seq, cell.cp, cell.x, cell.row, e.screenCp(state, cell.x, cell.row), (now - cell.due) / ms, e.tops[e.pane], cur.x, cur.y, e.acked }); + const cur = Term.grid(state); + std.debug.print("echo: key {d}'s {u} at {d},{d} not shown ({u} there) {d} ms past due; top {d}, the screen's cursor {d},{d}, acked {d}\n", .{ cell.seq, cell.cp, cell.x, cell.row, e.screenCp(state, cell.x, cell.row), (now - cell.due) / ms, e.tops[e.pane], cur.cursor_x, cur.cursor_y, e.acked }); } if (shown) e.doubt = true; e.trusted = false; @@ -424,8 +422,8 @@ pub const Echo = struct { } const cur = e.cursor orelse return; if (now < cur.due) return; - const screen = state.vt.screens.active; - if (screen.cursor.x == cur.x and e.tops[e.pane] + screen.cursor.y == cur.row) { + const g = Term.grid(state); + if (g.cursor_x == cur.x and e.tops[e.pane] + g.cursor_y == cur.row) { e.cursor = null; e.changed = true; } else if (now >= cur.due + slack) { @@ -449,7 +447,7 @@ pub const Echo = struct { if (id != e.pane or pane.serial != e.serial or p.live != e.view or pane.body.mode != .tty) return; if (!e.visible(p)) return; const state = pane.terminal orelse return; - const sb = state.vt.screens.active.pages.scrollbar(); + const sb = Term.grid(state); const top = e.tops[id]; // Off a prompt, the trust is inferred: underlined, as mosh does. const flag = !atPrompt(pane); @@ -533,7 +531,8 @@ fn blank(cp: u21) bool { /// pardes's marks is trusted only once its echo is confirmed. fn atPrompt(pane: *const Pane) bool { const state = pane.terminal orelse return false; - return state.vt.screens.active_key == .primary and state.stream.handler.phase == .input and terminal.prompt(state).input_ready; + const at = Term.prompt(state); + return !Term.modes(state).alternate and at.phase == .input and at.input_ready; } /// The terminal view `view`'s keys go to, in tty mode: none when they go @@ -553,7 +552,7 @@ fn keyboardPane(c: *const Pardes, view: u8) ?usize { // ---- tests: one authority and one replica, its shell played by hand ---- const testing = std.testing; -const replica = @import("../replica.zig"); +const replica = @import("replica.zig"); const Rig = struct { a: *replica.Authority, diff --git a/src/keys.zig b/src/keys.zig index bdf8a454..947954f1 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -523,6 +523,7 @@ fn leaderKey(p: *Pardes, key: Key) void { } test "Esc back into a tty leaves its view at the prompt" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); @@ -678,6 +679,7 @@ test "Del from a key asks which neighbour takes the rows; nothing else asks" { } test "raw tty Esc backs out and Shift-Esc is the program's Esc" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); _ = exec.spawnTty(p, 0); diff --git a/src/memory.zig b/src/memory.zig index 31b04b99..ae340bff 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -23,9 +23,6 @@ pub const limits = struct { /// /log's ring, which records whether or not anyone reads it. pub const log_bytes: usize = 64 * KiB; pub const max_tag_tail: usize = 4096; - /// Pixels one image may decode to (RGBA, 4 bytes each): checked from its - /// header before stb_image allocates them. - pub const image_decode_pixels: usize = 64 * 1024 * 1024; /// What the core's per-step scratch arena and the frame arena keep /// between steps: a step that needed more (a huge Callstack's sources) /// gives the rest back instead of holding its high-water mark. diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 6e7fe33e..be85a497 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -962,6 +962,7 @@ test "run on a command pane says no shell is there" { test "a run's answer says cut when its output's start is gone, and reads a bounded tail" { const gpa = testing.allocator; + if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator const p = try withTerm(gpa); defer p.deinit(); const node = Node.of(serialOf(p), .pty_run); @@ -1048,7 +1049,7 @@ test "a run's answer says cut when its output's start is gone, and reads a bound _ = std.fmt.bufPrint(&line, "{d:0>8}", .{i}) catch unreachable; sh.put(p, &line); } - try testing.expect(!pane.terminal.?.stream.handler.out_start.?.garbage); + try testing.expect(!pardes.Term.emulatorOf(pane.terminal.?).stream.handler.out_start.?.garbage); sh.put(p, d ++ prompt); got = sh.answered(p, node, h, into); try testing.expect(std.mem.startsWith(u8, got, "exit 0 cut\n")); @@ -1061,14 +1062,14 @@ test "a run's answer says cut when its output's start is gone, and reads a bound const q = try withTerm(gpa); defer q.deinit(); const kept = q.panes[0].?; - kept.terminal.?.vt.screens.get(.primary).?.pages.limits.set(.bytes, 1); + pardes.Term.emulatorOf(kept.terminal.?).vt.screens.get(.primary).?.pages.limits.set(.bytes, 1); const run = Node.of(serialOf(q), .pty_run); sh.put(q, prompt); h = sh.send(q, run); sh.put(q, c); const lines = std.mem.asBytes(&@as([64][8]u8, @splat("pruned\r\n".*))); var fed: usize = 0; - while (!kept.terminal.?.stream.handler.out_start.?.garbage) : (fed += 1) { + while (!pardes.Term.emulatorOf(kept.terminal.?).stream.handler.out_start.?.garbage) : (fed += 1) { if (fed == 1000) return error.TestUnexpectedResult; sh.put(q, lines); } diff --git a/src/pardes.zig b/src/pardes.zig index f173861b..0e05140e 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -16,6 +16,10 @@ const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); +/// A program's colours on a pane's body (a terminal's cells, its images). +pub const ansi = @import("ansi.zig"); +/// Predicted echo for a replica's terminal panes (`Pardes.echo`). +pub const Echo = @import("echo.zig").Echo; pub const exec = @import("exec.zig"); const recent_files = @import("recent.zig"); const Store = @import("Store.zig"); @@ -393,6 +397,8 @@ test { _ = @import("tape.zig"); _ = @import("replica.zig"); _ = Term; + _ = @import("echo.zig"); + _ = @import("ansi.zig"); _ = @import("modal.zig"); _ = @import("tagline.zig"); _ = @import("hunks.zig"); diff --git a/src/plain/plain.zig b/src/plain/plain.zig new file mode 100644 index 00000000..6ca96fe9 --- /dev/null +++ b/src/plain/plain.zig @@ -0,0 +1,161 @@ +//! The plain records the core and the terminal both name +//! (docs/next-terminal.md, Phase 1): a frame's cells, their styles and +//! colours, the pictures over them and a key read. Data that needs +//! nothing else, in a module of its own: the core (surface.zig and +//! Event.zig, under their old names) and the terminal (src/term/) both +//! import it, and neither imports the other. +const std = @import("std"); +/// The terminal as the core sees it: its entries and the records they +/// take and give. +pub const term = @import("term.zig"); + +pub const Color = union(enum) { default, index: u8, rgb: [3]u8 }; + +pub const FontRole = enum(u8) { body, tagline }; + +pub const CellStyle = struct { + fg: Color = .default, + bg: Color = .default, + bold: bool = false, + dim: bool = false, + italic: bool = false, + blink: bool = false, + reverse: bool = false, + invisible: bool = false, + strikethrough: bool = false, + ul: enum(u3) { off, single, double, curly, dotted, dashed } = .off, + font_role: FontRole = .body, +}; + +pub const Cell = struct { + text: [7]u8 = @splat(' '), + len: u8 = 1, + style: CellStyle = .{}, + default: bool = true, + + pub fn grapheme(c: *const Cell) []const u8 { + return c.text[0..c.len]; + } + + pub fn visuallyEqual(a: *const Cell, b: *const Cell) bool { + if (a.default or b.default) return a.default and b.default; + return a.len == b.len and + std.mem.eql(u8, a.grapheme(), b.grapheme()) and + std.meta.eql(a.style, b.style); + } + + pub fn printableAscii(c: *const Cell) ?u8 { + if (c.default) return ' '; + if (c.len != 1) return null; + const byte = c.text[0]; + return if (byte >= ' ' and byte <= '~') byte else null; + } +}; + +/// A rectangle in pixels. +pub const RectPx = struct { + x: u32 = 0, + y: u32 = 0, + w: u32 = 0, + h: u32 = 0, +}; + +/// A rectangle in the frame's cells. +pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; + +/// The pixels a placement shows: RGBA, straight alpha, `stride` bytes a +/// row. They are the pane's, and stay put until its next frame. +pub const Raster = struct { + ptr: [*]const u8, + w: u32, + h: u32, + stride: u32, + + pub fn of(rgba: []const u8, w: usize, h: usize) Raster { + return .{ .ptr = rgba.ptr, .w = @intCast(w), .h = @intCast(h), .stride = @intCast(w * 4) }; + } + + pub fn bytes(r: Raster) []const u8 { + return r.ptr[0 .. @as(usize, r.stride) * r.h]; + } +}; + +/// A picture over the frame's cells, which a frontend realises: the window +/// as a texture kept by `key`, the tty as a kitty image, or either as glyph +/// art in `dst`'s cells (Art.zig, the frontends' own) where it cannot show +/// pixels or the pane asks for art. The frame lists them a pane at a time, +/// lowest first. +pub const Placement = struct { + pane: u8, + raster: Raster, + /// The part of `raster` shown. + src: RectPx, + /// The cells it lies over, which clip it. + dst: RectCell, + /// Where it goes in `dst`, in pixels from `dst`'s top left corner; + /// null: the frontend fits `src` there, no larger than it is, at the + /// top left (as glyph art, centred). + at: ?RectPx = null, + /// The pixels' identity (`keyOf`): one key is one picture, so a + /// frontend keeps what it uploaded under it. + key: u64, + /// A terminal program's kitty `z=`: below 0 it is under the text, + /// which a tty passes on to the terminal outside. + z: i32 = 0, + /// Rows of `raster` that alone differ from the picture under the key + /// `from`: a frontend still holding that one updates those rows. + dirty: ?Dirty = null, + art: Art = .{}, + + pub const Dirty = struct { from: u64, y: u32, h: u32 }; + + /// How the pane wants it drawn as glyph art: the Petscii, Palette and + /// Ascii words on an image pane, Petscii and TermImages on a terminal. + pub const Art = struct { + /// Glyph art even where pixels could be shown (Petscii on). + glyph: bool = false, + palette: Palette = .commodore, + /// Letters and signs among the glyphs, not only blocks and lines. + ascii: bool = true, + + pub const Palette = enum { commodore, terminal }; + }; + + /// A pane's picture `page` (a PDF's page, a terminal's image id; 0 for + /// an image) as of `revision`. + pub fn keyOf(serial: u32, page: u32, revision: u32) u64 { + return std.hash.Wyhash.hash(0, std.mem.asBytes(&[3]u32{ serial, page, revision })); + } +}; + +/// A key a frontend read (Event.zig). +pub const Key = struct { + cp: u21, // codepoint or one of the specials below + text: []const u8 = "", + ctrl: bool = false, + alt: bool = false, + shift: bool = false, + + pub const enter: u21 = 0x0D; + pub const escape: u21 = 0x1B; + pub const tab: u21 = 0x09; + pub const backspace: u21 = 0x7F; + // private-use plane for non-text keys, matching no real codepoint + pub const up: u21 = 0xF0001; + pub const down: u21 = 0xF0002; + pub const left: u21 = 0xF0003; + pub const right: u21 = 0xF0004; + pub const home: u21 = 0xF0005; + pub const end: u21 = 0xF0006; + pub const page_up: u21 = 0xF0007; + pub const page_down: u21 = 0xF0008; + pub const delete: u21 = 0xF0009; + pub const insert: u21 = 0xF000A; + pub const print_screen: u21 = 0xF000B; + pub const scroll_lock: u21 = 0xF000C; + pub const pause: u21 = 0xF000D; + pub const menu: u21 = 0xF000E; + /// F1 to F25, in order: Fn is `f1 + n - 1`. + pub const f1: u21 = 0xF0011; + pub const f25: u21 = f1 + 24; +}; diff --git a/src/plain/term.zig b/src/plain/term.zig new file mode 100644 index 00000000..dbc4fc87 --- /dev/null +++ b/src/plain/term.zig @@ -0,0 +1,432 @@ +//! 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. src/term/term.zig is the +//! one implementation (ghostty-vt behind it); src/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 (src/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, gpa: std.mem.Allocator) 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, cols: u16, cells: []Painted, rows: []PaintedRow) void, + /// Its kitty images over the body's rows, appended to `out`, 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, +}; diff --git a/src/replica.zig b/src/replica.zig index b746ddb6..a60f54af 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -32,6 +32,7 @@ const daemon = @import("daemon.zig"); const writeAll = daemon.writeAll; const c_heap = @import("c_heap"); const Term = pardes.Term; +const Echo = @import("echo.zig").Echo; const Allocator = std.mem.Allocator; const Pardes = pardes.Pardes; @@ -168,6 +169,7 @@ pub const Authority = struct { const a = try gpa.create(Authority); errdefer gpa.destroy(a); a.* = .{ .gpa = gpa, .t = tape.memory(gpa), .core = undefined, .host = host }; + errdefer tape.release(&a.t); a.t.screen_state = screens; // One word a digest: every pty read is a unit. a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null; @@ -329,7 +331,8 @@ fn writeScreenHead(out: *std.ArrayListUnmanaged(u8), gpa: Allocator, pane: u8, s /// pane, and what each peer was sent of it. pub const Screens = struct { gpa: Allocator, - enc: Term.Encoder, + /// Made the first time a terminal is encoded (`encoder`). + enc: ?*Term.Encoder = null, tracks: [pardes.MAX_PANES]?Tracked = @splat(null), peers: std.ArrayListUnmanaged(*[pardes.MAX_PANES]PeerOf) = .empty, free_peers: std.ArrayListUnmanaged(u16) = .empty, @@ -337,16 +340,16 @@ pub const Screens = struct { /// Nanoseconds: what each flush spent encoding, for every peer. encode_ns: u64 = 0, - const Tracked = struct { serial: u32, state: *Term.State, track: Term.Track }; + const Tracked = struct { serial: u32, state: *Term.State, track: *Term.Track }; const PeerOf = struct { serial: u32 = 0, peer: Term.Peer = .{}, shadow: pardes.Kind.ShadowSent = .{} }; pub fn init(gpa: Allocator) Screens { - return .{ .gpa = gpa, .enc = .init(gpa) }; + return .{ .gpa = gpa }; } /// `core` is the session's, its terminals still there. pub fn deinit(s: *Screens, core: *Pardes) void { - for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| Term.untrack(&tr.track, s.gpa, if (s.live(core, id, tr)) tr.state else null); + for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| Term.untrack(tr.track, s.gpa, if (s.live(core, id, tr)) tr.state else null); for (s.peers.items) |p| { for (p) |*pp| { pp.peer.deinit(s.gpa); @@ -357,7 +360,7 @@ pub const Screens = struct { s.peers.deinit(s.gpa); s.free_peers.deinit(s.gpa); s.out.deinit(s.gpa); - s.enc.deinit(); + if (s.enc) |e| Term.encoderFree(e); } fn live(_: *const Screens, core: *Pardes, id: usize, tr: *const Tracked) bool { @@ -405,7 +408,7 @@ pub const Screens = struct { try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_delta); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - if (!try Term.encode(state, &s.enc, &tr.track, &pp.peer, &w.writer)) continue; + if (!try Term.encode(state, try s.encoder(), tr.track, &pp.peer, &w.writer)) continue; try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); } } @@ -483,7 +486,7 @@ pub const Screens = struct { try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_rows); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - try Term.encodeRows(state, &s.enc, &tr.track, lo, hi, &w.writer); + try Term.encodeRows(state, try s.encoder(), tr.track, lo, hi, &w.writer); try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); lo = hi; } @@ -504,12 +507,20 @@ pub const Screens = struct { if (s.tracks[id]) |*tr| { if (s.live(core, id, tr)) return tr; // Its pane closed (its emulator, the pin with it, gone). - Term.untrack(&tr.track, s.gpa, null); + Term.untrack(tr.track, s.gpa, null); + s.tracks[id] = null; } - s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = .init(s.gpa) }; + s.tracks[id] = .{ .serial = pane.serial, .state = pane.terminal.?, .track = try Term.track(s.gpa) }; return &s.tracks[id].?; } + /// The encoder, made the first time a terminal is encoded. + fn encoder(s: *Screens) !*Term.Encoder { + if (s.enc) |e| return e; + s.enc = try Term.encoder(s.gpa); + return s.enc.?; + } + /// A peer's message (`Replica.screen`'s, `Replica.screenRequest`'s): /// an answer for it (owned), or null. pub fn take(s: *Screens, core: *Pardes, peer: u16, msg: []const u8) !?[]u8 { @@ -531,7 +542,7 @@ pub const Screens = struct { try writeScreenHead(&s.out, s.gpa, m.pane, m.serial, kind_rows); var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); defer s.out = w.toArrayList(); - try Term.encodeRows(state, &s.enc, &tr.track, std.mem.readInt(u64, m.payload[0..8], .little), std.mem.readInt(u64, m.payload[8..16], .little), &w.writer); + try Term.encodeRows(state, try s.encoder(), tr.track, std.mem.readInt(u64, m.payload[0..8], .little), std.mem.readInt(u64, m.payload[8..16], .little), &w.writer); return try s.gpa.dupe(u8, w.written()); }, else => {}, @@ -680,11 +691,11 @@ pub const Replica = struct { blobs: pardes.Kind.Blobs = .{}, /// Its predicted echo (src/term/echo.zig), drawn over its core's terminals: /// fed by its keys, its units and its deltas here, and by `echoFrame`. - echo: Term.Echo = .{}, + echo: Echo = .{}, const ScreenOf = struct { serial: u32, - rep: Term.Replica = .{}, + rep: *Term.Replica, /// A delta was refused, and a reset asked for: those in flight /// before it are refused unasked. refused: bool = false, @@ -758,7 +769,7 @@ pub const Replica = struct { } pub fn deinit(r: *Replica) void { - for (&r.screens) |*slot| if (slot.*) |*sc| sc.rep.deinit(pardes.panes.emulator_gpa); + for (&r.screens) |*slot| if (slot.*) |*sc| Term.replicaFree(sc.rep, pardes.panes.emulator_gpa); if (r.t.core) |c| { const was = Stepping.begin(&r.t, &r.epoch); if (r.copy.held) _ = r.copy.restore(); @@ -1156,8 +1167,13 @@ pub const Replica = struct { const state = pane.terminal orelse return null; const slot = &r.screens[m.pane]; if (slot.* == null or slot.*.?.serial != m.serial) { - if (slot.*) |*old| old.rep.deinit(pardes.panes.emulator_gpa); - slot.* = .{ .serial = m.serial }; + if (slot.*) |*old| Term.replicaFree(old.rep, pardes.panes.emulator_gpa); + slot.* = null; + const rep = Term.replica(pardes.panes.emulator_gpa) catch { + r.fail("no memory for a terminal's replica"); + return null; + }; + slot.* = .{ .serial = m.serial, .rep = rep }; } const sc = &slot.*.?; // The emulator is the authority's: on the C heap, outside the @@ -1166,7 +1182,7 @@ pub const Replica = struct { switch (m.kind) { kind_delta => { const t0 = nowNs(); - const applied = Term.apply(state, &sc.rep, m.payload) catch |err| { + const applied = Term.apply(state, sc.rep, m.payload) catch |err| { if (err != error.BaseMismatch) r.fail("a terminal's delta did not apply"); if (sc.refused) return null; sc.refused = true; @@ -1174,7 +1190,7 @@ pub const Replica = struct { }; if (r.stats.samples) r.stats.apply_ns.append(r.gpa, nowNs() - t0) catch {}; sc.refused = false; - r.echo.delta(c, m.pane, sc.rep.top); + r.echo.delta(c, m.pane, Term.replicaTop(sc.rep)); // Its rows as the core keeps them read are another grid's. c.shell_rows.markStale(pane); // Its view is the authority's now: a rollback puts it back @@ -1187,7 +1203,7 @@ pub const Replica = struct { }, kind_rows => { sc.asked = null; - Term.applyRows(state, &sc.rep, m.payload) catch r.fail("a terminal's rows did not apply"); + Term.applyRows(state, sc.rep, m.payload) catch r.fail("a terminal's rows did not apply"); c.shell_rows.markStale(pane); r.overTerminals(); return null; @@ -1222,13 +1238,13 @@ pub const Replica = struct { const pane = c.panes[id] orelse continue; if (pane.serial != sc.serial) continue; const state = pane.terminal orelse continue; - const shown = Term.shown(state, &sc.rep); + const shown = Term.shown(state, sc.rep); var holes: std.ArrayList([2]u64) = .empty; defer holes.deinit(r.gpa); - sc.rep.missing(shown[0], shown[1], &holes, r.gpa) catch return null; + Term.missing(sc.rep, shown[0], shown[1], &holes, r.gpa) catch return null; if (holes.items.len == 0) continue; const want: [2]u64 = .{ holes.items[0][0], holes.items[holes.items.len - 1][1] }; - Term.blank(state, &sc.rep, want[0], want[1]); + Term.blank(state, sc.rep, want[0], want[1]); sc.asked = want; var range: [16]u8 = undefined; std.mem.writeInt(u64, range[0..8], want[0], .little); @@ -3772,6 +3788,7 @@ test "a replica joined from a themed dump paints its taglines in the restored th } test "a host's Adopt and a terminal reader's failure are inputs: a replica makes the same pane" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; // Its terminals as screen state, as a session's for its clients are. const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), true); diff --git a/src/surface.zig b/src/surface.zig index b832222f..73789dce 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -2,6 +2,7 @@ //! the image placements laid over them, and the Surface that holds a frame. const pardes = @import("pardes.zig"); const std = @import("std"); +const plain = @import("plain"); const layout = @import("layout.zig"); const uucode = @import("uucode"); const vaxis = @import("vaxis"); @@ -11,56 +12,16 @@ const MAX_PANES = pardes.MAX_PANES; const Layer = @import("Layer.zig"); const MAX_TAG_LAYERS = pardes.MAX_TAG_LAYERS; -pub const Color = union(enum) { default, index: u8, rgb: [3]u8 }; - -pub const FontRole = enum(u8) { body, tagline }; - -pub const CellStyle = struct { - fg: Color = .default, - bg: Color = .default, - bold: bool = false, - dim: bool = false, - italic: bool = false, - blink: bool = false, - reverse: bool = false, - invisible: bool = false, - strikethrough: bool = false, - ul: enum(u3) { off, single, double, curly, dotted, dashed } = .off, - font_role: FontRole = .body, -}; - -pub const Cell = struct { - text: [7]u8 = @splat(' '), - len: u8 = 1, - style: CellStyle = .{}, - default: bool = true, - - pub fn grapheme(c: *const Cell) []const u8 { - return c.text[0..c.len]; - } - - pub fn visuallyEqual(a: *const Cell, b: *const Cell) bool { - if (a.default or b.default) return a.default and b.default; - return a.len == b.len and - std.mem.eql(u8, a.grapheme(), b.grapheme()) and - std.meta.eql(a.style, b.style); - } - - pub fn printableAscii(c: *const Cell) ?u8 { - if (c.default) return ' '; - if (c.len != 1) return null; - const byte = c.text[0]; - return if (byte >= ' ' and byte <= '~') byte else null; - } -}; - -/// A rectangle in pixels. -pub const RectPx = struct { - x: u32 = 0, - y: u32 = 0, - w: u32 = 0, - h: u32 = 0, -}; +// The plain records (src/plain/plain.zig) both the core and the terminal +// name, under the names the core has always called them. +pub const Color = plain.Color; +pub const FontRole = plain.FontRole; +pub const CellStyle = plain.CellStyle; +pub const Cell = plain.Cell; +pub const RectPx = plain.RectPx; +pub const RectCell = plain.RectCell; +pub const Raster = plain.Raster; +pub const Placement = plain.Placement; pub const PixelPoint = struct { x: u32, y: u32 }; @@ -113,73 +74,8 @@ pub fn containGeometry(iw: usize, ih: usize, max_w: u32, max_h: u32) ?NativeGeom return .{ .src = .{ .w = src_w, .h = src_h }, .dst = dst }; } -/// A rectangle in the frame's cells. -pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; -/// The pixels a placement shows: RGBA, straight alpha, `stride` bytes a -/// row. They are the pane's, and stay put until its next frame. -pub const Raster = struct { - ptr: [*]const u8, - w: u32, - h: u32, - stride: u32, - pub fn of(rgba: []const u8, w: usize, h: usize) Raster { - return .{ .ptr = rgba.ptr, .w = @intCast(w), .h = @intCast(h), .stride = @intCast(w * 4) }; - } - - pub fn bytes(r: Raster) []const u8 { - return r.ptr[0 .. @as(usize, r.stride) * r.h]; - } -}; - -/// A picture over the frame's cells, which a frontend realises: the window -/// as a texture kept by `key`, the tty as a kitty image, or either as glyph -/// art in `dst`'s cells (Art.zig, the frontends' own) where it cannot show -/// pixels or the pane asks for art. The frame lists them a pane at a time, -/// lowest first. -pub const Placement = struct { - pane: u8, - raster: Raster, - /// The part of `raster` shown. - src: RectPx, - /// The cells it lies over, which clip it. - dst: RectCell, - /// Where it goes in `dst`, in pixels from `dst`'s top left corner; - /// null: the frontend fits `src` there, no larger than it is, at the - /// top left (as glyph art, centred). - at: ?RectPx = null, - /// The pixels' identity (`keyOf`): one key is one picture, so a - /// frontend keeps what it uploaded under it. - key: u64, - /// A terminal program's kitty `z=`: below 0 it is under the text, - /// which a tty passes on to the terminal outside. - z: i32 = 0, - /// Rows of `raster` that alone differ from the picture under the key - /// `from`: a frontend still holding that one updates those rows. - dirty: ?Dirty = null, - art: Art = .{}, - - pub const Dirty = struct { from: u64, y: u32, h: u32 }; - - /// How the pane wants it drawn as glyph art: the Petscii, Palette and - /// Ascii words on an image pane, Petscii and TermImages on a terminal. - pub const Art = struct { - /// Glyph art even where pixels could be shown (Petscii on). - glyph: bool = false, - palette: Palette = .commodore, - /// Letters and signs among the glyphs, not only blocks and lines. - ascii: bool = true, - - pub const Palette = enum { commodore, terminal }; - }; - - /// A pane's picture `page` (a PDF's page, a terminal's image id; 0 for - /// an image) as of `revision`. - pub fn keyOf(serial: u32, page: u32, revision: u32) u64 { - return std.hash.Wyhash.hash(0, std.mem.asBytes(&[3]u32{ serial, page, revision })); - } -}; /// One part of the frame and where it is, placed once by `draw.place` /// before anything is painted: every painter and every shell reads the diff --git a/src/term/TerminalImages.zig b/src/term/TerminalImages.zig index 6894945c..1420d9e3 100644 --- a/src/term/TerminalImages.zig +++ b/src/term/TerminalImages.zig @@ -8,14 +8,17 @@ //! moves with the text it was put on, and a virtual one (`U=1`) shown //! through the U+10EEEE placeholder cells the program prints. const std = @import("std"); +const plain = @import("plain"); const ghostty_vt = @import("ghostty-vt"); -const pardes = @import("../pardes.zig"); const zstbi = @import("zstbi"); const wuffs = @import("wuffs"); const TerminalImages = @This(); const gfx = ghostty_vt.kitty.graphics; -const PixelRect = @import("../surface.zig").RectPx; +const PixelRect = plain.RectPx; +/// Pixels one image may decode to (RGBA, 4 bytes each): checked from its +/// header before it is decoded. +const image_decode_pixels: usize = 64 * 1024 * 1024; /// The bytes ghostty-vt may hold for one screen's images (it evicts the /// oldest past this): a 4K picture in RGBA, with room for a second. @@ -140,7 +143,7 @@ fn decodePng(gpa: std.mem.Allocator, bytes: []const u8) ghostty_vt.sys.DecodeErr if (bytes.len < 24 or !std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n") or !std.mem.eql(u8, bytes[12..16], "IHDR")) return error.InvalidData; const w = std.mem.readInt(u32, bytes[16..20], .big); const h = std.mem.readInt(u32, bytes[20..24], .big); - if (@as(u64, w) * h > pardes.memory.limits.image_decode_pixels) return error.InvalidData; + if (@as(u64, w) * h > image_decode_pixels) return error.InvalidData; const got = wuffs.png.decode(gpa, bytes) catch return error.InvalidData; if (got.data.len != @as(usize, got.width) * got.height * 4) { gpa.free(got.data); @@ -160,38 +163,36 @@ fn decodePng(gpa: std.mem.Allocator, bytes: []const u8) ghostty_vt.sys.DecodeErr /// columns the body shows, from `tx`. pub fn draw( ti: *TerminalImages, - p: *pardes.Pardes, - s: *pardes.Surface, + gpa: std.mem.Allocator, vt: *ghostty_vt.Terminal, - pane_id: u8, - serial: u32, - tx: u16, - body_y: u16, - cols: u16, + where: plain.term.ImagesAt, rows_of: []const ?u16, + out: *std.ArrayList(plain.Placement), + frame: []plain.Cell, + frame_cols: u16, ) void { var conv = ti.converted.valueIterator(); while (conv.next()) |c| c.used = false; - defer ti.prune(p.gpa); + defer ti.prune(gpa); const screen = vt.screens.active; const storage = &screen.kitty_images; // Animations step on the core's clock, as this frame shows them; the // shown frame is `renderData()` (a new `generation` each step, which // the caches key on). - const now_ms = p.clock.stepped_ns / std.time.ns_per_ms; + const now_ms = where.now_ms; ti.animation_due_ms = if (storage.animationTick(vt.io(), now_ms)) |delay| now_ms +| delay else null; const pages = &screen.pages; const top = pages.getTopLeft(.viewport); const bottom = pages.getBottomRight(.viewport) orelse return; - const cw: u32 = @max(1, p.view().cell_pixels.w); - const ch: u32 = @max(1, p.view().cell_pixels.h); - const ctx: Ctx = .{ .ti = ti, .p = p, .pane = pane_id, .serial = serial, .tx = tx, .body_y = body_y, .cols = cols, .rows_of = rows_of, .cw = cw, .ch = ch }; + const cw: u32 = @max(1, where.cell_w); + const ch: u32 = @max(1, where.cell_h); + const ctx: Ctx = .{ .ti = ti, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch }; // Handed on lowest z first (the storage's order is a hash map's), the // order a shell draws them in; equal z keeps the order they came in. - const first = s.placements.items.len; - defer std.sort.insertion(pardes.Placement, s.placements.items[first..], {}, struct { - fn lessThan(_: void, a: pardes.Placement, b: pardes.Placement) bool { + const first = out.items.len; + defer std.sort.insertion(plain.Placement, out.items[first..], {}, struct { + fn lessThan(_: void, a: plain.Placement, b: plain.Placement) bool { return a.z < b.z; } }.lessThan); @@ -205,8 +206,8 @@ pub fn draw( if (v >= rows_of.len) continue; const row = rows_of[v] orelse continue; for (@as(usize, at.viewport.x)..@as(usize, at.viewport.x) + run.width) |x| { - if (x >= cols) break; - const cell = s.at(tx + @as(u16, @intCast(x)), body_y + row); + if (x >= where.cols) break; + const cell = &frame[@as(usize, where.body_y + row) * frame_cols + where.tx + x]; cell.text[0] = ' '; cell.len = 1; } @@ -267,7 +268,8 @@ pub fn draw( const Ctx = struct { ti: *TerminalImages, - p: *pardes.Pardes, + gpa: std.mem.Allocator, + out: *std.ArrayList(plain.Placement), pane: u8, serial: u32, tx: u16, @@ -285,7 +287,7 @@ const Ctx = struct { const x0 = @max(dst.x, 0); const x1 = @min(dst.x + dst.w, @as(i64, ctx.cols) * cw); if (x1 <= x0) return; - const rgba = ctx.ti.pixelsOf(ctx.p.gpa, img) orelse return; + const rgba = ctx.ti.pixelsOf(ctx.gpa, img) orelse return; const first_row = @divFloor(@max(dst.y, 0), ch); const last_row = @min(@divFloor(dst.y + dst.h - 1, ch), @as(i64, @intCast(ctx.rows_of.len)) - 1); var v = first_row; @@ -303,7 +305,7 @@ const Ctx = struct { }; const c0: u16 = @intCast(@divFloor(x0, cw)); const c1: u16 = @intCast(@divFloor(x1 + cw - 1, cw)); - _ = ctx.p.appendPlacement(.{ + ctx.out.append(ctx.gpa, .{ .pane = ctx.pane, .raster = .of(rgba, img.width, img.height), .src = piece, @@ -314,10 +316,10 @@ const Ctx = struct { .w = @intCast(x1 - x0), .h = @intCast(y1 - y0), }, - .key = pardes.Placement.keyOf(ctx.serial, img.id, @truncate(img.generation)), + .key = plain.Placement.keyOf(ctx.serial, img.id, @truncate(img.generation)), .z = z, .art = .{ .glyph = ctx.ti.petscii }, - }); + }) catch {}; } } }; diff --git a/src/term/pager.zig b/src/term/pager.zig index dca57024..0cf2ee21 100644 --- a/src/term/pager.zig +++ b/src/term/pager.zig @@ -5,28 +5,20 @@ //! motion, OSC titles and hyperlinks, modes). The spans are display state //! of the pane only: no 9P file reads them (File.recolorSyntax draws them). const std = @import("std"); -const pardes = @import("../pardes.zig"); -const CellStyle = @import("../surface.zig").CellStyle; +const plain = @import("plain"); +const CellStyle = plain.CellStyle; const ghostty_vt = @import("ghostty-vt"); /// Bytes `start..end` of the text, drawn in `style`. A palette colour stays /// `.index`, resolved through the theme as it is drawn (terminal.palColor), /// and `.default` is the pane's own. -pub const Span = struct { start: u32, end: u32, style: CellStyle }; +pub const Span = plain.term.Span; /// ponytail: past this many spans the rest of a page is plain, rather than /// ~100 MB of spans for a 256 MiB coloured log; a packed style if it matters. pub const max_spans = 4 << 20; -pub const Page = struct { - text: []u8, - spans: []Span, - - pub fn deinit(page: Page, gpa: std.mem.Allocator) void { - gpa.free(page.text); - gpa.free(page.spans); - } -}; +pub const Page = plain.term.Page; /// `raw`, a program's output for a terminal, as text and its spans. Both /// are `gpa`'s. diff --git a/src/term/screen_state.zig b/src/term/screen_state.zig index 43eae542..59085578 100644 --- a/src/term/screen_state.zig +++ b/src/term/screen_state.zig @@ -32,6 +32,7 @@ //! `applyRows`). const std = @import("std"); const vt = @import("ghostty-vt"); +const plain = @import("plain"); const snapshot = vt.snapshot; pub const Terminal = vt.Terminal; const Page = vt.page.Page; @@ -198,7 +199,7 @@ fn clampHoles(holes: *std.ArrayList([2]u64), oldest: u64) void { /// Deltas a peer may have in flight. At 207 ms and 60 frames a second about /// 13 are; past the bound a peer gets nothing until an acknowledgement, and /// then the newest state, the ones between skipped. -pub const bound = 32; +pub const bound = plain.term.flight_bound; /// What a peer holds once it has a version: the addresses of its active /// rows and its meta. A delta against it sends no blob for these. @@ -290,60 +291,30 @@ pub const Track = struct { } }; -/// 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: [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; - } +/// What the authority knows of one peer of one terminal: a plain record +/// both sides name (src/plain/term.zig), the core keeping one a peer. +pub const Peer = plain.term.Peer; - /// 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 }; - } - - /// Its replica's holes once it applies a delta to `tr`'s newest version - /// against `base`, as Replica.apply makes them. - fn noteSent(peer: *Peer, gpa: std.mem.Allocator, tr: *const Track, base: ?*const Known, rows: u16) !void { - const top = tr.rows.top; - const history = tr.history; - if (base) |b| { - if (top > peer.top) { - const tail = @min(top -| b.top, rows, history); - if (top - peer.top >= @as(u64, rows) + history) { - peer.holes.clearRetainingCapacity(); - if (history > tail) try peer.holes.append(gpa, .{ top - history, top - tail }); - } else if (top - tail > peer.top) try peer.holes.append(gpa, .{ peer.top, top - tail }); - } - } else { - peer.holes.clearRetainingCapacity(); - if (history > 0) try peer.holes.append(gpa, .{ top - history, top }); +/// Its replica's holes once it applies a delta to `tr`'s newest version +/// against `base`, as Replica.apply makes them. +fn noteSent(peer: *Peer, gpa: std.mem.Allocator, tr: *const Track, base: ?*const Known, rows: u16) !void { + const top = tr.rows.top; + const history = tr.history; + if (base) |b| { + if (top > peer.top) { + const tail = @min(top -| b.top, rows, history); + if (top - peer.top >= @as(u64, rows) + history) { + peer.holes.clearRetainingCapacity(); + if (history > tail) try peer.holes.append(gpa, .{ top - history, top - tail }); + } else if (top - tail > peer.top) try peer.holes.append(gpa, .{ peer.top, top - tail }); } - peer.top = top; - clampHoles(&peer.holes, top -| history); + } else { + peer.holes.clearRetainingCapacity(); + if (history > 0) try peer.holes.append(gpa, .{ top - history, top }); } -}; + peer.top = top; + clampHoles(&peer.holes, top -| history); +} /// The delta's fixed header: u32 seq, u32 base (0: none, the replica /// starts afresh), u8 flags, u32 epoch, u64 meta, u16 cursor x and y, u8 @@ -376,7 +347,7 @@ pub fn encode(e: *Encoder, tr: *Track, peer: *Peer, t: *Terminal, changes: u32, tr.cache_base = base_version; } try out.writeAll(tr.cache.written()); - try peer.noteSent(e.gpa, tr, base, t.rows); + try noteSent(peer, e.gpa, tr, base, t.rows); peer.sent = tr.version; peer.flight[peer.n] = tr.version; peer.n += 1; @@ -513,7 +484,7 @@ pub const Replica = struct { if (r.scratch) |*s| s.deinit(); } - pub const Applied = struct { seq: u32, extra: []const u8 }; + pub const Applied = plain.term.Applied; /// Write one delta into `t`: the seq to acknowledge, and the caller's /// extra bytes (borrowed from `bytes`). error.BaseMismatch: the delta @@ -1240,55 +1211,3 @@ test "several deltas in flight land in order, and a peer at the bound waits for try testing.expectEqual(@as(u64, 0), s.stats.refused); } -test "a replica's terminal pane draws as its authority's does" { - const pardes = @import("../pardes.zig"); - const gpa = testing.allocator; - const a = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer a.deinit(); - const b = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer b.deinit(); - while (a.nextEffect()) |_| {} - while (b.nextEffect()) |_| {} - var fa = std.heap.ArenaAllocator.init(gpa); - defer fa.deinit(); - var fb = std.heap.ArenaAllocator.init(gpa); - defer fb.deinit(); - // Laid out once, so both panes have their size before the first delta. - _ = try a.render(fa.allocator()); - _ = try b.render(fb.allocator()); - const ta = &a.panes[0].?.terminal.?.vt; - const tb = &b.panes[0].?.terminal.?.vt; - var enc: Encoder = .init(gpa); - defer enc.deinit(); - var peer: Peer = .{}; - defer peer.deinit(gpa); - var tr: Track = .init(gpa); - defer tr.deinit(gpa, ta); - var rep: Replica = .{}; - defer rep.deinit(gpa); - var delta: std.Io.Writer.Allocating = .init(gpa); - defer delta.deinit(); - var line: [256]u8 = undefined; - for (0..60) |i| { - const bytes = try std.fmt.bufPrint(&line, "\x1b[1;3{d}m{d}\x1b[0m 漢字 e\u{301} \x1b[48;2;{d};40;60mbg\x1b[0m and then some text that wraps past the width of the pane\r\n", .{ i % 8, i, i * 4 % 256 }); - a.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); - delta.clearRetainingCapacity(); - try testing.expect(try encode(&enc, &tr, &peer, ta, @intCast(i + 1), "", &delta.writer)); - peer.ack((try rep.apply(gpa, std.Io.Threaded.global_single_threaded.io(), tb, delta.written())).seq); - b.needs_frame = true; - _ = fa.reset(.retain_capacity); - _ = fb.reset(.retain_capacity); - const sa = try a.render(fa.allocator()); - const sb = try b.render(fb.allocator()); - const r = a.view().rects[0]; - // The body: below the pane's tag row. - for (r.y + 1..r.y + r.h) |y| for (r.x..r.x + r.w) |x| { - const ca = sa.at(@intCast(x), @intCast(y)); - const cb = sb.at(@intCast(x), @intCast(y)); - if (!ca.visuallyEqual(cb)) { - std.debug.print("step {d}: cell {d},{d}: '{s}' vs '{s}'\n", .{ i, x, y, ca.grapheme(), cb.grapheme() }); - return error.ReplicaDrawsDifferently; - } - }; - } -} diff --git a/src/term/term.zig b/src/term/term.zig new file mode 100644 index 00000000..87c06611 --- /dev/null +++ b/src/term/term.zig @@ -0,0 +1,164 @@ +//! The terminal, a module of its own (docs/next-terminal.md, Phase 1): +//! ghostty-vt's emulator and what pardes keeps beside it (terminal.zig), +//! the screen state its replicas are sent (screen_state.zig), the kitty +//! images it draws (TerminalImages.zig) and the pager's parse (pager.zig). +//! It imports std, ghostty-vt, wuffs, zstbi and `plain`, never the core: +//! the core reaches it through `ops` (src/Term.zig), the records of +//! src/plain/term.zig in and out. +const std = @import("std"); +const plain = @import("plain"); +const iface = plain.term; +const terminal_ = @import("terminal.zig"); +const pager = @import("pager.zig"); +const screen_state_ = @import("screen_state.zig"); +const TerminalImages = terminal_.TerminalImages; + +/// The screen state replicas are sent, its streams and soak (test/replicas.zig). +pub const screen_state = screen_state_; +/// The emulator itself, for the tests that read it through a core +/// (test/terminal.zig). +pub const terminal = terminal_; + +pub const ops: iface.Ops = .{ + .open = cast(iface.Ops, "open", terminal_.open), + .close = cast(iface.Ops, "close", terminal_.close), + .due = cast(iface.Ops, "due", terminal_.due), + .revive = cast(iface.Ops, "revive", terminal_.revive), + .start = TerminalImages.start, + .stop = TerminalImages.stop, + .gpa = cast(iface.Ops, "gpa", terminal_.gpaOf), + .digest = cast(iface.Ops, "digest", terminal_.digest), + .parts = cast(iface.Ops, "parts", terminal_.parts), + .snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot), + .load = cast(iface.Ops, "load", terminal_.load), + .feed = cast(iface.Ops, "feed", terminal_.feed), + .grid = cast(iface.Ops, "grid", terminal_.grid), + .viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo), + .scroll = cast(iface.Ops, "scroll", terminal_.scroll), + .follow = cast(iface.Ops, "follow", terminal_.follow), + .resize = cast(iface.Ops, "resize", terminal_.resize), + .resizeDeferred = cast(iface.Ops, "resizeDeferred", terminal_.resizeDeferred), + .cellPixels = cast(iface.Ops, "cellPixels", terminal_.cellPixels), + .replies = cast(iface.Ops, "replies", terminal_.replies), + .key = cast(iface.Ops, "key", terminal_.key), + .mouse = cast(iface.Ops, "mouse", terminal_.mouse), + .wheel = cast(iface.Ops, "wheel", terminal_.wheel), + .paste = cast(iface.Ops, "paste", terminal_.paste), + .modes = cast(iface.Ops, "modes", terminal_.modes), + .promptMoves = cast(iface.Ops, "promptMoves", terminal_.promptMoves), + .prompt = cast(iface.Ops, "prompt", terminal_.prompt), + .commandOutput = cast(iface.Ops, "commandOutput", terminal_.commandOutput), + .endOutputHere = cast(iface.Ops, "endOutputHere", terminal_.endOutputHere), + .scrollback = cast(iface.Ops, "scrollback", terminal_.scrollback), + .scrollbackLen = cast(iface.Ops, "scrollbackLen", terminal_.scrollbackLen), + .textRows = cast(iface.Ops, "textRows", terminal_.textRows), + .viewport = cast(iface.Ops, "viewport", terminal_.viewport), + .editRows = cast(iface.Ops, "editRows", terminal_.editRows), + .promptCut = cast(iface.Ops, "promptCut", terminal_.promptCutAt), + .markRead = cast(iface.Ops, "markRead", terminal_.markRead), + .echoCell = cast(iface.Ops, "echoCell", terminal_.echoCell), + .page = pager.parse, + .filter = terminal_.pagerFilter, + .spanColor = terminal_.spanColor, + .paint = cast(iface.Ops, "paint", terminal_.paint), + .images = cast(iface.Ops, "images", terminal_.images), + .petscii = cast(iface.Ops, "petscii", terminal_.petscii), + .togglePetscii = cast(iface.Ops, "togglePetscii", terminal_.togglePetscii), + .hasImages = cast(iface.Ops, "hasImages", terminal_.hasImages), + .encoder = cast(iface.Ops, "encoder", terminal_.encoder), + .encoderFree = cast(iface.Ops, "encoderFree", terminal_.encoderFree), + .track = cast(iface.Ops, "track", terminal_.track), + .untrack = cast(iface.Ops, "untrack", terminal_.untrack), + .encode = cast(iface.Ops, "encode", terminal_.encode), + .encodeRows = cast(iface.Ops, "encodeRows", terminal_.encodeRows), + .wasRead = cast(iface.Ops, "wasRead", terminal_.wasRead), + .clearRead = cast(iface.Ops, "clearRead", terminal_.clearRead), + .replica = cast(iface.Ops, "replica", terminal_.replica), + .replicaFree = cast(iface.Ops, "replicaFree", terminal_.replicaFree), + .replicaTop = cast(iface.Ops, "replicaTop", terminal_.replicaTop), + .missing = cast(iface.Ops, "missing", terminal_.missing), + .apply = cast(iface.Ops, "apply", terminal_.apply), + .applyRows = cast(iface.Ops, "applyRows", terminal_.applyRows), + .shown = cast(iface.Ops, "shown", terminal_.shown), + .blank = cast(iface.Ops, "blank", terminal_.blank), + .dumpScreen = cast(iface.Ops, "dumpScreen", terminal_.dumpScreen), +}; + +/// The term's handle types as the interface names them, and the module's +/// own behind each: a pointer to one is a pointer to the other. +const handles = .{ + .{ iface.State, terminal_.State }, + .{ iface.Encoder, screen_state_.Encoder }, + .{ iface.Track, screen_state_.Track }, + .{ iface.Replica, screen_state_.Replica }, +}; + +/// The interface's handle for one of this module's own types, or the type +/// itself. +fn handleOf(comptime T: type) type { + inline for (handles) |pair| if (T == pair[1]) return pair[0]; + return switch (@typeInfo(T)) { + .pointer => |p| if (p.size != .one) T else if (p.attrs.@"const") *const handleOf(p.child) else *handleOf(p.child), + .optional => |o| ?handleOf(o.child), + else => T, + }; +} + +/// Every error of `Have` is one of `Want`'s (anyerror holds them all). +fn within(comptime Have: type, comptime Want: type) bool { + const want = @typeInfo(Want).error_set.error_names orelse return true; + const have = @typeInfo(Have).error_set.error_names orelse return false; + outer: for (have) |h| { + for (want) |w| if (std.mem.eql(u8, h, w)) continue :outer; + return false; + } + return true; +} + +/// The errors of result `H` that result `W` has not, named. +fn missingFrom(comptime H: type, comptime W: type) []const u8 { + if (@typeInfo(H) != .error_union or @typeInfo(W) != .error_union) return ""; + const want = @typeInfo(@typeInfo(W).error_union.error_set).error_set.error_names orelse return ""; + const have = @typeInfo(@typeInfo(H).error_union.error_set).error_set.error_names orelse return " (anyerror)"; + var out: []const u8 = ": not"; + outer: for (have) |h| { + for (want) |w| if (std.mem.eql(u8, h, w)) continue :outer; + out = out ++ " " ++ h; + } + return out; +} + +/// `f`, one of this module's own entries, as the `Ops` field `name`: the +/// same function, its handles the interface's opaque ones. Refused at +/// compile time unless every parameter and the result match but for them. +fn cast(comptime O: type, comptime name: []const u8, comptime f: anytype) @FieldType(O, name) { + @setEvalBranchQuota(100_000); + const Want = @typeInfo(@FieldType(O, name)).pointer.child; + const want = @typeInfo(Want).@"fn"; + const have = @typeInfo(@TypeOf(f)).@"fn"; + if (want.param_types.len != have.param_types.len) @compileError(name ++ ": not as many parameters as Ops says"); + inline for (want.param_types, have.param_types, 0..) |w, h, i| { + if (w.? != handleOf(h.?)) @compileError(std.fmt.comptimePrint("{s}: parameter {d} is {s}, Ops says {s}", .{ name, i, @typeName(h.?), @typeName(w.?) })); + } + // A narrower error set is the same function pointer: an error is its + // number whatever set names it. + const W = want.return_type.?; + const H = have.return_type.?; + const same_result = switch (@typeInfo(W)) { + // Ops says anyerror: any error set of the same payload. + .error_union => |we| switch (@typeInfo(H)) { + .error_union => |he| we.payload == handleOf(he.payload) and within(he.error_set, we.error_set), + else => false, + }, + else => W == handleOf(H), + }; + if (!same_result) @compileError(name ++ ": returns " ++ @typeName(H) ++ ", Ops says " ++ @typeName(W) ++ missingFrom(H, W)); + return @ptrCast(&f); +} + +test { + _ = &ops; + _ = terminal_; + _ = pager; + _ = screen_state_; +} diff --git a/src/term/terminal.zig b/src/term/terminal.zig index 85ac859d..fff491f6 100644 --- a/src/term/terminal.zig +++ b/src/term/terminal.zig @@ -1,27 +1,20 @@ -//! A terminal pane: its VT emulator, prompt rows, the edit overlay -//! typed over shell rows, and the Filter that recolours output to the theme. -const panes = @import("../panes.zig"); +//! 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 src/term/term.zig's `ops`. const std = @import("std"); -const pardes = @import("../pardes.zig"); -const config = @import("../config.zig"); -const Pardes = pardes.Pardes; -const Surface = pardes.Surface; -const modal = @import("../modal.zig"); -const tracy = @import("../tracy.zig"); -const tagline = @import("../tagline.zig"); -const Key = pardes.Key; -const Pane = panes.Pane; -const Term = @import("../Term.zig"); -const BodyWalk = @import("../body_layer.zig").BodyWalk; +const plain = @import("plain"); +const Key = plain.Key; +const Term = plain.term; const screen_state = @import("screen_state.zig"); -const EditText = panes.EditText; -const File = panes.File; const ghostty_vt = @import("ghostty-vt"); - -const EditBuffer = panes.Text.EditBuffer; -const Snapshot = panes.Text.Snapshot; -const history_max = panes.Text.history_max; +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 (src/term/echo.zig). @@ -41,7 +34,7 @@ pub const prompt_aid = "pardes"; /// and a stray `133;D` in some file being printed all pass it by. pub const MarkedHandler = struct { inner: ghostty_vt.TerminalStream.Handler, - phase: enum { none, prompt, input, running } = .none, + 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 @@ -66,7 +59,7 @@ pub const MarkedHandler = struct { lost: bool = false, /// The newest command to end: which one, and its status if given. - finished: ?struct { seq: u32, status: ?i32 } = null, + finished: ?Term.Prompt.Finished = null, const Action = ghostty_vt.TerminalStream.Action; @@ -206,24 +199,26 @@ pub const State = struct { /// rows sent them for it (Screens.fill) are of that grid's numbering. resize_to: ?struct { cols: u16, rows: u16 } = null, - /// The emulator as its program has made it, for the replay digest - /// (src/walk.zig): the active screen's text, how much history is above - /// it and where the view is, the cursor, the answers not yet written. - /// Not its pages (their addresses are its own), nor the history's text - /// (the screen's was all of it once, and a session's digest is taken - /// every step), nor the kitty images, whose media is read off the host: - /// a replica's terminal is the authority's screen state from phase 5 - /// on (docs/next-daemon.md). - pub fn digest(s: *const State, h: *pardes.walk.Hasher) void { - // Under screen-state terminals the emulator is the authority's, and - // a replica's is what the last delta made it: compared as screens - // (test/replicas.zig), not step by step. - if (pardes.tape.screenState()) return; - s.digestScreen(h, true); + /// The stream over the emulator, its answers to the program and its + /// size reports routed here, PNG decoded: what `create` and a dump's + /// load both do once the emulator is in place. + fn wire(s: *State) void { + s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa }); + s.stream.handler.inner.effects.write_pty = ptyReport; + s.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; + s.stream.handler.inner.effects.size = ptySize; + if (comptime images_enabled) TerminalImages.installPngDecoder(); } +}; - /// `view`: where its view is too (a replica's speculation may move it). - pub fn digestScreen(s: *const State, h: *pardes.walk.Hasher, view: bool) void { +/// The emulator as its program has made it, for the replay digest (the +/// core's Term.State.digest, src/walk.zig): the active screen's text, how +/// much history is above it and, with `view`, where the view is, the +/// cursor, the answers not yet written. Not its pages (their addresses are +/// its own), nor the history's text (the screen's was all of it once, and +/// a session's digest is taken every step), nor the kitty images, whose +/// media is read off the host. +pub fn digest(s: *const State, h: *std.hash.Wyhash, view: bool) void { const screen = s.vt.screens.active; const sb = screen.pages.scrollbar(); const cur = screen.cursor; @@ -232,192 +227,128 @@ pub const State = struct { inline for (facts) |fact| h.update(std.mem.asBytes(&fact)); h.update(s.reply[0..s.reply_len]); var buf: [4096]u8 = undefined; - var text: std.Io.Writer.Hashing(pardes.walk.Hasher) = .initHasher(h.*, &buf); + 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; } - /// What the dump keeps of a terminal beside its emulator, by name as - /// every dump is (src/walk.zig). - const Parts = struct { - reply: []const u8 = "", - reply_dropped: u32 = 0, - mouse_cell: ?ghostty_vt.Coordinate = null, - petscii: bool = false, - /// The view's top row, counted from the top of the history. - view: usize = 0, - phase: @FieldType(MarkedHandler, "phase") = .none, - started: u32 = 0, - prompts: u32 = 0, - declined: u32 = 0, - continuation: bool = false, - lost: bool = false, - finished: @FieldType(MarkedHandler, "finished") = null, - out_start: ?ghostty_vt.Coordinate = null, - out_end: ?ghostty_vt.Coordinate = null, - }; +fn pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?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 pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?ghostty_vt.Coordinate { - const pin = slot orelse return null; - const screen = s.vt.screens.get(.primary) orelse return null; - return (screen.pages.pointFromPin(.screen, pin.*) orelse return null).screen; - } +fn coordinate(at: ?Term.Parts.Coordinate) ?ghostty_vt.Coordinate { + const c = at orelse return null; + return .{ .x = c.x, .y = c.y }; +} - /// The dump's: ghostty's snapshot of the emulator (both screens, their - /// history, styles, links and kitty images), then `Parts`. A sequence - /// its program had begun and not ended is not kept: the snapshot is at - /// the ground state. - pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { - const h = &s.stream.handler; - const parts: Parts = .{ - .reply = s.reply[0..s.reply_len], - .reply_dropped = s.reply_dropped, - .mouse_cell = s.mouse_cell, - .petscii = if (comptime images_enabled) s.images.petscii else false, - .view = s.vt.screens.active.pages.scrollbar().offset, - .phase = h.phase, - .started = h.started, - .prompts = h.prompts, - .declined = h.declined, - .continuation = h.continuation, - .lost = h.lost, - .finished = h.finished, - .out_start = s.pinAt(h.out_start), - .out_end = s.pinAt(h.out_end), - }; - const bytes = try pardes.walk.save(Parts, gpa, &parts); - defer gpa.free(bytes); - try w.writeAll(std.mem.asBytes(&@as(u64, bytes.len))); - try w.writeAll(bytes); - // A join's (dump.zig `dumpJoin`): its size alone, an emulator made - // afresh there, which its first delta replaces. - if (pardes.dump.slim_terminals) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows })); - try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground }); - } +/// What the dump keeps of it beside its emulator (the core's +/// Term.State.dumpWrite writes it by name, as every dump is). +pub fn parts(s: *const State) Term.Parts { + const h = &s.stream.handler; + return .{ + .reply = s.reply[0..s.reply_len], + .reply_dropped = s.reply_dropped, + .mouse_cell = if (s.mouse_cell) |c| .{ .x = c.x, .y = c.y } else null, + .petscii = if (comptime images_enabled) s.images.petscii else false, + .view = s.vt.screens.active.pages.scrollbar().offset, + .phase = h.phase, + .started = h.started, + .prompts = h.prompts, + .declined = h.declined, + .continuation = h.continuation, + .lost = h.lost, + .finished = h.finished, + .out_start = pinAt(s, h.out_start), + .out_end = pinAt(s, h.out_end), + }; +} - /// What `dumpRead` made, freed: a load that failed after it. - pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void { - if (comptime images_enabled) s.images.deinit(gpa); - s.stream.deinit(); - s.vt.deinit(gpa); - } +/// Its emulator as the dump keeps it: ghostty's snapshot (both screens, +/// their history, styles, links and kitty images). A sequence its program +/// had begun and not ended is not kept: the snapshot is at the ground +/// state. `slim`, a join's dump (dump.zig `dumpJoin`): its size alone, an +/// emulator made afresh there, which its first delta replaces. +pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) !void { + if (slim) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows })); + try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground }); +} - /// `dumpWrite`'s back into `out`, a new State, as `create` makes one. - pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void { - if (bytes.len < 8) return error.EndOfDump; - const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump; - if (bytes.len - 8 < n) return error.EndOfDump; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const parts = try pardes.walk.load(Parts, arena.allocator(), bytes[8..][0..n], null); - var reader: std.Io.Reader = .fixed(bytes[8 + n ..]); - if (reader.buffer.len == 4) { - const size = std.mem.bytesToValue([2]u16, bytes[8 + n ..][0..4]); - out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined }; - } else { - var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ - .max_continuation_bytes = 0, - .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, - }); - defer decoded.deinit(gpa); - out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; - } - if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { - if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); +/// `snapshot`'s bytes and `parts` back into a new terminal, as `open` +/// makes one. +pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) !*State { + const out = try gpa.create(State); + errdefer gpa.destroy(out); + var reader: std.Io.Reader = .fixed(bytes); + if (reader.buffer.len == 4) { + const size = std.mem.bytesToValue([2]u16, bytes[0..4]); + out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined }; + } else { + var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ + .max_continuation_bytes = 0, + .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, + }); + defer decoded.deinit(gpa); + out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; + } + if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { + if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); + }; + out.wire(); + const reply = saved.reply[0..@min(saved.reply.len, out.reply.len)]; + @memcpy(out.reply[0..reply.len], reply); + out.reply_len = @intCast(reply.len); + out.reply_dropped = saved.reply_dropped; + out.mouse_cell = coordinate(saved.mouse_cell); + out.images = if (images_enabled) .{ .petscii = saved.petscii } else {}; + const h = &out.stream.handler; + h.phase = saved.phase; + h.started = saved.started; + h.prompts = saved.prompts; + h.declined = saved.declined; + h.continuation = saved.continuation; + h.lost = saved.lost; + h.finished = saved.finished; + if (out.vt.screens.get(.primary)) |screen| { + inline for (.{ .{ "out_start", saved.out_start }, .{ "out_end", saved.out_end } }) |pair| if (coordinate(pair[1])) |at| { + if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null; }; - out.wire(); - const reply = parts.reply[0..@min(parts.reply.len, out.reply.len)]; - @memcpy(out.reply[0..reply.len], reply); - out.reply_len = @intCast(reply.len); - out.reply_dropped = parts.reply_dropped; - out.mouse_cell = parts.mouse_cell; - out.images = if (images_enabled) .{ .petscii = parts.petscii } else {}; - const h = &out.stream.handler; - h.phase = parts.phase; - h.started = parts.started; - h.prompts = parts.prompts; - h.declined = parts.declined; - h.continuation = parts.continuation; - h.lost = parts.lost; - h.finished = parts.finished; - if (out.vt.screens.get(.primary)) |screen| { - inline for (.{ .{ "out_start", parts.out_start }, .{ "out_end", parts.out_end } }) |pair| if (pair[1]) |at| { - if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null; - }; - } - const screen = out.vt.screens.active; - const bottom = screen.pages.scrollbar().offset; - screen.scroll(.{ .delta_row = @as(isize, @intCast(parts.view)) - @as(isize, @intCast(bottom)) }); } + const screen = out.vt.screens.active; + const bottom = screen.pages.scrollbar().offset; + screen.scroll(.{ .delta_row = @as(isize, @intCast(saved.view)) - @as(isize, @intCast(bottom)) }); + return out; +} - /// The stream over the emulator, its answers to the program and its - /// size reports routed here, PNG decoded: what `create` and a dump's - /// load both do once the emulator is in place. - fn wire(s: *State) void { - s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa }); - s.stream.handler.inner.effects.write_pty = ptyReport; - s.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; - s.stream.handler.inner.effects.size = ptySize; - if (comptime images_enabled) TerminalImages.installPngDecoder(); - } -}; +/// The 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; -const FilterPaletteKey = struct { - bg: GColor.RGB, - fg: GColor.RGB, - base: [16]GColor.RGB, -}; - -pub const FilterPalette = LivePalette; - -const LivePalette = struct { - key: ?FilterPaletteKey = null, - colors: GColor.Palette = GColor.default, +// Projected colors below this contrast use the theme's more legible anchor. +pub const min_contrast: f64 = 1.5; - fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { - const bg = asGhostRgb(theme.bg orelse theme.tag_bg); - const fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var base: [16]GColor.RGB = undefined; - if (theme.palette) |palette| { - for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); - } else { - const synthesized = [16][3]u8{ - theme.bg orelse theme.tag_bg, - theme.kw, - theme.str, - theme.num, - theme.box, - theme.sel_bg, - theme.comment, - theme.fg orelse theme.tag_fg, - theme.lineno, - theme.kw, - theme.str, - theme.num, - theme.scroll_thumb, - theme.sel_fg, - theme.tag_fg, - theme.fg orelse theme.tag_fg, - }; - for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); - } - - const wanted: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; - if (self.key) |old| if (std.meta.eql(old, wanted)) return &self.colors; - - var seed = GColor.default; - for (base, 0..) |rgb, i| seed[i] = rgb; - self.colors = GColor.generate256Color(seed, .empty, bg, fg, false); - self.key = wanted; - return &self.colors; - } -}; +/// The theme's 256 colours as the filter maps onto them (ghostty's +/// `generate256Color` over the theme's sixteen), made again only when the +/// theme's are not the ones `cache` was made of. +pub fn filterPalette(cache: *FilterPalette, ink: *const Ink) *const [256][3]u8 { + const wanted: FilterPalette.Key = .{ .bg = ink.bg orelse ink.tag_bg, .fg = ink.fg orelse ink.tag_fg, .base = ink.base }; + if (cache.key) |old| if (std.meta.eql(old, wanted)) return &cache.colors; + var seed = GColor.default; + for (ink.base, 0..) |rgb, i| seed[i] = asGhostRgb(rgb); + const colors = GColor.generate256Color(seed, .empty, asGhostRgb(wanted.bg), asGhostRgb(wanted.fg), false); + for (&cache.colors, colors) |*dst, src| dst.* = asTriple(src); + cache.key = wanted; + return &cache.colors; +} -fn asGhostRgb(rgb: [3]u8) GColor.RGB { +pub fn asGhostRgb(rgb: [3]u8) GColor.RGB { return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; } @@ -448,6 +379,7 @@ pub fn grid(state: ?*const State) Term.Grid { .cursor_y = @intCast(screen.cursor.y), .cursor_visible = s.vt.modes.get(.cursor_visible), .view = if (screen.pages.viewport == .active) null else sb.offset, + .cols = screen.pages.cols, }; } @@ -488,21 +420,64 @@ pub fn takeMarks(state: *State, bytes: []const u8) void { /// What `peer` is owed of it, a delta against what it was sent (with the /// marks of its prompt cycle), onto `out`; false when it has it already. -pub fn encode(state: *State, enc: *screen_state.Encoder, track: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool { +pub fn encode(state: *State, enc: *screen_state.Encoder, tr: *screen_state.Track, peer: *screen_state.Peer, out: *std.Io.Writer) !bool { var marks: [marks_len]u8 = undefined; - return screen_state.encode(enc, track, peer, &state.vt, state.changes, marksOf(state, &marks), out); + return screen_state.encode(enc, tr, peer, &state.vt, state.changes, marksOf(state, &marks), out); } /// Its rows `lo` to `hi` (absolute), as a replica holding them as holes /// is sent them. -pub fn encodeRows(state: *State, enc: *screen_state.Encoder, track: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { - return screen_state.encodeRows(enc, track, &state.vt, lo, hi, out); +pub fn encodeRows(state: *State, enc: *screen_state.Encoder, tr: *screen_state.Track, lo: u64, hi: u64, out: *std.Io.Writer) !void { + return screen_state.encodeRows(enc, tr, &state.vt, lo, hi, out); +} + +/// What a session's authority keeps to encode its terminals for its +/// peers, and what it keeps of one terminal for them: made and freed. +pub fn encoder(gpa: std.mem.Allocator) !*screen_state.Encoder { + const e = try gpa.create(screen_state.Encoder); + e.* = .init(gpa); + return e; +} + +pub fn encoderFree(e: *screen_state.Encoder) void { + const gpa = e.gpa; + e.deinit(); + gpa.destroy(e); +} + +pub fn track(gpa: std.mem.Allocator) !*screen_state.Track { + const t = try gpa.create(screen_state.Track); + t.* = .init(gpa); + return t; +} + +/// A replica's side of one terminal: made, freed, where its active area +/// begins, and the history rows `lo..hi` it does not hold. +pub fn replica(gpa: std.mem.Allocator) !*screen_state.Replica { + const r = try gpa.create(screen_state.Replica); + r.* = .{}; + return r; +} + +pub fn replicaFree(r: *screen_state.Replica, gpa: std.mem.Allocator) void { + r.deinit(gpa); + gpa.destroy(r); +} + +pub fn replicaTop(r: *const screen_state.Replica) u64 { + return r.top; +} + +pub fn missing(r: *const screen_state.Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void { + return r.missing(lo, hi, out, gpa); } /// What `track` kept of its versions, freed; `state` null when its pane is /// gone with the emulator. -pub fn untrack(track: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void { - track.deinit(gpa, if (state) |s| &s.vt else null); +/// A peer's track of it let go, and freed (`state` null: it is gone). +pub fn untrack(t: *screen_state.Track, gpa: std.mem.Allocator, state: ?*State) void { + t.deinit(gpa, if (state) |s| &s.vt else null); + gpa.destroy(t); } /// Whether a step read its rows since `clearRead` (`markRead`). @@ -516,7 +491,7 @@ pub fn clearRead(state: *State) void { /// A replica's terminal takes its authority's delta (and the marks riding /// it); error.BaseMismatch when it is against a state not held here. -pub fn apply(state: *State, rep: *screen_state.Replica, bytes: []const u8) !screen_state.Replica.Applied { +pub fn apply(state: *State, rep: *screen_state.Replica, bytes: []const u8) !Term.Applied { const applied = try rep.apply(state.gpa, terminalIo(), &state.vt, bytes); takeMarks(state, applied.extra); return applied; @@ -543,8 +518,6 @@ pub fn blank(state: *State, rep: *const screen_state.Replica, lo: u64, hi: u64) rep.blank(&state.vt, lo, hi); } -const authorityOnly = pardes.tape.authorityOnly; - /// Its view to row `at` of its history (from the top), or onto its output. pub fn viewTo(state: *State, at: ?usize) void { state.vt.screens.active.scroll(if (at) |row| .{ .row = row } else .active); @@ -846,8 +819,8 @@ fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { /// `rows` where it is after the read and in `erased` whether the program /// erased it (a negative row passes through untouched). With nothing /// tracked the read is parsed and nothing more. -pub fn feed(state: *State, bytes: []const u8, track: []const i32, rows: []i32, erased: []bool) Term.Told { - if (track.len == 0) { +pub fn feed(state: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Term.Told { + if (tracked.len == 0) { ingest(state, bytes); return .{ .rows = rows[0..0], .erased = erased[0..0], .cleared = false, .alive = true, .failed = false }; } @@ -857,14 +830,14 @@ pub fn feed(state: *State, bytes: []const u8, track: []const i32, rows: []i32, e const pages = &screens.active.pages; var failed = false; var room: [512]RowPin = undefined; - const pins = if (track.len <= room.len) room[0..track.len] else state.gpa.alloc(RowPin, track.len) catch { + 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..track.len], track); - @memset(erased[0..track.len], false); - return .{ .rows = rows[0..track.len], .erased = erased[0..track.len], .cleared = false, .alive = true, .failed = true }; + @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 (track.len > room.len) state.gpa.free(pins); - for (pins, track) |*pin, row| pin.* = trackRow(pages, row, &failed); + 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; @@ -872,12 +845,12 @@ pub fn feed(state: *State, bytes: []const u8, track: []const i32, rows: []i32, e const cleared = state.vt.flags.dirty.clear; // RIS can destroy the alternate screen and every pin it owned. const alive: ?*ghostty_vt.PageList = if (screens.generation(active) == generation) pages else null; - for (pins, rows[0..track.len], erased[0..track.len]) |pin, *row, *gone| { + 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..track.len], .erased = erased[0..track.len], .cleared = cleared, .alive = alive != null, .failed = failed }; + 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 @@ -1053,16 +1026,6 @@ pub fn promptMoves(state: *State, row: i32, col: i32) ?Term.Moves { /// What LEAVING raw tty mode does to one prompt row, decided from its cells /// alone: OSC 133 prompt cells are hidden in normal mode, what was typed at /// them stays. -const PromptCut = union(enum) { - /// show the row exactly as ghostty dumped it - keep, - /// show nothing at all - blank, - /// drop this many leading COLUMNS — the prompt — and keep the rest, which - /// is what was typed at it - cut: usize, -}; - fn promptCut(pin: ghostty_vt.Pin) PromptCut { const cells = pin.cells(.all); var cols: usize = 0; @@ -1075,18 +1038,22 @@ fn promptCut(pin: ghostty_vt.Pin) PromptCut { return .{ .cut = cols }; } -/// How many of the bytes `raw` of its row `row` (from the top of the -/// history), as the emulator dumps it, are the prompt the row starts with. -pub fn promptPrefix(state: ?*State, row: i32, raw: []const u8) usize { - if (row < 0) return 0; - const s = state orelse return 0; - const pin = s.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; - if (pin.rowAndCell().row.semantic_prompt == .none) return 0; - return switch (promptCut(pin)) { - .keep => 0, - .blank => raw.len, - .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), - }; +/// 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 +/// (src/echo.zig): null off it. +pub fn echoCell(state: *const State, x: u16, y: u16) ?Term.EchoCell { + if (y >= state.vt.rows) return null; + const ci = state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return null; + return .{ .cp = ci.cell.codepoint(), .input = ci.cell.semantic_content == .input, .style = ci.cell.style_id }; } fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { @@ -1127,6 +1094,31 @@ fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { 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 (src/ansi.zig). +pub fn editRows(state: *State, arena: std.mem.Allocator, first: usize, count: usize) ![]const []const u8 { + const screen = state.vt.screens.active; + const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return error.NoRow; + const br = screen.pages.pin(.{ .screen = .{ + .x = screen.pages.cols - 1, + .y = @intCast(first + count - 1), + } }) orelse return error.NoRow; + var output: std.Io.Writer.Allocating = .init(arena); + try screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }); + const shell = try arena.alloc([]const u8, count); + var raw = std.mem.splitScalar(u8, output.written(), '\n'); + var pins = tl.rowIterator(.right_down, br); + for (shell) |*row| { + const text = raw.next() orelse ""; + row.* = if (pins.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text + else + text; + } + return shell; +} + /// A step read its rows (its history too): a replica replaying the step /// must hold them (`State.read`). pub fn markRead(state: *State) void { @@ -1202,247 +1194,43 @@ pub fn viewport(state: *State, arena: std.mem.Allocator, cut: bool) ![]const []c return vp; } -// Match surviving edit-buffer rows to their original terminal styles. -const EditAnchors = struct { - /// the buffer's own text, walked in order: a line the VIEWPORT skipped still - /// consumes the row it came from, so the lines below it stay aligned - text: []const u8 = &.{}, - at: usize = 0, - shell: []const []const u8 = &.{}, - /// the covered span, absolute grid rows, as `[first, end)` - first: usize = 0, - end: usize = 0, - lines: usize = 0, - /// the line `at` names, and the first row still unclaimed - idx: usize = 0, - cursor: usize = 0, - budget: usize = 0, - active: bool = false, - - fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { - if (o.rows <= 0 or o.row < 0) return .{}; - const first: usize = @intCast(o.row); - const screen = pane.terminal.?.vt.screens.active; - const total = screen.pages.scrollbar().total; - if (first >= total) return .{}; - const covered: usize = @intCast(o.rows); - const count = @min(covered, total - first); - const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; - const br = screen.pages.pin(.{ .screen = .{ - .x = screen.pages.cols - 1, - .y = @intCast(first + count - 1), - } }) orelse return .{}; - const arena = p.scratch.allocator(); - var output: std.Io.Writer.Allocating = .init(arena); - screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; - const shell = arena.alloc([]const u8, count) catch return .{}; - var raw = std.mem.splitScalar(u8, output.written(), '\n'); - var pins = tl.rowIterator(.right_down, br); - for (shell) |*row| { - const text = raw.next() orelse ""; - row.* = if (pins.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text - else - text; - } - const lines = std.mem.count(u8, o.text, "\n") + 1; - return .{ - .text = o.text, - .shell = shell, - .first = first, - .end = first + count, - .lines = lines, - .cursor = first, - .budget = covered + 4 * lines, - .active = true, - }; - } - - fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { - if (!a.active or idx >= a.lines) return null; - var found: ?Anchor = null; - while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); - return found; - } - - fn nextLine(a: *EditAnchors) ?[]const u8 { - if (a.at > a.text.len) return null; - const rest = a.text[a.at..]; - if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { - a.at += n + 1; - return rest[0..n]; - } - // The last line has no terminator; one past the end ends the walk. - a.at = a.text.len + 1; - return rest; - } - - /// Where this line still stands over the grid, if anywhere. - fn claim(a: *EditAnchors, line: []const u8) ?Anchor { - const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; - var k = a.cursor; - while (k < end) : (k += 1) { - if (a.budget == 0) return null; - a.budget -= 1; - if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; - a.cursor = k + 1; - return .{ .row = @intCast(k) }; - } - if (a.cursor >= a.end) return null; - const shell = a.shell[a.cursor - a.first]; - var p: usize = 0; - while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; - var s: usize = 0; - const room = @min(line.len, shell.len) - p; - while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; - if (p + s == 0) return null; - if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; - const row = a.cursor; - if (s > 0 or p >= shell.len) a.cursor += 1; - return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; - } -}; - -const Anchor = struct { - /// the row, absolute while it comes from `EditAnchors`, viewport once - /// `recolorAnsi` has subtracted the walk's offset - row: i32, - prefix: usize = std.math.maxInt(usize), - suffix: usize = 0, - /// the row's own dumped length — what the suffix is measured from on the - /// GRID side, where the edit may have changed the byte count - shell_len: usize = 0, - - fn whole(an: Anchor) bool { - return an.prefix == std.math.maxInt(usize); - } -}; - -pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { - // No emulator, no ANSI cells: the whole pass — and the 256-colour theme - // projection behind it — is compiled out. - if (pane.terminal == null) return; - const body_y = p.bodyTop(pane, r); - var filtered_storage: FilteredColors = undefined; - const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { - const tz_filter = tracy.zone(@src(), "filterInit"); - defer tz_filter.end(); - filtered_storage = FilteredColors.init(p, &pane.terminal.?.vt); - break :blk &filtered_storage; +/// Its view's rows as cells, for the core's paint (Term.paint, the core's +/// src/ansi.zig): `rows.len` rows of `cols` cells 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, 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 = pane.terminal.?.vt.modes.get(.reverse_colors); - const pages = &pane.terminal.?.vt.screens.active.pages; - const vp_rows: i32 = @intCast(grid(pane.terminal).len); - // Which buffer lines the user has not actually changed, so a row swallowed - // by a growing buffer keeps the colour it still stands over. - var anchors: ?EditAnchors = null; - var walk: BodyWalk = .init(pane); - var lines = std.mem.splitScalar(u8, body, '\n'); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - // Before any early exit below, or the lines fall out of step with rows. - const text = lines.next() orelse ""; - const anchor: Anchor = switch (row) { - .edit => |e| blk: { - if (anchors == null) anchors = .init(p, pane, pane.ovl.?); - var an = anchors.?.shellRow(e.idx) orelse continue; - an.row -= walk.goff; - break :blk an; - }, - .grid => |v| .{ .row = v }, - }; - const vi = anchor.row; - if (vi < 0 or vi >= vp_rows) continue; + const scnm = state.vt.modes.get(.reverse_colors); + const pages = &state.vt.screens.active.pages; + for (rows, 0..) |*row, vi| { + row.* = .{ .prompt = null, .placeholder = false, .len = 0 }; const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { - if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; - break :cut switch (promptCut(row_pin)) { - .keep => 0, - // Blanked end to end: the row shows nothing of the grid, so - // projecting the prompt's own colours onto it would be a lie. - .blank => continue, - .cut => |n| std.math.cast(u16, n) orelse continue, - }; - }; - if (cut > 0 and text.len == 0) continue; - var at: usize = 0; - var sc: u16 = 0; - var gc: u16 = cut; - var sb: usize = 0; - const mine_from = @min(anchor.prefix, text.len); - const mine_to = text.len - @min(anchor.suffix, text.len); - var crossed = false; - while (at < text.len and sc < tw) { - const stop = modal.nextGrapheme(text, at); - if (stop <= at) break; - const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; - if (at >= mine_from and at < mine_to) { - sc += span; - at = stop; - continue; - } - if (at >= mine_to and !crossed) { - crossed = true; - const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); - while (sb < upto) { - const ci = cellAt(pages, row_pin, gc) orelse break; - sb += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - } - } - const want = stop - at; - // Consume every cell that contributed to this grapheme. A cluster - // ghostty split across several cells is still ONE printed glyph. - var covered: usize = 0; - var style: ?pardes.CellStyle = null; - while (covered < want) { - const ci = cellAt(pages, row_pin, gc) orelse break; - if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) - style = cellStyle(p, ci, filtered, scnm); - covered += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - // A spacer contributes no bytes; without this the loop would - // spin on a row that ends in one. - if (covered == 0 and gc >= pane.cols) break; - } - while (cellAt(pages, row_pin, gc)) |t| { - if (t.cell.wide != .spacer_tail) break; - gc = std.math.add(u16, gc, 1) catch break; - } - if (style) |st| for (0..span) |k| { - const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = st; - }; - sb += covered; - sc += span; - at = stop; - } - var tail: ?pardes.CellStyle = null; - if (anchor.whole() or anchor.suffix > 0) { - while (sc < tw) { - const ci = cellAt(pages, row_pin, gc) orelse break; - gc = std.math.add(u16, gc, 1) catch break; - if (ci.cell.wide == .spacer_tail) continue; - const cell = s.at(tx + sc, body_y + vr); - sc += 1; - const style = cellStyle(p, ci, filtered, scnm); - tail = style; - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - } - if (tail) |style| while (sc < tw) : (sc += 1) { - const cell = s.at(tx + sc, body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; + 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; } } @@ -1459,15 +1247,15 @@ fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghost // 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(pardes.CellStyle, "ul")).@"enum".field_names, 0..) |name, i| + for (@typeInfo(@FieldType(plain.CellStyle, "ul")).@"enum".field_names, 0..) |name, i| if (@backingInt(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's"); } -fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { +fn cellStyle(ink: *const Ink, ci: ghostty_vt.PageList.Cell, filtered: ?*Filter, scnm: bool) plain.CellStyle { const style = ci.style(); - var cs: pardes.CellStyle = .{ - .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), - .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), + 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, @@ -1478,7 +1266,7 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor .ul = @fromBackingInt(@intCast(@backingInt(style.flags.underline))), }; if (filtered == null) switch (ci.cell.content_tag) { - .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), + .bg_color_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 } }; @@ -1488,152 +1276,138 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor return cs; } -fn asPardesColor(rgb: GColor.RGB) pardes.Color { +pub fn asPardesColor(rgb: GColor.RGB) plain.Color { return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; } -/// A program's colours mapped to the theme (Filter): a terminal's cells, or -/// a +Pager's spans (`vt` null, the program's palette xterm's own). -pub const FilteredColors = struct { - source: GColor.Palette, - target: *const GColor.Palette, - theme_bg: GColor.RGB, - theme_fg: GColor.RGB, - dynamic_bg: ?GColor.RGB, - dynamic_fg: ?GColor.RGB, - default_bg: GColor.RGB, - /// What a foreground too near `default_bg` becomes instead. - fallback_fg: GColor.RGB, - default_bg_luminance: f64, - fg_for_palette: [256]pardes.Color = undefined, - bg_for_palette: [256]pardes.Color = undefined, - /// The two answers for a cell that names no colour of its own. - fg_default: pardes.Color = undefined, - bg_default: pardes.Color = undefined, - cache_rgb: [256]GColor.RGB = undefined, - cache_key: [256]u8 = undefined, - cache_valid: [256]bool = @splat(false), - - pub fn init(p: *Pardes, vt: ?*const ghostty_vt.Terminal) FilteredColors { - var source = GColor.default; - if (vt) |t| { - for (&source, 0..) |*rgb, i| - rgb.* = t.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; - } - const theme = p.theme(); - var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); - var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null; - var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null; - if (vt != null and vt.?.modes.get(.reverse_colors)) { - std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); - std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); - } - var self: FilteredColors = .{ - .source = source, - .target = p.tty_filter_palette.get(theme), - .theme_bg = theme_bg, - .theme_fg = theme_fg, - .dynamic_bg = dynamic_bg, - .dynamic_fg = dynamic_fg, - .default_bg = theme_bg, - .fallback_fg = theme_fg, - .default_bg_luminance = luminanceOf(theme_bg), - }; - if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); - self.default_bg_luminance = luminanceOf(self.default_bg); - if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) - self.fallback_fg = self.theme_bg; +fn asTriple(rgb: GColor.RGB) [3]u8 { + return .{ rgb.r, rgb.g, rgb.b }; +} - self.fg_default = asPardesColor(self.legible( - if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, - )); - self.bg_default = asPardesColor(self.default_bg); - for (&self.source, 0..) |current, i| { - const idx: u8 = @intCast(i); - const mapped = self.paletteRgb(idx, current); - self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); - self.bg_for_palette[idx] = asPardesColor(mapped); - } - return self; +/// 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.*; } - - fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { - return switch (style.fg_color) { - .none => self.fg_default, - .palette => |idx| self.fg_for_palette[idx], - .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ - .default = self.dynamic_fg orelse self.theme_fg, - .palette = &self.source, - .bold = null, - })))), - }; + var theme_bg = asGhostRgb(ink.bg orelse ink.tag_bg); + var theme_fg = asGhostRgb(ink.fg orelse ink.tag_fg); + var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null; + var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null; + if (vt != null and vt.?.modes.get(.reverse_colors)) { + std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); + std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); } + var self: Filter = .{ + .target = filterPalette(palette, ink), + .theme_bg = asTriple(theme_bg), + .theme_fg = asTriple(theme_fg), + .default_bg = asTriple(theme_bg), + .fallback_fg = asTriple(theme_fg), + .default_bg_luminance = luminanceOf(theme_bg), + .fg_for_palette = undefined, + .bg_for_palette = undefined, + .fg_default = undefined, + .bg_default = undefined, + }; + var default_bg = theme_bg; + if (dynamic_bg) |rgb| default_bg = keyedRgb(&self, rgb); + self.default_bg = asTriple(default_bg); + self.default_bg_luminance = luminanceOf(default_bg); + if (theme_bg.contrast(default_bg) > theme_fg.contrast(default_bg)) + self.fallback_fg = asTriple(theme_bg); - fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { - switch (cell.content_tag) { - .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], - .bg_color_rgb => {}, - else => switch (style.bg_color) { - .none => return self.bg_default, - .palette => |idx| return self.bg_for_palette[idx], - .rgb => {}, - }, - } - // Truecolour, from either the cell or its style. - return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); + 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; +} - /// A +Pager span's colour (Term.page), as `fg` and `bg` map a cell's. - pub fn spanColor(self: *FilteredColors, color: pardes.Color, is_bg: bool) pardes.Color { - return switch (color) { - .default => color, - .index => |idx| if (is_bg) self.bg_for_palette[idx] else self.fg_for_palette[idx], - .rgb => |rgb| blk: { - const keyed = self.keyedRgb(asGhostRgb(rgb)); - break :blk asPardesColor(if (is_bg) keyed else self.legible(keyed)); - }, - }; - } +/// 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 legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { - if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= - config.tty_filter_min_contrast) return rgb; - return self.fallback_fg; - } +fn 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 paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { - if (current.eql(GColor.default[idx])) return self.target[idx]; - return self.keyedRgb(current); +fn 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).?)); +} - fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { - return self.target[self.nearestKey(rgb)]; - } +/// 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)); + }, + }; +} - fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { - const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; - const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); - if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) - return self.cache_key[slot]; +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); +} - 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); - } +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] = rgb; - self.cache_key[slot] = best; - self.cache_valid[slot] = true; - return best; } -}; + 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); @@ -1648,7 +1422,7 @@ const channel_luminance: [256]f64 = blk: { break :blk table; }; -fn luminanceOf(rgb: GColor.RGB) f64 { +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]; @@ -1668,23 +1442,17 @@ fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { return @intCast(dr * dr + dg * dg + db * db); } -pub fn palColor(p: *Pardes, idx: u8) pardes.Color { - if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; - return .{ .index = idx }; -} - -fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { +fn ghostColor(ink: *const Ink, color: ghostty_vt.Style.Color, is_bg: bool) plain.Color { return switch (color) { .none => blk: { - const t = if (is_bg) p.theme().bg else p.theme().fg; + const t = if (is_bg) ink.bg else ink.fg; break :blk if (t) |c| .{ .rgb = c } else .default; }, - .palette => |idx| palColor(p, idx), + .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 { @@ -1714,302 +1482,30 @@ pub fn hasImages(maybe: ?*const State) bool { return state.vt.screens.active.kitty_images.images.count() > 0; } -/// Draw the pane's kitty graphics images over its body rows (after the -/// rows and their colours: placeholder cells are blanked here). -pub fn drawImages(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { +/// 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 state = pane.terminal orelse return; const screen = state.vt.screens.active; - cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); - // A body taller than this draws its images on the rows that fit. var rows_of: [1024]?u16 = undefined; - const vp_rows: usize = @min(grid(state).len, rows_of.len); - @memset(rows_of[0..vp_rows], null); + const vp_rows = @min(at.rows_of.len, rows_of.len); var any_placeholder = false; - var walk: BodyWalk = .init(pane); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - const vi = switch (row) { - .grid => |v| v, - .edit => continue, - }; - if (vi < 0 or vi >= vp_rows) continue; + for (rows_of[0..vp_rows], at.rows_of[0..vp_rows], 0..) |*slot, body_row, vi| { + slot.* = null; + const vr = body_row orelse continue; const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; const flags = row_pin.rowAndCell().row; - // A prompt row outside tty mode is cut or hidden: its columns are - // not the grid's. - if (pane.body.mode != .tty and flags.semantic_prompt != .none) continue; + if (!at.tty_mode and flags.semantic_prompt != .none) continue; any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; - rows_of[@intCast(vi)] = vr; + 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(p, s, &state.vt, @intCast(id), pane.serial, tx, body_y, @min(tw, pane.cols), rows_of[0..vp_rows]); -} - -/// Every byte the core wrote to each pane's pty since the last call, `\n` -/// between panes' shares: "0:<bytes>\n1:<bytes>\n" for panes that got any. -fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - var per: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty); - defer for (&per) |*b| b.deinit(p.gpa); - while (p.nextEffect()) |effect| { - if (effect == .write) try per[effect.write.pane].appendSlice(p.gpa, effect.write.bytes.slice()); - } - for (per, 0..) |b, id| if (b.items.len > 0) try out.print(p.gpa, "{d}:{s}\n", .{ id, b.items }); - return out.items; -} - -/// `a=T` of a 4x2 RGB image, `i=7`, red on the left half, blue on the -/// right, with the rest of the control data `extra` (`c=2,r=1` places it -/// over two cells). -inline fn kittyTransmit(comptime extra: []const u8) []const u8 { - return comptime blk: { - const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; - const pixels = row ++ row; - var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined; - const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*; - break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\"; - }; -} - -fn imagePlaces(s: *const Surface) []const pardes.Placement { - return s.placements.items; -} - -/// `n` line breaks: enough of them push the screen's rows into history. -fn lineBreaks(comptime n: usize) [2 * n]u8 { - var out: [2 * n]u8 = undefined; - for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; - return out; -} - -test "replay ownership is terminal-only and construction rolls back on allocation failure" { - const Case = struct { - fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try panes.createTerminal(gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); - defer gpa.destroy(pane); - defer if (pane.terminal) |state| close(state, gpa); - try std.testing.expectEqual(terminal, pane.terminal != null); - } - }; - try std.testing.expect(@sizeOf(Pane) < 128 * 1024); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); -} - -test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { - // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field - // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). - const Filling = struct { - child: std.mem.Allocator, - fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - const ptr = self.child.rawAlloc(len, a, ra) orelse return null; - @memset(ptr[0..len], 0xAA); - return ptr; - } - fn grow(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawResize(buf, a, n, ra); - } - fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawRemap(buf, a, n, ra); - } - fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { - const self: *@This() = @ptrCast(@alignCast(ctx)); - self.child.rawFree(buf, a, ra); - } - const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = grow, .remap = remap, .free = free }; - }; - var filling: Filling = .{ .child = std.testing.allocator }; - const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; - const pane = try panes.createTerminal(gpa, 40, 12); - defer gpa.destroy(pane); - defer if (pane.terminal) |state| close(state, gpa); - try std.testing.expect(pane.terminal.?.resize_to == null); -} - -test "document construction allocates only the pane and has inert terminal defaults" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); - const allocator = failing.allocator(); - const pane = try panes.createDoc(allocator, 40, 12); - defer allocator.destroy(pane); - defer if (pane.terminal) |state| close(state, allocator); - try std.testing.expect(pane.terminal == null); - try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); - try std.testing.expectEqual(@as(usize, 0), failing.resize_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); - try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); - try std.testing.expectEqual(Term.Modes{}, modes(pane.terminal)); - try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal)); - pane.scrollBy(100); - pane.followOutput(); - pane.resizeGrid(80, 24); - try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); - try std.testing.expectEqualStrings("", try scrollback(pane.terminal, allocator)); - try std.testing.expect(!failing.has_induced_failure); -} - -test "terminal state keeps parser fragments and sends emulator replies through its owner" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - const state = pane.terminal.?; - try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); - while (p.nextEffect()) |effect| { - if (effect == .write) return error.PrematureTerminalReply; - } - p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); - var answers: usize = 0; - while (p.nextEffect()) |effect| { - if (effect != .write) continue; - try std.testing.expectEqual(@as(u8, 0), effect.write.pane); - try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); - answers += 1; - } - try std.testing.expectEqual(@as(usize, 1), answers); - try std.testing.expectEqual(@as(u16, 0), state.reply_len); -} - -test "a terminal's dump restores the cells it drew, its history and where its view was" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.feedOutput(p, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - for (0..30) |i| { - var line: [16]u8 = undefined; - pane.feedOutput(p, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); - } - scroll(pane.terminal.?, -5); - const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); - defer gpa.free(bytes); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const state = try gpa.create(State); - defer gpa.destroy(state); - state.* = try pardes.walk.load(State, gpa, bytes, null); - defer { - state.stream.deinit(); - state.vt.deinit(gpa); - } - try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); - try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar()); -} - -test "a restored command pane comes back finished, its command not run again" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const cmd = p.freeSlot().?; - _ = try panes.newCommand(p, cmd, "/tmp", "make test"); - p.panes[cmd].?.feedOutput(p, "ok\r\n"); - p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); - try pardes.dump.dumpState(p); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); - defer restored.deinit(); - var spawns: usize = 0; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => spawns += 1, - else => {}, - }; - try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command - const again = for (restored.panes) |slot| { - if (slot) |pane| if (pane.command != null) break pane; - } else return error.CommandPaneLost; - try std.testing.expectEqualStrings("make test", again.command.?); - try std.testing.expect(again.command_done); - try std.testing.expectEqual(@as(?u8, 2), again.command_status); - const text = try scrollback(again.terminal, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); -} - -test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.feedOutput(p, "old output\r\n$ ls\r\n"); - try pane.setOwnedCwd("/tmp"); - pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash - try pardes.dump.dumpState(p); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); - defer restored.deinit(); - var spawned = false; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), - else => {}, - }; - try std.testing.expect(spawned); - const again = restored.panes[0].?; - try std.testing.expectEqualStrings("bash", again.shell.?); - try std.testing.expect(again.command == null); - try std.testing.expectEqual(.spawn, again.pending_command.wait); - const text = try scrollback(again.terminal, gpa); - defer gpa.free(text); - const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; - const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; - try std.testing.expect(old_at < mark_at); -} - -test "a position that cannot follow the output for want of memory is said on the message row, and logged" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.feedOutput(p, "one\r\ntwo\r\n"); - // More positions than the emulator's pins have room for: following them - // through the output needs memory, and there is none. - try std.testing.expect(pane.body.reserveSels()); - for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 }; - pane.body.nsel = 8; - failing.fail_index = failing.alloc_index; - pane.feedOutput(p, "three\r\n"); - failing.fail_index = std.math.maxInt(usize); - try std.testing.expect(failing.has_induced_failure); - try std.testing.expectEqualStrings(panes.positions_lost, pane.msg[0..pane.msg_len]); - const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; - try std.testing.expectEqualStrings(panes.positions_lost, logged.slice()); -} - -test "raw terminal output needs no position tracking allocations" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - pane.feedOutput(p, "warm"); - const allocations = failing.alloc_index; - failing.fail_index = allocations; - const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); - pane.feedOutput(p, " output"); - try std.testing.expectEqual(allocations, failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); -} - -test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - try std.testing.expect(pane.terminal != null); - _ = try pardes.edit.shellRows(p, pane); - // A pane's teardown drops its entry; the rows stay until the sweep. - p.shell_rows.dropPane(pane); - _ = try pardes.edit.shellRows(p, pane); + state.images.draw(gpa, &state.vt, at, rows_of[0..vp_rows], out, frame, frame_cols); } test "the luminance table answers exactly what ghostty computes" { @@ -2030,620 +1526,3 @@ test "the luminance table answers exactly what ghostty computes" { } } } - -test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { - const testing = std.testing; - // Raw index assertions require a theme that inherits the ANSI palette. - const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a one-row tag keeps this small screen's rows - p.sync(); - try testing.expect(pane.tty_filter); - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ - "\x1b[38;5;196mB" ++ - "\x1b[38;2;255;0;0mC" ++ - "\x1b[0;48;5;25mD" ++ - "\x1b[0;48;2;0;95;175mE" ++ - "\x1b[0;1;2;3;4;5;7;8;9mF" ++ - "\x1b[0;48;5;25m\x1b[K" ++ - "\r\n\x1b[0;38;5;2m界" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - const raw = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); - - pane.tty_filter = true; - _ = frame.reset(.retain_capacity); - const filtered = try p.render(frame.allocator()); - var expected_cache: FilterPalette = .{}; - const expected = expected_cache.get(p.theme()); - try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); - try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); - try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); - - const attrs = filtered.at(tx + 5, body_y).style; - try testing.expect(attrs.bold); - try testing.expect(attrs.dim); - try testing.expect(attrs.italic); - try testing.expect(attrs.blink); - try testing.expect(attrs.reverse); - try testing.expect(attrs.invisible); - try testing.expect(attrs.strikethrough); - try testing.expectEqual(.single, attrs.ul); - - const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; - try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); - try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); - try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); - // A filtered terminal never delegates either colour to a backend palette, - // including cells which were empty/default before the pass. - for (0..r.w - config.GUTTER) |col| { - const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); - try testing.expect(!cell.default); - switch (cell.style.fg) { - .rgb => {}, - else => return error.FilteredForegroundWasNotRgb, - } - switch (cell.style.bg) { - .rgb => {}, - else => return error.FilteredBackgroundWasNotRgb, - } - } - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); - const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; - try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); - pane.tty_filter = false; - pane.tty_filter = true; - try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); - _ = frame.reset(.retain_capacity); - const osc_palette = try p.render(frame.allocator()); - try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); - - // Dynamic default foreground/background colours key every default cell, - // including the otherwise blank end of the row. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ - "\x1b]11;#5f5f5f\x1b\\" } }); - const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; - const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; - try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); - try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); - _ = frame.reset(.retain_capacity); - const dynamic = try p.render(frame.allocator()); - const edge = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), edge.fg); - try testing.expectEqual(asPardesColor(expected[59]), edge.bg); - - const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; - try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); - const reversed_explicit = reversed.at(tx, body_y).style; - try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); - try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); - try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); - _ = frame.reset(.retain_capacity); - const unreversed = try p.render(frame.allocator()); - const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); - - // The cache is keyed by values, not a theme name. Replacing a custom - // theme in place immediately recolours already-rendered indexed cells. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); - var custom = p.theme().*; - custom.name = try p.gpa.dupe(u8, "same-name"); - custom.palette = null; - custom.kw = .{ 1, 2, 3 }; - p.custom_theme = custom; - _ = frame.reset(.retain_capacity); - const custom_first = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); - if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; - _ = frame.reset(.retain_capacity); - const custom_second = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); -} - -test "terminal Filter keeps extended keys dark-to-light on a light theme" { - const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); - defer p.deinit(); - try std.testing.expectEqualStrings("acme", p.theme().name); - var cache: FilterPalette = .{}; - const palette = cache.get(p.theme()); - try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); - try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); -} - -test "terminal Filter preserves exact palette-null light theme default roles" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - var light = p.theme().*; - light.name = try p.gpa.dupe(u8, "filter-light-defaults"); - light.bg = .{ 0xf8, 0xf8, 0xf8 }; - light.fg = .{ 0x38, 0x38, 0x38 }; - light.palette = null; - p.custom_theme = light; - - const pane = p.panes[0].?; - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); - pane.tty_filter = true; - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const ordinary = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); -} - -test "terminal Filter maps the default roles before it maps anything else" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - // Native dark/light palettes plus legacy helix/dark/acme, including - // the null-page fallback that only the legacy dark theme exercises. - for (0..9) |t| { - p.settings.theme = @intCast(t); - const stage_one = FilteredColors.init(p, &pane.terminal.?.vt); - // `dark` declares no background of its own, which is exactly why the - // resolver reads the tag colours as the fallback rather than `.?`. - const theme = p.theme(); - try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); - try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); - // With no OSC 11 in play the mapped page IS that anchor, and the - // fallback is the other one: a background never contrasts with itself. - try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); - try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); - } - - p.settings.theme = 0; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, &pane.terminal.?.vt); - try testing.expect(!moved.default_bg.eql(moved.theme_bg)); - try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); -} - -test "terminal Filter refuses a foreground that would collapse onto the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ - "\x1b[0;30mB" ++ - "\x1b[0;31mR" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, &pane.terminal.?.vt); - const page = asPardesColor(fc.default_bg); - const rescued = asPardesColor(fc.fallback_fg); - _ = frame.reset(.retain_capacity); - const g = try p.render(frame.allocator()); - - // The colour each of the three would have been given with no floor. - const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); - const raw_black = fc.paletteRgb(0, GColor.default[0]); - const raw_red = fc.paletteRgb(1, GColor.default[1]); - - for ([_]struct { at: u16, raw: GColor.RGB }{ - .{ .at = 0, .raw = raw_white }, - .{ .at = 1, .raw = raw_black }, - .{ .at = 2, .raw = raw_red }, - }) |case| { - const cell = g.at(tx + case.at, body_y).style; - try testing.expectEqual(page, cell.bg); - if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { - // Refused: the projection's answer is not painted, the anchor is. - try testing.expectEqual(rescued, cell.fg); - try testing.expect(!std.meta.eql(cell.fg, cell.bg)); - } else { - // Cleared the floor, so stage two leaves it exactly alone. - try testing.expectEqual(asPardesColor(case.raw), cell.fg); - } - // Either way a filtered cell delegates neither colour to a backend. - switch (cell.fg) { - .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= - config.tty_filter_min_contrast), - else => return error.FilteredForegroundWasNotRgb, - } - } - - // At least one of the three has to have been a real collapse, or this - // theme proved nothing: white on the light theme, black on the dark. - try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or - raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); - // A saturated red is never the page on any curated theme. - try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - } -} - -test "terminal Filter holds every projected foreground off the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, &pane.terminal.?.vt); - var refused: usize = 0; - for (fc.target, 0..) |projected, slot| { - const ink = fc.legible(projected); - try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - if (!ink.eql(projected)) { - refused += 1; - try testing.expect(ink.eql(fc.fallback_fg)); - // Only ever refused for being too near the page. - try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); - } - // The key a background asks for is handed back untouched, including - // the one whose value is the page itself. - try testing.expect(fc.keyedRgb(GColor.default[slot]).eql(fc.target[fc.nearestKey(GColor.default[slot])])); - } - // Every curated theme owns at least one collapsing key — that is why - // the floor exists — and the floor must not be flattening the palette. - try testing.expect(refused > 0); - try testing.expect(refused < fc.target.len / 8); - } -} - -test "tty ansi colors follow the prompt hug into normal mode" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; - const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; - - // tty mode projects the emulator's ansi colours cell for cell. - pane.body.mode = .tty; - p.shell_rows.stale = true; - const tty = try p.render(frame.allocator()); - try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); - try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); - - pane.body.mode = .normal; - p.shell_rows.stale = true; - _ = frame.reset(.retain_capacity); - const norm = try p.render(frame.allocator()); - try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); - try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); - try testing.expectEqual(red, norm.at(tx, body_y).style.fg); - try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); -} - -test "a prompt row hidden end to end paints nothing at all" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a 12x8 screen: the body, not the tag - p.sync(); - pane.tty_filter = false; - pane.body.mode = .normal; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - p.shell_rows.stale = true; - const s = try p.render(frame.allocator()); - - try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); - try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); -} - -test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 }); - defer p.deinit(); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - _ = try p.render(frame.allocator()); - var out: std.ArrayList(u8) = .empty; - defer out.deinit(gpa); - _ = try ptyWritesByPane(p, &out); - p.view().active = 0; - // Asking while its pane has the keyboard: told at once that it has. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1004h" } }); - try std.testing.expectEqualStrings("0:\x1b[I\n", try ptyWritesByPane(p, &out)); - p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?1004h" } }); - try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); - // A click into the other pane moves the keyboard: out of one, into the - // other. - const r = p.view().rects[1]; - const at_col = r.x + config.GUTTER + 2; - const at_row = p.bodyTop(p.panes[1].?, r) + 1; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = at_col, .row = at_row } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = at_col, .row = at_row } }); - try std.testing.expectEqual(@as(usize, 1), p.view().active); - try std.testing.expectEqualStrings("0:\x1b[O\n1:\x1b[I\n", try ptyWritesByPane(p, &out)); - // The window: away and back. - p.update(.{ .focus = false }); - try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); - p.update(.{ .focus = false }); - try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); - p.update(.{ .focus = true }); - try std.testing.expectEqualStrings("1:\x1b[I\n", try ptyWritesByPane(p, &out)); - // A program that did not ask hears nothing: pane 2. - p.view().active = 2; - p.update(.tick); - try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); -} - -test "a terminal's kitty graphics image is drawn where its program placed it, and a delete takes it away" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.view().active = 0; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;5H" ++ kittyTransmit("c=2,r=1") } }); - var s = try p.render(frame.allocator()); - const places = imagePlaces(s); - try std.testing.expectEqual(@as(usize, 1), places.len); - const place = places[0]; - const r = p.view().rects[0]; - const img = pane.terminal.?.vt.screens.active.kitty_images.imageById(7).?; - try std.testing.expectEqual(pardes.Placement.keyOf(pane.serial, 7, @truncate(img.generation)), place.key); - try std.testing.expectEqual(pardes.RectCell{ .x = r.x + config.GUTTER + 4, .y = p.bodyTop(pane, r) + 2, .w = 2, .h = 1 }, place.dst); - try std.testing.expectEqual(@as(u32, 4), place.raster.w); - try std.testing.expectEqual(@as(u32, 2), place.raster.h); - try std.testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, place.raster.bytes()[0..4]); - try std.testing.expectEqual(pardes.RectPx{ .x = 0, .y = 0, .w = 4, .h = 2 }, place.src); - try std.testing.expectEqual(pardes.RectPx{ .x = 0, .y = 0, .w = 20, .h = 20 }, place.at.?); - - // Scrolled up by the shell's output, it goes up with the text. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[24;1H\n\n" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(p.bodyTop(pane, r), imagePlaces(s)[0].dst.y); - p.update(.{ .output = .{ .pane = 0, .bytes = "\n" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b_Ga=d,d=A\x1b\\" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); -} - -test "ED 3 takes away a kitty placement whose row it erased: it never comes back at the top" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); - const storage = &pane.terminal.?.vt.screens.active.kitty_images; - try std.testing.expectEqual(@as(usize, 1), storage.placements.count()); - // Scrolled into the history, it is not on screen; `clear` (ED 2 then - // ED 3) erases that history and the placement with it. - p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(40) } }); - var s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[H\x1b[2J\x1b[3J" } }); - try std.testing.expectEqual(@as(usize, 0), storage.placements.count()); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); -} - -test "a finished command's output erased by a later ED 3 is not called whole, and no rows stand in for it" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); - defer p.deinit(); - const pane = p.panes[0].?; - const marked = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; - p.update(.{ .output = .{ .pane = 0, .bytes = marked ++ "\r\n\x1b]133;C;aid=pardes\x07printed\r\n\x1b]133;D;0;aid=pardes\x07" ++ marked } }); - const before = try commandOutput(pane.terminal, gpa, 100); - defer gpa.free(before.text); - try std.testing.expect(before.whole); - try std.testing.expect(std.mem.startsWith(u8, before.text, "printed")); - // The command's rows go into the history, and ED 3 erases them: its - // pins are `garbage` now (ghostty 1.4), not moved to the screen's top, - // where another program's text would be read as its output. - p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } }); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); - const after = try commandOutput(pane.terminal, gpa, 100); - defer gpa.free(after.text); - try std.testing.expect(!after.whole); - try std.testing.expectEqualStrings("", after.text); -} - -test "a selection whose row ED 3 erased goes; one on the screen stays" { - const gpa = std.testing.allocator; - for ([_]bool{ true, false }) |in_history| { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } }); - pane.body.mode = .normal; - const pages = &pane.terminal.?.vt.screens.active.pages; - const top: i32 = @intCast(pages.total_rows - pane.rows); - const row: i32 = if (in_history) top - 3 else top + 2; - pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); - try std.testing.expectEqual(!in_history, pane.body.vsel.active); - if (!in_history) try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.row); - } -} - -test "a virtual kitty placement shows through its placeholder cells, which draw no text" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - // yazi's way: a virtual placement two cells by one, then the two - // placeholders, the image's id in their colour, row and column in - // their diacritics. - p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("U=1,c=2,r=1,q=2") ++ - "\x1b[2;3H\x1b[38;2;0;0;7m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}\u{0305}\u{030D}\x1b[39mX" } }); - const s = try p.render(frame.allocator()); - const places = imagePlaces(s); - try std.testing.expectEqual(@as(usize, 1), places.len); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const y = p.bodyTop(pane, r) + 1; - try std.testing.expectEqual(pardes.RectCell{ .x = tx + 2, .y = y, .w = 2, .h = 1 }, places[0].dst); - try std.testing.expectEqualStrings(" ", s.at(tx + 2, y).grapheme()); - try std.testing.expectEqualStrings(" ", s.at(tx + 3, y).grapheme()); - try std.testing.expectEqualStrings("X", s.at(tx + 4, y).grapheme()); -} - -test "a terminal's image is a placement whatever the frontend draws, and the Petscii builtin asks for it as glyph art" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("c=2,r=1") } }); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const y = p.bodyTop(pane, r); - - // A frontend that draws no pixels (a tty under no kitty graphics) is - // handed the picture all the same, and the cells under it are its. - p.view().frontend.native_images = false; - var s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - try std.testing.expect(!imagePlaces(s)[0].art.glyph); - try std.testing.expectEqualStrings(" ", s.at(tx, y).grapheme()); - try std.testing.expectEqualStrings(" ", s.at(tx + 1, y).grapheme()); - // The tag says what that frontend draws, glyph art, as an image pane's does. - try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); - - // The builtin flips the pane to glyph art and back. - p.view().frontend.native_images = true; - try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - try std.testing.expect(imagePlaces(s)[0].art.glyph); - try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); - // Dumped and restored, it still asks for glyph art. - try pardes.dump.dumpState(p); - const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); - defer restored.deinit(); - try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal)); - try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expect(!imagePlaces(s)[0].art.glyph); -} - -test "a new terminal draws its program's images as pixels, and one without images says nothing of them" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?); - // A pane without images says nothing of them. - try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null); - const id = p.freeSlot().?; - const fresh = try p.newShell(id, ""); - try std.testing.expectEqual(false, petscii(fresh.terminal).?); -} - -test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var out: std.ArrayList(u8) = .empty; - defer out.deinit(gpa); - _ = try ptyWritesByPane(p, &out); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[16t" } }); - try std.testing.expectEqualStrings("0:\x1b[6;20;10t\n", try ptyWritesByPane(p, &out)); -} - -test "colors.xterm is the palette the emulator starts from, all 256" { - for (pardes.colors.xterm, ghostty_vt.color.default) |ours, its| try std.testing.expectEqual(ours, [3]u8{ its.r, its.g, its.b }); -} |
