diff options
| -rw-r--r-- | build.zig | 52 | ||||
| -rw-r--r-- | src/Core.zig | 10 | ||||
| -rw-r--r-- | src/Term.zig | 564 | ||||
| -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 | 3 | ||||
| -rw-r--r-- | src/plain/term.zig | 326 | ||||
| -rw-r--r-- | src/replica.zig | 59 | ||||
| -rw-r--r-- | src/term/TerminalImages.zig | 6 | ||||
| -rw-r--r-- | src/term/pager.zig | 13 | ||||
| -rw-r--r-- | src/term/screen_state.zig | 131 | ||||
| -rw-r--r-- | src/term/term.zig | 164 | ||||
| -rw-r--r-- | src/term/terminal.zig | 1273 | ||||
| -rw-r--r-- | test/kitty.zig | 10 | ||||
| -rw-r--r-- | test/panes.zig | 15 | ||||
| -rw-r--r-- | test/perf.zig | 2 | ||||
| -rw-r--r-- | test/replicas.zig | 48 | ||||
| -rw-r--r-- | test/terminal.zig | 983 |
21 files changed, 2236 insertions, 1504 deletions
@@ -197,6 +197,15 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("src/pardes.zig"), .link_libc = true, }); + // The core without the terminal module (docs/next-terminal.md, Phase 1): + // what core-test is compiled from. No ghostty-vt, wuffs, zstbi or C++; + // its terminal tests skip (Term.open), and run where the core has one. + const core_lean = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("src/pardes.zig"), + .link_libc = true, + }); const isolated_mod: ?*std.Build.Module = if (platform == .tui) b.createModule(.{ .target = target, @@ -225,8 +234,8 @@ pub fn build(b: *std.Build) void { }) else null; const CoreMod = struct { mod: ?*std.Build.Module, shell: Platform }; - var core_mods_buf: [5]*std.Build.Module = undefined; - var core_shells_buf: [5]Platform = undefined; + var core_mods_buf: [6]*std.Build.Module = undefined; + var core_shells_buf: [6]Platform = undefined; var core_mods_len: usize = 0; // root_mod FIRST: the module map below is folded out of its import table. for ([_]CoreMod{ @@ -234,6 +243,7 @@ pub fn build(b: *std.Build) void { // hxdiff's headless core and pardes-isolate are the primary shell's // configuration compiled two more ways, not two more frontends. .{ .mod = core_module, .shell = platform }, + .{ .mod = core_lean, .shell = platform }, .{ .mod = isolated_mod, .shell = platform }, .{ .mod = static_mod, .shell = platform }, .{ .mod = gui_mod, .shell = .gui }, @@ -838,6 +848,23 @@ pub fn build(b: *std.Build) void { for (builtin_mods) |m| m.addImport("image_addon", image_mod); // The records the core and the terminal both name (src/plain/plain.zig). const plain_mod = b.createModule(.{ .root_source_file = b.path("src/plain/plain.zig"), .target = target, .optimize = optimize }); + // The terminal, a module of its own (src/term/term.zig): the emulator and + // what it brings are its, and every core but core-test's is given it. + const term_mod = b.createModule(.{ .root_source_file = b.path("src/term/term.zig"), .target = target, .optimize = optimize, .link_libc = true }); + term_mod.addImport("plain", plain_mod); + if (ghostty_core_vt) |x| term_mod.addImport("ghostty-vt", x); + if (wuffs_mod) |x| term_mod.addImport("wuffs", x); + term_mod.addImport("zstbi", zstbi_mod); + const term_on = b.addOptions(); + term_on.addOption(bool, "terminal", true); + const term_off = b.addOptions(); + term_off.addOption(bool, "terminal", false); + for (core_mods) |m| if (m == core_lean) { + m.addOptions("term_options", term_off); + } else { + m.addImport("term", term_mod); + m.addOptions("term_options", term_on); + }; for (core_mods) |m| wireCore(m, .{ .plain = plain_mod, .kind = kind_mod, @@ -845,13 +872,10 @@ pub fn build(b: *std.Build) void { .tree_sitter = ts_mod, .ts_libs = ts_libs.items, .ts_queries = ts_queries_opts, - .zstbi = zstbi_mod, .mvzr = mvzr_mod, .c_heap = c_heap_mod, - .ghostty_vt = ghostty_core_vt, .vaxis = vaxis_mod, .uucode = uucode_mod, - .wuffs = wuffs_mod, .xitdb = xitdb_mod, }); @@ -1398,6 +1422,7 @@ pub fn build(b: *std.Build) void { .root_module = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("test/replicas.zig"), .link_libc = true }), }); replicas.root_module.addImport("pardes", core_module); + replicas.root_module.addImport("term", term_mod); const run_replicas = b.addRunArtifact(replicas); run_replicas.addPassthruArgs(); run_replicas.has_side_effects = true; @@ -1591,12 +1616,15 @@ pub fn build(b: *std.Build) void { // The perf and fs bench programs' own tests: they compile no editor. _ = units.add(b, perf_tests, null); _ = units.add(b, fs_bench_test, null); - const core_test = b.addTest(.{ .root_module = core_module, .filters = test_filters }); + const core_test = b.addTest(.{ .root_module = core_lean, .filters = test_filters }); const run_core_test = b.addRunArtifact(core_test); run_core_test.has_side_effects = true; - const core_test_step = b.step("core-test", "run core tests without native shell tests"); + const core_test_step = b.step("core-test", "run core tests without native shell tests, on the core without a terminal (its terminal tests skip)"); core_test_step.dependOn(&run_core_test.step); if (testMatch(b, unit_profile, test_filters, core_test_step)) |check| check.addArtifactArg(core_test); + // The terminal module's own tests (src/term/): the emulator without a core. + const run_term_test = units.add(b, b.addTest(.{ .root_module = term_mod, .filters = test_filters }), null); + b.step("term-test", "run the terminal module's own tests (src/term/)").dependOn(&run_term_test.step); const pane_module = b.createModule(.{ .target = target, .optimize = optimize, @@ -1604,6 +1632,10 @@ pub fn build(b: *std.Build) void { .link_libc = true, }); pane_module.addImport("pardes", core_module); + // test/terminal.zig reads the emulator behind a core's terminal. + pane_module.addImport("term", term_mod); + pane_module.addImport("plain", plain_mod); + if (ghostty_vt_for_tests) |x| pane_module.addImport("ghostty-vt", x); pane_module.addImport("pardes_config", core_module.import_table.get("pardes_config").?); const test_addons = b.addOptions(); test_addons.addOptionPath("image", image_addon.getEmittedBin()); @@ -2197,13 +2229,10 @@ fn wireCore(m: *std.Build.Module, d: struct { tree_sitter: ?*std.Build.Module = null, ts_libs: []const *std.Build.Step.Compile = &.{}, ts_queries: ?*std.Build.Step.Options = null, - zstbi: ?*std.Build.Module = null, mvzr: ?*std.Build.Module = null, c_heap: ?*std.Build.Module = null, - ghostty_vt: ?*std.Build.Module = null, vaxis: ?*std.Build.Module = null, uucode: ?*std.Build.Module = null, - wuffs: ?*std.Build.Module = null, xitdb: ?*std.Build.Module = null, }) void { if (d.plain) |x| m.addImport("plain", x); @@ -2212,12 +2241,9 @@ fn wireCore(m: *std.Build.Module, d: struct { if (d.tree_sitter) |x| m.addImport("tree-sitter", x); for (d.ts_libs) |lib| m.linkLibrary(lib); if (d.ts_queries) |x| m.addOptions("ts_queries", x); - if (d.zstbi) |x| m.addImport("zstbi", x); if (d.mvzr) |x| m.addImport("mvzr", x); if (d.c_heap) |x| m.addImport("c_heap", x); - if (d.ghostty_vt) |x| m.addImport("ghostty-vt", x); if (d.vaxis) |x| m.addImport("vaxis", x); if (d.uucode) |x| m.addImport("uucode", x); - if (d.wuffs) |x| m.addImport("wuffs", x); if (d.xitdb) |x| m.addImport("xitdb", x); } diff --git a/src/Core.zig b/src/Core.zig index 7d8cfb0e..070c4272 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -371,7 +371,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 @@ -2486,6 +2486,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)); @@ -2494,12 +2495,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, ""); @@ -3762,6 +3763,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 } }); @@ -3921,6 +3923,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(); @@ -3986,6 +3989,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/Term.zig b/src/Term.zig index ee178adc..8bd6e05b 100644 --- a/src/Term.zig +++ b/src/Term.zig @@ -1,220 +1,338 @@ -//! 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 builtin = @import("builtin"); const plain = @import("plain"); -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 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, - /// 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 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 ---- // @@ -225,58 +343,106 @@ pub const Span = pager.Span; /// Its view's rows as cells in the theme's colours, through the theme's /// filter when the pane has it on. -pub const paint = terminal.paint; +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.images; -/// Its rows `first` and the `count` after it as text, prompts cut off (the -/// edit copy's rows, as they were). -pub const editRows = terminal.editRows; +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; -/// The filter a +Pager's spans are drawn through, and a span's colour -/// through it. -pub const filter = terminal.pagerFilter; -pub const spanColor = terminal.spanColor; -pub const Ink = plain.term.Ink; -pub const FilterPalette = plain.term.FilterPalette; -pub const Filter = plain.term.Filter; -pub const Painted = plain.term.Painted; -pub const PaintedRow = plain.term.PaintedRow; -pub const ImagesAt = plain.term.ImagesAt; +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/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 86530157..ab2ee0ce 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -15,6 +15,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"); @@ -392,6 +396,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 index 6dc75f94..6ca96fe9 100644 --- a/src/plain/plain.zig +++ b/src/plain/plain.zig @@ -5,7 +5,8 @@ //! 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: the records it takes and gives. +/// 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 }; diff --git a/src/plain/term.zig b/src/plain/term.zig index 2f1323f0..dbc4fc87 100644 --- a/src/plain/term.zig +++ b/src/plain/term.zig @@ -1,11 +1,121 @@ //! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the -//! records its draw group takes and gives, plain data. src/Term.zig is the -//! core's side of it. +//! 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 @@ -17,6 +127,20 @@ pub const PromptCut = union(enum) { 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. @@ -108,3 +232,201 @@ pub const ImagesAt = struct { 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/term/TerminalImages.zig b/src/term/TerminalImages.zig index 3847be4c..1420d9e3 100644 --- a/src/term/TerminalImages.zig +++ b/src/term/TerminalImages.zig @@ -10,13 +10,15 @@ 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 = 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. @@ -141,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); diff --git a/src/term/pager.zig b/src/term/pager.zig index c4dbf721..0cf2ee21 100644 --- a/src/term/pager.zig +++ b/src/term/pager.zig @@ -6,28 +6,19 @@ //! of the pane only: no 9P file reads them (File.recolorSyntax draws them). const std = @import("std"); const plain = @import("plain"); -const pardes = @import("../pardes.zig"); 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 320ab6ad..fff491f6 100644 --- a/src/term/terminal.zig +++ b/src/term/terminal.zig @@ -1,22 +1,11 @@ -//! 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 plain = @import("plain"); -const pardes = @import("../pardes.zig"); -const config = @import("../config.zig"); -const Pardes = pardes.Pardes; -const Surface = pardes.Surface; -const modal = @import("../modal.zig"); -const tracy = @import("../tracy.zig"); -const tagline = @import("../tagline.zig"); const Key = plain.Key; -const Pane = panes.Pane; -const Term = @import("../Term.zig"); -const ansi = @import("../ansi.zig"); +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 Ink = plain.term.Ink; @@ -27,10 +16,6 @@ const PaintedRow = plain.term.PaintedRow; const ImagesAt = plain.term.ImagesAt; const PromptCut = plain.term.PromptCut; -const EditBuffer = panes.Text.EditBuffer; -const Snapshot = panes.Text.Snapshot; -const history_max = panes.Text.history_max; - pub const VtSlot = ghostty_vt.Terminal; /// A cell of an emulator's pages, as `getCell` reads it (src/term/echo.zig). pub const PageCell = ghostty_vt.PageList.Cell; @@ -49,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 @@ -74,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; @@ -214,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; @@ -240,147 +227,117 @@ 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; // Projected colors below this contrast use the theme's more legible anchor. -const min_contrast: f64 = 1.5; +pub const min_contrast: f64 = 1.5; /// The theme's 256 colours as the filter maps onto them (ghostty's /// `generate256Color` over the theme's sixteen), made again only when the /// theme's are not the ones `cache` was made of. -fn filterPalette(cache: *FilterPalette, ink: *const Ink) *const [256][3]u8 { +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; @@ -391,7 +348,7 @@ fn filterPalette(cache: *FilterPalette, ink: *const Ink) *const [256][3]u8 { 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] }; } @@ -463,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`). @@ -491,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; @@ -518,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); @@ -821,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 }; } @@ -832,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; @@ -847,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 @@ -1040,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 { @@ -1274,7 +1276,7 @@ fn cellStyle(ink: *const Ink, ci: ghostty_vt.PageList.Cell, filtered: ?*Filter, return cs; } -fn asPardesColor(rgb: GColor.RGB) plain.Color { +pub fn asPardesColor(rgb: GColor.RGB) plain.Color { return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; } @@ -1369,22 +1371,22 @@ pub fn spanColor(self: *Filter, color: plain.Color, is_bg: bool) plain.Color { }; } -fn legible(self: *const Filter, rgb: GColor.RGB) GColor.RGB { +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); } -fn paletteRgb(self: *Filter, idx: u8, current: GColor.RGB) GColor.RGB { +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); } -fn keyedRgb(self: *Filter, rgb: GColor.RGB) GColor.RGB { +pub fn keyedRgb(self: *Filter, rgb: GColor.RGB) GColor.RGB { return asGhostRgb(self.target[nearestKey(self, rgb)]); } -fn nearestKey(self: *Filter, rgb: GColor.RGB) u8 { +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)) @@ -1420,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]; @@ -1506,269 +1508,6 @@ pub fn images(state: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.Arr state.images.draw(gpa, &state.vt, at, rows_of[0..vp_rows], out, frame, frame_cols); } -/// 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 plain.Placement { - return s.placements.items; -} - -/// `n` line breaks: enough of them push the screen's rows into history. -fn lineBreaks(comptime n: usize) [2 * n]u8 { - var out: [2 * n]u8 = undefined; - for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; - return out; -} - -test "replay ownership is terminal-only and construction rolls back on allocation failure" { - const Case = struct { - fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try panes.createTerminal(gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); - defer gpa.destroy(pane); - defer if (pane.terminal) |state| close(state, gpa); - try std.testing.expectEqual(terminal, pane.terminal != null); - } - }; - try std.testing.expect(@sizeOf(Pane) < 128 * 1024); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); -} - -test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { - // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field - // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). - const Filling = struct { - child: std.mem.Allocator, - fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - const ptr = self.child.rawAlloc(len, a, ra) orelse return null; - @memset(ptr[0..len], 0xAA); - return ptr; - } - fn grow(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawResize(buf, a, n, ra); - } - fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawRemap(buf, a, n, ra); - } - fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { - const self: *@This() = @ptrCast(@alignCast(ctx)); - self.child.rawFree(buf, a, ra); - } - const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = grow, .remap = remap, .free = free }; - }; - var filling: Filling = .{ .child = std.testing.allocator }; - const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; - const pane = try panes.createTerminal(gpa, 40, 12); - defer gpa.destroy(pane); - defer if (pane.terminal) |state| close(state, gpa); - try std.testing.expect(pane.terminal.?.resize_to == null); -} - -test "document construction allocates only the pane and has inert terminal defaults" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); - const allocator = failing.allocator(); - const pane = try panes.createDoc(allocator, 40, 12); - defer allocator.destroy(pane); - defer if (pane.terminal) |state| close(state, allocator); - try std.testing.expect(pane.terminal == null); - try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); - try std.testing.expectEqual(@as(usize, 0), failing.resize_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); - try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); - try std.testing.expectEqual(Term.Modes{}, modes(pane.terminal)); - try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal)); - pane.scrollBy(100); - pane.followOutput(); - pane.resizeGrid(80, 24); - try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); - try std.testing.expectEqualStrings("", try scrollback(pane.terminal, allocator)); - try std.testing.expect(!failing.has_induced_failure); -} - -test "terminal state keeps parser fragments and sends emulator replies through its owner" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - const state = pane.terminal.?; - try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); - while (p.nextEffect()) |effect| { - if (effect == .write) return error.PrematureTerminalReply; - } - p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); - var answers: usize = 0; - while (p.nextEffect()) |effect| { - if (effect != .write) continue; - try std.testing.expectEqual(@as(u8, 0), effect.write.pane); - try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); - answers += 1; - } - try std.testing.expectEqual(@as(usize, 1), answers); - try std.testing.expectEqual(@as(u16, 0), state.reply_len); -} - -test "a terminal's dump restores the cells it drew, its history and where its view was" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.feedOutput(p, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - for (0..30) |i| { - var line: [16]u8 = undefined; - pane.feedOutput(p, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); - } - scroll(pane.terminal.?, -5); - const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); - defer gpa.free(bytes); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const state = try gpa.create(State); - defer gpa.destroy(state); - state.* = try pardes.walk.load(State, gpa, bytes, null); - defer { - state.stream.deinit(); - state.vt.deinit(gpa); - } - try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); - try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar()); -} - -test "a restored command pane comes back finished, its command not run again" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const cmd = p.freeSlot().?; - _ = try panes.newCommand(p, cmd, "/tmp", "make test"); - p.panes[cmd].?.feedOutput(p, "ok\r\n"); - p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); - try pardes.dump.dumpState(p); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); - defer restored.deinit(); - var spawns: usize = 0; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => spawns += 1, - else => {}, - }; - try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command - const again = for (restored.panes) |slot| { - if (slot) |pane| if (pane.command != null) break pane; - } else return error.CommandPaneLost; - try std.testing.expectEqualStrings("make test", again.command.?); - try std.testing.expect(again.command_done); - try std.testing.expectEqual(@as(?u8, 2), again.command_status); - const text = try scrollback(again.terminal, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); -} - -test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.feedOutput(p, "old output\r\n$ ls\r\n"); - try pane.setOwnedCwd("/tmp"); - pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash - try pardes.dump.dumpState(p); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); - defer restored.deinit(); - var spawned = false; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), - else => {}, - }; - try std.testing.expect(spawned); - const again = restored.panes[0].?; - try std.testing.expectEqualStrings("bash", again.shell.?); - try std.testing.expect(again.command == null); - try std.testing.expectEqual(.spawn, again.pending_command.wait); - const text = try scrollback(again.terminal, gpa); - defer gpa.free(text); - const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; - const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; - try std.testing.expect(old_at < mark_at); -} - -test "a position that cannot follow the output for want of memory is said on the message row, and logged" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.feedOutput(p, "one\r\ntwo\r\n"); - // More positions than the emulator's pins have room for: following them - // through the output needs memory, and there is none. - try std.testing.expect(pane.body.reserveSels()); - for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 }; - pane.body.nsel = 8; - failing.fail_index = failing.alloc_index; - pane.feedOutput(p, "three\r\n"); - failing.fail_index = std.math.maxInt(usize); - try std.testing.expect(failing.has_induced_failure); - try std.testing.expectEqualStrings(panes.positions_lost, pane.msg[0..pane.msg_len]); - const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; - try std.testing.expectEqualStrings(panes.positions_lost, logged.slice()); -} - -test "raw terminal output needs no position tracking allocations" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - pane.feedOutput(p, "warm"); - const allocations = failing.alloc_index; - failing.fail_index = allocations; - const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); - pane.feedOutput(p, " output"); - try std.testing.expectEqual(allocations, failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); -} - -test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - try std.testing.expect(pane.terminal != null); - _ = try pardes.edit.shellRows(p, pane); - // A pane's teardown drops its entry; the rows stay until the sweep. - p.shell_rows.dropPane(pane); - _ = try pardes.edit.shellRows(p, pane); -} - test "the luminance table answers exactly what ghostty computes" { for (0..256) |i| { const c: u8 = @intCast(i); @@ -1787,621 +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(plain.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); - try testing.expectEqual(plain.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); - try testing.expectEqual(plain.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); - - pane.tty_filter = true; - _ = frame.reset(.retain_capacity); - const filtered = try p.render(frame.allocator()); - var expected_cache: FilterPalette = .{}; - const expected = filterPalette(&expected_cache, &ansi.inkOf(p.theme())); - try testing.expectEqual(asPardesColor(asGhostRgb(expected[1])), filtered.at(tx, body_y).style.fg); - try testing.expectEqual(asPardesColor(asGhostRgb(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(asGhostRgb(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(asGhostRgb(expected[25])), filtered.at(tx + 6, body_y).style.bg); - try testing.expectEqual(asPardesColor(asGhostRgb(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(asGhostRgb(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(asGhostRgb(expected[196])), edge.fg); - try testing.expectEqual(asPardesColor(asGhostRgb(expected[59])), edge.bg); - - const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; - try testing.expectEqual(asPardesColor(asGhostRgb(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(asGhostRgb(expected[59])), reversed_blank.fg); - try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), reversed_blank.bg); - const reversed_explicit = reversed.at(tx, body_y).style; - try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), reversed_explicit.bg); - try testing.expectEqual(plain.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); - try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); - _ = frame.reset(.retain_capacity); - const unreversed = try p.render(frame.allocator()); - const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), unreversed_blank.fg); - try testing.expectEqual(asPardesColor(asGhostRgb(expected[59])), unreversed_blank.bg); - - // The cache is keyed by values, not a theme name. Replacing a custom - // theme in place immediately recolours already-rendered indexed cells. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); - var custom = p.theme().*; - custom.name = try p.gpa.dupe(u8, "same-name"); - custom.palette = null; - custom.kw = .{ 1, 2, 3 }; - p.custom_theme = custom; - _ = frame.reset(.retain_capacity); - const custom_first = try p.render(frame.allocator()); - try testing.expectEqual(plain.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); - if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; - _ = frame.reset(.retain_capacity); - const custom_second = try p.render(frame.allocator()); - try testing.expectEqual(plain.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); -} - -test "terminal Filter keeps extended keys dark-to-light on a light theme" { - const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); - defer p.deinit(); - try std.testing.expectEqualStrings("acme", p.theme().name); - var cache: FilterPalette = .{}; - const palette = filterPalette(&cache, &ansi.inkOf(p.theme())); - try std.testing.expect(asGhostRgb(palette[16]).eql(asGhostRgb(p.theme().fg.?))); - try std.testing.expect(asGhostRgb(palette[231]).eql(asGhostRgb(p.theme().bg.?))); -} - -test "terminal Filter preserves exact palette-null light theme default roles" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - var light = p.theme().*; - light.name = try p.gpa.dupe(u8, "filter-light-defaults"); - light.bg = .{ 0xf8, 0xf8, 0xf8 }; - light.fg = .{ 0x38, 0x38, 0x38 }; - light.palette = null; - p.custom_theme = light; - - const pane = p.panes[0].?; - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); - pane.tty_filter = true; - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const ordinary = try p.render(frame.allocator()); - try testing.expectEqual(plain.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); - try testing.expectEqual(plain.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - try testing.expectEqual(plain.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); - try testing.expectEqual(plain.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); -} - -test "terminal Filter maps the default roles before it maps anything else" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - // Native dark/light palettes plus legacy helix/dark/acme, including - // the null-page fallback that only the legacy dark theme exercises. - for (0..9) |t| { - p.settings.theme = @intCast(t); - const stage_one = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &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(asGhostRgb(stage_one.theme_bg).eql(asGhostRgb(theme.bg orelse theme.tag_bg))); - try testing.expect(asGhostRgb(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(asGhostRgb(stage_one.default_bg).eql(asGhostRgb(stage_one.theme_bg))); - try testing.expect(asGhostRgb(stage_one.fallback_fg).eql(asGhostRgb(stage_one.theme_fg))); - } - - p.settings.theme = 0; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &pane.terminal.?.vt); - try testing.expect(!asGhostRgb(moved.default_bg).eql(asGhostRgb(moved.theme_bg))); - try testing.expect(asGhostRgb(moved.default_bg).eql(keyedRgb(&moved, .{ .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 = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &pane.terminal.?.vt); - const page = asPardesColor(asGhostRgb(fc.default_bg)); - const rescued = asPardesColor(asGhostRgb(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 = keyedRgb(&fc, .{ .r = 255, .g = 255, .b = 255 }); - const raw_black = paletteRgb(&fc, 0, GColor.default[0]); - const raw_red = paletteRgb(&fc, 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(asGhostRgb(fc.default_bg)) < 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(asGhostRgb(fc.default_bg)) >= - 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(asGhostRgb(fc.default_bg)) < min_contrast or - raw_black.contrast(asGhostRgb(fc.default_bg)) < min_contrast); - // A saturated red is never the page on any curated theme. - try testing.expect(raw_red.contrast(asGhostRgb(fc.default_bg)) >= 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 = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &pane.terminal.?.vt); - var refused: usize = 0; - for (fc.target, 0..) |projected_triple, slot| { - const projected = asGhostRgb(projected_triple); - const ink = legible(&fc, projected); - try testing.expect(ink.contrast(asGhostRgb(fc.default_bg)) >= min_contrast); - if (!ink.eql(projected)) { - refused += 1; - try testing.expect(ink.eql(asGhostRgb(fc.fallback_fg))); - // Only ever refused for being too near the page. - try testing.expect(projected.contrast(asGhostRgb(fc.default_bg)) < min_contrast); - } - // The key a background asks for is handed back untouched, including - // the one whose value is the page itself. - try testing.expect(keyedRgb(&fc, GColor.default[slot]).eql(asGhostRgb(fc.target[nearestKey(&fc, GColor.default[slot])]))); - } - // Every curated theme owns at least one collapsing key — that is why - // the floor exists — and the floor must not be flattening the palette. - try testing.expect(refused > 0); - try testing.expect(refused < fc.target.len / 8); - } -} - -test "tty ansi colors follow the prompt hug into normal mode" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const red: plain.Color = .{ .rgb = p.theme().palette.?[1] }; - const blue: plain.Color = .{ .rgb = p.theme().palette.?[4] }; - - // tty mode projects the emulator's ansi colours cell for cell. - pane.body.mode = .tty; - p.shell_rows.stale = true; - const tty = try p.render(frame.allocator()); - try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); - try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); - - pane.body.mode = .normal; - p.shell_rows.stale = true; - _ = frame.reset(.retain_capacity); - const norm = try p.render(frame.allocator()); - try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); - try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); - try testing.expectEqual(red, norm.at(tx, body_y).style.fg); - try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); -} - -test "a prompt row hidden end to end paints nothing at all" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a 12x8 screen: the body, not the tag - p.sync(); - pane.tty_filter = false; - pane.body.mode = .normal; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - p.shell_rows.stale = true; - const s = try p.render(frame.allocator()); - - try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); - try testing.expect(!std.meta.eql(plain.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); -} - -test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 }); - defer p.deinit(); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - _ = try p.render(frame.allocator()); - var out: std.ArrayList(u8) = .empty; - defer out.deinit(gpa); - _ = try ptyWritesByPane(p, &out); - p.view().active = 0; - // Asking while its pane has the keyboard: told at once that it has. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1004h" } }); - try std.testing.expectEqualStrings("0:\x1b[I\n", try ptyWritesByPane(p, &out)); - p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?1004h" } }); - try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); - // A click into the other pane moves the keyboard: out of one, into the - // other. - const r = p.view().rects[1]; - const at_col = r.x + config.GUTTER + 2; - const at_row = p.bodyTop(p.panes[1].?, r) + 1; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = at_col, .row = at_row } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = at_col, .row = at_row } }); - try std.testing.expectEqual(@as(usize, 1), p.view().active); - try std.testing.expectEqualStrings("0:\x1b[O\n1:\x1b[I\n", try ptyWritesByPane(p, &out)); - // The window: away and back. - p.update(.{ .focus = false }); - try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); - p.update(.{ .focus = false }); - try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); - p.update(.{ .focus = true }); - try std.testing.expectEqualStrings("1:\x1b[I\n", try ptyWritesByPane(p, &out)); - // A program that did not ask hears nothing: pane 2. - p.view().active = 2; - p.update(.tick); - try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); -} - -test "a terminal's kitty graphics image is drawn where its program placed it, and a delete takes it away" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.view().active = 0; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;5H" ++ kittyTransmit("c=2,r=1") } }); - var s = try p.render(frame.allocator()); - const places = imagePlaces(s); - try std.testing.expectEqual(@as(usize, 1), places.len); - const place = places[0]; - const r = p.view().rects[0]; - const img = pane.terminal.?.vt.screens.active.kitty_images.imageById(7).?; - try std.testing.expectEqual(plain.Placement.keyOf(pane.serial, 7, @truncate(img.generation)), place.key); - try std.testing.expectEqual(plain.RectCell{ .x = r.x + config.GUTTER + 4, .y = p.bodyTop(pane, r) + 2, .w = 2, .h = 1 }, place.dst); - try std.testing.expectEqual(@as(u32, 4), place.raster.w); - try std.testing.expectEqual(@as(u32, 2), place.raster.h); - try std.testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, place.raster.bytes()[0..4]); - try std.testing.expectEqual(plain.RectPx{ .x = 0, .y = 0, .w = 4, .h = 2 }, place.src); - try std.testing.expectEqual(plain.RectPx{ .x = 0, .y = 0, .w = 20, .h = 20 }, place.at.?); - - // Scrolled up by the shell's output, it goes up with the text. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[24;1H\n\n" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(p.bodyTop(pane, r), imagePlaces(s)[0].dst.y); - p.update(.{ .output = .{ .pane = 0, .bytes = "\n" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b_Ga=d,d=A\x1b\\" } }); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); -} - -test "ED 3 takes away a kitty placement whose row it erased: it never comes back at the top" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); - const storage = &pane.terminal.?.vt.screens.active.kitty_images; - try std.testing.expectEqual(@as(usize, 1), storage.placements.count()); - // Scrolled into the history, it is not on screen; `clear` (ED 2 then - // ED 3) erases that history and the placement with it. - p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(40) } }); - var s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[H\x1b[2J\x1b[3J" } }); - try std.testing.expectEqual(@as(usize, 0), storage.placements.count()); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); -} - -test "a finished command's output erased by a later ED 3 is not called whole, and no rows stand in for it" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); - defer p.deinit(); - const pane = p.panes[0].?; - const marked = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; - p.update(.{ .output = .{ .pane = 0, .bytes = marked ++ "\r\n\x1b]133;C;aid=pardes\x07printed\r\n\x1b]133;D;0;aid=pardes\x07" ++ marked } }); - const before = try commandOutput(pane.terminal, gpa, 100); - defer gpa.free(before.text); - try std.testing.expect(before.whole); - try std.testing.expect(std.mem.startsWith(u8, before.text, "printed")); - // The command's rows go into the history, and ED 3 erases them: its - // pins are `garbage` now (ghostty 1.4), not moved to the screen's top, - // where another program's text would be read as its output. - p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } }); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); - const after = try commandOutput(pane.terminal, gpa, 100); - defer gpa.free(after.text); - try std.testing.expect(!after.whole); - try std.testing.expectEqualStrings("", after.text); -} - -test "a selection whose row ED 3 erased goes; one on the screen stays" { - const gpa = std.testing.allocator; - for ([_]bool{ true, false }) |in_history| { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = &lineBreaks(20) } }); - pane.body.mode = .normal; - const pages = &pane.terminal.?.vt.screens.active.pages; - const top: i32 = @intCast(pages.total_rows - pane.rows); - const row: i32 = if (in_history) top - 3 else top + 2; - pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); - try std.testing.expectEqual(!in_history, pane.body.vsel.active); - if (!in_history) try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.row); - } -} - -test "a virtual kitty placement shows through its placeholder cells, which draw no text" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.view().frontend.native_images = true; - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - // yazi's way: a virtual placement two cells by one, then the two - // placeholders, the image's id in their colour, row and column in - // their diacritics. - p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("U=1,c=2,r=1,q=2") ++ - "\x1b[2;3H\x1b[38;2;0;0;7m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}\u{0305}\u{030D}\x1b[39mX" } }); - const s = try p.render(frame.allocator()); - const places = imagePlaces(s); - try std.testing.expectEqual(@as(usize, 1), places.len); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const y = p.bodyTop(pane, r) + 1; - try std.testing.expectEqual(plain.RectCell{ .x = tx + 2, .y = y, .w = 2, .h = 1 }, places[0].dst); - try std.testing.expectEqualStrings(" ", s.at(tx + 2, y).grapheme()); - try std.testing.expectEqualStrings(" ", s.at(tx + 3, y).grapheme()); - try std.testing.expectEqualStrings("X", s.at(tx + 4, y).grapheme()); -} - -test "a terminal's image is a placement whatever the frontend draws, and the Petscii builtin asks for it as glyph art" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("c=2,r=1") } }); - const r = p.view().rects[0]; - const tx = r.x + config.GUTTER; - const y = p.bodyTop(pane, r); - - // A frontend that draws no pixels (a tty under no kitty graphics) is - // handed the picture all the same, and the cells under it are its. - p.view().frontend.native_images = false; - var s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - try std.testing.expect(!imagePlaces(s)[0].art.glyph); - try std.testing.expectEqualStrings(" ", s.at(tx, y).grapheme()); - try std.testing.expectEqualStrings(" ", s.at(tx + 1, y).grapheme()); - // The tag says what that frontend draws, glyph art, as an image pane's does. - try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); - - // The builtin flips the pane to glyph art and back. - p.view().frontend.native_images = true; - try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); - try std.testing.expect(imagePlaces(s)[0].art.glyph); - try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); - // Dumped and restored, it still asks for glyph art. - try pardes.dump.dumpState(p); - const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); - defer restored.deinit(); - try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal)); - try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); - _ = frame.reset(.retain_capacity); - s = try p.render(frame.allocator()); - try std.testing.expect(!imagePlaces(s)[0].art.glyph); -} - -test "a new terminal draws its program's images as pixels, and one without images says nothing of them" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?); - // A pane without images says nothing of them. - try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null); - const id = p.freeSlot().?; - const fresh = try p.newShell(id, ""); - try std.testing.expectEqual(false, petscii(fresh.terminal).?); -} - -test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { - if (comptime !images_enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); - defer p.deinit(); - p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); - var out: std.ArrayList(u8) = .empty; - defer out.deinit(gpa); - _ = try ptyWritesByPane(p, &out); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[16t" } }); - try std.testing.expectEqualStrings("0:\x1b[6;20;10t\n", try ptyWritesByPane(p, &out)); -} - -test "colors.xterm is the palette the emulator starts from, all 256" { - for (pardes.colors.xterm, ghostty_vt.color.default) |ours, its| try std.testing.expectEqual(ours, [3]u8{ its.r, its.g, its.b }); -} diff --git a/test/kitty.zig b/test/kitty.zig index 760d22be..1ba96745 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -116,8 +116,8 @@ const Rig = struct { return r.p.panes[id].?; } - fn vt(r: *Rig, id: u8) @TypeOf(&r.pane(id).terminal.?.vt) { - return &r.pane(id).terminal.?.vt; + fn vt(r: *Rig, id: u8) @TypeOf(&pardes.Term.emulatorOf(r.pane(id).terminal.?).vt) { + return &pardes.Term.emulatorOf(r.pane(id).terminal.?).vt; } fn storage(r: *Rig, id: u8) @TypeOf(&r.vt(id).screens.active.kitty_images) { @@ -133,7 +133,7 @@ const Rig = struct { /// The id its program gave the image a place draws. fn idOf(r: *Rig, place: pardes.Placement) ?u32 { const shown = r.p.panes[place.pane] orelse return null; - var it = shown.terminal.?.vt.screens.active.kitty_images.images.iterator(); + var it = pardes.Term.emulatorOf(shown.terminal.?).vt.screens.active.kitty_images.images.iterator(); while (it.next()) |e| if (pardes.Placement.keyOf(shown.serial, e.key_ptr.*, @truncate(e.value_ptr.generation)) == place.key) return e.key_ptr.*; return null; } @@ -727,7 +727,7 @@ test "kitty: answers past what one read may hold are dropped whole, never cut" { r.feed(0, batch.items); const got = try r.take(0); try std.testing.expect(got.len > 0); - try std.testing.expect(r.pane(0).terminal.?.reply_dropped > 0); + try std.testing.expect(pardes.Term.emulatorOf(r.pane(0).terminal.?).reply_dropped > 0); // Whole sequences only, each its own `ESC _ G ... ESC \`. var rest = got; while (rest.len > 0) { @@ -1306,7 +1306,7 @@ test "kitty: a dumped and restored terminal keeps its images" { defer restored.deinit(); const pane = restored.panes[0].?; // ghostty's snapshot of the emulator (src/term/terminal.zig) carries them. - try std.testing.expect(pane.terminal.?.vt.screens.active.kitty_images.placements.count() > 0); + try std.testing.expect(pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.kitty_images.placements.count() > 0); } // ---- Real clients' traffic ---- diff --git a/test/panes.zig b/test/panes.zig index 5562105e..04769ccf 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -993,7 +993,7 @@ test "terminal output keeps following new rows after scrollback eviction" { const pane = p.panes[0].?; pane.body.mode = .tty; pane.tty_filter = false; - const pages = &pane.terminal.?.vt.screens.active.pages; + const pages = &pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.pages; pages.limits.set(.bytes, 64 * 1024); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); @@ -1049,7 +1049,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.body.mode = .tty; - const pages = &pane.terminal.?.vt.screens.active.pages; + const pages = &pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.pages; pages.limits.set(.bytes, 64 * 1024); var next: usize = 0; while (next < 3000) { @@ -1101,7 +1101,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen if (action == .reset_alternate) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h" } }); p.update(.{ .output = .{ .pane = 0, .bytes = std.mem.asBytes(&@as([40][9]u8, @splat("old row\r\n".*))) } }); - const pages = &pane.terminal.?.vt.screens.active.pages; + const pages = &pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.pages; pages.limits.set(.bytes, 64 * 1024); const row: i32 = @as(i32, @intCast(pages.total_rows - pane.rows)) + @as(i32, if (action == .partial_clear_history) -1 else 2); @@ -1152,7 +1152,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen try std.testing.expectEqual(expected + 1, snapshot.cur_row); try std.testing.expectEqualStrings("edit one\nedit two", snapshot.ovl.?.text); } - try std.testing.expectEqual(@as(usize, 2), pane.terminal.?.vt.screens.active.pages.countTrackedPins()); + try std.testing.expectEqual(@as(usize, 2), pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.pages.countTrackedPins()); try pardes.edit.undoStep(p, &pane.body, true); try std.testing.expectEqualStrings("edit one\nedit two", pane.ovl.?.text); try std.testing.expectEqual(expected, pane.ovl.?.row); @@ -1192,7 +1192,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.body.mode = .tty; - const pages = &pane.terminal.?.vt.screens.active.pages; + const pages = &pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.pages; pages.limits.set(.bytes, 64 * 1024); var next: usize = 0; while (next < 3000) { @@ -1548,8 +1548,8 @@ test "unplaced terminal panes keep their allocated grid until placement" { try std.testing.expectEqual(pardes.Rect{}, p.view().rects[id]); try std.testing.expectEqual(@as(u16, 100), pane.cols); try std.testing.expectEqual(@as(u16, 30), pane.rows); - try std.testing.expectEqual(pane.cols, pane.terminal.?.vt.cols); - try std.testing.expectEqual(pane.rows, pane.terminal.?.vt.rows); + try std.testing.expectEqual(pane.cols, pardes.Term.emulatorOf(pane.terminal.?).vt.cols); + try std.testing.expectEqual(pane.rows, pardes.Term.emulatorOf(pane.terminal.?).vt.rows); while (p.nextEffect()) |effect| { if (effect == .resize_pty and effect.resize_pty.pane == id) return error.ResizedUnplacedPane; } @@ -3501,6 +3501,7 @@ const TerminalTests = struct { }; test { + _ = @import("terminal.zig"); _ = TagLayerTests; _ = TagNameTintTests; _ = TreeContextTests; diff --git a/test/perf.zig b/test/perf.zig index d9341cad..cb4e907e 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -865,7 +865,7 @@ const UndoOutput = struct { fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.heap.ArenaAllocator, samples: []u64) ![3]UndoOutput { const pane = core.panes[0].?; - const pages = &pane.terminal.?.vt.screens.active.pages; + const pages = &pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.pages; if (pane.body.ed_undo_len != 0 or pane.body.ed_redo_len != 0) return error.UnexpectedTerminalHistory; if (pane.ovl) |overlay| core.gpa.free(overlay.text); pane.ovl = null; diff --git a/test/replicas.zig b/test/replicas.zig index c100a8c1..f6aa2af2 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -35,8 +35,8 @@ const std = @import("std"); const libc = std.c; const pardes = @import("pardes"); const replica = pardes.replica; -const screen_state = pardes.Term.screen_state; -const Echo = pardes.Term.Echo; +const screen_state = @import("term").screen_state; +const Echo = pardes.Echo; const Key = pardes.Key; const gpa = std.heap.c_allocator; @@ -223,7 +223,17 @@ fn writeText(path: [:0]const u8, text: []const u8) !void { const Run = struct { seed: u64, rtt_ms: u64, steps: usize, clients: u16, shared: bool, flood_mb: u64 }; /// The terminal pane's screen as a hash of screen_state's dump of it. -fn screenHash(t: *pardes.Term.screen_state.Terminal) u64 { +/// The module's own replica behind the core's handle (Replica.screens). +fn replicaOf(r: *pardes.Term.Replica) *screen_state.Replica { + return @ptrCast(@alignCast(r)); +} + +/// The module's own track behind the core's handle (Screens.tracks). +fn trackOf(t: *pardes.Term.Track) *screen_state.Track { + return @ptrCast(@alignCast(t)); +} + +fn screenHash(t: *screen_state.Terminal) u64 { var buf: [8192]u8 = undefined; var h: std.Io.Writer.Hashing(std.hash.Wyhash) = .initHasher(.init(0), &buf); screen_state.dumpScreen(t, &h.writer) catch {}; @@ -416,12 +426,12 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { if (reply[5] == 1) { // Applied: the screen is the authority's at that version. const sc = rp.screens[pane].?; - const vt = &rp.core().panes[pane].?.terminal.?.vt; + const vt = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt; totals.screens_checked += 1; - if (versions.get(@as(u64, sc.serial) << 32 | sc.rep.seq)) |want| { + if (versions.get(@as(u64, sc.serial) << 32 | replicaOf(sc.rep).seq)) |want| { if (want != screenHash(vt)) { totals.screens_wrong += 1; - std.debug.print("seed {d} rtt {d} ms: replica {d}'s terminal {d} at version {d} is not the authority's\n", .{ r.seed, r.rtt_ms, m.who, pane, sc.rep.seq }); + std.debug.print("seed {d} rtt {d} ms: replica {d}'s terminal {d} at version {d} is not the authority's\n", .{ r.seed, r.rtt_ms, m.who, pane, replicaOf(sc.rep).seq }); } } else totals.screens_wrong += 1; // Deltas while the flood runs (an RTT/2 behind it). @@ -459,7 +469,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { totals.unequal += 1; continue; }).terminal orelse continue; - if (screenHash(&state.vt) != screenHash(&mine.vt)) { + if (screenHash(&pardes.Term.emulatorOf(state).vt) != screenHash(&pardes.Term.emulatorOf(mine).vt)) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: replica {d}'s terminal {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid }); } @@ -567,10 +577,10 @@ fn flushAll(sc: *replica.Screens, core: *pardes.Pardes, ps: []const u16, list: * } // Each version as the authority's screen showed it. for (&sc.tracks, 0..) |*slot, id| if (slot.*) |*tr| { - const key = @as(u64, tr.serial) << 32 | tr.track.version; - if (tr.track.version == 0 or vs.contains(key)) continue; + const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version; + if (trackOf(tr.track).version == 0 or vs.contains(key)) continue; _ = core.panes[id] orelse continue; - try vs.put(gpa, key, screenHash(&tr.state.vt)); + try vs.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)); }; } @@ -976,7 +986,7 @@ const EchoTotals = struct { }; fn cellCp(state: *pardes.Term.State, x: u16, y: u16) u21 { - const ci = state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return 0x10ffff; + const ci = pardes.Term.emulatorOf(state).vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = y } }) orelse return 0x10ffff; const cp = ci.cell.codepoint(); return if (cp == 0) ' ' else cp; } @@ -1071,7 +1081,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { for (made.items) |pr| { const k = &typed.items[pr.seq - 1]; if (trace) { - const sc = rp.core().panes[shell].?.terminal.?.vt.screens.active.cursor; + const sc = pardes.Term.emulatorOf(rp.core().panes[shell].?.terminal.?).vt.screens.active.cursor; std.debug.print("{d} ms ({t}): key {d} predicted {any} cursor {d}; acked {d} wait {d} nd {d}; the screen's cursor {d},{d}\n", .{ m.at / 1000, m.kind, pr.seq, pr.cell, pr.cursor.x, rp.echo.acked, rp.echo.wait, rp.echo.nd, sc.x, sc.y }); } if (pr.cell) |cell| k.pred = .{ .x = cell.x, .y = @intCast(cell.row - top), .cp = cell.cp }; @@ -1106,7 +1116,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { const state = a.core.panes[shell].?.terminal.?; if (ty) |k| { k.mode = sh.mode; - k.version_before = if (screens.tracks[shell]) |*tr| tr.track.version else 0; + k.version_before = if (screens.tracks[shell]) |*tr| trackOf(tr.track).version else 0; } sh.key(m.bytes); if (sh.out.items.len > 0) { @@ -1115,7 +1125,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { if (ty) |k| k.echoed = true; } if (ty) |k| { - const cur = state.vt.screens.active.cursor; + const cur = pardes.Term.emulatorOf(state).vt.screens.active.cursor; k.after = .{ .x = @intCast(cur.x), .y = @intCast(cur.y), .row = undefined }; for (&k.after.?.row, 0..) |*cp, x| cp.* = cellCp(state, @intCast(x), @intCast(cur.y)); judgeTruth(k); @@ -1157,11 +1167,11 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { k.first_visible = m.at; if (trace) { const st = core.panes[shell].?.terminal.?; - std.debug.print("{d} ms: key {d} ('{u}') drawn: trusted {} doubt {} phase {t} sem {t}\n", .{ m.at / 1000, cell.seq, cell.cp, rp.echo.trusted, rp.echo.doubt, st.stream.handler.phase, st.vt.screens.active.cursor.semantic_content }); + std.debug.print("{d} ms: key {d} ('{u}') drawn: trusted {} doubt {} phase {t} sem {t}\n", .{ m.at / 1000, cell.seq, cell.cp, rp.echo.trusted, rp.echo.doubt, pardes.Term.emulatorOf(st).stream.handler.phase, pardes.Term.emulatorOf(st).vt.screens.active.cursor.semantic_content }); } } }; - const applied = if (rp.screens[shell]) |sc| sc.rep.seq else 0; + const applied = if (rp.screens[shell]) |sc| replicaOf(sc.rep).seq else 0; for (typed.items) |*k| if (k.echoed and k.seen == null and applied > k.version_before) { k.seen = m.at; }; @@ -1178,8 +1188,8 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { const pane = m.bytes[0]; if (reply[5] == 1) { const sc = rp.screens[pane].?; - if (versions.get(@as(u64, sc.serial) << 32 | sc.rep.seq)) |want| { - if (want != screenHash(&rp.core().panes[pane].?.terminal.?.vt)) t.screens_wrong += 1; + if (versions.get(@as(u64, sc.serial) << 32 | replicaOf(sc.rep).seq)) |want| { + if (want != screenHash(&pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt)) t.screens_wrong += 1; } else t.screens_wrong += 1; } try push(&queue, &n, .{ .at = up[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_up, .who = 1, .bytes = try gpa.dupe(u8, reply) }); @@ -1238,7 +1248,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { et.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the replica at quiescence: {s}\n", .{ seed, rtt_ms, if (rp.quiet()) "another digest" else "inputs still pending" }); } - if (screenHash(&a.core.panes[shell].?.terminal.?.vt) != screenHash(&rp.core().panes[shell].?.terminal.?.vt)) { + if (screenHash(&pardes.Term.emulatorOf(a.core.panes[shell].?.terminal.?).vt) != screenHash(&pardes.Term.emulatorOf(rp.core().panes[shell].?.terminal.?).vt)) { et.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the shell at quiescence is not the authority's\n", .{ seed, rtt_ms }); } diff --git a/test/terminal.zig b/test/terminal.zig new file mode 100644 index 00000000..cfc58e52 --- /dev/null +++ b/test/terminal.zig @@ -0,0 +1,983 @@ +//! The terminal through the core (docs/next-terminal.md, Phase 1): what +//! were src/term/terminal.zig's and screen_state.zig's tests of a terminal +//! pane, moved as they were. They boot a core and read the emulator behind +//! it, so they need both modules, which only a suite outside both has: +//! pane-test's (test/panes.zig). The emulator's own tests stay in src/term/. +const std = @import("std"); +const pardes = @import("pardes"); +const plain = @import("plain"); +const term = @import("term"); +const ghostty_vt = @import("ghostty-vt"); +const emu = term.terminal; +const screen_state = term.screen_state; +const Encoder = screen_state.Encoder; +const Track = screen_state.Track; +const Peer = screen_state.Peer; +const Replica = screen_state.Replica; +const encode = screen_state.encode; +const Surface = pardes.Surface; +const Pane = pardes.Pane; +const FilterPalette = Term.FilterPalette; +const Pardes = pardes.Pardes; +const panes = pardes.panes; +const config = pardes.config; +const tagline = pardes.tagline; +const ansi = pardes.ansi; +const Term = pardes.Term; +const State = Term.State; +const GColor = ghostty_vt.color; +const images_enabled = emu.images_enabled; +const close = Term.close; +const grid = Term.grid; +const modes = Term.modes; +const prompt = Term.prompt; +const scroll = Term.scroll; +const scrollback = Term.scrollback; +const commandOutput = Term.commandOutput; +const petscii = Term.petscii; +const filterOf = emu.filterOf; +const filterPalette = emu.filterPalette; +const keyedRgb = emu.keyedRgb; +const paletteRgb = emu.paletteRgb; +const legible = emu.legible; +const nearestKey = emu.nearestKey; +const asGhostRgb = emu.asGhostRgb; +const asPardesColor = emu.asPardesColor; +const min_contrast = emu.min_contrast; + +/// The module's own state behind a pane's handle. +fn of(s: *Term.State) *emu.State { + return @ptrCast(@alignCast(s.impl)); +} + +/// 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 plain.Placement { + return s.placements.items; +} + +/// `n` line breaks: enough of them push the screen's rows into history. +fn lineBreaks(comptime n: usize) [2 * n]u8 { + var out: [2 * n]u8 = undefined; + for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; + return out; +} + +test "replay ownership is terminal-only and construction rolls back on allocation failure" { + const Case = struct { + fn run(gpa: std.mem.Allocator, terminal: bool) !void { + const pane = if (terminal) try panes.createTerminal(gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); + defer gpa.destroy(pane); + defer if (pane.terminal) |state| close(state, gpa); + try std.testing.expectEqual(terminal, pane.terminal != null); + } + }; + try std.testing.expect(@sizeOf(Pane) < 128 * 1024); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); +} + +test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { + // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field + // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). + const Filling = struct { + child: std.mem.Allocator, + fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + const ptr = self.child.rawAlloc(len, a, ra) orelse return null; + @memset(ptr[0..len], 0xAA); + return ptr; + } + fn grow(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { + const self: *@This() = @ptrCast(@alignCast(ctx)); + return self.child.rawResize(buf, a, n, ra); + } + fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + return self.child.rawRemap(buf, a, n, ra); + } + fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + self.child.rawFree(buf, a, ra); + } + const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = grow, .remap = remap, .free = free }; + }; + var filling: Filling = .{ .child = std.testing.allocator }; + const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; + const pane = try panes.createTerminal(gpa, 40, 12); + defer gpa.destroy(pane); + defer if (pane.terminal) |state| close(state, gpa); + try std.testing.expect(of(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 = of(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.dumpFree(state, gpa); + try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); + try std.testing.expectEqual(of(pane.terminal.?).vt.screens.active.pages.scrollbar(), of(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 = of(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, of(pane.terminal.?).vt.screens.active.pages.countTrackedPins()); +} + +test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = p.panes[0].?; + try std.testing.expect(pane.terminal != null); + _ = try pardes.edit.shellRows(p, pane); + // A pane's teardown drops its entry; the rows stay until the sweep. + p.shell_rows.dropPane(pane); + _ = try pardes.edit.shellRows(p, pane); +} + + +test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { + const testing = std.testing; + // Raw index assertions require a theme that inherits the ANSI palette. + const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tag_expanded = false; // a one-row tag keeps this small screen's rows + p.sync(); + try testing.expect(pane.tty_filter); + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ + "\x1b[38;5;196mB" ++ + "\x1b[38;2;255;0;0mC" ++ + "\x1b[0;48;5;25mD" ++ + "\x1b[0;48;2;0;95;175mE" ++ + "\x1b[0;1;2;3;4;5;7;8;9mF" ++ + "\x1b[0;48;5;25m\x1b[K" ++ + "\r\n\x1b[0;38;5;2m界" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.view().rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + + const raw = try p.render(frame.allocator()); + try testing.expectEqual(plain.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); + try testing.expectEqual(plain.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); + try testing.expectEqual(plain.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); + + pane.tty_filter = true; + _ = frame.reset(.retain_capacity); + const filtered = try p.render(frame.allocator()); + var expected_cache: FilterPalette = .{}; + const expected = filterPalette(&expected_cache, &ansi.inkOf(p.theme())); + try testing.expectEqual(asPardesColor(asGhostRgb(expected[1])), filtered.at(tx, body_y).style.fg); + try testing.expectEqual(asPardesColor(asGhostRgb(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(asGhostRgb(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 = of(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(asGhostRgb(expected[25])), filtered.at(tx + 6, body_y).style.bg); + try testing.expectEqual(asPardesColor(asGhostRgb(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 = of(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(of(pane.terminal.?).vt.colorForXterm(.{ .palette = 1 }).?)); + _ = frame.reset(.retain_capacity); + const osc_palette = try p.render(frame.allocator()); + try testing.expectEqual(asPardesColor(asGhostRgb(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 = of(pane.terminal.?).vt.colorForXterm(.{ .dynamic = .foreground }).?; + const dyn_bg = of(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(asGhostRgb(expected[196])), edge.fg); + try testing.expectEqual(asPardesColor(asGhostRgb(expected[59])), edge.bg); + + const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; + try testing.expectEqual(asPardesColor(asGhostRgb(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(asGhostRgb(expected[59])), reversed_blank.fg); + try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), reversed_blank.bg); + const reversed_explicit = reversed.at(tx, body_y).style; + try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), reversed_explicit.bg); + try testing.expectEqual(plain.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); + try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); + _ = frame.reset(.retain_capacity); + const unreversed = try p.render(frame.allocator()); + const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(asGhostRgb(expected[196])), unreversed_blank.fg); + try testing.expectEqual(asPardesColor(asGhostRgb(expected[59])), unreversed_blank.bg); + + // The cache is keyed by values, not a theme name. Replacing a custom + // theme in place immediately recolours already-rendered indexed cells. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); + var custom = p.theme().*; + custom.name = try p.gpa.dupe(u8, "same-name"); + custom.palette = null; + custom.kw = .{ 1, 2, 3 }; + p.custom_theme = custom; + _ = frame.reset(.retain_capacity); + const custom_first = try p.render(frame.allocator()); + try testing.expectEqual(plain.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); + if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; + _ = frame.reset(.retain_capacity); + const custom_second = try p.render(frame.allocator()); + try testing.expectEqual(plain.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); +} + +test "terminal Filter keeps extended keys dark-to-light on a light theme" { + const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); + defer p.deinit(); + try std.testing.expectEqualStrings("acme", p.theme().name); + var cache: FilterPalette = .{}; + const palette = filterPalette(&cache, &ansi.inkOf(p.theme())); + try std.testing.expect(asGhostRgb(palette[16]).eql(asGhostRgb(p.theme().fg.?))); + try std.testing.expect(asGhostRgb(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), of(pane.terminal.?).vt.colorForXterm(.{ .dynamic = .foreground })); + try testing.expectEqual(@as(?GColor.RGB, null), of(pane.terminal.?).vt.colorForXterm(.{ .dynamic = .background })); + pane.tty_filter = true; + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.view().rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + const ordinary = try p.render(frame.allocator()); + try testing.expectEqual(plain.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); + try testing.expectEqual(plain.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + try testing.expectEqual(plain.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); + try testing.expectEqual(plain.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); +} + +test "terminal Filter maps the default roles before it maps anything else" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + // Native dark/light palettes plus legacy helix/dark/acme, including + // the null-page fallback that only the legacy dark theme exercises. + for (0..9) |t| { + p.settings.theme = @intCast(t); + const stage_one = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &of(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(asGhostRgb(stage_one.theme_bg).eql(asGhostRgb(theme.bg orelse theme.tag_bg))); + try testing.expect(asGhostRgb(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(asGhostRgb(stage_one.default_bg).eql(asGhostRgb(stage_one.theme_bg))); + try testing.expect(asGhostRgb(stage_one.fallback_fg).eql(asGhostRgb(stage_one.theme_fg))); + } + + p.settings.theme = 0; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); + var moved = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &of(pane.terminal.?).vt); + try testing.expect(!asGhostRgb(moved.default_bg).eql(asGhostRgb(moved.theme_bg))); + try testing.expect(asGhostRgb(moved.default_bg).eql(keyedRgb(&moved, .{ .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 = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &of(pane.terminal.?).vt); + const page = asPardesColor(asGhostRgb(fc.default_bg)); + const rescued = asPardesColor(asGhostRgb(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 = keyedRgb(&fc, .{ .r = 255, .g = 255, .b = 255 }); + const raw_black = paletteRgb(&fc, 0, GColor.default[0]); + const raw_red = paletteRgb(&fc, 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(asGhostRgb(fc.default_bg)) < 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(asGhostRgb(fc.default_bg)) >= + 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(asGhostRgb(fc.default_bg)) < min_contrast or + raw_black.contrast(asGhostRgb(fc.default_bg)) < min_contrast); + // A saturated red is never the page on any curated theme. + try testing.expect(raw_red.contrast(asGhostRgb(fc.default_bg)) >= 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 = filterOf(&ansi.inkOf(p.theme()), &p.tty_filter_palette, &of(pane.terminal.?).vt); + var refused: usize = 0; + for (fc.target, 0..) |projected_triple, slot| { + const projected = asGhostRgb(projected_triple); + const ink = legible(&fc, projected); + try testing.expect(ink.contrast(asGhostRgb(fc.default_bg)) >= min_contrast); + if (!ink.eql(projected)) { + refused += 1; + try testing.expect(ink.eql(asGhostRgb(fc.fallback_fg))); + // Only ever refused for being too near the page. + try testing.expect(projected.contrast(asGhostRgb(fc.default_bg)) < min_contrast); + } + // The key a background asks for is handed back untouched, including + // the one whose value is the page itself. + try testing.expect(keyedRgb(&fc, GColor.default[slot]).eql(asGhostRgb(fc.target[nearestKey(&fc, GColor.default[slot])]))); + } + // Every curated theme owns at least one collapsing key — that is why + // the floor exists — and the floor must not be flattening the palette. + try testing.expect(refused > 0); + try testing.expect(refused < fc.target.len / 8); + } +} + +test "tty ansi colors follow the prompt hug into normal mode" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.view().rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + const red: plain.Color = .{ .rgb = p.theme().palette.?[1] }; + const blue: plain.Color = .{ .rgb = p.theme().palette.?[4] }; + + // tty mode projects the emulator's ansi colours cell for cell. + pane.body.mode = .tty; + p.shell_rows.stale = true; + const tty = try p.render(frame.allocator()); + try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); + try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); + + pane.body.mode = .normal; + p.shell_rows.stale = true; + _ = frame.reset(.retain_capacity); + const norm = try p.render(frame.allocator()); + try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); + try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); + try testing.expectEqual(red, norm.at(tx, body_y).style.fg); + try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); +} + +test "a prompt row hidden end to end paints nothing at all" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tag_expanded = false; // a 12x8 screen: the body, not the tag + p.sync(); + pane.tty_filter = false; + pane.body.mode = .normal; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.view().rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + p.shell_rows.stale = true; + const s = try p.render(frame.allocator()); + + try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); + try testing.expect(!std.meta.eql(plain.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); +} + +test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + _ = try ptyWritesByPane(p, &out); + p.view().active = 0; + // Asking while its pane has the keyboard: told at once that it has. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1004h" } }); + try std.testing.expectEqualStrings("0:\x1b[I\n", try ptyWritesByPane(p, &out)); + p.update(.{ .output = .{ .pane = 1, .bytes = "\x1b[?1004h" } }); + try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); + // A click into the other pane moves the keyboard: out of one, into the + // other. + const r = p.view().rects[1]; + const at_col = r.x + config.GUTTER + 2; + const at_row = p.bodyTop(p.panes[1].?, r) + 1; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = at_col, .row = at_row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = at_col, .row = at_row } }); + try std.testing.expectEqual(@as(usize, 1), p.view().active); + try std.testing.expectEqualStrings("0:\x1b[O\n1:\x1b[I\n", try ptyWritesByPane(p, &out)); + // The window: away and back. + p.update(.{ .focus = false }); + try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); + p.update(.{ .focus = false }); + try std.testing.expectEqualStrings("", try ptyWritesByPane(p, &out)); + p.update(.{ .focus = true }); + try std.testing.expectEqualStrings("1:\x1b[I\n", try ptyWritesByPane(p, &out)); + // A program that did not ask hears nothing: pane 2. + p.view().active = 2; + p.update(.tick); + try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); +} + +test "a terminal's kitty graphics image is drawn where its program placed it, and a delete takes it away" { + if (comptime !images_enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); + defer p.deinit(); + p.view().frontend.native_images = true; + p.view().active = 0; + p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const pane = p.panes[0].?; + pane.body.mode = .tty; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;5H" ++ kittyTransmit("c=2,r=1") } }); + var s = try p.render(frame.allocator()); + const places = imagePlaces(s); + try std.testing.expectEqual(@as(usize, 1), places.len); + const place = places[0]; + const r = p.view().rects[0]; + const img = of(pane.terminal.?).vt.screens.active.kitty_images.imageById(7).?; + try std.testing.expectEqual(plain.Placement.keyOf(pane.serial, 7, @truncate(img.generation)), place.key); + try std.testing.expectEqual(plain.RectCell{ .x = r.x + config.GUTTER + 4, .y = p.bodyTop(pane, r) + 2, .w = 2, .h = 1 }, place.dst); + try std.testing.expectEqual(@as(u32, 4), place.raster.w); + try std.testing.expectEqual(@as(u32, 2), place.raster.h); + try std.testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, place.raster.bytes()[0..4]); + try std.testing.expectEqual(plain.RectPx{ .x = 0, .y = 0, .w = 4, .h = 2 }, place.src); + try std.testing.expectEqual(plain.RectPx{ .x = 0, .y = 0, .w = 20, .h = 20 }, place.at.?); + + // Scrolled up by the shell's output, it goes up with the text. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[24;1H\n\n" } }); + _ = frame.reset(.retain_capacity); + s = try p.render(frame.allocator()); + try std.testing.expectEqual(p.bodyTop(pane, r), imagePlaces(s)[0].dst.y); + p.update(.{ .output = .{ .pane = 0, .bytes = "\n" } }); + _ = frame.reset(.retain_capacity); + s = try p.render(frame.allocator()); + try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); + _ = frame.reset(.retain_capacity); + s = try p.render(frame.allocator()); + try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b_Ga=d,d=A\x1b\\" } }); + _ = frame.reset(.retain_capacity); + s = try p.render(frame.allocator()); + try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); +} + +test "ED 3 takes away a kitty placement whose row it erased: it never comes back at the top" { + if (comptime !images_enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); + defer p.deinit(); + p.view().frontend.native_images = true; + p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const pane = p.panes[0].?; + pane.body.mode = .tty; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[1;1H" ++ kittyTransmit("c=2,r=1") } }); + const storage = &of(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 = &of(pane.terminal.?).vt.screens.active.pages; + const top: i32 = @intCast(pages.total_rows - pane.rows); + const row: i32 = if (in_history) top - 3 else top + 2; + pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3J" } }); + try std.testing.expectEqual(!in_history, pane.body.vsel.active); + if (!in_history) try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.row); + } +} + +test "a virtual kitty placement shows through its placeholder cells, which draw no text" { + if (comptime !images_enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); + defer p.deinit(); + p.view().frontend.native_images = true; + p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const pane = p.panes[0].?; + pane.body.mode = .tty; + // yazi's way: a virtual placement two cells by one, then the two + // placeholders, the image's id in their colour, row and column in + // their diacritics. + p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("U=1,c=2,r=1,q=2") ++ + "\x1b[2;3H\x1b[38;2;0;0;7m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}\u{0305}\u{030D}\x1b[39mX" } }); + const s = try p.render(frame.allocator()); + const places = imagePlaces(s); + try std.testing.expectEqual(@as(usize, 1), places.len); + const r = p.view().rects[0]; + const tx = r.x + config.GUTTER; + const y = p.bodyTop(pane, r) + 1; + try std.testing.expectEqual(plain.RectCell{ .x = tx + 2, .y = y, .w = 2, .h = 1 }, places[0].dst); + try std.testing.expectEqualStrings(" ", s.at(tx + 2, y).grapheme()); + try std.testing.expectEqualStrings(" ", s.at(tx + 3, y).grapheme()); + try std.testing.expectEqualStrings("X", s.at(tx + 4, y).grapheme()); +} + +test "a terminal's image is a placement whatever the frontend draws, and the Petscii builtin asks for it as glyph art" { + if (comptime !images_enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const pane = p.panes[0].?; + pane.body.mode = .tty; + p.update(.{ .output = .{ .pane = 0, .bytes = kittyTransmit("c=2,r=1") } }); + const r = p.view().rects[0]; + const tx = r.x + config.GUTTER; + const y = p.bodyTop(pane, r); + + // A frontend that draws no pixels (a tty under no kitty graphics) is + // handed the picture all the same, and the cells under it are its. + p.view().frontend.native_images = false; + var s = try p.render(frame.allocator()); + try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); + try std.testing.expect(!imagePlaces(s)[0].art.glyph); + try std.testing.expectEqualStrings(" ", s.at(tx, y).grapheme()); + try std.testing.expectEqualStrings(" ", s.at(tx + 1, y).grapheme()); + // The tag says what that frontend draws, glyph art, as an image pane's does. + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); + + // The builtin flips the pane to glyph art and back. + p.view().frontend.native_images = true; + try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); + _ = frame.reset(.retain_capacity); + s = try p.render(frame.allocator()); + try std.testing.expectEqual(@as(usize, 1), imagePlaces(s).len); + try std.testing.expect(imagePlaces(s)[0].art.glyph); + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, pane), " petscii:on") != null); + // Dumped and restored, it still asks for glyph art. + try pardes.dump.dumpState(p); + const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal)); + try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); + _ = frame.reset(.retain_capacity); + s = try p.render(frame.allocator()); + try std.testing.expect(!imagePlaces(s)[0].art.glyph); +} + +test "a new terminal draws its program's images as pixels, and one without images says nothing of them" { + if (comptime !images_enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); + defer p.deinit(); + try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?); + // A pane without images says nothing of them. + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null); + const id = p.freeSlot().?; + const fresh = try p.newShell(id, ""); + try std.testing.expectEqual(false, petscii(fresh.terminal).?); +} + +test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { + if (comptime !images_enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 80, .rows = 24, .cell_pixels = .{ .w = 10, .h = 20 } } }); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + _ = try ptyWritesByPane(p, &out); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[16t" } }); + try std.testing.expectEqualStrings("0:\x1b[6;20;10t\n", try ptyWritesByPane(p, &out)); +} + +test "colors.xterm is the palette the emulator starts from, all 256" { + for (pardes.colors.xterm, ghostty_vt.color.default) |ours, its| try std.testing.expectEqual(ours, [3]u8{ its.r, its.g, its.b }); +} + +test "a replica's terminal pane draws as its authority's does" { + const testing = std.testing; + 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 = &of(a.panes[0].?.terminal.?).vt; + const tb = &of(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; + } + }; + } +} |
