//! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the //! entries of the terminal module (core/term/, its own module: ghostty-vt, //! wuffs and zstbi are its, not the core's) and the plain records they take //! and give (abi/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 walk = @import("walk.zig"); const tape = @import("tape.zig"); const dump = @import("dump.zig"); const File = @import("File.zig"); const iface = plain.term; /// The writes of a core's emulators, which live outside its rollback copy /// (`Pardes.outside`): a field of the core, so copied with a speculation, /// digested and dumped, a function of the tape, the same on every side (one /// side's emulator written where the others' are not is a digest that says /// `outside`). Every write below takes it and counts, and so does a write a /// speculation owes (`resize`): over an input's apply, the count moved is /// "this input wrote, or owes, state outside the copy", the one question /// core/replica.zig `confirm` asks a unit. A load sets it from the dump. pub const Outside = struct { n: u64 = 0 }; /// The reloads this process made (a join's, on every side) and their time, /// for the soak's join line (test/replicas.zig `--bytes`). pub var reloads: struct { n: u32 = 0, ns: u64 = 0, worst_ns: u64 = 0 } = .{}; /// The terminal module's entries; null in a core built without it. pub const ops: ?*const iface.Ops = if (@import("pardes_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; /// A grid cell (the one a program last heard the mouse at: Pane.term_mouse). pub const Coordinate = iface.Parts.Coordinate; 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; fn the() *const iface.Ops { return ops orelse unreachable; // no State is made without it } /// A terminal pane's terminal: the module's handle, and the walk's hooks /// (core/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, /// Written since its last reload (a feed, a reflow, a load: what cuts /// its rows into pages), which a join reloads (panes.reloadTerminals, /// the session's choice). One not holds the pages its last reload's /// snapshot loads to, on every side, and so does a joiner loading the /// same snapshot again from the dump. written: bool = true, /// Not walked by a replica's rollback copy (core/rollback.zig): its /// emulator is written by confirmed units alone, each write counted /// (Pardes.outside), never by a speculation, so no copy holds any of it. pub const outside_copy = {}; /// The emulator as its program has made it, for the replay digest. pub fn digest(s: *const State, h: *walk.Hasher) void { the().digest(s.impl, h); } 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, _: std.mem.Allocator) void { the().close(s.impl); } 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); o.media(media); 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 terminal, `cols` by `rows`, allocated with `gpa` (its own from /// then on). Refused in a core without one: `error.NoTerminal`, which a /// word reports as `none` says it. pub fn open(outside: *Outside, gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { const o = ops orelse return error.NoTerminal; const s = try gpa.create(State); errdefer gpa.destroy(s); o.media(media); s.* = .{ .impl = try o.open(gpa, cols, rows) }; outside.n +%= 1; return s; } /// A kitty image's medium (a file, a temporary file, shared memory: the /// session's machine's) as its emulator reads it, made the tape's answer /// (P30: the device's answer as it was, as a file's bytes are): the session /// reads it, a temporary file deleted and shared memory unlinked there once, /// and every replica is handed the same bytes, or the same failure. fn media(ctx: *const anyopaque, read: *const fn (*const anyopaque) iface.MediumError![]u8, gpa: std.mem.Allocator) iface.MediumError![]u8 { return tape.valueIn(.medium, gpa, readMedium, .{ read, ctx }); } fn readMedium(read: *const fn (*const anyopaque) iface.MediumError![]u8, ctx: *const anyopaque) iface.MediumError![]u8 { return read(ctx); } /// It and what it holds, freed, all of it with its own allocator (the /// one it was opened with): the allocator a caller hands is not used. pub fn close(outside: *Outside, s: *State) void { const own = the().gpa(s.impl); outside.n +%= 1; the().close(s.impl); own.destroy(s); } /// Its emulator made again from its own snapshot, where it is: at a join /// every side does it, so that all hold the same pages (ghostty prunes its /// history a page at a time, and a snapshot does not say how its rows were /// cut into pages). The snapshot's hash, which every side compares. pub fn reload(outside: *Outside, s: *State) !u64 { outside.n +%= 1; const t0 = @import("FrameStats.zig").nowNs(); defer { reloads.n += 1; const dt = @import("FrameStats.zig").nowNs() -| t0; reloads.ns += dt; reloads.worst_ns = @max(reloads.worst_ns, dt); } const hash = try the().reload(s.impl); s.written = false; return hash; } /// 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 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 fn revive(outside: *Outside, s: *State) void { outside.n +%= 1; s.written = true; the().revive(s.impl); } /// The PNG resize workers kitty images are decoded with, started and /// stopped with the host. 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 size ---- /// One read of its program's output (`Told` says where the tracked rows /// went), every view's place in its history carried through it (`resize`). pub fn feed(outside: *Outside, s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool, places: []?usize) Told { outside.n +%= 1; s.written = true; return the().feed(s.impl, bytes, tracked, rows, erased, places); } /// How much history it has and where its cursor is; all zero without a /// terminal. Where a view stands in it is the view's (Pane.scrolled_to). pub fn grid(s: ?*const State) Grid { const o = ops orelse return .{}; return o.grid(if (s) |state| state.impl else null); } /// Its grid reflowed, every view's place in its history (Pane.scrolled_to, /// each view's) carried through it as ghostty carries a view of its own. /// A speculation owes it (counted, not made): its input is replayed when it /// is confirmed (core/replica.zig `confirm`), never taken as speculated. pub fn resize(outside: *Outside, s: *State, cols: u16, rows: u16, places: []?usize) void { outside.n +%= 1; if (tape.speculating()) return; s.written = true; the().resize(s.impl, cols, rows, places); } /// Its cells' size in pixels (kitty graphics, CSI 14/16 t). 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 fn replies(outside: *Outside, s: *State) []const u8 { const r = the().replies(s.impl); if (r.len > 0) outside.n +%= 1; return r; } // ---- input ---- /// One key for its program, as the program's keyboard protocol and modes /// ask for it, written out. 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 fn mouse(s: *State, last: *?Coordinate, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { return the().mouse(s.impl, last, buf, action, button, mods, col, row, any_pressed); } /// A wheel turn for its program; null when the wheel is not the program's. pub fn wheel(s: *State, last: *?Coordinate, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { return the().wheel(s.impl, last, buf, turn, col, row, mods); } /// A paste as xterm makes one: three parts, the text between the brackets /// when the program set 2004. 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 (its row from the top of /// the history) moves the shell's cursor, at the prompt the cursor is at. pub fn promptMoves(s: *State, row: i32, col: i32) ?Moves { return the().promptMoves(s.impl, row, col); } // ---- prompt and commands ---- /// 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); } /// 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); } /// The shell exited in the middle of a command: its output ends at the /// cursor. pub fn endOutputHere(outside: *Outside, s: *State) void { outside.n +%= 1; 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; 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 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 fn textRows(s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) iface.TextError!Rows { return the().textRows(s.impl, alloc, scratch); } /// The rows a view at `place` (Pane.scrolled_to) shows as text, prompts /// cut off or not. pub fn viewport(s: *State, arena: std.mem.Allocator, cut: bool, place: ?usize) iface.TextError![]const []const u8 { return the().viewport(s.impl, arena, cut, place); } /// 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: the prompt's columns, measured in /// the row's text as the core measures a display. pub fn promptPrefix(tab: u16, 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(tab, raw, cols)), }; } /// 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, /// 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 ---- // // Plain data both ways: the core hands the theme's colours (`Ink`) and a // buffer, and is given its view's cells (`Painted`, `PaintedRow`) and its // images as placements; which of the body's rows they stand under is the // core's (core/ansi.zig). /// The rows a view at `place` (Pane.scrolled_to) shows from its row /// `first`, `rows.len` of them, as cells in the theme's colours, through /// the theme's filter when the pane has it on. pub fn paint(s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, place: ?usize, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void { the().paint(s.impl, ink, palette, filtered, place, first, cols, cells, rows); } /// Its kitty graphics over the body's rows, as placements. 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); } /// Whether the screen showing holds any kitty graphics image. pub fn hasImages(s: ?*const State) bool { const o = ops orelse return false; return o.hasImages(if (s) |state| state.impl else null); } // ---- the boundary (S1): every call of the core's into its terminal ---- /// Every call of the core's (core/, but this file and the module's own /// core/term/) into a terminal, by entry, its files and how many in each /// (a test's among them), and its rule: the emulator is outside the /// rollback copy and its digest is the terminal's (`State.digest`, which /// covers what abi/term.zig `replicated` lists a step reads, but the /// history's text). A READ from a step is covered by the digest or is /// said not to be; a WRITE outside the copy is never made by a unit kept /// to replay, or its record puts it back exactly; a LOCAL entry /// (abi/term.zig `local`) is never read into a step's state. A new call /// fails the test below until it is listed here with its rule (round 6's /// and pardes-image-loop's tables, kept as a test). pub const calls = [_]struct { []const u8, []const u8, []const u8 }{ // ---- writes: outside the copy ---- .{ "open", "dump.zig:1 panes.zig:1", "WRITE: a terminal made by a step (a shell's pane) or a load, counted (`Outside`); a speculation is refused it" }, .{ "close", "panes.zig:1", "WRITE: let go by a step that closes its pane, counted; a speculation is refused it" }, .{ "revive", "dump.zig:1", "WRITE: a load's (a join's dump, a Restore): no copy is held" }, .{ "reload", "panes.zig:1", "WRITE: a join's step remakes each terminal written since its last reload, on every side (panes.reloadTerminals, the session's choice taped, the snapshot's hash compared)" }, .{ "feed", "keys.zig:1 panes.zig:3 replica.zig:1", "WRITE: the pty's bytes in a unit, every side in the tape's order, every view's place (Pane.scrolled_to, in the copy) carried through it, counted: a unit that moved the count is applied once, to the confirmed core (replica.zig `confirm`); a speculation is refused it (keys.zig's, replica.zig's: tests')" }, .{ "resize", "panes.zig:1", "WRITE: a step's reflow, every view's place carried through it, counted; a speculation owes it (counted, not made): its input is taken when confirmed, never as speculated" }, .{ "endOutputHere", "ninep/pty.zig:1", "WRITE: a 9P pty/run's step ends a command's output at the cursor: the session's step, replayed as such" }, .{ "replies", "Core.zig:1", "WRITE: a step drains the reply buffer (in the digest), counted when it held any (the feed's own unit, which filled it); only the session writes it to the pty (pty_write is off the tape)" }, // ---- reads by a step: in the digest ---- .{ "grid", "Core.zig:2 ansi.zig:3 body_layer.zig:3 draw.zig:2 dump.zig:4 echo.zig:8 exec.zig:2 layout.zig:2 panes.zig:5 replica.zig:2", "READ: the size, the history's length, the cursor: in the digest (a view's place is its pane's; ansi.zig, body_layer.zig, draw.zig, echo.zig: a draw's)" }, .{ "modes", "Core.zig:5 draw.zig:1 dump.zig:2 echo.zig:3 exec.zig:3 mouse.zig:4 ninep/pty.zig:3 panes.zig:2 replica.zig:1", "READ: the program's modes (mouse, focus, bracketed paste, the alternate screen): in the digest (draw.zig, echo.zig: a draw's; panes.zig: a view scrolls no history on the alternate screen)" }, .{ "prompt", "Core.zig:1 builtins.zig:1 echo.zig:1 exec.zig:3 ninep/pty.zig:1 panes.zig:1", "READ: the OSC 133 cycle: in the digest (`marksOf`); Core.zig's and ninep/pty.zig's also taped (`.prompt`, each side's compared)" }, .{ "promptPrefix", "body_layer.zig:1 edit.zig:1 exec.zig:1", "READ: a row's prompt cells (`promptCut`): the active area's in the digest; a history row's text is not (below)" }, .{ "hasImages", "replica.zig:3 tagline.zig:1", "READ: whether it holds a kitty image (the tag's prefix): in the digest" }, .{ "key", "keys.zig:1", "READ: a key's bytes for the pty from its modes (in the digest): a write the session makes" }, .{ "mouse", "mouse.zig:4", "READ: a report's bytes from its modes (in the digest); the last cell told is the pane's (in the copy)" }, .{ "wheel", "mouse.zig:1", "READ: a wheel's report from its modes (in the digest)" }, .{ "paste", "edit.zig:1", "READ: a paste's bracketing from its modes (in the digest)" }, .{ "promptMoves", "keys.zig:1", "READ: the cursor keys a click at its prompt types, from the prompt's cells and the cursor (in the digest)" }, .{ "page", "Core.zig:1 ninep/ctl.zig:1", "PURE: a pager's parse of bytes the step holds; no emulator" }, .{ "filter", "File.zig:1", "PURE: a pager's colours from the theme; no emulator" }, .{ "spanColor", "File.zig:2", "PURE: as `filter`" }, // ---- reads by a step: NOT in the digest (the history's text) ---- .{ "scrollback", "Core.zig:3 Effect.zig:1 dump.zig:1 ninep/pane.zig:1 ninep/screen.zig:2", "READ, NOT COVERED: the history's text (a 9P read, a Save, an exit dump): each side fed the same bytes; a parting there is found when it reaches the core's state" }, .{ "scrollbackLen", "ninep/ctl.zig:1 ninep/pane.zig:1", "READ, NOT COVERED: the history's text's length (its row count is in the digest)" }, .{ "commandOutput", "ninep/pty.zig:1", "READ, NOT COVERED: a command's output rows (a 9P pty/run): taped as the session's answer" }, .{ "textRows", "edit.zig:2", "READ, NOT COVERED: every row's text, the history's among them (a selection, a Look over a shell)" }, .{ "viewport", "body_layer.zig:1 replica.zig:1", "READ: the rows' text a view's place (in the digest, with its pane) shows (body_layer.zig: a draw's; replica.zig: a test's)" }, .{ "editRows", "ansi.zig:1", "READ: rows' text for a draw" }, // ---- local ---- .{ "due", "Core.zig:1", "LOCAL: its next wake (a blink, an animation): the loop's, never a step's state" }, .{ "cellPixels", "ansi.zig:1 panes.zig:2", "LOCAL: a frontend's draw sets its view's cell size (ansi.zig); a step sets the view's (in the digest) before each feed (panes.zig), so a reply to CSI 16 t is the step's" }, .{ "echoCell", "echo.zig:1", "LOCAL: the predicted echo's judge reads a cell; the echo is no core state" }, .{ "paint", "ansi.zig:1", "LOCAL: its cells drawn" }, .{ "images", "ansi.zig:1", "LOCAL: its kitty images drawn" }, .{ "start", "tape.zig:1", "LOCAL: the module's start, a test's (its own process's)" }, .{ "emulatorOf", "Core.zig:2 ninep/pty.zig:3 replica.zig:1", "the module's state itself: tests only" }, }; test "every call of the core's into a terminal is listed with its rule (S1): a new read, writer or local use fails until it is" { const gpa = std.testing.allocator; const io = std.testing.io; var dir = try std.Io.Dir.cwd().openDir(io, "core", .{ .iterate = true }); defer dir.close(io); var walker = try dir.walk(gpa); defer walker.deinit(); var wrong: usize = 0; var counts: std.StringHashMapUnmanaged(usize) = .empty; defer { var it = counts.keyIterator(); while (it.next()) |k| gpa.free(k.*); counts.deinit(gpa); } while (try walker.next(io)) |e| { if (e.kind != .file or !std.mem.endsWith(u8, e.basename, ".zig")) continue; if (std.mem.eql(u8, e.path, "Term.zig") or std.mem.startsWith(u8, e.path, "term/")) continue; const src = try e.dir.readFileAlloc(io, e.basename, gpa, .limited(16 << 20)); defer gpa.free(src); var lines = std.mem.splitScalar(u8, src, '\n'); while (lines.next()) |line| { if (std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), "//")) continue; var at: usize = 0; while (std.mem.indexOfPos(u8, line, at, "Term.")) |i| { at = i + 5; var end = at; while (end < line.len and (std.ascii.isAlphanumeric(line[end]) or line[end] == '_')) end += 1; if (end == at or end >= line.len or line[end] != '(' or !std.ascii.isLower(line[at])) continue; if (i > 0 and (std.ascii.isAlphanumeric(line[i - 1]) or line[i - 1] == '_')) continue; const k = try std.fmt.allocPrint(gpa, "{s} {s}", .{ line[at..end], e.path }); const got = try counts.getOrPut(gpa, k); if (got.found_existing) { gpa.free(k); got.value_ptr.* += 1; } else got.value_ptr.* = 1; } } } // Each listed file's count is what the tree has, and nothing else calls. for (calls) |c| { var files = std.mem.tokenizeScalar(u8, c[1], ' '); while (files.next()) |fc| { const colon = std.mem.lastIndexOfScalar(u8, fc, ':').?; const want = try std.fmt.parseInt(usize, fc[colon + 1 ..], 10); var buf: [256]u8 = undefined; const pair = try std.fmt.bufPrint(&buf, "{s} {s}", .{ c[0], fc[0..colon] }); const have = counts.get(pair) orelse 0; if (have == want) continue; wrong += 1; std.debug.print("core/{s}: {d} calls of Term.{s}, Term.zig's `calls` says {d}: {s}\n", .{ fc[0..colon], have, c[0], want, c[2] }); } } var it = counts.iterator(); while (it.next()) |kv| { const space = std.mem.indexOfScalar(u8, kv.key_ptr.*, ' ').?; const name = kv.key_ptr.*[0..space]; const file = kv.key_ptr.*[space + 1 ..]; if (listedCall(name, file)) continue; wrong += 1; std.debug.print("core/{s}: {d} calls of Term.{s}, not in Term.zig's `calls`: list it with its rule (a step's read the digest covers, a write the copy puts back, a local use)\n", .{ file, kv.value_ptr.*, name }); } try std.testing.expectEqual(@as(usize, 0), wrong); } // Every WRITE above takes its core's count first (`Outside`): a call // cannot be written without one, so the count cannot be forgotten at a call // site (the compiler holds that); that a new op is listed as a WRITE is the // test's above and a reviewer's. comptime { for (calls) |c| if (std.mem.startsWith(u8, c[2], "WRITE")) { const params = @typeInfo(@TypeOf(@field(@This(), c[0]))).@"fn".param_types; if (params.len == 0 or params[0] != *Outside) @compileError("Term." ++ c[0] ++ " writes an emulator: it takes its core's count (`*Outside`) first"); }; } fn listedCall(name: []const u8, file: []const u8) bool { for (calls) |c| { if (!std.mem.eql(u8, c[0], name)) continue; var files = std.mem.tokenizeScalar(u8, c[1], ' '); while (files.next()) |fc| if (std.mem.eql(u8, fc[0..std.mem.lastIndexOfScalar(u8, fc, ':').?], file)) return true; } return false; } // ---- a core without a terminal (core-test's) ---- test "a core without a terminal boots to a scratch pane" { if (ops != null) return error.SkipZigTest; const pardes = @import("root.zig"); for ([_]pardes.Options{ .{}, .{ .tty_only = true }, .{ .boot = .tty }, .{ .shells = 3 } }) |opts| { const p = try pardes.Pardes.init(std.testing.allocator, opts); defer p.deinit(); const pane = p.panes[0].?; try std.testing.expect(pane.terminal == null); try std.testing.expect(pane.file != null); try std.testing.expectEqual(null, p.panes[1]); } } test "a core without a terminal: Term refuses in words, and no line is typed at a shell" { if (ops != null) return error.SkipZigTest; const pardes = @import("root.zig"); const p = try pardes.Pardes.init(std.testing.allocator, .{ .file = "mise.toml" }); defer p.deinit(); try std.testing.expectError(error.NoTerminal, p.newShell(p.freeSlot().?, "")); try std.testing.expect(p.executeBuiltinLine(0, "Term")); const pane = p.panes[0].?; try std.testing.expectEqualStrings("Term: " ++ none, pane.msg[0..pane.msg_len]); // A line no shell can take runs in a command pane, a terminal: refused. try std.testing.expectEqual(null, pardes.exec.execute(p, 0, "make")); try std.testing.expectEqualStrings("exec: " ++ none, pane.msg[0..pane.msg_len]); for (p.panes, 0..) |slot, id| if (slot) |_| try std.testing.expect(!pardes.exec.takesCommandLine(p, id)); } test "a core without a terminal pages a program's output as plain text" { if (ops != null) return error.SkipZigTest; const pardes = @import("root.zig"); const raw = "one\n\x1b[31mtwo\x1b[0m\n"; const paged = try page(std.testing.allocator, raw); defer paged.deinit(std.testing.allocator); try std.testing.expectEqualStrings(raw, paged.text); try std.testing.expectEqual(0, paged.spans.len); const p = try pardes.Pardes.init(std.testing.allocator, .{ .stdin_text = "one\ntwo\n" }); defer p.deinit(); for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.pager) { try std.testing.expectEqualStrings("one\ntwo\n", f.content); try std.testing.expectEqual(0, f.pager_spans.len); return; }; return error.NoPager; }