1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
|
//! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the
//! entries of the terminal module (src/term/, its own module: ghostty-vt,
//! wuffs and zstbi are its, not the core's) and the plain records they take
//! and give (src/plain/term.zig). A terminal pane holds a `*State` the core
//! never looks into: what it knows of one it is told here, as numbers,
//! bytes, text and cells. A core built without the module (a test
//! configuration: core-test) has `ops` null, and no terminal at all.
const std = @import("std");
const builtin = @import("builtin");
const plain = @import("plain");
const walk = @import("walk.zig");
const tape = @import("tape.zig");
const dump = @import("dump.zig");
const File = @import("File.zig");
const iface = plain.term;
/// The terminal module's entries; null in a core built without it.
pub const ops: ?*const iface.Ops = if (@import("term_options").terminal) &@import("term").ops else null;
/// What a core without a terminal says, once, where one would have been.
pub const none = "no terminal in this build";
pub const Grid = iface.Grid;
pub const Told = iface.Told;
pub const Modes = iface.Modes;
pub const Prompt = iface.Prompt;
pub const CommandOutput = iface.CommandOutput;
pub const Rows = iface.Rows;
pub const Moves = iface.Moves;
pub const MouseMods = iface.MouseMods;
pub const MouseButton = iface.MouseButton;
pub const MouseAction = iface.MouseAction;
pub const Page = iface.Page;
pub const Span = iface.Span;
pub const Ink = iface.Ink;
pub const FilterPalette = iface.FilterPalette;
pub const Filter = iface.Filter;
pub const Painted = iface.Painted;
pub const PaintedRow = iface.PaintedRow;
pub const ImagesAt = iface.ImagesAt;
pub const EchoCell = iface.EchoCell;
pub const Peer = iface.Peer;
pub const Applied = iface.Applied;
pub const Encoder = iface.Encoder;
pub const Track = iface.Track;
pub const Replica = iface.Replica;
fn the() *const iface.Ops {
return ops orelse unreachable; // no State, Encoder or Replica is made without it
}
/// A terminal pane's terminal: the module's handle, and the walk's hooks
/// (src/walk.zig) for it: the replay digest, and the dump, which keeps it
/// as it always has (`Parts` by name, then ghostty's snapshot).
pub const State = struct {
impl: *iface.State,
/// The emulator as its program has made it, for the replay digest.
/// Under screen-state terminals the emulator is the authority's, and a
/// replica's is what the last delta made it: compared as screens
/// (test/replicas.zig), not step by step.
pub fn digest(s: *const State, h: *walk.Hasher) void {
if (tape.screenState()) return;
s.digestScreen(h, true);
}
/// `view`: where its view is too (a replica's speculation may move it).
pub fn digestScreen(s: *const State, h: *walk.Hasher, view: bool) void {
the().digest(s.impl, h, view);
}
pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void {
const parts = the().parts(s.impl);
const bytes = try walk.save(iface.Parts, gpa, &parts);
defer gpa.free(bytes);
try w.writeAll(std.mem.asBytes(&@as(u64, bytes.len)));
try w.writeAll(bytes);
try the().snapshot(s.impl, gpa, w, dump.slim_terminals);
}
/// What `dumpRead` made, freed: a load that failed after it.
pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void {
the().close(s.impl, gpa);
}
pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void {
const o = ops orelse return error.NoTerminal;
if (bytes.len < 8) return error.EndOfDump;
const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump;
if (bytes.len - 8 < n) return error.EndOfDump;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null);
out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) };
}
};
/// The module's own state behind a handle: for a test that reads the
/// emulator itself, in a core with the module (a test in one without skips
/// before it gets here: `ops == null` is known at compile time).
pub fn emulatorOf(s: *State) *@import("term").terminal.State {
return @ptrCast(@alignCast(s.impl));
}
// ---- lifecycle ----
/// A new terminal, `cols` by `rows`, allocated with `gpa` (its own from
/// then on). Refused in a core without one: `error.NoTerminal`, which a
/// word reports as `none` says it.
pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State {
const o = ops orelse return error.NoTerminal;
const s = try gpa.create(State);
errdefer gpa.destroy(s);
s.* = .{ .impl = try o.open(gpa, cols, rows) };
return s;
}
/// It and what it holds, freed; the kitty images' caches were `gpa`'s.
pub fn close(s: *State, gpa: std.mem.Allocator) void {
const own = the().gpa(s.impl);
the().close(s.impl, gpa);
own.destroy(s);
}
/// When its next kitty animation frame is due (ms on the core's clock), as
/// its last drawn frame left it; null when nothing plays.
pub fn due(s: *const State) ?u64 {
return the().due(s.impl);
}
/// Loaded from a dump without its shell: its program's modes reset, its
/// history marked off from what the next shell prints.
pub fn revive(s: *State) void {
the().revive(s.impl);
}
/// The PNG resize workers kitty images are decoded with, started and
/// stopped with the host.
pub fn start(gpa: std.mem.Allocator) void {
if (ops) |o| o.start(gpa);
}
pub fn stop() void {
if (ops) |o| o.stop();
}
// ---- output and view ----
/// One read of its program's output (`Told` says where the tracked rows
/// went).
pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told {
return the().feed(s.impl, bytes, tracked, rows, erased);
}
/// Where the view and the cursor are; all zero without a terminal.
pub fn grid(s: ?*const State) Grid {
const o = ops orelse return .{};
return o.grid(if (s) |state| state.impl else null);
}
/// Its view to a row of its history, or onto its output (null).
pub fn viewTo(s: *State, at: ?usize) void {
the().viewTo(s.impl, at);
}
/// Its view moved by a number of rows (negative scrolls back).
pub fn scroll(s: *State, delta: i32) void {
the().scroll(s.impl, delta);
}
/// Its view back onto its output.
pub fn follow(s: *State) void {
the().follow(s.impl);
}
/// Its grid reflowed, now or when `resizeDeferred` makes it.
pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void {
the().resize(s.impl, cols, rows, later);
}
pub fn resizeDeferred(s: *State) bool {
return the().resizeDeferred(s.impl);
}
/// Its cells' size in pixels (kitty graphics, CSI 14/16 t).
pub fn cellPixels(s: *State, w: u32, h: u32) void {
the().cellPixels(s.impl, w, h);
}
/// What it answered its program since the last call, to be written to its
/// pty.
pub fn replies(s: *State) []const u8 {
return the().replies(s.impl);
}
// ---- input ----
/// One key for its program, as the program's keyboard protocol and modes
/// ask for it, written out.
pub fn key(s: *State, k: plain.Key, out: *std.Io.Writer) !void {
return the().key(s.impl, k, out);
}
/// One mouse event for its program, as the mode and format it set ask for
/// it; empty when the program does not hear of it.
pub fn mouse(s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 {
return the().mouse(s.impl, buf, action, button, mods, col, row, any_pressed);
}
/// A wheel turn for its program; null when the wheel is not the program's.
pub fn wheel(s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 {
return the().wheel(s.impl, buf, turn, col, row, mods);
}
/// A paste as xterm makes one: three parts, the text between the brackets
/// when the program set 2004.
pub fn paste(s: ?*const State, text: []u8) [3][]const u8 {
const o = ops orelse return .{ "", text, "" };
return o.paste(if (s) |state| state.impl else null, text);
}
/// The modes its program set that the core decides by.
pub fn modes(s: ?*const State) Modes {
const o = ops orelse return .{};
return o.modes(if (s) |state| state.impl else null);
}
/// How far left or right a click on the prompt line moves the shell's
/// cursor, at the prompt the cursor is at.
pub fn promptMoves(s: *State, row: i32, col: i32) ?Moves {
return the().promptMoves(s.impl, row, col);
}
// ---- prompt and commands ----
/// Where its shell is in its command cycle; all zero without a terminal.
pub fn prompt(s: ?*State) Prompt {
const o = ops orelse return .{};
return o.prompt(if (s) |state| state.impl else null);
}
/// What the newest finished command printed, read from at most so many
/// rows above its end.
pub fn commandOutput(s: ?*State, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput {
const o = ops orelse return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = true };
return o.commandOutput(if (s) |state| state.impl else null, gpa, max_rows);
}
/// The shell exited in the middle of a command: its output ends at the
/// cursor.
pub fn endOutputHere(s: *State) void {
the().endOutputHere(s.impl);
}
// ---- text ----
/// Its whole scrollback as plain text, logical lines (rows it wrapped
/// joined again), ending in a newline: what its body reads and Save
/// writes. The caller's; empty without a terminal.
pub fn scrollback(s: ?*State, gpa: std.mem.Allocator) ![]const u8 {
const o = ops orelse return gpa.dupe(u8, "");
return o.scrollback(if (s) |state| state.impl else null, gpa);
}
/// How long `scrollback` would be, counted without keeping it.
pub fn scrollbackLen(s: ?*State) usize {
const o = ops orelse return 0;
return o.scrollbackLen(if (s) |state| state.impl else null);
}
/// Its rows from the top of its history as text, a prompt's own cells cut
/// off (`Rows`).
pub fn textRows(s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) iface.TextError!Rows {
return the().textRows(s.impl, alloc, scratch);
}
/// The rows its view shows as text, prompts cut off or not.
pub fn viewport(s: *State, arena: std.mem.Allocator, cut: bool) iface.TextError![]const []const u8 {
return the().viewport(s.impl, arena, cut);
}
/// Its rows `first` and the `count` after it as text, prompts cut off (the
/// edit copy's rows, as they were).
pub fn editRows(s: *State, arena: std.mem.Allocator, first: usize, count: usize) ![]const []const u8 {
return the().editRows(s.impl, arena, first, count);
}
/// How many bytes of one of its rows, as `viewport` and `textRows` give it
/// uncut, are the prompt it starts with: the prompt's columns, measured in
/// the row's text as the core measures a display.
pub fn promptPrefix(s: ?*State, row: i32, raw: []const u8) usize {
const state = s orelse return 0;
if (row < 0) return 0;
const cut = the().promptCut(state.impl, row) orelse return 0;
return switch (cut) {
.keep => 0,
.blank => raw.len,
.cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)),
};
}
/// A step read its rows: its replicas must hold them for the step's
/// replay.
pub fn markRead(s: *State) void {
the().markRead(s.impl);
}
/// What a predicted echo reads of a cell of its active area.
pub fn echoCell(s: *const State, x: u16, y: u16) ?EchoCell {
return the().echoCell(s.impl, x, y);
}
// ---- the pager ----
/// A program's output, as a terminal reads it, paged (`pardes -`, a
/// /pager write): its printed text and its SGR colours as spans over it,
/// every other control dropped. The emulator's own parse, so a +Pager
/// pages what a terminal pane would print. Without a terminal the bytes
/// are paged as they are: plain text, no colours (nothing in the core
/// parses an escape).
pub fn page(gpa: std.mem.Allocator, raw: []const u8) error{OutOfMemory}!Page {
if (ops) |o| return o.page(gpa, raw);
const text = try gpa.dupe(u8, raw);
errdefer gpa.free(text);
return .{ .text = text, .spans = try gpa.alloc(Span, 0) };
}
/// The filter a +Pager's spans are drawn through, and a span's colour
/// through it.
pub fn filter(ink: *const Ink, palette: *FilterPalette) Filter {
return the().filter(ink, palette);
}
pub fn spanColor(f: *Filter, color: plain.Color, is_bg: bool) plain.Color {
return the().spanColor(f, color, is_bg);
}
// ---- draw ----
//
// Plain data both ways: the core hands the theme's colours (`Ink`) and a
// buffer, and is given its view's cells (`Painted`, `PaintedRow`) and its
// images as placements; which of the body's rows they stand under is the
// core's (src/ansi.zig).
/// Its view's rows from `first`, `rows.len` of them, as cells in the
/// theme's colours, through the theme's filter when the pane has it on.
pub fn paint(s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void {
the().paint(s.impl, ink, palette, filtered, first, cols, cells, rows);
}
/// Its kitty graphics over the body's rows, as placements.
pub fn images(s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void {
the().images(s.impl, gpa, at, out, frame, frame_cols);
}
/// The Petscii builtin on it: its kitty graphics as glyph art, or back to
/// pixels; null for none.
pub fn petscii(s: ?*const State) ?bool {
const o = ops orelse return null;
return o.petscii(if (s) |state| state.impl else null);
}
pub fn togglePetscii(s: *State) void {
the().togglePetscii(s.impl);
}
/// Whether the screen showing holds any kitty graphics image.
pub fn hasImages(s: ?*const State) bool {
const o = ops orelse return false;
return o.hasImages(if (s) |state| state.impl else null);
}
// ---- its replicas ----
pub fn encoder(gpa: std.mem.Allocator) !*Encoder {
return the().encoder(gpa);
}
pub fn encoderFree(e: *Encoder) void {
the().encoderFree(e);
}
pub fn track(gpa: std.mem.Allocator) !*Track {
return the().track(gpa);
}
/// A peer's track of it let go (`s` null: it is gone).
pub fn untrack(t: *Track, gpa: std.mem.Allocator, s: ?*State) void {
the().untrack(t, gpa, if (s) |state| state.impl else null);
}
/// What a peer is owed of it, a delta against what the peer was sent.
pub fn encode(s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) !bool {
return the().encode(s.impl, e, t, peer, out);
}
/// Rows of it a replica holds as holes.
pub fn encodeRows(s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) !void {
return the().encodeRows(s.impl, e, t, lo, hi, out);
}
/// Whether a step read its rows since `clearRead`.
pub fn wasRead(s: *const State) bool {
return the().wasRead(s.impl);
}
pub fn clearRead(s: *State) void {
the().clearRead(s.impl);
}
/// A replica's side of one terminal: made, freed, where its active area
/// begins, and the history rows it does not hold.
pub fn replica(gpa: std.mem.Allocator) !*Replica {
return the().replica(gpa);
}
pub fn replicaFree(r: *Replica, gpa: std.mem.Allocator) void {
the().replicaFree(r, gpa);
}
pub fn replicaTop(r: *const Replica) u64 {
return the().replicaTop(r);
}
pub fn missing(r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) !void {
return the().missing(r, lo, hi, out, gpa);
}
/// A replica's side: a delta applied, rows applied, the rows its view
/// shows, rows blank until they come.
pub fn apply(s: *State, r: *Replica, bytes: []const u8) !Applied {
return the().apply(s.impl, r, bytes);
}
pub fn applyRows(s: *State, r: *Replica, bytes: []const u8) !void {
return the().applyRows(s.impl, r, bytes);
}
pub fn shown(s: *State, r: *const Replica) [2]u64 {
return the().shown(s.impl, r);
}
pub fn blank(s: *State, r: *const Replica, lo: u64, hi: u64) void {
the().blank(s.impl, r, lo, hi);
}
pub fn dumpScreen(s: *State, w: *std.Io.Writer) !void {
return the().dumpScreen(s.impl, w);
}
// ---- a core without a terminal (core-test's) ----
test "a core without a terminal boots to a scratch pane" {
if (ops != null) return error.SkipZigTest;
const pardes = @import("pardes.zig");
for ([_]pardes.Options{ .{}, .{ .tty_only = true }, .{ .boot = .tty }, .{ .shells = 3 } }) |opts| {
const p = try pardes.Pardes.init(std.testing.allocator, opts);
defer p.deinit();
const pane = p.panes[0].?;
try std.testing.expect(pane.terminal == null);
try std.testing.expect(pane.file != null);
try std.testing.expectEqual(null, p.panes[1]);
}
}
test "a core without a terminal: Term refuses in words, and no line is typed at a shell" {
if (ops != null) return error.SkipZigTest;
const pardes = @import("pardes.zig");
const p = try pardes.Pardes.init(std.testing.allocator, .{ .file = "mise.toml" });
defer p.deinit();
try std.testing.expectError(error.NoTerminal, p.newShell(p.freeSlot().?, ""));
try std.testing.expect(p.executeBuiltinLine(0, "Term"));
const pane = p.panes[0].?;
try std.testing.expectEqualStrings("Term: " ++ none, pane.msg[0..pane.msg_len]);
// A line no shell can take runs in a command pane, a terminal: refused.
try std.testing.expectEqual(null, pardes.exec.execute(p, 0, "make"));
try std.testing.expectEqualStrings("exec: " ++ none, pane.msg[0..pane.msg_len]);
for (p.panes, 0..) |slot, id| if (slot) |_| try std.testing.expect(!pardes.exec.takesCommandLine(p, id));
}
test "a core without a terminal pages a program's output as plain text" {
if (ops != null) return error.SkipZigTest;
const pardes = @import("pardes.zig");
const raw = "one\n\x1b[31mtwo\x1b[0m\n";
const paged = try page(std.testing.allocator, raw);
defer paged.deinit(std.testing.allocator);
try std.testing.expectEqualStrings(raw, paged.text);
try std.testing.expectEqual(0, paged.spans.len);
const p = try pardes.Pardes.init(std.testing.allocator, .{ .stdin_text = "one\ntwo\n" });
defer p.deinit();
for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.pager) {
try std.testing.expectEqualStrings("one\ntwo\n", f.content);
try std.testing.expectEqual(0, f.pager_spans.len);
return;
};
return error.NoPager;
}
|