summaryrefslogtreecommitdiff
path: root/src/term
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 03:44:57 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commita22b579ad2df8d1811f0e194fa1bbc06e2282cf8 (patch)
tree9dcaaa6d17c6c67048b58456dcd9dbdb74b9fc9a /src/term
parenta3509e4df5efc94b0deee3b06dd72f85b0d96647 (diff)
downloadpardes-a22b579ad2df8d1811f0e194fa1bbc06e2282cf8.tar.gz
pardes-a22b579ad2df8d1811f0e194fa1bbc06e2282cf8.zip
term: the terminal a module of its own (docs/next-terminal.md, Phase 1): src/term/term.zig roots it, importing std, ghostty-vt, wuffs, zstbi and plain, never the core, and gives the core one table, `ops` (plain.term.Ops: about 60 entries, the records they take and give and the opaque handles State, Encoder, Track and Replica, in src/plain/term.zig), its own functions put in it through a cast refused at compile time unless each parameter and result matches the table's but for the handles and every error is one the table names; src/Term.zig, the core's side, takes `ops` from the term module when the build's term_options say the core has one (every core module but core-test's), null otherwise, and Term.State is a handle with the walk's hooks, so a dump keeps a terminal as it did (its Parts by name through walk.save, then ghostty's snapshot) and the digest is the emulator's; echo.zig comes back to the core (src/echo.zig: predicted echo is the replica's presentation, its five reads of the emulator through Term.grid, modes, prompt and Term.echoCell); screen_state's Peer is a plain record both sides name (its noteSent a function of screen_state's), its Encoder, Track and Replica handles made and freed through the table (replica.Screens makes its encoder at the first encode); a prompt's cut is told in columns and measured in its row's text by the core (Term.promptPrefix, File.rawAtDisplay); TerminalImages' decode bound moves from memory.limits to the decoder it bounds; build.zig: core_lean, the core module without the terminal, is core-test's, and wireCore no longer gives any core module ghostty-vt, wuffs or zstbi (the term module has them), so core-test's compile names none of ghostty, wuffs, zstbi, simdutf, highway or -lc++ (from --verbose); term-test runs the module's own tests (the pager's, screen_state's, the luminance table's); the tests of a terminal through a core move as they were to test/terminal.zig, in pane-test, which imports both (`of` reads the emulator behind a handle; the dump round trip frees through State.dumpFree), and tests elsewhere that read the emulator do it through Term.emulatorOf, a test in core-test skipping first; core-test skips a test whose terminal Term.open refuses; Authority.init releases its tape when the core it boots fails (it leaked); tests: core-test (no terminal) 409 of 941, 532 skipped, shell-test (the same tests with the terminal) 984 of 984, pane-test 180 of 181 (1 skipped, as before), term-test 15 of 15, kitty-test 45 of 45, replicas checked/wrong 0, hxdiff 658 cases 0 mismatches, behaviour-test 268 of 272 (the base's four addon ABI tests), lib-test
Diffstat (limited to 'src/term')
-rw-r--r--src/term/TerminalImages.zig6
-rw-r--r--src/term/echo.zig835
-rw-r--r--src/term/pager.zig13
-rw-r--r--src/term/screen_state.zig131
-rw-r--r--src/term/term.zig164
-rw-r--r--src/term/terminal.zig1273
6 files changed, 392 insertions, 2030 deletions
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/echo.zig b/src/term/echo.zig
deleted file mode 100644
index a5c65f7e..00000000
--- a/src/term/echo.zig
+++ /dev/null
@@ -1,835 +0,0 @@
-//! Predicted echo for a replica's terminal panes, mosh's way
-//! (docs/next-daemon.md, "Phase 6: predicted echo notes"). A key typed into
-//! a terminal goes to the authority, and its echo comes back as screen state
-//! a round trip later: this shows it at once.
-//!
-//! Presentation only. The overlay is the replica's own (`Pardes.echo`, a
-//! `.local` field the rollback copy skips), painted over a terminal's body
-//! after it is drawn (`paint`, from body_layer.renderBody, which the tty and
-//! the GUI share). The core's emulator stays the authority's, and no digest
-//! sees any of this.
-//!
-//! What is predicted: a printable character at the cursor, backspace, and
-//! left and right, in tty mode on the primary screen at the live bottom. Any
-//! other input this replica could not apply itself (Enter, Tab, a chord, a
-//! paste, a click) stops prediction until the authority has confirmed it and
-//! its echo has had `grace` to come back: predictions start again from the
-//! screen's own cursor. So a key typed after Tab waits a round trip; it is
-//! never drawn where the completion was not.
-//!
-//! Judged as mosh does, once the authority confirmed the key and `grace`
-//! passed: at a delta, a cell the screen shows goes, and one it does not is
-//! a misprediction, and every prediction goes. With no delta (nothing
-//! changed: no echo), a frame judges it `stale` later. Shown at once at a
-//! shell's prompt (pardes's OSC 133 marks say its line editor echoes);
-//! elsewhere only once an echo was confirmed there since the last key that
-//! was not predicted (`cat`, a shell without marks), and underlined; never
-//! after a shown misprediction until an echo is confirmed again. A password
-//! 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 = pardes.Pardes;
-const Pane = pardes.Pane;
-const Surface = pardes.Surface;
-const Key = pardes.Key;
-
-const ms = std.time.ns_per_ms;
-/// After the authority confirmed a key, how long its echo has to come back
-/// before a delta that does not show it makes a misprediction (mosh's
-/// ECHO_TIMEOUT): the shell's echo, then the authority's next frame.
-// ponytail: fixed; a loaded host's later echo makes a drawn character go and
-// come back. The echo delay measured per terminal would be the bound.
-pub const grace_ns = 50 * ms;
-/// With no delta at all, how much longer a frame waits to judge a key.
-pub const stale_ns = 250 * ms;
-const never = std.math.maxInt(u64);
-/// Cells predicted at once: a line typed a round trip ahead.
-const max = 64;
-
-/// A cell predicted: `cp` at column `x` of absolute row `row` (the
-/// authority's numbering, screen_state's), a space for a cell backspace
-/// cleared; `was` what the screen showed there before; `seq` the key's.
-pub const Cell = struct { x: u16, row: u64, cp: u21, was: u21, seq: u32, due: u64 = never };
-pub const Cursor = struct { x: u16, row: u64, seq: u32, due: u64 = never };
-
-pub const Stats = struct {
- /// Keys into a terminal predicted, and not.
- predicted: u32 = 0,
- unpredicted: u32 = 0,
- /// Cells the screen showed when judged; cells and cursors it did not.
- confirmed: u32 = 0,
- mispredicted: u32 = 0,
- cursor_missed: u32 = 0,
-};
-
-pub const Echo = struct {
- /// Off: nothing predicted (the harness's baseline).
- on: bool = true,
- /// The harness's clock (ns); the monotonic one when null.
- now: ?u64 = null,
- /// Its client's view, and the terminal it predicts into.
- view: u8 = 0,
- pane: u8 = 0,
- serial: u32 = 0,
- /// Each terminal's last delta: its active area's first row, absolute.
- tops: [pardes.MAX_PANES]u64 = @splat(0),
- cells: [max]Cell = undefined,
- n: u8 = 0,
- cursor: ?Cursor = null,
- /// The newest of its client's inputs the authority confirmed.
- acked: u32 = 0,
- /// The newest input not predicted, and when its echo is due: nothing is
- /// predicted until then. `wait_key`: it was a key forwarded to this
- /// terminal (no other pane's), so the keys typed into it meanwhile wait
- /// in `deferred`, to be predicted over the screen that shows its doing.
- wait: u32 = 0,
- wait_due: u64 = 0,
- wait_key: bool = false,
- deferred: [max]Deferred = undefined,
- nd: u8 = 0,
- /// An echo confirmed since the last key not predicted: shown off a
- /// prompt too. A shown misprediction since the last confirmed echo:
- /// shown nowhere.
- trusted: bool = false,
- doubt: bool = false,
- /// What it draws changed: the client draws a frame.
- changed: bool = false,
- stats: Stats = .{},
- /// Each key's prediction as it is made, when set (the harness's; on
- /// the C heap).
- log: ?*std.ArrayListUnmanaged(Predicted) = null,
-
- pub const Predicted = struct { seq: u32, cell: ?Cell, cursor: Cursor };
-
- fn time(e: *const Echo) u64 {
- return e.now orelse pardes.FrameStats.nowNs();
- }
-
- const Deferred = struct { seq: u32, kind: ?Kind, due: u64 = never };
-
- fn drop(e: *Echo) void {
- if (e.n > 0 or e.cursor != null) e.changed = true;
- e.n = 0;
- e.cursor = null;
- }
-
- /// Every prediction goes, and the keys that made them may still be on
- /// their way: the keys typed next wait for the newest of them to show,
- /// as keys typed behind one not predicted do (`deferred`). Predicted
- /// at once from the screen's cursor, they would land where those keys'
- /// echo is about to (found at 207 ms, where three keys are in flight:
- /// one drop, and every key after it misjudged, drawn nowhere).
- fn lose(e: *Echo) void {
- // The cursor after the newest key: its `due` is that key's, never
- // until the authority has it.
- const newest = e.cursor;
- e.drop();
- const cur = newest orelse return;
- if (e.waiting() or e.time() >= cur.due) return;
- e.wait = cur.seq;
- e.wait_key = true;
- e.nd = 0;
- e.wait_due = cur.due;
- }
-
- fn waiting(e: *const Echo) bool {
- return e.acked < e.wait or e.time() < e.wait_due;
- }
-
- fn waitFor(e: *Echo, seq: u32, key: bool) void {
- e.wait = seq;
- e.wait_due = never;
- e.wait_key = key;
- e.nd = 0;
- }
-
- /// Its client's input `seq`, after the replica took it: `applied`,
- /// it was applied here at once (so it was no key into a terminal).
- pub fn typed(e: *Echo, c: *Pardes, view: u8, ev: pardes.Event, seq: u32, applied: bool) void {
- e.view = view;
- if (applied) return;
- switch (ev) {
- // ponytail: a motion or focus report a program asked for could
- // move its cursor; the judgement catches that.
- .mouse => |m| if (m.kind == .motion) return,
- .pointer_leave, .focus => return,
- else => {},
- }
- const id = keyboardPane(c, view) orelse {
- // Another pane's, or not a key: where the keys after it go is
- // not known here until the authority has it. ponytail: so they
- // wait for it too, each, until a pause.
- e.waitFor(seq, false);
- return;
- };
- if (id != e.pane or c.panes[id].?.serial != e.serial) {
- e.drop();
- e.nd = 0;
- e.pane = @intCast(id);
- e.serial = c.panes[id].?.serial;
- }
- const kind = kindOf(ev);
- const key = forwarded(c, ev);
- // A key that is not one of those predicted says nothing of the
- // program the keys after it reach (Enter: a password prompt's).
- if (kind == null) e.trusted = false;
- if (!e.on) {
- e.stats.unpredicted += 1;
- return e.waitFor(seq, key);
- }
- // Behind keys still deferred: after them, in order.
- e.catchUp(c);
- if (e.waiting() or e.nd > 0) {
- if (e.wait_key and key and e.nd < max) {
- e.deferred[e.nd] = .{ .seq = seq, .kind = kind };
- e.nd += 1;
- return;
- }
- e.stats.unpredicted += 1;
- return e.waitFor(seq, false);
- }
- if (kind) |k| if (e.predict(c.panes[id].?, k, seq)) {
- e.stats.predicted += 1;
- e.changed = true;
- return;
- };
- e.stats.unpredicted += 1;
- e.waitFor(seq, key);
- }
-
- /// The wait over (its key's doing on the screen), the keys deferred
- /// behind it that the screen does not show yet are predicted over it,
- /// in order; those it shows are not. One the authority has whose echo
- /// may be on its way puts it off until its grace has passed.
- fn catchUp(e: *Echo, c: *Pardes) void {
- if (e.nd == 0 or e.waiting()) return;
- const now = e.time();
- var i: usize = 0;
- while (i < e.nd and e.deferred[i].due <= now) i += 1;
- if (i < e.nd and e.deferred[i].due != never) return;
- e.stats.unpredicted += @intCast(i);
- const pane = c.panes[e.pane] orelse return e.waitFor(e.wait, false);
- if (pane.serial != e.serial) return e.waitFor(e.wait, false);
- while (i < e.nd) : (i += 1) {
- const d = e.deferred[i];
- if (d.kind) |k| if (e.predict(pane, k, d.seq)) {
- e.stats.predicted += 1;
- e.changed = true;
- continue;
- };
- // The next to wait for, the rest behind it.
- e.stats.unpredicted += 1;
- const rest = e.nd - i - 1;
- std.mem.copyForwards(Deferred, e.deferred[0..rest], e.deferred[i + 1 .. e.nd]);
- e.wait = d.seq;
- e.wait_due = never;
- e.wait_key = true;
- e.nd = @intCast(rest);
- return;
- }
- e.nd = 0;
- }
-
- /// 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 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;
- var next: Cursor = .{ .x = cur.x, .row = cur.row, .seq = seq };
- var cell: ?Cell = null;
- switch (kind) {
- .char => |cp| {
- // The last column wraps as a program pleases; a cell that
- // holds another character is a line edited in its middle,
- // 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;
- 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 };
- next.x += 1;
- },
- // At the end of a line only: in its middle a line editor moves
- // the rest left.
- .backspace => {
- if (cur.x == 0 or !e.isInput(state, cur.x - 1, cur.row) or !blank(e.cpAt(state, cur.x, cur.row))) return false;
- cell = .{ .x = cur.x - 1, .row = cur.row, .cp = ' ', .was = e.cpAt(state, cur.x - 1, cur.row), .seq = seq };
- next.x -= 1;
- },
- .left => {
- if (cur.x == 0 or !e.isInput(state, cur.x - 1, cur.row)) return false;
- next.x -= 1;
- },
- // 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;
- next.x += 1;
- },
- }
- if (cell) |want| e.put(want);
- e.cursor = next;
- if (e.log) |l| l.append(std.heap.c_allocator, .{ .seq = seq, .cell = cell, .cursor = next }) catch {};
- return true;
- }
-
- fn put(e: *Echo, want: Cell) void {
- for (e.cells[0..e.n]) |*have| if (have.x == want.x and have.row == want.row) {
- const was = have.was;
- have.* = want;
- have.was = was;
- return;
- };
- e.cells[e.n] = want;
- e.n += 1;
- }
-
- fn mine(e: *const Echo, x: u16, row: u64) ?*const Cell {
- for (e.cells[0..e.n]) |*have| if (have.x == x and have.row == row) return have;
- return null;
- }
-
- /// What the screen shows at a cell as predicted so far.
- fn cpAt(e: *const Echo, state: *terminal.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 screenCell(e: *const Echo, state: *terminal.State, x: u16, row: u64) ?terminal.PageCell {
- 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) } });
- }
-
- /// A prompt's input there, or a character predicted.
- fn isInput(e: *const Echo, state: *terminal.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;
- }
-
- /// 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 {
- 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;
- 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;
- }
-
- /// The authority confirmed its client's input `seq`.
- pub fn confirmed(e: *Echo, c: *Pardes, seq: u32) void {
- e.acked = seq;
- const due = e.time() + grace_ns;
- for (e.deferred[0..e.nd]) |*d| if (d.seq <= seq and d.due == never) {
- d.due = due;
- };
- for (e.cells[0..e.n]) |*cell| if (cell.seq <= seq and cell.due == never) {
- cell.due = due;
- };
- if (e.cursor) |*cur| if (cur.seq <= seq and cur.due == never) {
- cur.due = due;
- };
- if (e.wait <= seq and e.wait_due == never) {
- // The authority stepped a key this did not predict, after every
- // one it did: its deltas from here show that key's doing, which
- // no prediction knew of. They go, judged neither way.
- e.wait_due = due;
- e.drop();
- }
- e.catchUp(c);
- }
-
- /// Terminal `id`'s delta was applied, its active area's first row now
- /// `top`.
- pub fn delta(e: *Echo, c: *Pardes, id: u8, top: u64) void {
- if (id == e.pane and top != e.tops[id] and (e.n > 0 or e.cursor != null)) {
- // Scrolled: the rows predicted are others now.
- e.tops[id] = top;
- return e.lose();
- }
- e.tops[id] = top;
- if (id == e.pane) e.judge(c, 0);
- e.catchUp(c);
- }
-
- /// Once a frame: what is stale judged. Whether to draw.
- pub fn frame(e: *Echo, c: *Pardes) bool {
- if (e.n > 0 or e.cursor != null) e.judge(c, stale_ns);
- e.catchUp(c);
- defer e.changed = false;
- return e.changed;
- }
-
- fn judge(e: *Echo, c: *Pardes, slack: u64) void {
- if (e.n == 0 and e.cursor == null) return;
- const now = e.time();
- 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();
- const shown = e.visible(c);
- var i: usize = 0;
- while (i < e.n) {
- const cell = e.cells[i];
- if (now < cell.due) {
- i += 1;
- continue;
- }
- if (!blank(cell.cp) and e.screenCp(state, cell.x, cell.row) != cell.cp) {
- if (now < cell.due + slack) {
- i += 1;
- continue;
- }
- 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 });
- }
- if (shown) e.doubt = true;
- e.trusted = false;
- return e.lose();
- }
- // Shown, or a space (mosh: too easy to show by chance to vouch).
- // A key before the last one not predicted vouches for nothing
- // after it (a line's characters for the password prompt its
- // Enter brought up).
- if (!blank(cell.cp)) {
- e.stats.confirmed += 1;
- if (cell.was != cell.cp and cell.seq > e.wait) {
- e.trusted = true;
- e.doubt = false;
- }
- }
- e.cells[i] = e.cells[e.n - 1];
- e.n -= 1;
- e.changed = true;
- }
- 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) {
- e.cursor = null;
- e.changed = true;
- } else if (now >= cur.due + slack) {
- e.stats.cursor_missed += 1;
- e.lose();
- }
- }
-
- /// Whether its predictions are drawn now.
- pub fn visible(e: *const Echo, c: *const Pardes) bool {
- if (e.doubt) return false;
- if (e.trusted) return true;
- const pane = c.panes[e.pane] orelse return false;
- return atPrompt(pane);
- }
-
- /// Over terminal pane `id`'s body, as renderBody drew it: the
- /// characters predicted and the cursor after them.
- pub fn paint(e: *const Echo, p: *const Pardes, s: *Surface, pane: *const Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16, active: bool) void {
- if (e.n == 0 and e.cursor == null) return;
- 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 top = e.tops[id];
- // Off a prompt, the trust is inferred: underlined, as mosh does.
- const flag = !atPrompt(pane);
- const at = struct {
- fn f(sb_: @TypeOf(sb), pan: u16, h: u16, top_: u64, row: u64) ?u16 {
- if (row < top_ or row - top_ >= sb_.len) return null;
- const screen_row = sb_.total - sb_.len + (row - top_);
- if (screen_row < sb_.offset + pan) return null;
- const y = screen_row - sb_.offset - pan;
- return if (y < h) @intCast(y) else null;
- }
- }.f;
- for (e.cells[0..e.n]) |cell| {
- const y = at(sb, pane.pan, body_h, top, cell.row) orelse continue;
- if (cell.x >= tw) continue;
- const dst = s.at(tx + cell.x, body_y + y);
- // Typed text continues the text before it (mosh's heuristic).
- var style = dst.style;
- if (cell.x > 0) {
- const before = s.at(tx + cell.x - 1, body_y + y);
- if (!before.default and !blank(before.text[0])) style = before.style;
- }
- if (flag and !blank(cell.cp)) style.ul = .single;
- dst.default = false;
- dst.text[0] = @intCast(cell.cp);
- dst.len = 1;
- dst.style = style;
- }
- if (!active or pane.focus != .body) return;
- const cur = e.cursor orelse return;
- const y = at(sb, pane.pan, body_h, top, cur.row) orelse return;
- if (cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + y };
- }
-};
-
-const Kind = union(enum) { char: u21, backspace, left, right };
-
-fn kindOf(ev: pardes.Event) ?Kind {
- const k = switch (ev) {
- .key => |k| k,
- else => return null,
- };
- if (k.ctrl or k.alt) return null;
- switch (k.cp) {
- Key.backspace => return .backspace,
- Key.left => return .left,
- Key.right => return .right,
- else => {},
- }
- // As forwardKey sends it. ponytail: ASCII only; a width table would
- // let the rest in.
- const cp: u21 = if (k.text.len == 1)
- k.text[0]
- else if (k.text.len == 0 and k.cp >= 'a' and k.cp <= 'z' and k.shift)
- k.cp - 'a' + 'A'
- else if (k.text.len == 0)
- k.cp
- else
- return null;
- return if (cp >= 0x20 and cp < 0x7f) .{ .char = cp } else null;
-}
-
-/// Whether key `ev` goes to the terminal's program as it is (forwardKey's)
-/// and not to pardes: Esc backs out of the pane, the tty chord leaves tty
-/// mode, Ctrl-V pastes the register.
-fn forwarded(c: *const Pardes, ev: pardes.Event) bool {
- const k = switch (ev) {
- .key => |k| k,
- else => return false,
- };
- if (k.cp == Key.escape) return false;
- return !(k.ctrl and (k.cp == c.tty_toggle or k.cp == 'v' or k.cp == 'V'));
-}
-
-fn blank(cp: u21) bool {
- return cp == 0 or cp == ' ';
-}
-
-/// At a shell's prompt, reading its input: pardes's marks (a B and no C
-/// since) and the cursor's own, on the primary screen. A shell without
-/// 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;
-}
-
-/// The terminal view `view`'s keys go to, in tty mode: none when they go
-/// elsewhere (a prompt, a header, window mode, another pane).
-fn keyboardPane(c: *const Pardes, view: u8) ?usize {
- const live = c.live == view;
- const v = &(c.views[view] orelse return null);
- const id = v.active;
- if (v.window_pick != null or v.header != null) return null;
- const pane = c.panes[id] orelse return null;
- if (!pane.isTerminal() or pane.terminal == null or pane.prompt != .none) return null;
- const mode = if (live) pane.body.mode else pane.pv[view].body.mode;
- const focus = if (live) pane.focus else pane.pv[view].focus;
- return if (mode == .tty and focus == .body) id else null;
-}
-
-// ---- tests: one authority and one replica, its shell played by hand ----
-
-const testing = std.testing;
-const replica = @import("../replica.zig");
-
-const Rig = struct {
- a: *replica.Authority,
- r: *replica.Replica,
- screens: replica.Screens,
- peer: u16,
- shell: u8,
- /// What the authority wrote its shell's pty.
- written: std.ArrayListUnmanaged(u8) = .empty,
- now: u64 = 1_000 * ms,
-
- fn ptyWrite(ctx: ?*anyopaque, _: u8, bytes: []const u8) void {
- const g: *Rig = @ptrCast(@alignCast(ctx.?));
- g.written.appendSlice(testing.allocator, bytes) catch {};
- }
- fn watched(_: ?*anyopaque) bool {
- return false;
- }
- const vtable: pardes.Host.VTable = .{ .watched = watched, .pty_write = ptyWrite };
-
- fn init(g: *Rig) !void {
- const gpa = testing.allocator;
- g.written = .empty;
- g.now = 1_000 * ms;
- g.a = try replica.Authority.init(gpa, .{ .cols = 60, .rows = 16, .boot = .tty_shell }, .{ .ctx = g, .vtable = &vtable }, true);
- g.screens = .init(gpa);
- g.peer = try g.screens.addPeer();
- g.r = try replica.Replica.init(gpa, 1, try g.a.unit(0, 0), true);
- g.shell = for (g.a.core.panes, 0..) |slot, id| {
- if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
- } else return error.NoShell;
- g.r.echo.now = g.now;
- }
-
- fn deinit(g: *Rig) void {
- g.r.deinit();
- g.screens.deinit(g.a.core);
- g.a.deinit();
- g.written.deinit(testing.allocator);
- }
-
- fn later(g: *Rig, dt: u64) void {
- g.now += dt;
- g.r.echo.now = g.now;
- }
-
- /// The shell prints `bytes`; the replica gets the unit and the delta.
- fn prints(g: *Rig, bytes: []const u8) !void {
- g.a.output(.{ .output = .{ .pane = g.shell, .bytes = bytes } });
- try g.sync();
- }
-
- fn sync(g: *Rig) !void {
- const gpa = testing.allocator;
- if (try g.a.pending()) |u| g.r.confirm(u);
- g.r.settle();
- var msgs: std.ArrayListUnmanaged([]u8) = .empty;
- defer {
- for (msgs.items) |m| gpa.free(m);
- msgs.deinit(gpa);
- }
- try g.screens.flush(g.a.core, g.peer, g.r.view, &msgs);
- for (msgs.items) |m| if (g.r.screen(m)) |reply| {
- _ = try g.screens.take(g.a.core, g.peer, reply);
- };
- }
-
- /// The replica's client types `k`; the message for the authority.
- fn key(g: *Rig, k: Key) ![]u8 {
- return testing.allocator.dupe(u8, try g.r.input(.{ .key = k }));
- }
-
- /// The authority takes it, and the replica its unit.
- fn take(g: *Rig, msg: []u8) !void {
- defer testing.allocator.free(msg);
- if (try g.a.pending()) |u| g.r.confirm(u);
- g.r.confirm(try g.a.take(msg));
- g.r.settle();
- }
-
- /// What the replica's screen shows at the shell's cursor row, drawn,
- /// and whether the cell at `x` is underlined.
- fn drawn(g: *Rig, arena: *std.heap.ArenaAllocator, x: u16) !struct { cp: u8, ul: bool, cursor: ?u16 } {
- _ = arena.reset(.retain_capacity);
- const c = g.r.core();
- c.needs_frame = true;
- const s = try c.render(arena.allocator());
- const pane = c.panes[g.shell].?;
- const body = s.region(.body, g.shell).?.rect;
- const y = body.y + pardes.Term.grid(pane.terminal).cursor_y;
- const cell = s.at(body.x + x, y);
- return .{ .cp = cell.text[0], .ul = cell.style.ul != .off, .cursor = if (s.cursor) |cur| if (cur.y == y) cur.x - body.x else null else null };
- }
-};
-
-const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
-
-test "keys typed at a shell's prompt are drawn at once, and the authority's echo takes their place" {
- var g: Rig = undefined;
- try g.init();
- defer g.deinit();
- try g.prints(prompt);
- var arena: std.heap.ArenaAllocator = .init(testing.allocator);
- defer arena.deinit();
- const before = try g.drawn(&arena, 2);
- try testing.expectEqual(@as(?u16, 2), before.cursor);
- // Typed: shown at once, the cursor past it, and nothing underlined at
- // a prompt.
- const l = try g.key(.{ .cp = 'l', .text = "l" });
- const s = try g.key(.{ .cp = 's', .text = "s" });
- try testing.expectEqual(@as(u32, 2), g.r.echo.stats.predicted);
- var shown = try g.drawn(&arena, 2);
- try testing.expectEqual(@as(u8, 'l'), shown.cp);
- try testing.expect(!shown.ul);
- try testing.expectEqual(@as(?u16, 4), shown.cursor);
- try testing.expectEqual(@as(u8, 's'), (try g.drawn(&arena, 3)).cp);
- // The authority's core draws no overlay of its own.
- try testing.expect(g.a.core.echo == null);
- // The authority takes them, its shell echoes, the delta lands after the
- // grace: confirmed, and the screen's own cells and cursor shown.
- try g.take(l);
- try g.take(s);
- try testing.expectEqualStrings("ls", g.written.items);
- g.later(grace_ns);
- try g.prints("ls");
- try testing.expectEqual(@as(u8, 0), g.r.echo.n);
- try testing.expect(g.r.echo.cursor == null);
- try testing.expectEqual(@as(u32, 2), g.r.echo.stats.confirmed);
- shown = try g.drawn(&arena, 3);
- try testing.expectEqual(@as(u8, 's'), shown.cp);
- try testing.expectEqual(@as(?u16, 4), shown.cursor);
- // Backspace at the end of the line, shown at once.
- const bs = try g.key(.{ .cp = Key.backspace });
- shown = try g.drawn(&arena, 3);
- try testing.expectEqual(@as(u8, ' '), shown.cp);
- try testing.expectEqual(@as(?u16, 3), shown.cursor);
- try g.take(bs);
- g.later(grace_ns);
- try g.prints("\x08\x1b[K");
- try testing.expectEqual(@as(u32, 0), g.r.echo.stats.mispredicted + g.r.echo.stats.cursor_missed);
- try testing.expect(g.r.quiet());
- try testing.expectEqual(replica.digestOf(g.a), g.r.digest());
-}
-
-test "a password prompt shows nothing typed, and a full-screen program is not predicted" {
- var g: Rig = undefined;
- try g.init();
- defer g.deinit();
- try g.prints(prompt ++ "sudo ls\r\n\x1b]133;C;aid=pardes\x07[sudo] password: ");
- var arena: std.heap.ArenaAllocator = .init(testing.allocator);
- defer arena.deinit();
- const x = pardes.Term.grid(g.r.core().panes[g.shell].?.terminal).cursor_x;
- const k = try g.key(.{ .cp = 'h', .text = "h" });
- // Predicted, and not drawn: nothing has confirmed an echo here.
- try testing.expectEqual(@as(u32, 1), g.r.echo.stats.predicted);
- try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, x)).cp);
- try g.take(k);
- // No echo, so no delta: a frame lets it go once it is stale.
- g.later(grace_ns + stale_ns);
- _ = g.r.echoFrame();
- try testing.expectEqual(@as(u8, 0), g.r.echo.n);
- try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
- // The next key still shows nothing.
- const k2 = try g.key(.{ .cp = 'i', .text = "i" });
- try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, x)).cp);
- try g.take(k2);
- // vim: the alternate screen, never predicted.
- try g.prints("\r\n\x1b]133;D;1;aid=pardes\x07" ++ prompt ++ "vim\r\n\x1b]133;C;aid=pardes\x07\x1b[?1049h\x1b[H~");
- g.later(grace_ns + stale_ns);
- _ = g.r.echoFrame();
- const before = g.r.echo.stats.predicted;
- try g.take(try g.key(.{ .cp = 'i', .text = "i" }));
- try testing.expectEqual(before, g.r.echo.stats.predicted);
-}
-
-test "keys still on their way when their predictions go: the next waits for their echo, never predicted where it is about to land" {
- var g: Rig = undefined;
- try g.init();
- defer g.deinit();
- try g.prints(prompt);
- // Three keys typed a round trip ahead; the authority has the first,
- // and its shell echoes something else: every prediction goes.
- const a = try g.key(.{ .cp = 'a', .text = "a" });
- const b = try g.key(.{ .cp = 'b', .text = "b" });
- const c = try g.key(.{ .cp = 'c', .text = "c" });
- try testing.expectEqual(@as(u32, 3), g.r.echo.stats.predicted);
- try g.take(a);
- g.later(grace_ns);
- try g.prints("A");
- try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
- try testing.expectEqual(@as(u8, 0), g.r.echo.n);
- // The next key is not predicted at the screen's cursor, where b's
- // echo lands: it waits for b and c.
- const d = try g.key(.{ .cp = 'd', .text = "d" });
- try testing.expectEqual(@as(u32, 3), g.r.echo.stats.predicted);
- try testing.expectEqual(@as(u8, 0), g.r.echo.n);
- try g.take(b);
- try g.take(c);
- g.later(grace_ns);
- try g.prints("bc");
- // Their echo shown: d is predicted after it.
- try testing.expectEqual(@as(u32, 4), g.r.echo.stats.predicted);
- try testing.expectEqual(@as(u8, 1), g.r.echo.n);
- try testing.expectEqual(@as(u16, 5), g.r.echo.cells[0].x);
- try g.take(d);
- g.later(grace_ns);
- try g.prints("d");
- try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
- try testing.expect(!g.r.echo.doubt);
- try testing.expectEqual(@as(u8, 0), g.r.echo.n);
-}
-
-test "a misprediction takes every prediction back and shows none until an echo is confirmed; after Tab nothing is predicted until its echo" {
- var g: Rig = undefined;
- try g.init();
- defer g.deinit();
- try g.prints(prompt);
- var arena: std.heap.ArenaAllocator = .init(testing.allocator);
- defer arena.deinit();
- // A line editor that echoes something else (vi's command mode): shown,
- // then taken back.
- const a = try g.key(.{ .cp = 'a', .text = "a" });
- try testing.expectEqual(@as(u8, 'a'), (try g.drawn(&arena, 2)).cp);
- try g.take(a);
- g.later(grace_ns);
- try g.prints("A");
- try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
- try testing.expect(g.r.echo.doubt);
- try testing.expectEqual(@as(u8, 'A'), (try g.drawn(&arena, 2)).cp);
- // Doubted: predicted, not drawn, until one is confirmed.
- const b = try g.key(.{ .cp = 'b', .text = "b" });
- try testing.expectEqual(@as(u8, ' '), (try g.drawn(&arena, 3)).cp);
- try g.take(b);
- g.later(grace_ns);
- try g.prints("b");
- try testing.expect(!g.r.echo.doubt);
- const c = try g.key(.{ .cp = 'c', .text = "c" });
- try testing.expectEqual(@as(u8, 'c'), (try g.drawn(&arena, 4)).cp);
- // Tab: not predicted, and neither is what follows until the authority
- // has it and its echo has had its grace.
- const tab = try g.key(.{ .cp = Key.tab });
- const d = try g.key(.{ .cp = 'd', .text = "d" });
- try testing.expectEqual(@as(u32, 1), g.r.echo.stats.unpredicted);
- try g.take(c);
- try testing.expectEqual(@as(u8, 'c'), (try g.drawn(&arena, 4)).cp);
- // The authority has Tab (and the key after it): what was predicted
- // before it goes, the screen's own shown.
- try g.take(tab);
- try g.take(d);
- try testing.expectEqual(@as(u8, 0), g.r.echo.n);
- g.later(grace_ns);
- try g.prints("c" ++ "ompleted d");
- // `d`, typed behind Tab, the screen showed by then: not predicted.
- try testing.expectEqual(@as(u32, 2), g.r.echo.stats.unpredicted);
- const e = try g.key(.{ .cp = 'e', .text = "e" });
- try testing.expectEqual(@as(u8, 'e'), (try g.drawn(&arena, 15)).cp);
- try g.take(e);
- g.later(grace_ns);
- try g.prints("e");
- // A key typed behind Tab that the authority does not have yet is
- // predicted once Tab's doing is on the screen, where it now goes.
- const tab2 = try g.key(.{ .cp = Key.tab });
- const f = try g.key(.{ .cp = 'f', .text = "f" });
- try g.take(tab2);
- try g.prints("ff");
- try testing.expectEqual(@as(u8, 0), g.r.echo.n);
- g.later(grace_ns);
- _ = g.r.echoFrame();
- try testing.expectEqual(@as(u8, 1), g.r.echo.n);
- try testing.expectEqual(@as(u8, 'f'), (try g.drawn(&arena, 18)).cp);
- try g.take(f);
- g.later(grace_ns);
- try g.prints("f");
- try testing.expectEqual(@as(u8, 0), g.r.echo.n);
- try testing.expectEqual(@as(u32, 1), g.r.echo.stats.mispredicted);
- try testing.expectEqual(@as(u32, 0), g.r.echo.stats.cursor_missed);
- try testing.expect(g.r.quiet());
- try testing.expectEqual(replica.digestOf(g.a), g.r.digest());
-}
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 });
-}