summaryrefslogtreecommitdiff
path: root/core/Term.zig
diff options
context:
space:
mode:
Diffstat (limited to 'core/Term.zig')
-rw-r--r--core/Term.zig497
1 files changed, 497 insertions, 0 deletions
diff --git a/core/Term.zig b/core/Term.zig
new file mode 100644
index 00000000..116c1118
--- /dev/null
+++ b/core/Term.zig
@@ -0,0 +1,497 @@
+//! 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 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
+/// (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,
+
+ /// 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 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(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);
+ 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 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(s: *State) void {
+ 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 view ----
+
+/// One read of its program's output (`Told` says where the tracked rows
+/// went).
+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 fn viewTo(s: *State, at: ?usize) void {
+ the().viewTo(s.impl, at);
+}
+
+/// Its view moved by a number of rows (negative scrolls back).
+pub fn scroll(s: *State, delta: i32) void {
+ the().scroll(s.impl, delta);
+}
+
+/// Its view back onto its output.
+pub fn follow(s: *State) void {
+ the().follow(s.impl);
+}
+
+/// Its grid reflowed, now or when `resizeDeferred` makes it.
+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 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(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 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, 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 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 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 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(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; 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 its view shows as text, prompts cut off or not.
+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: 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 fn markRead(s: *State) void {
+ the().markRead(s.impl);
+}
+
+/// 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).
+
+/// Its view's rows from `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, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void {
+ the().paint(s.impl, ink, palette, filtered, 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);
+}
+
+/// The Petscii builtin on it: its kitty graphics as glyph art, or back to
+/// pixels; null for none.
+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 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 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 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 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 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);
+}
+
+pub fn dumpScreen(s: *State, w: *std.Io.Writer) !void {
+ return the().dumpScreen(s.impl, w);
+}
+
+// ---- 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;
+}