summaryrefslogtreecommitdiff
path: root/src/term/terminal.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/term/terminal.zig')
-rw-r--r--src/term/terminal.zig1273
1 files changed, 197 insertions, 1076 deletions
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 });
-}