summaryrefslogtreecommitdiff
path: root/abi
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-18 21:43:03 -0300
committerGabriel Schneider <[email protected]>2026-11-18 22:03:06 -0300
commit92d553123673376adf6126ab90d49a22c5b833d2 (patch)
tree2a4e83a7e5a0d8766358ce87ccebba72b95f9a2a /abi
parentf9a3179542012ec1a700e2020ac9f616b819f972 (diff)
downloadpardes-92d553123673376adf6126ab90d49a22c5b833d2.tar.gz
pardes-92d553123673376adf6126ab90d49a22c5b833d2.zip
abi: plain.zig and term.zig, the addon header and its Zig module, pardes.h and the replica stream's wire into abi/ (the reorganisation's tree, step 2c; abi.zig, the seam, is step 12's): plain, the addon's and pardes.h's modules as before from their new place, the wire a module of its own (`wire`, named by the core, the runtime and main.zig); shell-test runs the wire's tests on the core's set, since a window's set links the window's C, whose allocator gui.zig holds; nothing else changes: the ledger, frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'abi')
-rw-r--r--abi/addon.zig388
-rw-r--r--abi/pardes.h564
-rw-r--r--abi/pardes_addon.h448
-rw-r--r--abi/plain.zig161
-rw-r--r--abi/term.zig432
-rw-r--r--abi/wire.zig927
6 files changed, 2920 insertions, 0 deletions
diff --git a/abi/addon.zig b/abi/addon.zig
new file mode 100644
index 00000000..1fa2279a
--- /dev/null
+++ b/abi/addon.zig
@@ -0,0 +1,388 @@
+//! A kind of pane in Zig: what an addon imports beside the C ABI it is
+//! built to (pardes_addon.h, translated: `c`), which stays the contract.
+//! It imports nothing of the core. A kind is a struct whose `head` names
+//! it and whose functions are any of pa_ops's, each over a `*T` that
+//! `open` is handed zeroed (its defaults set) in the pane's arena: `init`
+//! (once, at load), `open`, `close`, `tick`, `prefix`, `paint` (required), `view`, `key`, `mouse`,
+//! `body`, `address`, `where`, `ctl`, `ctlRead`, `jobRun`, `jobDone`,
+//! `dump`, `load` and `search`, with these types:
+//!
+//! init() bool false refuses the addon
+//! open(s, path: ?[]const u8, bytes: ?[]const u8) void
+//! tick(s, now: u64, flags: Flags) u64 the next step's time, 0 none
+//! prefix(s, w: *Writer) !void its tag's start, after every tick
+//! paint(s, Window, Paint) void view(s, View) void
+//! key(s, Key) bool mouse(s, Mouse) bool address(s, text) bool
+//! body, where, ctlRead(s, w: *Writer) !void ctl(s, line, reply: *Writer) bool
+//! body(s) []const u8 a body the kind holds, of any length
+//! jobRun(in, Allocator) ?[]u8 jobDone(s, token, out) void
+//! dump(s, buf) usize load(s, bytes, version) bool search(s, pat) void
+//!
+//! and pardes's side (pa_api) as the functions below: `arena` and `heap`
+//! as Allocators, `seed`, `say`, `job`, `draw`, `cancel`, `look`, `text`, `exec`,
+//! `select` and `found`. A body written is at most `body_max` bytes.
+//!
+//! pub const pardes_addon = addon.ops(Snake);
+//! comptime {
+//! addon.exportLib(&pardes_addon);
+//! }
+//!
+//! The library's one export; a pardes with the kind compiled in reads the
+//! declaration instead (Addon.zig), so two kinds there never collide.
+//! addons/snake/snake.zig, addons/life/life.zig and addons/image/image.zig
+//! are the examples.
+const std = @import("std");
+pub const c = @import("pardes_addon");
+const Allocator = std.mem.Allocator;
+
+/// The ABI this file speaks: a header of another needs it brought along.
+pub const abi = 0x30002;
+comptime {
+ if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 3.2 and the header another");
+}
+
+/// A word the kind brings: `opens` a pane of it, else goes to the pane's
+/// `ctl`; `leader` is the keys after Space that run it ("ng": SPC n g).
+pub const Word = struct { name: [:0]const u8, leader: ?[:0]const u8 = null, arg: enum(u8) { none, optional, required } = .none, opens: bool = false, doc: [:0]const u8 = "" };
+/// `pictures`: its panes place pictures, and their tag says how they show.
+/// `plain`: PA_PLAIN, the kind is its extern struct and its step pure (the
+/// header says what that promises): a client runs it itself.
+pub const Head = struct { name: []const u8, version: u32, exts: [:0]const u8 = "", words: []const Word = &.{}, pictures: bool = false, plain: bool = false };
+
+/// pardes's side, kept from init: about the pane of the current call.
+pub var api: *const c.pa_api = undefined;
+
+/// The pane's arena: 16-aligned zeroed memory, all of it freed at the
+/// pane's close (a free frees nothing).
+pub const arena: Allocator = .{ .ptr = undefined, .vtable = &.{ .alloc = arenaAlloc, .resize = Allocator.noResize, .remap = Allocator.noRemap, .free = Allocator.noFree } };
+fn arenaAlloc(_: *anyopaque, n: usize, a: std.mem.Alignment, _: usize) ?[*]u8 {
+ return if (a.toByteUnits() > 16) null else @ptrCast(api.alloc.?(n));
+}
+/// pardes's heap: memory that outlives a call, from any thread.
+pub const heap: Allocator = .{ .ptr = undefined, .vtable = &.{ .alloc = heapAlloc, .resize = Allocator.noResize, .remap = heapRemap, .free = heapFree } };
+fn heapAlloc(_: *anyopaque, n: usize, a: std.mem.Alignment, _: usize) ?[*]u8 {
+ return if (a.toByteUnits() > 16) null else @ptrCast(api.heap.?(null, n));
+}
+fn heapRemap(_: *anyopaque, m: []u8, _: std.mem.Alignment, n: usize, _: usize) ?[*]u8 {
+ return @ptrCast(api.heap.?(m.ptr, n));
+}
+fn heapFree(_: *anyopaque, m: []u8, _: std.mem.Alignment, _: usize) void {
+ _ = api.heap.?(m.ptr, 0);
+}
+/// A job's (`pa_out`): freed after its job_done, the last its answer.
+fn jobAlloc(ctx: *anyopaque, n: usize, a: std.mem.Alignment, _: usize) ?[*]u8 {
+ const out: *c.pa_out = @ptrCast(@alignCast(ctx));
+ return if (a.toByteUnits() > 16) null else @ptrCast(out.alloc.?(out, n));
+}
+
+/// The pane's seed: the same pane, the same number, on every machine.
+pub fn seed() u64 {
+ return api.seed.?();
+}
+/// A message on the pane; an error also refuses an `open`.
+pub fn say(text_: []const u8, how: enum { note, err }) void {
+ api.say.?(text_.ptr, @intCast(text_.len), @backingInt(how));
+}
+/// `jobRun` over a copy of `in` on a worker: its token, 0 when refused.
+pub fn job(in: []const u8) u32 {
+ return api.job.?(in.ptr, @intCast(in.len));
+}
+/// A picture's job (pa_api.draw): `jobRun` over a copy of `in` on a worker
+/// of the process that shows the pane, its answer to `jobDone` there alone
+/// (`token & drawn`), which keeps it for `paint` only. 0 when refused.
+pub fn draw(in: []const u8) u32 {
+ if (api.size < @sizeOf(c.pa_api)) return 0;
+ return api.draw.?(in.ptr, @intCast(in.len));
+}
+pub const drawn = c.PA_DRAWN;
+/// A job's answer not yet come dropped.
+pub fn cancel(token: u32) void {
+ api.cancel.?(token);
+}
+/// Looked at as a click would: a URL, `file:12`, a word.
+pub fn look(text_: []const u8) void {
+ api.look.?(text_.ptr, @intCast(text_.len));
+}
+/// Run as a middle click would.
+pub fn exec(text_: []const u8) void {
+ api.exec.?(text_.ptr, @intCast(text_.len));
+}
+/// What the pane has selected now; empty, none.
+pub fn select(text_: []const u8) void {
+ api.select.?(text_.ptr, @intCast(text_.len));
+}
+/// `place text` rows onto the pane's +Search, from `search` or later.
+pub fn found(rows: []const u8) void {
+ api.found.?(rows.ptr, @intCast(rows.len));
+}
+/// A new text pane `name` holding `bytes`: its serial, 0 if none.
+pub fn text(name: []const u8, bytes: []const u8) u32 {
+ return api.text.?(name.ptr, @intCast(name.len), bytes.ptr, @intCast(bytes.len));
+}
+
+pub const Color = enum(u32) {
+ default = c.PA_DEFAULT,
+ _,
+ /// One of the theme's 256.
+ pub fn index(n: u8) Color {
+ return @fromBackingInt(@intCast(0x02000000 | @as(u32, n)));
+ }
+ pub fn rgb(r: u8, g: u8, b: u8) Color {
+ return @fromBackingInt(@as(u32, r) << 16 | @as(u32, g) << 8 | b);
+ }
+};
+pub const Attrs = packed struct(u16) { bold: bool = false, dim: bool = false, italic: bool = false, _3: bool = false, reverse: bool = false, _5: u3 = 0, underline: bool = false, _9: u7 = 0 };
+pub const Style = struct { fg: Color = .default, bg: Color = .default, attrs: Attrs = .{} };
+
+/// The pane's body in one view as `paint` sees it, every cell unpainted.
+pub const Window = struct {
+ cells: [*]c.pa_cell,
+ stride: u32,
+ cols: u16,
+ rows: u16,
+ cell_w: u16,
+ cell_h: u16,
+ focused: bool,
+ /// The view painted (View.id), and whether it shows pictures as glyph art.
+ view: u8,
+ glyphs: bool,
+
+ /// `text` (UTF-8) from column x of row y on, a character a cell, cut at
+ /// the edge: column first, where the header's pa_put is row first.
+ pub fn put(w: Window, x: usize, y: usize, text_: []const u8, style: Style) void {
+ if (y >= w.rows) return;
+ var it: std.unicode.Utf8Iterator = .{ .bytes = text_, .i = 0 };
+ var col = x;
+ while (it.nextCodepointSlice()) |ch| : (col += 1) {
+ if (col >= w.cols) return;
+ const cell = &w.cells[y * w.stride + col];
+ const n: u8 = @intCast(@min(ch.len, 7));
+ cell.* = .{ .fg = @backingInt(style.fg), .bg = @backingInt(style.bg), .attrs = @bitCast(style.attrs), .len = n, .flags = c.PA_PAINTED };
+ @memcpy(cell.text[0..n], ch[0..n]);
+ }
+ }
+};
+
+/// What `paint` hands back beside the cells; `out`'s at, span and pointer
+/// as the header has them.
+pub const Paint = struct {
+ out: *c.pa_paint,
+ /// Optional display data; always paint a text/raster fallback too.
+ pub fn gpu(p: Paint, bytes: []const u8) bool {
+ if (api.abi < 0x00030001 or bytes.len > 4 << 20) return false;
+ const emit = p.out.gpu orelse return false;
+ return emit(p.out.gpu_ctx, bytes.ptr, @intCast(bytes.len)) == c.PA_OK;
+ }
+ /// A picture over the cells (pa_placement), lowest first.
+ pub fn place(p: Paint, at: c.pa_placement) void {
+ if (p.out.n == p.out.cap) return;
+ p.out.placements[p.out.n] = at;
+ p.out.n += 1;
+ }
+};
+
+/// A view of the pane (pa_view): `id` 1 and up, `cols` 0 when it stops.
+pub const View = extern struct { cols: u16, rows: u16, cell_w: u16, cell_h: u16, fg: Color, bg: Color, sel: Color, link: Color, dpi: u16, max_px: u16, fill: bool, glyphs: bool, id: u8, _: u8 = 0 };
+/// A key: a codepoint (`char('h')`), or one of these; `view` it came from.
+pub const Code = enum(u32) { tab = 0x09, enter = 0x0D, esc = 0x1B, backspace = 0x7F, up = 0xF0001, down, left, right, home, end, page_up, page_down, delete, _ };
+pub const Key = extern struct { code: Code, ctrl: bool = false, alt: bool = false, shift: bool = false, view: u8 = 0 };
+pub fn char(comptime ch: u21) Code {
+ return @fromBackingInt(@intCast(ch));
+}
+/// A pointer event at a cell of view `view`'s window (pa_mouse).
+pub const Mouse = extern struct {
+ button: enum(u8) { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right, _ },
+ action: enum(u8) { press, release, motion, drag, _ },
+ ctrl: bool,
+ shift: bool,
+ alt: bool,
+ view: u8,
+ col: u16,
+ row: u16,
+ amount: f32,
+};
+comptime {
+ if (@sizeOf(View) != @sizeOf(c.pa_view) or @sizeOf(Key) != @sizeOf(c.pa_key) or @sizeOf(Mouse) != @sizeOf(c.pa_mouse)) @compileError("addon.zig's records are not the header's");
+}
+
+/// tick's flags.
+pub const Flags = packed struct(u32) { focused: bool, framed: bool, _: u30 };
+
+/// When a step is next due: what `tick` answers.
+pub const Deadline = extern struct {
+ at: u64 = 0,
+ /// Set and come.
+ pub fn due(d: Deadline, now: u64) bool {
+ return d.at != 0 and now >= d.at;
+ }
+ /// Due a period after it was (a tick comes on a frame, late), or a
+ /// period from now when that is more than a period behind or ahead (a
+ /// record's, of another clock); kept while ahead: its time.
+ pub fn every(d: *Deadline, now: u64, period: u64) u64 {
+ if (d.at == 0 or now -| d.at >= period or d.at > now + period) d.at = now + period else if (now >= d.at) d.at += period;
+ return d.at;
+ }
+ /// None: tick is next called when something happens to the pane.
+ pub fn stop(d: *Deadline) u64 {
+ d.at = 0;
+ return 0;
+ }
+};
+
+/// dump and load as the bytes of an extern struct, refused across
+/// versions: `pub const dump = addon.dumpBytes;` and `load = addon.loadBytes`.
+pub fn dumpBytes(s: anytype, buf: []u8) usize {
+ const b = std.mem.asBytes(s);
+ if (b.len > buf.len) return 0;
+ @memcpy(buf[0..b.len], b);
+ return b.len;
+}
+pub fn loadBytes(s: anytype, bytes: []const u8, version: u32) bool {
+ const T = @TypeOf(s.*);
+ if (version != T.head.version or bytes.len != @sizeOf(T)) return false;
+ s.* = std.mem.bytesToValue(T, bytes);
+ return true;
+}
+
+/// The most a body holds: past it, it is cut (said once in Debug).
+pub const body_max = 4096;
+var body_cut = false;
+
+fn span(p: [*c]const u8, n: u64) []const u8 {
+ return if (p == null) "" else p[0..n];
+}
+
+/// `pardes_addon` exported, when built as a library alone: the kind is its
+/// root (a pardes built as a library, macOS's, has the kinds compiled in).
+pub fn exportLib(comptime ops_: *const c.pa_ops) void {
+ if (@import("builtin").output_mode == .Lib and @hasDecl(@import("root"), "pardes_addon")) @export(ops_, .{ .name = "pardes_addon" });
+}
+
+/// A kind's `pa_ops`: its head, and a C function for each of its own.
+pub fn ops(comptime T: type) c.pa_ops {
+ const F = struct {
+ const words = blk: {
+ var ws: [T.head.words.len]c.pa_word = undefined;
+ for (T.head.words, &ws) |w, *out| out.* = .{ .name = w.name, .leader = if (w.leader) |l| l.ptr else null, .arg = @backingInt(w.arg), .opens = @intFromBool(w.opens), .doc = w.doc };
+ break :blk ws;
+ };
+ fn self(st: ?*anyopaque) ?*T {
+ return @ptrCast(@alignCast(st));
+ }
+ /// What `f(s, writer)` writes into `buf[0..n]`: its length.
+ fn write(comptime f: anytype, s: anytype, buf: [*c]u8, n: usize) u32 {
+ var w: std.Io.Writer = .fixed(buf[0..n]);
+ f(s, &w) catch {};
+ return @intCast(w.end);
+ }
+ fn init(a: [*c]const c.pa_api) callconv(.c) c_int {
+ api = a;
+ return if (!@hasDecl(T, "init") or T.init()) c.PA_OK else 1;
+ }
+ fn open(path: [*c]const u8, bytes: [*c]const u8, len: u64) callconv(.c) ?*anyopaque {
+ const s = arena.create(T) catch return null;
+ s.* = std.mem.zeroInit(T, .{});
+ if (@hasDecl(T, "open")) T.open(s, if (path == null) null else std.mem.span(path), if (bytes == null) null else bytes[0..len]);
+ return s;
+ }
+ fn close(st: ?*anyopaque) callconv(.c) void {
+ T.close(self(st) orelse return);
+ }
+ fn tick(st: ?*anyopaque, t: [*c]c.pa_tick) callconv(.c) void {
+ const s = self(st) orelse return;
+ if (@hasDecl(T, "tick")) t.*.next = T.tick(s, t.*.now, @bitCast(t.*.flags));
+ if (@hasDecl(T, "prefix")) t.*.prefix_len = write(T.prefix, s, &t.*.prefix, t.*.prefix.len);
+ }
+ fn paint(st: ?*anyopaque, w: [*c]const c.pa_window, out: [*c]c.pa_paint) callconv(.c) void {
+ T.paint(self(st) orelse return, .{ .cells = w.*.cells, .stride = w.*.stride, .cols = w.*.cols, .rows = w.*.rows, .cell_w = w.*.cell_w, .cell_h = w.*.cell_h, .focused = w.*.focused != 0, .view = w.*.view, .glyphs = w.*.glyphs != 0 }, .{ .out = out });
+ }
+ fn view(st: ?*anyopaque, v: [*c]const c.pa_view) callconv(.c) void {
+ T.view(self(st) orelse return, @as(*const View, @ptrCast(v)).*);
+ }
+ fn key(st: ?*anyopaque, k: [*c]const c.pa_key) callconv(.c) c_int {
+ return @intFromBool(T.key(self(st) orelse return 0, @as(*const Key, @ptrCast(k)).*));
+ }
+ fn mouse(st: ?*anyopaque, m: [*c]const c.pa_mouse) callconv(.c) c_int {
+ return @intFromBool(T.mouse(self(st) orelse return 0, @as(*const Mouse, @ptrCast(m)).*));
+ }
+ /// The body, the kind's own or written whole, read in pieces.
+ fn text_(st: ?*anyopaque, buf: *[body_max]u8) []const u8 {
+ const s = self(st) orelse return "";
+ if (comptime @typeInfo(@TypeOf(T.body)).@"fn".param_types.len == 1) return T.body(s) else {
+ var w: std.Io.Writer = .fixed(buf);
+ T.body(s, &w) catch if (@import("builtin").mode == .debug and !body_cut) {
+ body_cut = true;
+ std.log.warn("{s}: a body cut at {d} bytes (addon.body_max)", .{ T.head.name, body_max });
+ };
+ return w.buffered();
+ }
+ }
+ fn body_len(st: ?*anyopaque) callconv(.c) u64 {
+ var buf: [body_max]u8 = undefined;
+ return text_(st, &buf).len;
+ }
+ fn body(st: ?*anyopaque, off: u64, out: [*c]u8, n: u32) callconv(.c) u32 {
+ var buf: [body_max]u8 = undefined;
+ const t = text_(st, &buf);
+ const from = t[@min(off, t.len)..][0..@min(t.len -| off, n)];
+ @memcpy(out[0..from.len], from);
+ return @intCast(from.len);
+ }
+ fn address(st: ?*anyopaque, t: [*c]const u8, n: u32) callconv(.c) c_int {
+ return @intFromBool(T.address(self(st) orelse return 0, span(t, n)));
+ }
+ fn where(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 {
+ return write(T.where, self(st) orelse return 0, buf, n);
+ }
+ fn ctl(st: ?*anyopaque, line: [*c]const u8, n: u32, reply: [*c]u8, cap: u32) callconv(.c) c_int {
+ var w: std.Io.Writer = .fixed(reply[0..cap -| 1]);
+ defer reply[w.end] = 0;
+ return if (T.ctl(self(st) orelse return 1, span(line, n), &w)) c.PA_OK else 1;
+ }
+ fn ctl_read(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 {
+ return write(T.ctlRead, self(st) orelse return 0, buf, n);
+ }
+ fn job_run(in: [*c]const u8, n: u32, out: [*c]c.pa_out) callconv(.c) u32 {
+ const gpa: Allocator = .{ .ptr = out, .vtable = &.{ .alloc = jobAlloc, .resize = Allocator.noResize, .remap = Allocator.noRemap, .free = Allocator.noFree } };
+ return @intCast((T.jobRun(span(in, n), gpa) orelse return 0).len);
+ }
+ fn job_done(st: ?*anyopaque, token: u32, out: [*c]const u8, n: u32) callconv(.c) void {
+ T.jobDone(self(st) orelse return, token, span(out, n));
+ }
+ fn dump(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 {
+ return @intCast(T.dump(self(st) orelse return 0, buf[0..n]));
+ }
+ fn load(st: ?*anyopaque, buf: [*c]const u8, n: u32, version: u32) callconv(.c) c_int {
+ return @intFromBool(!T.load(self(st) orelse return 1, span(buf, n), version));
+ }
+ fn search(st: ?*anyopaque, pat: [*c]const u8, n: u32) callconv(.c) void {
+ T.search(self(st) orelse return, span(pat, n));
+ }
+ };
+ if (T.head.name.len > 15) @compileError(@typeName(T) ++ "'s name " ++ T.head.name ++ " is over 15 bytes");
+ var name: [16]u8 = @splat(0);
+ @memcpy(name[0..T.head.name.len], T.head.name);
+ var o: c.pa_ops = .{ .init = F.init, .open = F.open, .paint = F.paint, .head = .{ .size = @sizeOf(c.pa_head), .abi = c.PA_ABI, .name = name, .version = T.head.version, .flags = (if (T.head.pictures) c.PA_PICTURES else 0) | (if (T.head.plain) c.PA_PLAIN else 0), .exts = T.head.exts, .words = &F.words, .nwords = F.words.len } };
+ // The kind's function, then the pa_ops field its wrapper fills.
+ const fns = .{
+ .{ "close", "close" }, .{ "tick", "tick" }, .{ "prefix", "tick" }, .{ "view", "view" }, .{ "key", "key" },
+ .{ "mouse", "mouse" }, .{ "body", "body_len" }, .{ "body", "body" }, .{ "address", "address" }, .{ "where", "where" },
+ .{ "ctl", "ctl" }, .{ "ctlRead", "ctl_read" }, .{ "jobRun", "job_run" }, .{ "jobDone", "job_done" }, .{ "dump", "dump" },
+ .{ "load", "load" }, .{ "search", "search" },
+ };
+ inline for (fns) |m| if (@hasDecl(T, m[0])) {
+ @field(o, m[1]) = @field(F, m[1]);
+ };
+ // A word for its pane goes to `ctl`.
+ if (!@hasDecl(T, "ctl")) for (T.head.words) |w| if (!w.opens) @compileError(@typeName(T) ++ "'s word " ++ w.name ++ " opens no pane, and it has no ctl to take it");
+ // A public function of another name (a typo) would be left out unsaid.
+ const names = [_][]const u8{ "init", "open", "paint" } ++ blk: {
+ var ns: [fns.len][]const u8 = undefined;
+ for (fns, &ns) |m, *n| n.* = m[0];
+ break :blk ns;
+ };
+ inline for (@typeInfo(T).@"struct".decl_names) |d| if (comptime @typeInfo(@TypeOf(@field(T, d))) == .@"fn" and for (names) |n| {
+ if (std.mem.eql(u8, n, d)) break false;
+ } else true) @compileError(@typeName(T) ++ "." ++ d ++ " is none of a kind's functions (addon.zig's ops)");
+ return o;
+}
diff --git a/abi/pardes.h b/abi/pardes.h
new file mode 100644
index 00000000..c4470569
--- /dev/null
+++ b/abi/pardes.h
@@ -0,0 +1,564 @@
+// libpardes — the C ABI the macOS app links against.
+//
+// Hand-written, and kept honest by a test: build.zig translate-C's this file
+// into the unit-test build, and src/macos.zig asserts every constant and
+// struct layout below against the Zig side (ghostty's trick — see docs/macos.md).
+// Change nothing here without running `zig build unit-test -Dplatform=macos`.
+//
+// Division of labour, which is the whole design in two lines:
+// Zig owns the core, the ptys, every effect, and the worker threads.
+// Swift owns NSApplication, the window, input translation, and drawing.
+//
+// There is exactly one core per process, so there are no handles: the state is
+// a file-scoped singleton. Every function below must be
+// called from the main thread. The one exception is the `wakeup` callback,
+// which fires from a pty reader thread.
+
+#ifndef PARDES_H
+#define PARDES_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// ---------------------------------------------------------------- frame
+
+// One rendered cell. Mirrors pardes.Cell (src/pardes.zig) flattened for the
+// wire.
+typedef struct {
+ // UTF-8 grapheme, `len` bytes. The core caps graphemes at seven bytes; the
+ // eighth is always zero so a debugger prints something sensible.
+ uint8_t text[8];
+ // 0x01000000 terminal default
+ // 0x02000000 | index 256-color palette entry
+ // 0x00RRGGBB direct color
+ uint32_t fg;
+ uint32_t bg;
+ // bit 0 bold, 1 dim, 2 italic, 3 blink, 4 reverse, 5 invisible,
+ // 6 strikethrough; bits 8.. hold PARDES_UL_*.
+ uint16_t attrs;
+ uint8_t len;
+ // bit 0: the core never painted this cell — draw it as the default cell
+ // (background only), which is what makes a partial redraw cheap.
+ // bit 1: rasterize text and its colour band with the tagline face's measured
+ // height. Logical cell geometry stays body-sized; this is a visual role.
+ uint8_t flags;
+} pardes_cell_s;
+
+#define PARDES_COLOR_DEFAULT 0x01000000u
+#define PARDES_COLOR_INDEXED 0x02000000u
+#define PARDES_COLOR_TAG_MASK 0xff000000u
+#define PARDES_COLOR_RGB_MASK 0x00ffffffu
+
+#define PARDES_ATTR_BOLD 0x0001u
+#define PARDES_ATTR_DIM 0x0002u
+#define PARDES_ATTR_ITALIC 0x0004u
+#define PARDES_ATTR_BLINK 0x0008u
+#define PARDES_ATTR_REVERSE 0x0010u
+#define PARDES_ATTR_INVISIBLE 0x0020u
+#define PARDES_ATTR_STRIKETHROUGH 0x0040u
+#define PARDES_ATTR_UL_SHIFT 8
+// Literals rather than (1u << n): Swift's macro importer is dependable on a
+// plain integer and less so on an expression, and nothing here can compile the
+// Swift side to find out. The ABI guard asserts each value against the encoder.
+
+#define PARDES_UL_OFF 0
+#define PARDES_UL_SINGLE 1
+#define PARDES_UL_DOUBLE 2
+#define PARDES_UL_CURLY 3
+#define PARDES_UL_DOTTED 4
+#define PARDES_UL_DASHED 5
+
+#define PARDES_CELL_DEFAULT 0x01u
+#define PARDES_CELL_TAGLINE 0x02u
+// The look-hover affordance: the word under the pointer is a real Look or
+// Exec operand. Hosts that draw the affordance as more than the quiet tint
+// (macOS composes a liquid-glass overlay) read this instead of guessing
+// from the background colour, which a real selection shares.
+#define PARDES_CELL_HOVER 0x04u
+
+// One coherent snapshot for the full-window shader pass (CRT);
+// time/frame advance only on pardes_animation_tick's display clock.
+typedef struct {
+ uint32_t flags;
+ float time_seconds;
+ uint32_t frame;
+} pardes_scene_s;
+
+#define PARDES_SCENE_CRT 0x01u
+
+// One backend-neutral pane transition. Boxes are logical cell rectangles;
+// the native shader converts them to backing pixels using the same measured
+// cell as the renderer. The list is already in paint order: moving first,
+// opening next, frozen closing tombstones last, and slot order within a phase.
+typedef struct {
+ float x;
+ float y;
+ float w;
+ float h;
+} pardes_panel_box_s;
+
+typedef struct {
+ uint32_t serial;
+ uint8_t pane;
+ uint8_t phase;
+ uint8_t effect;
+ uint8_t motion;
+ uint16_t frame;
+ uint16_t frame_count;
+ pardes_panel_box_s from;
+ pardes_panel_box_s to;
+ float launch;
+} pardes_panel_track_s;
+
+#define PARDES_PANEL_OPENING 0u
+#define PARDES_PANEL_MOVING 1u
+#define PARDES_PANEL_CLOSING 2u
+
+#define PARDES_PANEL_OFF 0u
+#define PARDES_PANEL_SLIDE 1u
+#define PARDES_PANEL_ZOOM 2u
+#define PARDES_PANEL_DISSOLVE 3u
+#define PARDES_PANEL_ASCII 4u
+#define PARDES_PANEL_VERTICAL 5u
+// Character effects composed in the core: the host receives finished glyphs
+// and only clips the panel batch for them.
+#define PARDES_PANEL_EDGES 6u
+#define PARDES_PANEL_FALL 7u
+#define PARDES_PANEL_WAVE 8u
+#define PARDES_PANEL_CURTAIN 9u
+#define PARDES_PANEL_SCRAMBLE 10u
+#define PARDES_PANEL_TYPEWRITER 11u
+
+// ---------------------------------------------------------------- input
+
+// Modifier bitmask shared by key and mouse events.
+#define PARDES_MOD_CTRL 0x0001u
+#define PARDES_MOD_ALT 0x0002u
+#define PARDES_MOD_SHIFT 0x0004u
+// Command. Only a click reads it (Cmd-click is B3); a Command key chord never reaches the core.
+#define PARDES_MOD_SUPER 0x0008u
+
+// Keys that carry no text. The four editing keys are their ASCII controls;
+// everything else lives in a private-use plane so it can never collide with a
+// real codepoint arriving as text.
+#define PARDES_KEY_ENTER 0x0Du
+#define PARDES_KEY_ESCAPE 0x1Bu
+#define PARDES_KEY_TAB 0x09u
+#define PARDES_KEY_BACKSPACE 0x7Fu
+#define PARDES_KEY_UP 0xF0001u
+#define PARDES_KEY_DOWN 0xF0002u
+#define PARDES_KEY_LEFT 0xF0003u
+#define PARDES_KEY_RIGHT 0xF0004u
+#define PARDES_KEY_HOME 0xF0005u
+#define PARDES_KEY_END 0xF0006u
+#define PARDES_KEY_PAGE_UP 0xF0007u
+#define PARDES_KEY_PAGE_DOWN 0xF0008u
+#define PARDES_KEY_DELETE 0xF0009u
+
+// acme's three buttons carry the whole vocabulary: 1 selects, 2 executes,
+// 3 looks. Wheel buttons are ordinary buttons, not a separate axis.
+typedef enum {
+ PARDES_MOUSE_LEFT = 0,
+ PARDES_MOUSE_MIDDLE = 1,
+ PARDES_MOUSE_RIGHT = 2,
+ PARDES_MOUSE_WHEEL_UP = 3,
+ PARDES_MOUSE_WHEEL_DOWN = 4,
+ PARDES_MOUSE_WHEEL_LEFT = 5,
+ PARDES_MOUSE_WHEEL_RIGHT = 6,
+ PARDES_MOUSE_NONE = 7,
+ PARDES_MOUSE_BACK = 8,
+ PARDES_MOUSE_FORWARD = 9,
+} pardes_mouse_button_e;
+
+typedef enum {
+ PARDES_MOUSE_PRESS = 0,
+ PARDES_MOUSE_RELEASE = 1,
+ PARDES_MOUSE_MOTION = 2,
+ PARDES_MOUSE_DRAG = 3,
+} pardes_mouse_kind_e;
+
+// What the core just did, for a shell that can answer with something the hand
+// feels. Taken with pardes_take_haptic once per pump; the two acme verbs are
+// distinguished because they deserve distinct taps.
+typedef enum {
+ PARDES_HAPTIC_NONE = 0,
+ PARDES_HAPTIC_EXEC = 1,
+ PARDES_HAPTIC_LOOK = 2,
+} pardes_haptic_e;
+
+// ---------------------------------------------------------------- runtime
+
+// What the host lends the core. Three callbacks, because everything else the
+// core wants done it already does itself: it owns the ptys, and it opens URLs
+// through /usr/bin/open. Copied by value during pardes_init, so the struct
+// need only outlive that call.
+typedef struct {
+ // Passed back to every callback below. Conventionally the AppDelegate.
+ void *userdata;
+
+ // "Your state moved; please pump me." Called from a pty reader thread, so
+ // the host must hop to the main thread before calling pardes_tick — see
+ // AppDelegate.wakeup, which does exactly one DispatchQueue.main.async.
+ void (*wakeup)(void *userdata);
+
+ // The yank register changed. `text` is borrowed for the duration of the
+ // call only. Main thread, inside pardes_tick.
+ void (*set_clipboard)(void *userdata, const char *text, size_t len);
+
+ // Ask the host for the system clipboard. The host answers by calling
+ // pardes_paste, which may be synchronous inside this call. Main thread,
+ // inside pardes_tick.
+ void (*read_clipboard)(void *userdata);
+} pardes_runtime_s;
+
+// ---------------------------------------------------------------- lifecycle
+
+// Returns 0 on success, or a nonzero opaque error code. Pass the real window
+// grid, not a placeholder: init delivers it as the first resize EVENT (the
+// core defers each shell's greeting until it has seen one), and the first
+// forkpty takes its winsize straight off the core — boot at 80x24 and the
+// shell draws its first prompt to a width the window never had.
+int pardes_init(const pardes_runtime_s *runtime, uint16_t cols, uint16_t rows);
+void pardes_deinit(void);
+
+// Drain pty output into the core and perform the effects it queued. Call after
+// every input function and on every wakeup.
+//
+// The return value is whether this tick did any IO — bytes arrived from a pty,
+// or an effect was performed. It is NOT a repaint signal, and a host that uses
+// it as one shows a stale screen: moving the cursor, extending a selection,
+// changing mode and scrolling all mutate the grid while queueing nothing and
+// performing nothing, so they tick false. Mark the view dirty after any call
+// into the core and use this only to decide whether there was work.
+bool pardes_tick(void);
+
+// Advance one frame-count animation step. Call only from the scheduled ~60 Hz
+// callback, never from ordinary input or pty pumps: those drain work but do
+// not represent elapsed display time. Returns whether anything advanced.
+bool pardes_animation_tick(void);
+
+// The core asked to exit (the Exit builtin, or the last pane closing).
+bool pardes_should_quit(void);
+
+// A theme/pane transition, scene effect, or rotation coast wants ~60 Hz ticks.
+bool pardes_animating(void);
+
+// What to paint where the grid does not: the window background behind the
+// titlebar and behind a live resize the view has not caught up with. The
+// theme's own background, so it changes the instant the theme does — chrome
+// (taglines, the move box) fades instead, which is why this is not it.
+//
+// PARDES_COLOR_DEFAULT means the theme declares NO background of its own. A
+// terminal wears whatever it was already wearing; a window has nothing to
+// wear, so the host should go transparent and show its own backdrop.
+uint32_t pardes_theme_bg(void);
+
+// The percentage the host must paint window BACKGROUNDS at: the ground behind
+// the grid, cell and band backgrounds, and the chrome rules over them. Glyph
+// ink and the block cursor are never scaled by it — see shaders/ui.frag.glsl,
+// which states the same rule for the SDL shell.
+//
+// Read it once per pump beside pardes_theme_bg(): reading also acknowledges
+// whatever `WindowOpacity` asked for. 100 is opaque and is the default.
+uint8_t pardes_window_opacity(void);
+
+// Pane taglines use this percentage of the current body font size. It is the
+// embedded default before init and the live core setting afterwards; the host
+// polls it and rebuilds only tagline glyph/metric state.
+uint8_t pardes_gui_tagline_font_percent(void);
+
+// Where a reduced-height tagline band sits inside its body-sized grid row, in
+// PHYSICAL PIXELS down from the row's top, and the rule joining the topbar band
+// to the first pane-tag band. The core owns this geometry so that this shell and
+// the SDL one cannot disagree about it; centring every band is what this shell
+// used to do, and it left a strip of window background between the two.
+//
+// Points in, pixels out: multiply by the backing scale before calling and divide
+// the answer back, the same snapping the cell metrics already use.
+uint32_t pardes_tagline_band_offset(uint16_t row, float canvas_h, uint32_t cell_h,
+ uint32_t tagline_h);
+uint32_t pardes_topbar_pane_border_px(uint32_t cell_h, uint32_t tagline_h);
+
+// The column a compact tagline band anchors at: the pane's left edge, so a tag
+// row advances on the tagline face's own narrower pitch instead of centring a
+// smaller glyph inside every body-width cell. CELLS, not pixels — the host
+// knows both widths — and fractional, because an animating panel's origin is.
+//
+// glyph_x = origin * body_cell_w + (col - origin) * tagline_cell_w
+float pardes_tagline_origin_col(uint16_t col, uint16_t row);
+
+// The inverse, for the pointer: which grid column `x` falls in on `row`, given
+// that a tag row's glyphs step at the narrower pitch. Compacting the text
+// without compacting this makes a click drift one word further right for every
+// word along the row. `x` and both widths must share a unit; only the ratio is
+// read, so a host measuring in points passes points.
+uint16_t pardes_grid_col_at(float x, uint16_t row, float body_w, float tagline_w);
+
+// The tag band's own background, the base a compact tag row is painted on: the
+// pane-wide band goes down in THIS colour on the body grid, then each cell's
+// own background on the narrower grid its glyph uses. One pass would put a
+// highlighted word's box on body pitch and its letters on tagline pitch.
+// PARDES_COLOR_DEFAULT before there is a session to ask.
+uint32_t pardes_tagline_bg(void);
+
+// The fallback font PREFERENCE ORDER, shared with the SDL shell. Only the order
+// travels: resolving a name is the host's business, because SDL matches font
+// FILE STEMS while walking the font directories and CoreText matches PostScript
+// and family names, which for one face are routinely different strings.
+//
+// `pardes_fallback_font_name` returns a borrowed, NOT NUL-terminated pointer
+// and writes its byte length through `len`; NULL past the end.
+uint32_t pardes_fallback_font_count(void);
+const char *pardes_fallback_font_name(uint32_t index, uint32_t *len);
+
+// Colour of that rule: a compiled override, else the theme's scrollbar track.
+// PARDES_COLOR_DEFAULT before there is a session to ask — do not draw it then.
+uint32_t pardes_topbar_pane_border_rgb(void);
+
+// Rows the global topbar occupies, and therefore the row index of the FIRST
+// pane tagline — the one the rule above joins the topbar band to. Mirrors
+// pardes.TOPBAR_H, and src/macos.zig asserts the two agree.
+#define PARDES_TOPBAR_H 1u
+
+// The active pane's tag row background, for hosts that afford the active
+// tagline more than a tint — macOS raises it like an old-school bevel.
+uint32_t pardes_tag_active_bg(void);
+
+// Persistent full-window effect switches and their display-clock time. A zero
+// flags word means draw the CoreText frame directly; any nonzero combination
+// is one postprocess pass. Snapshot by value, with no borrowed storage.
+pardes_scene_s pardes_scene(void);
+
+// The shared Metal/Core Image pass is unavailable for this session. Clears
+// scene effects and future panel transitions so Config reflects what the host
+// can actually present and the display clock cannot retry forever.
+void pardes_postprocessor_unavailable(void);
+
+// A transient postprocess failure will be presented as the canonical grid.
+// Drop current panel tracks so a later scene retry cannot resume them midway.
+void pardes_panel_animation_failed(void);
+
+// ---------------------------------------------------------------- events in
+
+// `cp` is a codepoint or one of PARDES_KEY_*; `text`/`len` are the host's
+// already-composed characters for printable keys and empty for functional
+// ones. `text` is borrowed for the call.
+void pardes_key(uint32_t cp, const char *text, size_t len, uint32_t mods);
+void pardes_paste(const char *text, size_t len);
+void pardes_mouse(pardes_mouse_button_e button, pardes_mouse_kind_e kind,
+ uint16_t col, uint16_t row, uint32_t mods);
+// The pointer left the view. A clamped motion on its final cell is not the
+// same event: it would keep hover previews and resize hints alive off-window.
+void pardes_mouse_pixel(pardes_mouse_button_e button, pardes_mouse_kind_e kind,
+ uint16_t col, uint16_t row, uint32_t mods, float x, float y,
+ float body_w, float body_h, float tagline_w, float tagline_h);
+void pardes_row_metrics(uint16_t body_w, uint16_t body_h, uint16_t tagline_w, uint16_t tagline_h);
+uint32_t pardes_tag_text_inset(void);
+uint32_t pardes_grip_columns(void);
+uint32_t pardes_tag_layer_limit(void);
+// Tag layer fields 11 and 12 carry tag-bottom placement and chrome border RGB.
+uint32_t pardes_tag_layer_value(uint32_t index, uint32_t field);
+const pardes_cell_s *pardes_tag_layer_cells(uint32_t index);
+uint32_t pardes_body_layer_limit(void);
+uint32_t pardes_body_layer_value(uint32_t index, uint32_t field);
+const pardes_cell_s *pardes_body_layer_cells(uint32_t index);
+void pardes_pointer_leave(void);
+
+// Host file watchers call this after their debounce interval. `pane` is the
+// opaque watch slot (including pardes' private ThemeFile slot), and `generation`
+// makes events queued before a replacement inert. The callback only schedules
+// the ordinary main-thread pump; text, PDF, and theme IO happen in pardes_tick.
+void pardes_watch_changed(uint8_t pane, uint32_t generation);
+
+// Trackpad/precision wheel distance in CELLS, sign following the grid
+// (positive scrolls down and right). The core has no fractional scroll — it
+// moves a row or a column at a time — so libpardes accumulates here and emits
+// whole wheel presses, keeping the remainder. Both other shells do this same
+// accumulation host-side (stepScroll in gui.zig, the drain loop in
+// web/app.mjs); it lives in Zig here so the Swift side stays a translator, and
+// so the quantizer is unit-tested on a machine with no trackpad. A discrete
+// wheel notch should go through pardes_mouse instead.
+void pardes_scroll(float delta_rows, float delta_cols, uint16_t col,
+ uint16_t row);
+
+// The gesture boundaries around pardes_scroll, and the whole of scroll
+// momentum. `begin` is fingers down: it catches a coast the way a hand catches
+// a spinning dial, and drops whatever the last gesture left banked. `end` is
+// fingers up: a swipe still moving when it ended becomes a fling, in
+// proportion to how hard it was thrown, on the same curve pardes_rotate_end
+// uses — momentum ramps up from zero rather than switching on at a threshold.
+//
+// A coast makes pardes_animating true and is spent by pardes_animation_tick,
+// and it stops at the end of a document instead of spinning against the edge.
+//
+// A host whose windowing system already flings for it needs no suppression:
+// the system's momentum arrives as ordinary pardes_scroll calls, every one of
+// which cancels the coast before spending its own travel, so that momentum
+// simply takes the gesture over. A host that calls neither — a discrete wheel
+// has no phases — scrolls with no momentum at all.
+void pardes_scroll_begin(void);
+void pardes_scroll_end(void);
+
+// A two-finger trackpad rotation, in degrees since the last call, positive
+// counterclockwise (AppKit's sign, unchanged). The core has no rotation: this
+// is spent as the search-step keys, clockwise `n` and counterclockwise `N`, a
+// notch at a time with the remainder kept — the same accumulate-and-spend
+// shape as pardes_scroll, and in Zig for the same reason. Feed it the raw
+// per-event delta; pass 0 at gesture start to drop a stale remainder and to
+// stop a fling still coasting.
+void pardes_rotate(float degrees);
+
+// The fingers lifted. How fast they were moving decides everything: a slow
+// twist stops exactly where it was put, a flick keeps turning in proportion to
+// how hard it was thrown, and the two are the same curve — momentum ramps up
+// from zero rather than switching on at a threshold.
+//
+// A coast makes pardes_animating true and is spent by
+// pardes_animation_tick, so a host that already re-pumps for theme transitions
+// needs no new machinery; one that never calls this simply has a dial with no
+// momentum.
+void pardes_rotate_end(void);
+
+// Run one builtin command line, exactly as executing the same text in a tag
+// would. This is the core's own `command` event, which is how a nested pardes
+// talks to its host; here it is what a menu item is made of, and what opens
+// the file named on argv or dropped on the Dock icon (`Look <path>`).
+void pardes_command(const char *text, size_t len);
+
+// `cell_w`/`cell_h` are one cell in physical pixels, which only the native PDF
+// placement path reads. Pass the backing-store size, not points.
+void pardes_resize(uint16_t cols, uint16_t rows, uint16_t cell_w,
+ uint16_t cell_h);
+
+// ---------------------------------------------------------------- frame out
+
+// Render one frame. Returns the cell count (cols * rows), or 0 on failure.
+// The buffer returned by pardes_frame_cells is valid until the next call.
+uint32_t pardes_frame(void);
+const pardes_cell_s *pardes_frame_cells(void);
+// Frozen old grid and its byte-per-cell semantic change mask. Both are either
+// present for exactly cols*rows cells or NULL together, and are borrowed until
+// the next pardes_frame call just like the canonical cells.
+const pardes_cell_s *pardes_frame_previous_cells(void);
+const uint8_t *pardes_frame_changed_cells(void);
+uint16_t pardes_frame_cols(void);
+uint16_t pardes_frame_rows(void);
+
+// One rasterized pixel attachment: a PDF page, or an image pane's pixels.
+//
+// Geometry is in PHYSICAL PIXELS, the space pardes_resize's cell_w/cell_h put
+// the core in. `cell_x`/`cell_y` are the pane body's origin in CELLS and the
+// only thing to multiply out; `dst_*` is relative to that origin and `src_*`
+// is the crop of the raster to take. Both are already clipped to the viewport,
+// so a continuous-scroll page needs no overflow clip of its own — but the body
+// (`cell_w` x `cell_h` cells) is still the rectangle nothing may paint past.
+//
+// `serial`, `page` and `revision` together are the cache key: a host holds its
+// decoded texture while all three hold still, and panning, fit and scrolling
+// deliberately do not move them.
+typedef struct {
+ uint32_t serial;
+ uint32_t page;
+ uint32_t revision;
+ uint16_t cell_x;
+ uint16_t cell_y;
+ uint16_t cell_w;
+ uint16_t cell_h;
+ uint32_t dst_x;
+ uint32_t dst_y;
+ uint32_t dst_w;
+ uint32_t dst_h;
+ uint32_t src_x;
+ uint32_t src_y;
+ uint32_t src_w;
+ uint32_t src_h;
+ // subpixel vertical displacement a proportional wheel kept
+ float offset_y;
+ uint32_t iw;
+ uint32_t ih;
+ // iw * ih * 4 bytes, RGBA8, borrowed until the next pardes_frame
+ const uint8_t *rgba;
+ // PDF paper RGB; PARDES_COLOR_DEFAULT means an ordinary image.
+ uint32_t paper_bg;
+} pardes_image_s;
+
+// This frame's attachments, in paint order. Ask after pardes_frame; both are
+// valid until the next one, exactly like the cell buffer.
+uint32_t pardes_frame_images(void);
+const pardes_image_s *pardes_frame_image_list(void);
+
+// Shader transition records for this frame, borrowed until pardes_frame is
+// called again. Empty means draw the canonical grid without a panel pass.
+uint32_t pardes_frame_panel_tracks(void);
+const pardes_panel_track_s *pardes_frame_panel_track_list(void);
+// Call only after the host has put this frame on screen. `true` commits the
+// borrowed panel-track list above; `false` records a direct canonical fallback.
+// Returns true only when remapping a stationary pointer newly started a clock
+// the host was not already running.
+bool pardes_frame_presented(bool animated_panels);
+
+// The file behind the FOCUSED pane, or NULL when there is none: a terminal, an
+// output buffer, or nothing focused. PDFs and images count — they are real
+// paths, and a titlebar proxy icon is about the file, not about who may edit
+// it. Borrowed until the next call, like pardes_font_take.
+const char *pardes_active_path(void);
+
+// ...and whether that pane holds edits which are not on disk. Always false for
+// anything with no buffer to save, PDFs and images included.
+bool pardes_active_dirty(void);
+
+// -1 when the cursor is hidden. `bar` asks for a thin insert-mode caret.
+int32_t pardes_cursor_x(void);
+int32_t pardes_cursor_y(void);
+bool pardes_cursor_bar(void);
+// Mouse pointer affordance: 0 = default text pointer, 1 = link hand,
+// 2 = a validated Look/Exec target under the pointer (the acme arrow).
+uint32_t pardes_pointer_shape(void);
+
+// The Look or Exec the core performed since this was last asked, and clears
+// it. Call it once per pump, after pardes_tick — the input functions run the
+// dispatch synchronously, so a gesture's pulse is already waiting by the time
+// its tick returns. PARDES_HAPTIC_NONE means nothing to feel.
+pardes_haptic_e pardes_take_haptic(void);
+
+// The font file the `Font` builtin asked for since this was last called, and
+// clears it; NULL when nothing was asked. Ask once per pump, beside the haptic
+// above. The string is a NUL-terminated absolute path owned by libpardes and
+// valid until the next call.
+//
+// A path rather than a family name: the core found the file by walking the
+// font directories itself, so both shells agree on which faces exist and
+// neither has to ask its platform to resolve a name it might resolve
+// differently. A `.ttc` collection names its first face, which is the cut the
+// file is named after.
+//
+// The host loads it, re-measures its cell, and reports the new grid through
+// pardes_resize. A file the host cannot load must be rejected explicitly while
+// keeping the face that works; otherwise Config would leave the request pending
+// forever or claim a fallback was accepted.
+// Optional size in native points; zero preserves the current size.
+const char *pardes_font_take(uint16_t *size_hundredths);
+
+// Boot, zoom and display-scale changes observe the face already on screen;
+// this never consumes a pending request. `point_hundredths` is the effective
+// body size (14pt => 1400).
+bool pardes_font_observe(const char *effective_name, size_t len,
+ uint16_t point_hundredths);
+
+// A taken Font request is not effective until the host says what CoreText
+// actually accepted. Calling this without a request from pardes_font_take is
+// inert, so an unrelated host report cannot consume the request.
+bool pardes_font_ack(const char *effective_name, size_t len,
+ uint16_t point_hundredths);
+void pardes_font_reject(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // PARDES_H
diff --git a/abi/pardes_addon.h b/abi/pardes_addon.h
new file mode 100644
index 00000000..11dcec38
--- /dev/null
+++ b/abi/pardes_addon.h
@@ -0,0 +1,448 @@
+/* pardes_addon.h: an addon, a shared library that brings pardes one
+ * kind of pane (a picture, a game, a plot).
+ *
+ * An addon exports one symbol, `pardes_addon`, a `pa_ops` whose `head`
+ * names its kind. pardes calls it on its own thread, one call at a time;
+ * it keeps no pointer pardes hands it past the call (but its `pa_api`),
+ * starts no threads (it has jobs), and reads no file, clock or
+ * environment (it is handed bytes and the time), and is back from every
+ * call within 2 ms: what takes longer goes on a job (a Debug pardes says
+ * a call over 16 ms, and `--addon-test` fails on it). Every function but
+ * `paint` is optional: leave it NULL and pardes does the default the
+ * comment beside it says.
+ *
+ * cc -shared -fPIC -o game.so game.c
+ * echo 'Addon load ./game.so' > $PARDES_MOUNT/ctl
+ * pardes --addon-test ./game.so game.script a test, as a script
+ *
+ * Conventions: init, ctl and load return PA_OK (0), or nonzero to refuse;
+ * key, mouse and address return nonzero when the event or text was theirs.
+ * The pa_api pointer handed to init is kept by the addon; it is about the
+ * pane of the current call. A kind's state is one thing, stepped by `tick`
+ * however many views show it; what a view sees of it is laid out by `view`
+ * and drawn by `paint`, which writes nothing a step reads. Minors after 3.0
+ * add fields at the ends of records: a core reads an addon's new ones by
+ * its head's minor, an addon pardes's by api->size.
+ *
+ * addons/fake/fake.c implements every function; it is the template. In
+ * Zig, src/kinds/addon.zig makes the pa_ops from a struct, and
+ * addons/snake/snake.zig is a game in it.
+ */
+#ifndef PARDES_ADDON_H
+#define PARDES_ADDON_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h> /* memcpy, for pa_copy and PA_POD */
+
+/* Major in the high half: an addon of another major is refused. */
+#define PA_ABI_MAJOR 3u
+#define PA_ABI_MINOR 2u
+#define PA_ABI ((PA_ABI_MAJOR << 16) | PA_ABI_MINOR)
+#define PA_OK 0
+#define PA_RASTER_MAX (32u << 20) /* a placement's w*h*4 above this is dropped, said once */
+#define PA_RECORD_MAX (1u << 20) /* the most a dump's record holds */
+
+/* ---- the picture ---- */
+
+/* A cell's colour: the theme's own, one of its 256, or RGB. */
+#define PA_DEFAULT 0x01000000u
+#define PA_INDEX(n) (0x02000000u | (uint8_t)(n))
+#define PA_RGB(r, g, b) (((uint32_t)(uint8_t)(r) << 16) | ((uint32_t)(uint8_t)(g) << 8) | (uint32_t)(uint8_t)(b))
+
+#define PA_BOLD 0x01u
+#define PA_DIM 0x02u
+#define PA_ITALIC 0x04u
+#define PA_REVERSE 0x10u
+#define PA_UNDERLINE 0x100u
+
+/* A cell: one character, `len` bytes of UTF-8 (at most 7), drawn only
+ * with PA_PAINTED in its flags (pa_put sets it); a zero cell is the pane's
+ * background. */
+#define PA_PAINTED 0x01u
+typedef struct pa_cell {
+ uint8_t text[8];
+ uint32_t fg, bg;
+ uint16_t attrs;
+ uint8_t len;
+ uint8_t flags;
+} pa_cell;
+
+/* The pane's body in one view, which `paint` writes: `rows` rows of
+ * `cols` cells, `stride` cells apart, every one zero (unpainted) when the
+ * call begins. How a frontend shows the placements (glyph art, its
+ * palette) is the core's words' (Petscii, Palette, Ascii), never the
+ * addon's. */
+typedef struct pa_window {
+ pa_cell *cells;
+ uint32_t stride;
+ uint16_t rows, cols;
+ /* A cell's size in pixels, as the frontend draws it. */
+ uint16_t cell_w, cell_h;
+ /* The pane has the keyboard in some view: for the picture ("paused").
+ * `view`: the id of the view painted (pa_view's), whose layout paint
+ * draws; `glyphs`: it shows pictures as glyph art. */
+ uint8_t focused, view, glyphs, pad;
+} pa_window;
+
+typedef struct pa_rect { uint32_t x, y, w, h; } pa_rect; /* pixels */
+typedef struct pa_cells { uint16_t x, y, w, h; } pa_cells; /* cells of the window */
+
+/* A picture over the cells: the `src` part of an RGBA raster (straight
+ * alpha, packed rows of w*4 bytes), over the `dst` cells, at `at` pixels in
+ * them, or fitted there (no larger than it is) when at.w is 0; one of
+ * more than PA_RASTER_MAX bytes is dropped. The raster is the addon's and must stay as it is until the pane's next paint or
+ * close. `key` names the pixels in this pane: one key, one picture, so a
+ * frontend keeps what it uploaded under it. `from` is 0, or the key of a
+ * picture a frontend may still hold of which rows dirty_y .. dirty_y +
+ * dirty_h of this one alone differ (a frontend that holds it may patch
+ * those rows; any other uploads the whole). */
+typedef struct pa_placement {
+ const uint8_t *rgba;
+ uint32_t w, h;
+ pa_rect src;
+ pa_cells dst;
+ pa_rect at;
+ uint64_t key;
+ uint64_t from;
+ uint32_t dirty_y, dirty_h;
+} pa_placement;
+
+/* What `paint` hands back beside the cells: placements (room for `cap`,
+ * at least 64, lowest first); `at` and `span`, where the window is in the
+ * pane's whole (the share above it and the share it shows, 0 to 1), the
+ * rail's thumb, 0 and 0 for none; and `pointer`, the pointer a frontend
+ * shows over the pane (PA_POINTER_*), which a terminal ignores. paint is
+ * called once a frame in each view, never over no cells. */
+#define PA_POINTER_DEFAULT 0u
+#define PA_POINTER_LINK 1u
+typedef struct pa_paint {
+ pa_placement *placements;
+ uint32_t cap, n;
+ float at, span;
+ uint32_t pointer, pad;
+ /* Optional since 3.1: one sketchbook SGPU v1 scene for this pane.
+ * Check api->abi >= 3.1 BEFORE reading these fields on an older host.
+ * NULL means unsupported. Copies bytes during the call (stack is OK);
+ * returns PA_OK or refuses. At most 4 MiB, last successful call wins.
+ * Keep cells/rasters as fallback: accepting a scene does not promise a
+ * GPU in every view. GPU scenes are display data, never saved state. */
+ int (*gpu)(void *ctx, const uint8_t *bytes, uint32_t n);
+ void *gpu_ctx;
+} pa_paint;
+
+/* ---- input ---- */
+
+/* A key: a codepoint, or one of these. */
+#define PA_KEY_ENTER 0x0Du
+#define PA_KEY_TAB 0x09u
+#define PA_KEY_BACKSPACE 0x7Fu
+#define PA_KEY_UP 0xF0001u
+#define PA_KEY_DOWN 0xF0002u
+#define PA_KEY_LEFT 0xF0003u
+#define PA_KEY_RIGHT 0xF0004u
+#define PA_KEY_HOME 0xF0005u
+#define PA_KEY_END 0xF0006u
+#define PA_KEY_PAGE_UP 0xF0007u
+#define PA_KEY_PAGE_DOWN 0xF0008u
+#define PA_KEY_DELETE 0xF0009u
+/* `view`: the id of the view it came from (pa_view's), whose layout it is
+ * about (a key's count of lines, a click's cell). */
+typedef struct pa_key {
+ uint32_t cp;
+ uint8_t ctrl, alt, shift, view;
+} pa_key;
+
+#define PA_LEFT 0
+#define PA_MIDDLE 1
+#define PA_RIGHT 2
+#define PA_WHEEL_UP 3
+#define PA_WHEEL_DOWN 4
+#define PA_WHEEL_LEFT 5
+#define PA_WHEEL_RIGHT 6
+#define PA_PRESS 0
+#define PA_RELEASE 1
+#define PA_MOTION 2
+#define PA_DRAG 3
+/* A pointer event in the cells of view `view`'s window; a motion at col
+ * and row 0xffff when the pointer leaves the window. `amount`: a wheel's
+ * turn in notches, a touchpad's fraction of one (a terminal's are whole). */
+typedef struct pa_mouse {
+ uint8_t button, action, ctrl, shift, alt, view;
+ uint16_t col, row;
+ float amount;
+} pa_mouse;
+
+/* ---- what pardes does for an addon ---- */
+
+/* A view of the pane (`view`, `id` 1 and up): its window, a cell's
+ * pixels; the theme's text, paper, selection and link colours (PA_RGB);
+ * the raster a picture is wanted at: `dpi`, at most `max_px` a side, and
+ * never smaller than the pixels it covers when `fill` is set; and
+ * `glyphs`, 1 when the frontend shows placements as glyph art (a terminal
+ * without graphics). */
+typedef struct pa_view {
+ uint16_t cols, rows, cell_w, cell_h;
+ uint32_t fg, bg, sel, link;
+ uint16_t dpi, max_px;
+ uint8_t fill, glyphs, id, pad;
+} pa_view;
+
+/* Valid during any call pardes makes for a pane, and about that pane. */
+typedef struct pa_api {
+ uint32_t size;
+ /* Zeroed memory from the pane's arena, which pardes frees at its close;
+ * NULL when the arena is full. */
+ void *(*alloc)(size_t n);
+ void (*free)(void *ptr, size_t n);
+ /* `job_run` over a copy of `in` on a worker; its answer comes to
+ * `job_done` with the token returned here (0: refused). */
+ uint32_t (*job)(const void *in, uint32_t n);
+ /* Look at `text` as a click would: a URL, `file:12`, a word. */
+ void (*look)(const char *text, uint32_t n);
+ /* A message on the pane, or an error (`err` 1: also refuses an `open`). */
+ void (*say)(const char *text, uint32_t n, int err);
+ /* A new text pane named `name` holding `bytes`; its serial, 0 if none. */
+ uint32_t (*text)(const char *name, uint32_t name_len, const char *bytes, uint32_t n);
+ /* The pane's seed: the same pane, the same number, on every machine (a
+ * game's board), and what `pardes --addon-test`'s `seed N` sets. A pane
+ * restored from a dump is a new one: a kind keeps its seed in its record
+ * to reseed alike. */
+ uint64_t (*seed)(void);
+ /* Memory of pardes's that outlives a call, as realloc's (n 0 frees it),
+ * on any thread at any time: what a pane's arena cannot hold, a cache, a
+ * library's own heap. */
+ void *(*heap)(void *ptr, size_t n);
+ /* Run `text` as a middle click would. */
+ void (*exec)(const char *text, uint32_t n);
+ /* The text the pane has selected now, which a yank, a chord's Snarf and
+ * a keyboard Look take; n 0, none. */
+ void (*select)(const char *text, uint32_t n);
+ /* A job's answer not yet come is dropped (a job running runs on). */
+ void (*cancel)(uint32_t token);
+ /* `place text` rows, a line each, onto the pane's +Search list: from
+ * `search`, or later (a job_done). */
+ void (*found)(const char *rows, uint32_t n);
+ /* The core's PA_ABI. */
+ uint32_t abi, pad;
+ /* Since 3.2 (check api->size): a picture's job, made where the pane is
+ * shown. `job_run` over a copy of `in` on a worker of this process, its
+ * answer to `job_done` here alone, its token PA_DRAWN: never on the tape,
+ * in the digest or sent to another process (each that shows the pane
+ * asks its own, from the same call). A draw's answer changes pixels
+ * only: what job_done keeps of it (memory of its own, api->heap: never a
+ * PA_PLAIN kind's block, nor its token) `paint` alone reads; no other
+ * call reads it, or anything made from it. 0: refused. */
+ uint32_t (*draw)(const void *in, uint32_t n);
+} pa_api;
+/* A token of api->draw's. */
+#define PA_DRAWN 0x80000000u
+
+/* What a job allocates from, on its worker (pa_api is not there): as often
+ * as it needs, all of it freed after its job_done. The last it allocates
+ * is the answer, which the job writes and returns the length of. */
+typedef struct pa_out {
+ void *(*alloc)(struct pa_out *out, size_t n);
+ void *ctx;
+} pa_out;
+
+/* ---- the addon ---- */
+
+#define PA_ARG_NONE 0
+#define PA_ARG_OPTIONAL 1
+#define PA_ARG_REQUIRED 2
+
+/* A word the addon brings. An `opens` word opens a pane of the kind
+ * wherever it runs (`open` with its argument as the path, or none); any
+ * other goes to `ctl` of the pane of its kind it is written to, refused
+ * elsewhere. The core checks `arg` before the call; ctl is required when a
+ * word has opens 0. */
+typedef struct pa_word {
+ const char *name;
+ /* The keys after the leader (Space) that run it, "ng" for SPC n g, or NULL. */
+ const char *leader;
+ uint8_t arg, opens, pad[6];
+ const char *doc;
+} pa_word;
+#define PA_WORD(nm, ld, a, op, dc) { .name = (nm), .leader = (ld), .arg = (a), .opens = (op), .doc = (dc) }
+
+/* tick's in and out. `now`, monotonic, any origin (--addon-test's starts
+ * at 1 s); `flags`: PA_FOCUSED, the pane has the keyboard in some view,
+ * PA_FRAMED, a frame of it was drawn since the last tick. `next`: the
+ * absolute time of the next step, 0 for none. `prefix`: the start of the
+ * pane's tag after this step, which the core follows with one space, its
+ * art words for a kind of PA_PICTURES, and the pane's path; empty, the
+ * kind's name. */
+#define PA_FOCUSED 0x1u
+#define PA_FRAMED 0x2u
+typedef struct pa_tick {
+ uint64_t now;
+ uint32_t flags, pad;
+ uint64_t next;
+ char prefix[96];
+ uint32_t prefix_len, pad2;
+} pa_tick;
+
+/* head.flags: its panes show pictures, and the core says how in their tag
+ * (`petscii:on palette:commodore ascii:off`, Petscii, Palette, Ascii). */
+#define PA_PICTURES 0x1u
+/* head.flags: its state is plain and its step pure. The kind's whole state
+ * is the one block its `open` allocates with api->alloc (any other alloc
+ * is refused): bytes with no pointer or handle in them, changed only by its
+ * calls, each a function of the block and what the call is handed (no
+ * statics, no clock, randomness or file of its own: the time is tick's
+ * `now`, a seed api->seed's; tick is never told PA_FRAMED, a frame being
+ * one view's). pardes keeps the block where its own state is (its digest, a
+ * client's rollback copy) and dumps it as it is, `dump` uncalled and `load`
+ * given it at a Restore; so a client of the session runs the kind itself
+ * from the session's very bytes, its keys at once
+ * and its pictures its own, and a client without the addon shows a line.
+ * A kind that breaks the promise is caught: the client's state is not the
+ * session's, and it joins again without the kind. Its pictures are each
+ * process's own (api->draw), kept outside the block (api->heap), found by
+ * the block's address; a pane with a file is opened in a client from the
+ * file's bytes as the session's was. */
+#define PA_PLAIN 0x2u
+
+typedef struct pa_head {
+ uint32_t size, abi;
+ /* The pane's kind word in /index, NUL-padded. */
+ char name[16];
+ uint32_t version, flags;
+ /* The extensions it opens, space-separated (".png .jpg"), or "". */
+ const char *exts;
+ const pa_word *words;
+ uint32_t nwords, pad;
+} pa_head;
+
+typedef struct pa_ops {
+ pa_head head;
+ /* Once, at load: PA_OK, or nonzero to refuse the addon. */
+ int (*init)(const pa_api *api);
+ /* A new pane (path and bytes NULL for one a word opened): its state,
+ * which every call below is handed. NULL with nothing said is a pane
+ * with no state; `say` an error to refuse it. */
+ void *(*open)(const char *path, const uint8_t *bytes, uint64_t len);
+ /* The pane closes; its arena is freed after. */
+ void (*close)(void *st);
+ /* Time has come to t->now: step the state, once however many views show
+ * it, and set t->next and t->prefix (pa_tick). Called when that time
+ * comes and once after open, a taken key or mouse, ctl, job_done, load,
+ * view, and a change of PA_FOCUSED: a kind that set no next is woken by
+ * the next thing that happens to it. Absent: the prefix is the name. */
+ void (*tick)(void *st, pa_tick *t);
+ /* Required. Pure over the state and win->view's layout: the same paints
+ * the same, and changes nothing. */
+ void (*paint)(void *st, const pa_window *win, pa_paint *out);
+ /* Every key, Esc first; nonzero if taken. A key not taken goes to the
+ * editor's own navigation (Esc: it leaves). Absent: no keys. */
+ int (*key)(void *st, const pa_key *k);
+ /* Nonzero if taken. Absent: a click focuses the pane. */
+ int (*mouse)(void *st, const pa_mouse *m);
+ /* The pane's body as text (9P `body`). Absent: empty. */
+ uint64_t (*body_len)(void *st);
+ uint32_t (*body)(void *st, uint64_t off, char *buf, uint32_t n);
+ /* Go to `text` (`:12`, `12:0.33`); nonzero if it is a place here (a miss
+ * may `say` why, an error). A place looked at in a list the kind made
+ * (`text`) comes as `<name> <place>`. And where the pane is now, as such
+ * a text (jumps, Recent, a Restore): `L` or `L:F`, its first number a
+ * line's and F how far into it, then, after a space, the window's height
+ * in lines if it has one: two places within it are one visit of the
+ * jumps. */
+ int (*address)(void *st, const char *text, uint32_t n);
+ uint32_t (*where)(void *st, char *buf, uint32_t n);
+ /* One of the addon's words, as written (`Fit width`): PA_OK, else
+ * refused with `reply`. Required when a word has opens 0. */
+ int (*ctl)(void *st, const char *line, uint32_t n, char *reply, uint32_t cap);
+ /* What the pane's ctl file reads after the core's fields: `name value`
+ * lines. */
+ uint32_t (*ctl_read)(void *st, char *buf, uint32_t n);
+ /* On a worker thread, pure over `in`: the answer's length. */
+ uint32_t (*job_run)(const uint8_t *in, uint32_t n, pa_out *out);
+ /* Back on pardes's thread; `out` is gone after the call. */
+ void (*job_done)(void *st, uint32_t token, const uint8_t *out, uint32_t n);
+ /* The pane's record for a dump, the kind's own small state (its file is
+ * the pane's path, read again at a Restore): its length, at most n
+ * (PA_RECORD_MAX); 0 is no record (load is not called and the pane
+ * reopens from its path, its `where` and its words' last values), and so
+ * is having no dump. */
+ uint32_t (*dump)(void *st, uint8_t *buf, uint32_t n);
+ /* On the state open(path, bytes, len) made from the file as it is, with
+ * the writer's head.version: PA_OK, or nonzero to refuse (the pane waits
+ * as a placeholder, its record kept). */
+ int (*load)(void *st, const uint8_t *buf, uint32_t n, uint32_t version);
+ /* The pane's own search for the core's `/`, which returns at once: its
+ * rows go to api->found, now or from a job_done. Absent: `/` finds
+ * nothing here. */
+ void (*search)(void *st, const char *pat, uint32_t n);
+ /* A view shows the pane (its facts, or new ones), or stops (cols 0): lay
+ * out for v->id, ask for its rasters. Absent: paint lays out from the
+ * window. */
+ void (*view)(void *st, const pa_view *v);
+} pa_ops;
+
+/* The records' sizes on a 64-bit target: an addon built against another
+ * copy of this header that disagrees does not compile. */
+#if UINTPTR_MAX == 0xffffffffffffffffu
+_Static_assert(sizeof(pa_cell) == 20, "pa_cell");
+_Static_assert(sizeof(pa_window) == 24, "pa_window");
+_Static_assert(sizeof(pa_rect) == 16 && sizeof(pa_cells) == 8, "pa_rect");
+_Static_assert(sizeof(pa_placement) == 80, "pa_placement");
+_Static_assert(sizeof(pa_paint) == 48 && sizeof(pa_view) == 32 && sizeof(pa_tick) == 128, "pa_paint");
+_Static_assert(sizeof(pa_key) == 8 && sizeof(pa_mouse) == 16, "pa_key");
+_Static_assert(sizeof(pa_api) == 120 && sizeof(pa_out) == 16, "pa_api");
+_Static_assert(sizeof(pa_word) == 32 && sizeof(pa_head) == 56, "pa_head");
+_Static_assert(sizeof(pa_ops) == 208, "pa_ops");
+#endif
+
+/* ---- helpers ---- */
+
+static inline pa_cell *pa_at(const pa_window *w, unsigned row, unsigned col) {
+ return row < w->rows && col < w->cols ? &w->cells[row * w->stride + col] : 0;
+}
+
+/* `text` (UTF-8) from (row, col) on, a character a cell, cut at the edge;
+ * the cells written. */
+static inline unsigned pa_put(const pa_window *w, unsigned row, unsigned col, const char *text, uint32_t fg, uint32_t bg, uint16_t attrs) {
+ unsigned n = 0;
+ while (*text) {
+ pa_cell *c = pa_at(w, row, col + n);
+ unsigned len = 1;
+ while (len < 7 && (text[len] & 0xC0) == 0x80) len++;
+ if (c) {
+ for (unsigned i = 0; i < 8; i++) c->text[i] = i < len ? (uint8_t)text[i] : 0;
+ c->len = (uint8_t)len;
+ c->fg = fg;
+ c->bg = bg;
+ c->attrs = attrs;
+ c->flags = PA_PAINTED;
+ n++;
+ }
+ text += len;
+ if (!c) break;
+ }
+ return n;
+}
+
+/* `n` bytes of src[off..len] into buf: the body of a kind whose text is small. */
+static inline uint32_t pa_copy(const void *src, uint64_t len, uint64_t off, void *buf, uint32_t n) {
+ if (off >= len) return 0;
+ if (n > len - off) n = (uint32_t)(len - off);
+ memcpy(buf, (const uint8_t *)src + off, n);
+ return n;
+}
+
+/* dump and load as a byte copy of a plain struct `type`, refused across
+ * versions: PA_POD(snake, VERSION) then .dump = snake_dump, .load = snake_load */
+#define PA_POD(type, ver) \
+ static uint32_t type##_dump(void *st, uint8_t *buf, uint32_t n) { \
+ return n < sizeof(type) ? 0 : (memcpy(buf, st, sizeof(type)), (uint32_t)sizeof(type)); } \
+ static int type##_load(void *st, const uint8_t *buf, uint32_t n, uint32_t version) { \
+ return version != (ver) || n != sizeof(type) ? 1 : (memcpy(st, buf, sizeof(type)), PA_OK); }
+
+/* An addon's head, its size and ABI filled:
+ * const pa_ops pardes_addon = { .head = PA_ADDON("game", 1, 0, "", words, 1), .paint = paint }; */
+#define PA_ADDON(nm, ver, fl, ex, ws, nws) \
+ { .size = sizeof(pa_head), .abi = PA_ABI, .name = nm, .version = (ver), .flags = (fl), .exts = (ex), .words = (ws), .nwords = (nws) }
+
+#endif
diff --git a/abi/plain.zig b/abi/plain.zig
new file mode 100644
index 00000000..6ca96fe9
--- /dev/null
+++ b/abi/plain.zig
@@ -0,0 +1,161 @@
+//! The plain records the core and the terminal both name
+//! (docs/next-terminal.md, Phase 1): a frame's cells, their styles and
+//! colours, the pictures over them and a key read. Data that needs
+//! nothing else, in a module of its own: the core (surface.zig and
+//! Event.zig, under their old names) and the terminal (src/term/) both
+//! import it, and neither imports the other.
+const std = @import("std");
+/// The terminal as the core sees it: its entries and the records they
+/// take and give.
+pub const term = @import("term.zig");
+
+pub const Color = union(enum) { default, index: u8, rgb: [3]u8 };
+
+pub const FontRole = enum(u8) { body, tagline };
+
+pub const CellStyle = struct {
+ fg: Color = .default,
+ bg: Color = .default,
+ bold: bool = false,
+ dim: bool = false,
+ italic: bool = false,
+ blink: bool = false,
+ reverse: bool = false,
+ invisible: bool = false,
+ strikethrough: bool = false,
+ ul: enum(u3) { off, single, double, curly, dotted, dashed } = .off,
+ font_role: FontRole = .body,
+};
+
+pub const Cell = struct {
+ text: [7]u8 = @splat(' '),
+ len: u8 = 1,
+ style: CellStyle = .{},
+ default: bool = true,
+
+ pub fn grapheme(c: *const Cell) []const u8 {
+ return c.text[0..c.len];
+ }
+
+ pub fn visuallyEqual(a: *const Cell, b: *const Cell) bool {
+ if (a.default or b.default) return a.default and b.default;
+ return a.len == b.len and
+ std.mem.eql(u8, a.grapheme(), b.grapheme()) and
+ std.meta.eql(a.style, b.style);
+ }
+
+ pub fn printableAscii(c: *const Cell) ?u8 {
+ if (c.default) return ' ';
+ if (c.len != 1) return null;
+ const byte = c.text[0];
+ return if (byte >= ' ' and byte <= '~') byte else null;
+ }
+};
+
+/// A rectangle in pixels.
+pub const RectPx = struct {
+ x: u32 = 0,
+ y: u32 = 0,
+ w: u32 = 0,
+ h: u32 = 0,
+};
+
+/// A rectangle in the frame's cells.
+pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 };
+
+/// The pixels a placement shows: RGBA, straight alpha, `stride` bytes a
+/// row. They are the pane's, and stay put until its next frame.
+pub const Raster = struct {
+ ptr: [*]const u8,
+ w: u32,
+ h: u32,
+ stride: u32,
+
+ pub fn of(rgba: []const u8, w: usize, h: usize) Raster {
+ return .{ .ptr = rgba.ptr, .w = @intCast(w), .h = @intCast(h), .stride = @intCast(w * 4) };
+ }
+
+ pub fn bytes(r: Raster) []const u8 {
+ return r.ptr[0 .. @as(usize, r.stride) * r.h];
+ }
+};
+
+/// A picture over the frame's cells, which a frontend realises: the window
+/// as a texture kept by `key`, the tty as a kitty image, or either as glyph
+/// art in `dst`'s cells (Art.zig, the frontends' own) where it cannot show
+/// pixels or the pane asks for art. The frame lists them a pane at a time,
+/// lowest first.
+pub const Placement = struct {
+ pane: u8,
+ raster: Raster,
+ /// The part of `raster` shown.
+ src: RectPx,
+ /// The cells it lies over, which clip it.
+ dst: RectCell,
+ /// Where it goes in `dst`, in pixels from `dst`'s top left corner;
+ /// null: the frontend fits `src` there, no larger than it is, at the
+ /// top left (as glyph art, centred).
+ at: ?RectPx = null,
+ /// The pixels' identity (`keyOf`): one key is one picture, so a
+ /// frontend keeps what it uploaded under it.
+ key: u64,
+ /// A terminal program's kitty `z=`: below 0 it is under the text,
+ /// which a tty passes on to the terminal outside.
+ z: i32 = 0,
+ /// Rows of `raster` that alone differ from the picture under the key
+ /// `from`: a frontend still holding that one updates those rows.
+ dirty: ?Dirty = null,
+ art: Art = .{},
+
+ pub const Dirty = struct { from: u64, y: u32, h: u32 };
+
+ /// How the pane wants it drawn as glyph art: the Petscii, Palette and
+ /// Ascii words on an image pane, Petscii and TermImages on a terminal.
+ pub const Art = struct {
+ /// Glyph art even where pixels could be shown (Petscii on).
+ glyph: bool = false,
+ palette: Palette = .commodore,
+ /// Letters and signs among the glyphs, not only blocks and lines.
+ ascii: bool = true,
+
+ pub const Palette = enum { commodore, terminal };
+ };
+
+ /// A pane's picture `page` (a PDF's page, a terminal's image id; 0 for
+ /// an image) as of `revision`.
+ pub fn keyOf(serial: u32, page: u32, revision: u32) u64 {
+ return std.hash.Wyhash.hash(0, std.mem.asBytes(&[3]u32{ serial, page, revision }));
+ }
+};
+
+/// A key a frontend read (Event.zig).
+pub const Key = struct {
+ cp: u21, // codepoint or one of the specials below
+ text: []const u8 = "",
+ ctrl: bool = false,
+ alt: bool = false,
+ shift: bool = false,
+
+ pub const enter: u21 = 0x0D;
+ pub const escape: u21 = 0x1B;
+ pub const tab: u21 = 0x09;
+ pub const backspace: u21 = 0x7F;
+ // private-use plane for non-text keys, matching no real codepoint
+ pub const up: u21 = 0xF0001;
+ pub const down: u21 = 0xF0002;
+ pub const left: u21 = 0xF0003;
+ pub const right: u21 = 0xF0004;
+ pub const home: u21 = 0xF0005;
+ pub const end: u21 = 0xF0006;
+ pub const page_up: u21 = 0xF0007;
+ pub const page_down: u21 = 0xF0008;
+ pub const delete: u21 = 0xF0009;
+ pub const insert: u21 = 0xF000A;
+ pub const print_screen: u21 = 0xF000B;
+ pub const scroll_lock: u21 = 0xF000C;
+ pub const pause: u21 = 0xF000D;
+ pub const menu: u21 = 0xF000E;
+ /// F1 to F25, in order: Fn is `f1 + n - 1`.
+ pub const f1: u21 = 0xF0011;
+ pub const f25: u21 = f1 + 24;
+};
diff --git a/abi/term.zig b/abi/term.zig
new file mode 100644
index 00000000..de969796
--- /dev/null
+++ b/abi/term.zig
@@ -0,0 +1,432 @@
+//! The terminal as the core sees it (docs/next-terminal.md, Phase 1): the
+//! entries (`Ops`) a terminal module gives the core, and the records they
+//! take and give. A terminal's state, its replicas' encoder and tracks are
+//! handles the core holds and never looks into; what it knows of them it is
+//! told here, as numbers, bytes, text and cells. src/term/term.zig is the
+//! one implementation (ghostty-vt behind it); src/Term.zig is the core's
+//! side of it.
+const std = @import("std");
+const plain = @import("plain.zig");
+const Color = plain.Color;
+const CellStyle = plain.CellStyle;
+
+/// A terminal: its emulator, its parse and what is kept beside it.
+pub const State = opaque {};
+/// What a session's authority keeps to encode its terminals for its peers
+/// (one for all of them), and what it keeps of one terminal for them.
+pub const Encoder = opaque {};
+pub const Track = opaque {};
+/// A replica's side of one terminal: what it was sent.
+pub const Replica = opaque {};
+
+/// Where the view and the cursor are, in rows counted from the top of the
+/// history: `total` rows, the view's top at `offset`, `len` of them shown.
+/// All zero without a terminal.
+pub const Grid = struct {
+ total: usize = 0,
+ offset: usize = 0,
+ len: usize = 0,
+ /// The cursor, in cells of the active area (the history's last `len`
+ /// rows).
+ cursor_x: u16 = 0,
+ cursor_y: u16 = 0,
+ /// The program shows the cursor (DECTCEM).
+ cursor_visible: bool = false,
+ /// The view's top row while it is scrolled to one, null while it
+ /// follows the output.
+ view: ?usize = null,
+ /// Its grid's width (a pane's may differ while a resize is deferred).
+ cols: u16 = 0,
+};
+
+/// What a `feed` told the rows the core keeps positions on: each tracked
+/// row where it is after the read, whether the program erased it, whether
+/// it cleared the screen, whether the pages the rows were on lived through
+/// it (a reset can take them) and whether a row could not be followed (no
+/// memory for its pin). Taped: a screen-state replica, which feeds
+/// nothing, is told its authority's.
+pub const Told = struct { rows: []const i32, erased: []const bool, cleared: bool, alive: bool, failed: bool };
+
+pub const MouseMods = struct { shift: bool = false, alt: bool = false, ctrl: bool = false };
+pub const MouseButton = enum { left, middle, right, wheel_up, wheel_down, wheel_left, wheel_right };
+pub const MouseAction = enum { press, release, motion };
+/// Cursor-key presses: so many left, so many right.
+pub const Moves = struct { left: usize = 0, right: usize = 0 };
+
+/// The modes a program set that the core decides by.
+pub const Modes = struct {
+ /// It tracks the mouse itself (1000, 1002, 1003).
+ mouse: bool = false,
+ /// ...every move of it (1003).
+ all_motion: bool = false,
+ /// A wheel over it is its own: it tracks the mouse, or it is on the
+ /// alternate screen with alternate scroll (1007).
+ wheel: bool = false,
+ /// It wants to hear focus in and out (1004).
+ focus: bool = false,
+ /// It wants its pastes bracketed (2004).
+ bracketed_paste: bool = false,
+ /// It has the alternate screen (1049).
+ alternate: bool = false,
+};
+
+/// Where a shell is in its command cycle, as pardes's own OSC 133 marks
+/// tell it (marks carrying its `aid` alone: a nested shell's pass it by),
+/// and what is at its cursor. All zero without a terminal.
+pub const Prompt = struct {
+ phase: Phase = .none,
+ /// Commands started (C at the input phase), prompts drawn (B), and D
+ /// marks outside a running command (a line the shell handled without
+ /// starting it).
+ started: u32 = 0,
+ prompts: u32 = 0,
+ declined: u32 = 0,
+ /// The newest prompt continues an unfinished line (bash's PS2).
+ continuation: bool = false,
+ /// The newest command to end: which one, and its status if given.
+ finished: ?Finished = null,
+ /// The cursor is at a prompt's input, on either screen.
+ input_ready: bool = false,
+ /// ...and nothing is typed on its line up to the cursor.
+ input_empty: bool = false,
+ /// The cursor is on a prompt's row or at its input, on the primary
+ /// screen.
+ at_prompt: bool = false,
+
+ pub const Phase = enum { none, prompt, input, running };
+ pub const Finished = struct { seq: u32, status: ?i32 };
+};
+
+/// What a command printed. `text` is the caller's.
+pub const CommandOutput = struct {
+ text: [:0]const u8,
+ /// Whether `text` starts where the command did. It does not when that
+ /// start is not there to read: cut off by the rows asked for, scrolled
+ /// out of the history or erased from it (ED 3), erased under it while
+ /// it ran, or never marked (a C or D on the alternate screen).
+ whole: bool,
+};
+
+/// A terminal's rows as text: `rows` slices into `text`, which is a prefix
+/// of `text_alloc` (a prompt cut off shortens the join), the last row the
+/// empty one after the cursor's.
+pub const Rows = struct {
+ text_alloc: []u8,
+ text: []const u8,
+ rows: [][]const u8,
+};
+
+/// How much of a row the prompt it starts with is.
+pub const PromptCut = union(enum) {
+ /// no prompt: the row as the emulator dumps it
+ keep,
+ /// all prompt, nothing typed yet: show nothing of it
+ blank,
+ /// this many leading COLUMNS are the prompt; the rest is what was typed
+ /// at it
+ cut: usize,
+};
+
+/// 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.
+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);
+ }
+};
+/// Bytes `start..end` of a page's text, drawn in `style`.
+pub const Span = struct { start: u32, end: u32, style: CellStyle };
+
+// ---- its colours on the body ----
+
+/// A theme's colours as a terminal's paint takes them.
+pub const Ink = struct {
+ fg: ?[3]u8,
+ bg: ?[3]u8,
+ tag_fg: [3]u8,
+ tag_bg: [3]u8,
+ /// The theme's own sixteen, when it has them.
+ palette: ?[16][3]u8,
+ /// The sixteen the filter keys a program's colours to: `palette`, else
+ /// made of the theme's roles.
+ base: [16][3]u8,
+
+ /// A palette index as the theme draws it: its own sixteen, else the
+ /// index.
+ pub fn palColor(ink: *const Ink, idx: u8) Color {
+ if (ink.palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] };
+ return .{ .index = idx };
+ }
+};
+
+/// The theme's 256 colours as the filter maps onto them, kept while the
+/// theme is the same (`Pardes.tty_filter_palette`).
+pub const FilterPalette = struct {
+ key: ?Key = null,
+ colors: [256][3]u8 = undefined,
+
+ pub const Key = struct { bg: [3]u8, fg: [3]u8, base: [16][3]u8 };
+};
+
+/// A program's colours mapped to the theme, once a frame: what a +Pager's
+/// spans are drawn through (`spanColor`), as a terminal's cells are.
+pub const Filter = struct {
+ target: *const [256][3]u8,
+ /// The theme's page and ink, and the page a program's colours are
+ /// drawn on (its OSC 11, keyed to the theme, else the theme's).
+ theme_bg: [3]u8,
+ theme_fg: [3]u8,
+ default_bg: [3]u8,
+ /// What a foreground too near the page's background becomes instead.
+ fallback_fg: [3]u8,
+ default_bg_luminance: f64,
+ fg_for_palette: [256]Color,
+ bg_for_palette: [256]Color,
+ /// The two answers for a cell that names no colour of its own.
+ fg_default: Color,
+ bg_default: Color,
+ cache_rgb: [256][3]u8 = undefined,
+ cache_key: [256]u8 = undefined,
+ cache_valid: [256]bool = @splat(false),
+};
+
+/// One cell of a terminal's view as its paint gives it: its style (its
+/// colours the theme's already), the bytes it spells in the view's text,
+/// and whether it is half of a wide one.
+pub const Painted = struct {
+ style: CellStyle,
+ bytes: u16,
+ wide: enum(u2) { narrow, wide, spacer_tail, spacer_head },
+};
+
+/// One row of a terminal's view as its paint gives it.
+pub const PaintedRow = struct {
+ /// The shell marked it a prompt's: how much of it the prompt is.
+ prompt: ?PromptCut,
+ /// It holds kitty placeholder cells.
+ placeholder: bool,
+ /// Its cells given, from its first: the grid's past them are none.
+ len: u16,
+};
+
+/// Where a terminal's kitty images go, as the body lays out its rows:
+/// `rows_of[v]` is the body row its view's row `v` shows on, null for one
+/// not shown.
+pub const ImagesAt = struct {
+ pane: u8,
+ serial: u32,
+ tx: u16,
+ body_y: u16,
+ cols: u16,
+ rows_of: []const ?u16,
+ /// The pane shows its terminal's rows as they are (tty mode): a prompt
+ /// row is the grid's then, and its images show.
+ tty_mode: bool,
+ /// The core's clock (animations step on it), and a cell's size in
+ /// pixels.
+ now_ms: u64,
+ cell_w: u32,
+ cell_h: u32,
+};
+
+/// What a predicted echo reads of a cell: its codepoint, whether the shell
+/// marked it input, and its style's identity.
+pub const EchoCell = struct { cp: u21, input: bool, style: u32 };
+
+// ---- its replicas ----
+
+/// 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 flight_bound = 32;
+
+/// 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: [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;
+ }
+
+ /// 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 };
+ }
+};
+
+/// A delta applied: its version, and what its authority sent beside it.
+pub const Applied = struct { seq: u32, extra: []const u8 };
+
+/// What the dump keeps of a terminal beside its emulator, by name as every
+/// dump is (src/walk.zig, through the core's `Term.State`).
+pub const Parts = struct {
+ reply: []const u8 = "",
+ reply_dropped: u32 = 0,
+ mouse_cell: ?Coordinate = null,
+ petscii: bool = false,
+ /// The view's top row, counted from the top of the history.
+ view: usize = 0,
+ phase: Prompt.Phase = .none,
+ started: u32 = 0,
+ prompts: u32 = 0,
+ declined: u32 = 0,
+ continuation: bool = false,
+ lost: bool = false,
+ finished: ?Prompt.Finished = null,
+ out_start: ?Coordinate = null,
+ out_end: ?Coordinate = null,
+
+ /// A cell's place on a screen (ghostty's `Coordinate`, as it dumps).
+ pub const Coordinate = extern struct { x: u16 = 0, y: u32 = 0 };
+};
+
+/// What reading its text can fail with.
+pub const TextError = error{ OutOfMemory, WriteFailed, UnknownPoint };
+
+/// The entries, as `term.ops` gives them. An error set named here is what
+/// the core's callers name (the tape's `Failure` reads `open`'s, the text
+/// readers' are edit.zig's); `anyerror` where the core only passes one on
+/// or reports it. Each takes the handles above
+/// (none is made without a terminal module: the core asks `Term.ops`
+/// first).
+pub const Ops = struct {
+ // ---- lifecycle ----
+ /// A new terminal, `cols` by `rows`, allocated with `gpa` (its own from
+ /// then on).
+ open: *const fn (gpa: std.mem.Allocator, cols: u16, rows: u16) error{ OutOfMemory, InvalidValue }!*State,
+ /// It and what it holds, freed.
+ close: *const fn (s: *State, gpa: std.mem.Allocator) void,
+ /// 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.
+ due: *const fn (s: *const State) ?u64,
+ /// Loaded from a dump without its shell: its program's modes reset, its
+ /// history marked off from what the next shell prints.
+ revive: *const fn (s: *State) void,
+ /// The PNG resize workers kitty images are decoded with, started and
+ /// stopped with the host.
+ start: *const fn (gpa: std.mem.Allocator) void,
+ stop: *const fn () void,
+ /// The allocator it was opened with.
+ gpa: *const fn (s: *const State) std.mem.Allocator,
+
+ // ---- the dump and the digest (`Term.State`'s walk hooks) ----
+ /// Its screen into the replay digest (`view`: where its view is too).
+ digest: *const fn (s: *const State, h: *std.hash.Wyhash, view: bool) void,
+ /// What the dump keeps of it beside its emulator.
+ parts: *const fn (s: *const State) Parts,
+ /// Its emulator as the dump keeps it (ghostty's snapshot); `slim`: its
+ /// size alone (a join's dump, its first delta replaces it).
+ snapshot: *const fn (s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) anyerror!void,
+ /// `snapshot`'s bytes and `parts` back into a new terminal.
+ load: *const fn (gpa: std.mem.Allocator, snapshot: []const u8, parts: *const Parts) anyerror!*State,
+
+ // ---- output and view ----
+ /// One read of its program's output (`Told` says where the tracked
+ /// rows went).
+ feed: *const fn (s: *State, bytes: []const u8, track: []const i32, rows: []i32, erased: []bool) Told,
+ // A null handle: what a pane without a terminal is told (all zero).
+ grid: *const fn (s: ?*const State) Grid,
+ viewTo: *const fn (s: *State, at: ?usize) void,
+ scroll: *const fn (s: *State, delta: i32) void,
+ follow: *const fn (s: *State) void,
+ resize: *const fn (s: *State, cols: u16, rows: u16, later: bool) void,
+ resizeDeferred: *const fn (s: *State) bool,
+ cellPixels: *const fn (s: *State, w: u32, h: u32) void,
+ replies: *const fn (s: *State) []const u8,
+
+ // ---- input ----
+ key: *const fn (s: *State, k: plain.Key, out: *std.Io.Writer) error{WriteFailed}!void,
+ mouse: *const fn (s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8,
+ wheel: *const fn (s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8,
+ paste: *const fn (s: ?*const State, text: []u8) [3][]const u8,
+ modes: *const fn (s: ?*const State) Modes,
+ promptMoves: *const fn (s: *State, row: i32, col: i32) ?Moves,
+
+ // ---- prompt and commands ----
+ prompt: *const fn (s: ?*State) Prompt,
+ commandOutput: *const fn (s: ?*State, gpa: std.mem.Allocator, max_rows: usize) error{OutOfMemory}!CommandOutput,
+ endOutputHere: *const fn (s: *State) void,
+
+ // ---- text ----
+ scrollback: *const fn (s: ?*State, gpa: std.mem.Allocator) error{ OutOfMemory, WriteFailed }![]const u8,
+ scrollbackLen: *const fn (s: ?*State) usize,
+ textRows: *const fn (s: *State, alloc: std.mem.Allocator, scratch: std.mem.Allocator) TextError!Rows,
+ viewport: *const fn (s: *State, arena: std.mem.Allocator, cut: bool) TextError![]const []const u8,
+ /// Its rows `first` and the `count` after it (from the top of its
+ /// history) as text, a prompt's own cells cut off: `arena`'s.
+ editRows: *const fn (s: *State, arena: std.mem.Allocator, first: usize, count: usize) (TextError || error{ NoRow })![]const []const u8,
+ /// How much of its row `row` (from the top of its history) the prompt
+ /// it starts with is; null for a row no prompt starts.
+ promptCut: *const fn (s: *State, row: i32) ?PromptCut,
+ markRead: *const fn (s: *State) void,
+ /// What a predicted echo reads of cell `x`, `y` of its active area.
+ echoCell: *const fn (s: *const State, x: u16, y: u16) ?EchoCell,
+
+ // ---- the pager ----
+ /// `raw`, a program's output, as a terminal reads it: its text and its
+ /// SGR spans, every other control dropped. `gpa`'s.
+ page: *const fn (gpa: std.mem.Allocator, raw: []const u8) error{OutOfMemory}!Page,
+ /// The filter a +Pager's spans are drawn through (`spanColor`).
+ filter: *const fn (ink: *const Ink, palette: *FilterPalette) Filter,
+ spanColor: *const fn (f: *Filter, color: Color, is_bg: bool) Color,
+
+ // ---- draw ----
+ /// Its view's rows, `rows.len` of them, `cols` cells each, into
+ /// `cells`: each cell's style in the theme's colours (through the
+ /// filter when `filtered`), its bytes and width.
+ paint: *const fn (s: *State, ink: *const Ink, palette: *FilterPalette, filtered: bool, first: u16, cols: u16, cells: []Painted, rows: []PaintedRow) void,
+ /// Its kitty images over the body's rows, appended to `out`, and their
+ /// placeholder cells blanked in `frame` (`frame_cols` wide).
+ images: *const fn (s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void,
+ petscii: *const fn (s: ?*const State) ?bool,
+ togglePetscii: *const fn (s: *State) void,
+ hasImages: *const fn (s: ?*const State) bool,
+
+ // ---- its replicas ----
+ encoder: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Encoder,
+ encoderFree: *const fn (e: *Encoder) void,
+ track: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Track,
+ /// A peer's track of it let go (`s` null: it is gone).
+ untrack: *const fn (t: *Track, gpa: std.mem.Allocator, s: ?*State) void,
+ /// What a peer is owed of it, a delta against what the peer was sent.
+ encode: *const fn (s: *State, e: *Encoder, t: *Track, peer: *Peer, out: *std.Io.Writer) anyerror!bool,
+ /// Rows of it a replica holds as holes.
+ encodeRows: *const fn (s: *State, e: *Encoder, t: *Track, lo: u64, hi: u64, out: *std.Io.Writer) anyerror!void,
+ wasRead: *const fn (s: *const State) bool,
+ clearRead: *const fn (s: *State) void,
+ replica: *const fn (gpa: std.mem.Allocator) error{OutOfMemory}!*Replica,
+ replicaFree: *const fn (r: *Replica, gpa: std.mem.Allocator) void,
+ /// The absolute row its replica's active area begins at.
+ replicaTop: *const fn (r: *const Replica) u64,
+ /// History rows `lo..hi` it does not hold.
+ missing: *const fn (r: *const Replica, lo: u64, hi: u64, out: *std.ArrayList([2]u64), gpa: std.mem.Allocator) error{OutOfMemory}!void,
+ apply: *const fn (s: *State, r: *Replica, bytes: []const u8) anyerror!Applied,
+ applyRows: *const fn (s: *State, r: *Replica, bytes: []const u8) anyerror!void,
+ shown: *const fn (s: *State, r: *const Replica) [2]u64,
+ blank: *const fn (s: *State, r: *const Replica, lo: u64, hi: u64) void,
+ dumpScreen: *const fn (s: *State, w: *std.Io.Writer) error{WriteFailed}!void,
+};
diff --git a/abi/wire.zig b/abi/wire.zig
new file mode 100644
index 00000000..d6098325
--- /dev/null
+++ b/abi/wire.zig
@@ -0,0 +1,927 @@
+//! The framed stream a replica speaks (docs/next-daemon.md, phase 5), on
+//! the daemon's `pardes-replica.sock` and then its session's: fixed-width
+//! little-endian fields and explicit tags, the hello and its version, a
+//! ping, and the input Events. Native struct layout never reaches the wire.
+//! The cell frames that went the other way, and the frontends that drew
+//! them, went with phase 3.
+const std = @import("std");
+const builtin = @import("builtin");
+const pardes = @import("core");
+const config = @import("pardes_config");
+
+/// 23: a pane of a kind's frame names its rasters by key, their pixels
+/// crossing before it as strips of 4 MiB at most over the rows it shows
+/// (screen kind 5), and a replica lacking one asks for its pane again
+/// (kind 4); a tick's prefix is on the tape, out of the frame;
+/// 22: a PDF's pixel scroll (0x1a) is gone with the core's PDF, the pdf
+/// addon's panes scrolled by the wheel as any kind's are;
+/// 21: a session's views are `Pardes.views` in its dump and its digest
+/// (src/views.zig), the panes' shares of the others under `shares`;
+/// 20: a digest takes a blob of 4 KiB and up (a file's text, a register's,
+/// an undo entry's bytes) by its length, not its bytes (src/walk.zig): a
+/// text's revision says what it holds;
+/// 19: a client joining again names the view it had in its hello, and a
+/// bye says whether it joins again for it (views.away);
+/// 18: a replica's input is stamped with its guess of the session's
+/// clocks, the time its step reads (phase 6's instant interaction notes);
+/// 17: a pointer's hit carries the place it was made on (Layer.Place) and
+/// a tag hit its line, which the step resolves it by, not by its frame;
+/// 16: a far client says so, the session sends it its blobs' hashes before
+/// the rest and only the blobs it asks for, all of it in zstd (phase 6's
+/// content cache and zstd notes), and a client says its frontend (a window
+/// or a terminal) as its first input, a window replicating a terminal's
+/// session and back (phase 6's GUI replica notes); 15: the session streams
+/// a replica its dump and units, and terminal deltas both ways (phase 5
+/// part B); 14: the hello names a session and
+/// carries the semantics hash, and a ping is answered (phase 5's
+/// groundwork); 13: the frames went (phase 3).
+pub const version: u16 = 23;
+
+/// The terminal's build and the window's step alike (`semantics`).
+const family = switch (config.platform) {
+ .tui, .gui => "desktop",
+ else => @tagName(config.platform),
+};
+
+/// What makes two cores step differently, hashed: a replica's hello carries
+/// its own, and one of another build is refused. The protocol, the release
+/// and commit, the platform and build options, every dependency's content
+/// hash (grammars, the terminal emulator, Unicode), the walker codec's assumptions
+/// (pointer width, byte order) and the tape's shape (tape.shape: what each
+/// input and each answer of the host's is laid out as). Not the OS: a Linux
+/// client of a FreeBSD session is the main case, and what differs there is
+/// the host's, taped, in a shape every OS shares (an error by its name, a
+/// stat as fs.OsStat). Nor the build mode: a Debug build steps as a
+/// release one does (regexp.zig's one budget).
+/// Nor the terminal's build against the window's: their cores step alike,
+/// the GUI's own words by the view's frontend (builtins.zig `here`), so a
+/// window replicates a terminal's session and a terminal a window's.
+/// ponytail: an unstamped build (Debug with -Dplatform, every test build)
+/// has no commit, so two dev trees of one release are told apart only by
+/// their options and dependencies; -Dstamp-commit stamps one.
+pub const semantics: u64 = blk: {
+ @setEvalBranchQuota(1_000_000);
+ // The two long ones (the dependencies, 2.5 KB, and the tape's shape,
+ // 11 KB) joined on, not formatted: formatting them at comptime was 5 %
+ // of a compile of the core.
+ break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint(
+ "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n",
+ .{
+ version, config.version, config.commit orelse "unstamped",
+ family, config.syntax_highlighting, config.syntax_zig_grammar,
+ config.syntax_minimal_grammars, config.syntax_full_grammars, config.workspace_tag,
+ config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(),
+ },
+ ) ++ config.deps ++ "\n" ++ pardes.tape.shape);
+};
+
+/// EndOfStream: the message ends early; WriteFailed: no room for it.
+/// ReadFailed is in only because std.Io.Reader says so: a fixed one never
+/// fails a read.
+pub const Error = error{ EndOfStream, ReadFailed, Overlong, BadTag, BadValue, Trailing, WriteFailed };
+
+pub const max_cols: u16 = 512;
+pub const max_rows: u16 = 128;
+pub const max_payload: u32 = 16 << 20;
+pub const header_len = 5; // tag:u8, payload length:u32le
+
+// Stable wire numbers; gaps are retired tags. Unknown tags are rejected by the decoder.
+pub const ClientTag = enum(u8) {
+ hello = 0x01,
+ bye = 0x02,
+ ping = 0x03,
+ /// A replica's word about a terminal's state (src/term/screen_state.zig): the
+ /// delta it holds, or rows it asks for. Opaque here.
+ screen_ack = 0x04,
+ /// What is the session's digest, in stream order (a replica checks
+ /// itself against it once quiet).
+ check = 0x05,
+ /// A client's first word after its hello: whether it is far (through
+ /// ssh), so that it holds blobs by their hash and reads zstd.
+ far = 0x06,
+ /// The join's blobs a far client lacks, a bit each in `blobs` order.
+ want = 0x07,
+ /// The session's clocks (realtime and monotonic, ns) as the client
+ /// guessed them for the input that follows: its time, which the step
+ /// reads (src/replica.zig).
+ stamp = 0x08,
+
+ key = 0x10,
+ mouse = 0x11,
+ resize = 0x12,
+ paste = 0x18,
+ command = 0x19,
+ // 0x1a was a PDF's pixel scroll, 0x1b and 0x1c a pinch and a touch
+ // scroll, gone since.
+ pointer_leave = 0x1d,
+ focus = 0x1e,
+ /// Which frontend the client is: a window, or a terminal.
+ frontend = 0x20,
+};
+
+const ButtonTag = enum(u8) {
+ left = 0x00,
+ middle = 0x01,
+ right = 0x02,
+ wheel_up = 0x03,
+ wheel_down = 0x04,
+ wheel_left = 0x05,
+ wheel_right = 0x06,
+ none = 0x07,
+ back = 0x08,
+ forward = 0x09,
+};
+const KindTag = enum(u8) { press = 0x00, release = 0x01, motion = 0x02, drag = 0x03 };
+
+// ---------------------------------------------------------------------------
+// messages
+// ---------------------------------------------------------------------------
+
+/// First message on every connection, and `version` is its first field at a
+/// fixed offset for exactly one reason: a mismatch has to be diagnosable even
+/// when the rest of the layout is the part that changed.
+pub const Hello = struct {
+ version: u16 = version,
+ /// The client's `semantics`: the daemon refuses it unless the session's
+ /// is the same.
+ semantics: u64 = semantics,
+ /// Which session (its 9P name, as `--attach=` names it).
+ session: []const u8,
+ /// The view it had, joining again for it (a divergence's rejoin, an
+ /// Upgrade's): the daemon hands it on with the connection. 0xff: none.
+ view: ?u8 = null,
+};
+
+/// A session's name on the wire, as the daemon keeps it.
+pub const max_name = 128;
+/// The longest hello there is, header and all.
+pub const hello_max = header_len + 2 + 8 + 2 + max_name + 1;
+
+/// Daemon or session -> client.
+pub const ServerTag = enum(u8) {
+ /// The hello is accepted and the connection is the session's now: its pid
+ /// and name.
+ welcome = 0x01,
+ /// Refused, said in words; the connection ends.
+ refused = 0x02,
+ /// A ping's value back.
+ pong = 0x03,
+ /// A piece of the join's dump (src/dump.zig): the welcome says how long
+ /// it is whole.
+ dump = 0x04,
+ /// A unit of the authority's stream (src/replica.zig): its origin, seq,
+ /// clocks and tape.
+ unit = 0x05,
+ /// A terminal's delta, or rows asked for (src/term/screen_state.zig), applied
+ /// before the next unit. Opaque here.
+ screen = 0x06,
+ /// The session's digest (u64le), after every unit before it.
+ check = 0x07,
+ /// Part of the join's list of blobs, to a far client: each one's place
+ /// in the state, its length and its BLAKE3 hash (src/replica.zig).
+ blobs = 0x08,
+ /// A piece of a far client's stream from here on, zstd-compressed: the
+ /// messages in it are framed as these are. Opaque here.
+ zstd = 0x09,
+ /// A piece of a record's bytes by hash (tape.zig `Big`), before the
+ /// unit naming it: the hash, the whole's length and this piece's place
+ /// (u64le each), then at most 1 MiB of it (src/replica.zig).
+ blob = 0x0a,
+};
+
+pub const ServerMsg = union(ServerTag) {
+ /// Who the client is now (its id and view in the session), how long the
+ /// dump that follows is, and the session's offset from UTC (a replica
+ /// guesses the session's time of day). A far client is told how many
+ /// blobs the dump holds (`blobs`).
+ welcome: struct { pid: u32, session: []const u8, client: u16 = 0, view: u8 = 0, dump_len: u64 = 0, gmtoff: i32 = 0, digest: u64 = 0, semantics: u64 = 0, blobs: u32 = 0 },
+ refused: []const u8,
+ pong: u64,
+ dump: []const u8,
+ unit: []const u8,
+ screen: []const u8,
+ check: u64,
+ blobs: []const u8,
+ zstd: []const u8,
+ blob: []const u8,
+};
+
+/// A message's header, for a payload sent on its own (a unit, a dump's
+/// piece): no copy of it into a message buffer.
+pub fn header(tag: u8, len: usize) [header_len]u8 {
+ var h: [header_len]u8 = undefined;
+ h[0] = tag;
+ std.mem.writeInt(u32, h[1..5], @intCast(len), .little);
+ return h;
+}
+
+/// The other way: what a client is told, its slices borrowing `payload`.
+pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg {
+ var r: std.Io.Reader = .fixed(payload);
+ const msg: ServerMsg = switch (std.enums.fromInt(ServerTag, tag) orelse return error.BadTag) {
+ .welcome => .{ .welcome = .{
+ .pid = try r.takeInt(u32, .little),
+ .session = try r.take(try r.takeInt(u16, .little)),
+ .client = try r.takeInt(u16, .little),
+ .view = try r.takeByte(),
+ .dump_len = try r.takeInt(u64, .little),
+ .gmtoff = try r.takeInt(i32, .little),
+ .digest = try r.takeInt(u64, .little),
+ .semantics = try r.takeInt(u64, .little),
+ .blobs = try r.takeInt(u32, .little),
+ } },
+ .refused => .{ .refused = try r.take(try r.takeInt(u16, .little)) },
+ .pong => .{ .pong = try r.takeInt(u64, .little) },
+ .dump => return .{ .dump = payload },
+ .unit => return .{ .unit = payload },
+ .screen => return .{ .screen = payload },
+ .check => .{ .check = try r.takeInt(u64, .little) },
+ .blobs => return .{ .blobs = payload },
+ .zstd => return .{ .zstd = payload },
+ .blob => return .{ .blob = payload },
+ };
+ try end(&r);
+ return msg;
+}
+
+pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 {
+ var w: std.Io.Writer = .fixed(out);
+ const at = try beginMessage(&w, @backingInt(std.meta.activeTag(msg)));
+ switch (msg) {
+ .welcome => |h| {
+ try w.writeInt(u32, h.pid, .little);
+ try putSlice16(&w, h.session);
+ try w.writeInt(u16, h.client, .little);
+ try w.writeByte(h.view);
+ try w.writeInt(u64, h.dump_len, .little);
+ try w.writeInt(i32, h.gmtoff, .little);
+ try w.writeInt(u64, h.digest, .little);
+ try w.writeInt(u64, h.semantics, .little);
+ try w.writeInt(u32, h.blobs, .little);
+ },
+ .refused => |words| try putSlice16(&w, words),
+ .pong => |v| try w.writeInt(u64, v, .little),
+ .dump, .unit, .screen, .blobs, .zstd, .blob => |bytes| try w.writeAll(bytes),
+ .check => |v| try w.writeInt(u64, v, .little),
+ }
+ try finishMessage(&w, at);
+ return w.buffered();
+}
+
+/// `Hello.version` alone, read before the rest of the hello, whose layout
+/// may have moved: a mismatch is said in words, and a payload shorter than
+/// two bytes is an error, not version 0.
+pub fn helloVersion(payload: []const u8) Error!u16 {
+ var r: std.Io.Reader = .fixed(payload);
+ return r.takeInt(u16, .little);
+}
+
+/// Frontend -> core, decoded. The `Event`'s slices BORROW the payload buffer,
+/// exactly like the pty chunks the tui host hands to `update`: valid for that
+/// one call and no longer.
+pub const ClientMsg = union(enum) {
+ hello: Hello,
+ /// The client's end: `again`, it joins again for its view at once.
+ bye: struct { again: bool = false },
+ /// A round trip's probe, answered `pong` with the same value.
+ ping: u64,
+ screen_ack: []const u8,
+ check,
+ far: bool,
+ want: []const u8,
+ stamp: [2]i64,
+ event: pardes.Event,
+};
+
+// ---------------------------------------------------------------------------
+// primitives
+// ---------------------------------------------------------------------------
+
+/// Length-prefixed, u16: paths, command lines, a key's text. Nothing here
+/// is legitimately longer than 64 KiB and a u16 says so on the wire.
+fn putSlice16(w: *std.Io.Writer, v: []const u8) Error!void {
+ if (v.len > std.math.maxInt(u16)) return error.Overlong;
+ try w.writeInt(u16, @intCast(v.len), .little);
+ try w.writeAll(v);
+}
+
+/// ...and u32 for the ones that are: pty output, a paste, a file.
+fn putSlice32(w: *std.Io.Writer, v: []const u8) Error!void {
+ if (v.len > max_payload) return error.Overlong;
+ try w.writeInt(u32, @intCast(v.len), .little);
+ try w.writeAll(v);
+}
+
+/// One byte, 0 or 1, never "nonzero": the writer's `@intFromBool`.
+fn getBool(r: *std.Io.Reader) Error!bool {
+ return switch (try r.takeByte()) {
+ 0 => false,
+ 1 => true,
+ else => error.BadValue,
+ };
+}
+
+/// IEEE-754 binary32, as its bit pattern in an explicit u32. A scalar
+/// bitcast and not a struct blit: the format is the one thing a riscv32
+/// and an x86_64 do agree about.
+fn getF32(r: *std.Io.Reader) Error!f32 {
+ const v: f32 = @bitCast(try r.takeInt(u32, .little));
+ // A NaN or an infinity here is not a scroll distance.
+ if (!std.math.isFinite(v)) return error.BadValue;
+ return v;
+}
+
+fn getSlice32(r: *std.Io.Reader) Error![]const u8 {
+ const n = try r.takeInt(u32, .little);
+ if (n > max_payload) return error.Overlong;
+ return r.take(n);
+}
+
+/// A grid the core can render into. Zero is refused rather than clamped: a
+/// frontend that has not been sized yet must not be allowed to collapse a
+/// shared session to nothing.
+fn getCols(r: *std.Io.Reader) Error!u16 {
+ const v = try r.takeInt(u16, .little);
+ if (v == 0 or v > max_cols) return error.BadValue;
+ return v;
+}
+
+fn getRows(r: *std.Io.Reader) Error!u16 {
+ const v = try r.takeInt(u16, .little);
+ if (v == 0 or v > max_rows) return error.BadValue;
+ return v;
+}
+
+fn getTag(r: *std.Io.Reader, comptime T: type) Error!T {
+ return std.enums.fromInt(T, try r.takeByte()) orelse error.BadTag;
+}
+
+fn end(r: *std.Io.Reader) Error!void {
+ if (r.seek != r.end) return error.Trailing;
+}
+
+/// Reserve a message header; `finishMessage` back-patches the length. Two
+/// passes would mean walking a frame's runs twice to find out how long they
+/// are, and the walk is the expensive half.
+fn beginMessage(w: *std.Io.Writer, tag: u8) Error!usize {
+ const at = w.end;
+ try w.writeByte(tag);
+ try w.writeInt(u32, 0, .little);
+ return at;
+}
+
+fn finishMessage(w: *std.Io.Writer, at: usize) Error!void {
+ const len = w.end - at - header_len;
+ if (len > max_payload) return error.Overlong;
+ std.mem.writeInt(u32, w.buffer[at + 1 ..][0..4], @intCast(len), .little);
+}
+
+/// One complete message at the front of a stream buffer, or null when the rest
+/// has not arrived. `total` is what the caller consumes.
+pub const Framed = struct { tag: u8, payload: []const u8, total: usize };
+
+pub fn framed(buf: []const u8) Error!?Framed {
+ if (buf.len < header_len) return null;
+ const len = std.mem.readInt(u32, buf[1..5], .little);
+ // Refused BEFORE the caller grows a buffer to hold it: an over-long prefix
+ // is the one field in this protocol that can ask for memory.
+ if (len > max_payload) return error.Overlong;
+ if (buf.len - header_len < len) return null;
+ return .{ .tag = buf[0], .payload = buf[header_len..][0..len], .total = header_len + len };
+}
+
+// ---------------------------------------------------------------------------
+// frontend -> core
+// ---------------------------------------------------------------------------
+
+/// Which tag a message travels under: the `ClientTag` of the same NAME, so a
+/// new `Event` variant does not compile until it has a number here, rather
+/// than a written-out table that can drift.
+fn clientTag(msg: ClientMsg) ClientTag {
+ return switch (msg) {
+ .event => |ev| switch (ev) {
+ // Machine-local reports and 9P requests belong to the session owner.
+ .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .addon, .job, .tick => unreachable,
+ inline else => |_, t| @field(ClientTag, @tagName(t)),
+ },
+ inline else => |_, t| @field(ClientTag, @tagName(t)),
+ };
+}
+
+fn putMetrics(w: *std.Io.Writer, metrics: ?pardes.RowMetrics) Error!void {
+ try w.writeByte(@intFromBool(metrics != null));
+ if (metrics) |m| {
+ try w.writeInt(u16, m.body_w, .little);
+ try w.writeInt(u16, m.body_h, .little);
+ try w.writeInt(u16, m.tagline_w, .little);
+ try w.writeInt(u16, m.tagline_h, .little);
+ }
+}
+
+fn getMetrics(r: *std.Io.Reader) Error!?pardes.RowMetrics {
+ if (!try getBool(r)) return null;
+ const m: pardes.RowMetrics = .{ .body_w = try r.takeInt(u16, .little), .body_h = try r.takeInt(u16, .little), .tagline_w = try r.takeInt(u16, .little), .tagline_h = try r.takeInt(u16, .little) };
+ if (m.body_w == 0 or m.body_h == 0 or m.tagline_w == 0 or m.tagline_h == 0) return error.BadValue;
+ return m;
+}
+
+fn putPlace(w: *std.Io.Writer, at: pardes.Layer.Place) Error!void {
+ for ([_]u16{ at.viewport.x, at.viewport.y, at.viewport.w, at.viewport.h, at.cols, at.rows, at.context_rows }) |n| try w.writeInt(u16, n, .little);
+}
+
+fn getPlace(r: *std.Io.Reader) Error!pardes.Layer.Place {
+ var n: [7]u16 = undefined;
+ for (&n) |*x| x.* = try r.takeInt(u16, .little);
+ if (n[6] > n[5]) return error.BadValue;
+ return .{ .viewport = .{ .x = n[0], .y = n[1], .w = n[2], .h = n[3] }, .cols = n[4], .rows = n[5], .context_rows = n[6] };
+}
+
+fn putBodyHit(w: *std.Io.Writer, hit: ?pardes.Mouse.BodyHit) Error!void {
+ try w.writeByte(@intFromBool(hit != null));
+ if (hit) |h| {
+ try w.writeInt(u32, h.serial, .little);
+ try w.writeInt(u16, h.row, .little);
+ try w.writeInt(u16, h.col, .little);
+ try w.writeInt(u32, @bitCast(h.pixel_x), .little);
+ try w.writeInt(u32, @bitCast(h.pixel_y), .little);
+ try putMetrics(w, h.metrics);
+ try putPlace(w, h.place);
+ }
+}
+
+fn getBodyHit(r: *std.Io.Reader) Error!?pardes.Mouse.BodyHit {
+ if (!try getBool(r)) return null;
+ const hit: pardes.Mouse.BodyHit = .{ .serial = try r.takeInt(u32, .little), .row = try r.takeInt(u16, .little), .col = try r.takeInt(u16, .little), .pixel_x = try getF32(r), .pixel_y = try getF32(r), .metrics = (try getMetrics(r)) orelse return error.BadValue, .place = try getPlace(r) };
+ if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue;
+ return hit;
+}
+
+fn putTagHit(w: *std.Io.Writer, hit: ?pardes.TagHit) Error!void {
+ try w.writeByte(@intFromBool(hit != null));
+ if (hit) |h| {
+ try w.writeByte(@backingInt(h.kind));
+ try w.writeInt(u16, h.id, .little);
+ try w.writeInt(u32, h.serial, .little);
+ try w.writeInt(u16, h.col, .little);
+ try w.writeInt(u16, h.line, .little);
+ try w.writeInt(u32, @bitCast(h.pixel_x), .little);
+ try w.writeInt(u32, @bitCast(h.pixel_y), .little);
+ try putMetrics(w, h.metrics);
+ try putPlace(w, h.place);
+ }
+}
+
+fn getTagHit(r: *std.Io.Reader) Error!?pardes.TagHit {
+ if (!try getBool(r)) return null;
+ const hit: pardes.TagHit = .{
+ .kind = try getTag(r, pardes.TagKind),
+ .id = try r.takeInt(u16, .little),
+ .serial = try r.takeInt(u32, .little),
+ .col = try r.takeInt(u16, .little),
+ .line = try r.takeInt(u16, .little),
+ .pixel_x = try getF32(r),
+ .pixel_y = try getF32(r),
+ .metrics = (try getMetrics(r)) orelse return error.BadValue,
+ .place = try getPlace(r),
+ };
+ if (!std.math.isFinite(hit.pixel_x) or !std.math.isFinite(hit.pixel_y)) return error.BadValue;
+ return hit;
+}
+
+pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 {
+ var w: std.Io.Writer = .fixed(out);
+ const at = try beginMessage(&w, @backingInt(clientTag(msg)));
+ switch (msg) {
+ .hello => |h| {
+ try w.writeInt(u16, h.version, .little);
+ try w.writeInt(u64, h.semantics, .little);
+ if (h.session.len > max_name) return error.Overlong;
+ try putSlice16(&w, h.session);
+ try w.writeByte(h.view orelse 0xff);
+ },
+ .bye => |b| try w.writeByte(@intFromBool(b.again)),
+ .ping => |v| try w.writeInt(u64, v, .little),
+ .screen_ack, .want => |bytes| try w.writeAll(bytes),
+ .check => {},
+ .far => |far| try w.writeByte(@intFromBool(far)),
+ .stamp => |s| for (s) |v| try w.writeInt(i64, v, .little),
+ .event => |ev| switch (ev) {
+ .key => |k| {
+ try w.writeInt(u32, k.cp, .little);
+ try putSlice16(&w, k.text);
+ try w.writeByte(@intFromBool(k.ctrl));
+ try w.writeByte(@intFromBool(k.alt));
+ try w.writeByte(@intFromBool(k.shift));
+ },
+ .mouse => |m| {
+ try w.writeByte(switch (m.button) {
+ inline else => |t| @backingInt(@field(ButtonTag, @tagName(t))),
+ });
+ try w.writeByte(switch (m.kind) {
+ inline else => |t| @backingInt(@field(KindTag, @tagName(t))),
+ });
+ try w.writeInt(u16, m.col, .little);
+ try w.writeInt(u16, m.row, .little);
+ try w.writeByte(@intFromBool(m.ctrl));
+ try w.writeByte(@intFromBool(m.shift));
+ try w.writeByte(@intFromBool(m.alt));
+ try w.writeInt(u32, @bitCast(m.amount), .little);
+ try putBodyHit(&w, m.body_hit);
+ try putTagHit(&w, m.tag_hit);
+ },
+ .resize => |rs| {
+ try w.writeInt(u16, rs.cols, .little);
+ try w.writeInt(u16, rs.rows, .little);
+ try w.writeInt(u16, rs.cell_pixels.w, .little);
+ try w.writeInt(u16, rs.cell_pixels.h, .little);
+ try putMetrics(&w, rs.row_metrics);
+ },
+ .paste => |b| try putSlice32(&w, b),
+ .command => |line| try putSlice16(&w, line),
+ .pointer_leave => {},
+ .focus => |focused| try w.writeByte(@intFromBool(focused)),
+ .frontend => |f| {
+ try w.writeByte(@intFromBool(f.windowed));
+ try w.writeByte(@intFromBool(f.native_images));
+ try w.writeByte(@intFromBool(f.native_image_patches));
+ },
+ // See `clientTag`: no tag, so nothing to encode.
+ .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .addon, .job, .tick => unreachable,
+ },
+ }
+ try finishMessage(&w, at);
+ return w.buffered();
+}
+
+pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg {
+ var r: std.Io.Reader = .fixed(payload);
+ const msg: ClientMsg = switch (std.enums.fromInt(ClientTag, tag) orelse return error.BadTag) {
+ .hello => .{ .hello = .{
+ .version = try r.takeInt(u16, .little),
+ .semantics = try r.takeInt(u64, .little),
+ .session = blk: {
+ const n = try r.takeInt(u16, .little);
+ if (n > max_name) return error.BadValue;
+ break :blk try r.take(n);
+ },
+ .view = switch (try r.takeByte()) {
+ 0xff => null,
+ else => |k| k,
+ },
+ } },
+ .bye => .{ .bye = .{ .again = try getBool(&r) } },
+ .ping => .{ .ping = try r.takeInt(u64, .little) },
+ .screen_ack => return .{ .screen_ack = payload },
+ .check => .check,
+ .far => .{ .far = try getBool(&r) },
+ .want => return .{ .want = payload },
+ .stamp => .{ .stamp = .{ try r.takeInt(i64, .little), try r.takeInt(i64, .little) } },
+ .key => blk: {
+ const cp = try r.takeInt(u32, .little);
+ // `Key.cp` is a u21, and the specials live in the private-use
+ // plane below this bound. A larger number is not a codepoint and
+ // @intCast of it would panic in a release build's own decoder.
+ if (cp > 0x10FFFF) return error.BadValue;
+ break :blk .{ .event = .{ .key = .{
+ .cp = @intCast(cp),
+ .text = try r.take(try r.takeInt(u16, .little)),
+ .ctrl = try getBool(&r),
+ .alt = try getBool(&r),
+ .shift = try getBool(&r),
+ } } };
+ },
+ .mouse => .{ .event = .{ .mouse = .{
+ .button = switch (try getTag(&r, ButtonTag)) {
+ inline else => |t| @field(pardes.Mouse.Button, @tagName(t)),
+ },
+ .kind = switch (try getTag(&r, KindTag)) {
+ inline else => |t| @field(pardes.Mouse.Kind, @tagName(t)),
+ },
+ .col = try r.takeInt(u16, .little),
+ .row = try r.takeInt(u16, .little),
+ .ctrl = try getBool(&r),
+ .shift = try getBool(&r),
+ .alt = try getBool(&r),
+ .amount = @bitCast(try r.takeInt(u32, .little)),
+ .body_hit = try getBodyHit(&r),
+ .tag_hit = try getTagHit(&r),
+ } } },
+ .resize => blk: {
+ var ev: pardes.Event = .{ .resize = .{ .cols = try getCols(&r), .rows = try getRows(&r) } };
+ const px_w = try r.takeInt(u16, .little);
+ ev.resize.cell_pixels = .{ .w = px_w, .h = try r.takeInt(u16, .little) };
+ ev.resize.row_metrics = try getMetrics(&r);
+ break :blk .{ .event = ev };
+ },
+ .paste => .{ .event = .{ .paste = try getSlice32(&r) } },
+ .command => .{ .event = .{ .command = try r.take(try r.takeInt(u16, .little)) } },
+ .pointer_leave => .{ .event = .pointer_leave },
+ .focus => .{ .event = .{ .focus = try getBool(&r) } },
+ .frontend => .{ .event = .{ .frontend = .{ .windowed = try getBool(&r), .native_images = try getBool(&r), .native_image_patches = try getBool(&r) } } },
+ };
+ try end(&r);
+ return msg;
+}
+
+/// Slack over a message's variable payload, covering every fixed field any
+/// message here has plus its own header.
+const msg_slack = header_len + 64;
+
+/// An upper bound on `encodeClient`'s output, so a caller sizes its buffer
+/// once instead of guessing and retrying.
+pub fn clientBound(msg: ClientMsg) usize {
+ return msg_slack + switch (msg) {
+ .hello => |h| h.session.len,
+ .bye, .ping, .check, .far, .stamp => 0,
+ .screen_ack, .want => |bytes| bytes.len,
+ .event => |ev| switch (ev) {
+ // Its hits' places (14 bytes each) past the slack.
+ .mouse => 32,
+ .resize, .pointer_leave, .focus, .frontend => 0,
+ .key => |k| k.text.len,
+ .paste => |b| b.len,
+ .command => |line| line.len,
+ // See `clientTag`: not on this wire in this direction.
+ .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .addon, .job, .tick => unreachable,
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// tests
+// ---------------------------------------------------------------------------
+//
+// Two obligations. Every message round-trips to a deep-equal value, because a
+// codec written by hand is a codec whose two halves drift; and every malformed
+// shape is REFUSED, because this parser is fed by a socket and a frame that is
+// misread rather than refused is an out-of-bounds index.
+
+const testing = std.testing;
+
+/// Round-trip one frontend -> core message through the framing too, so a
+/// length prefix that disagrees with the payload cannot pass.
+fn roundClient(buf: []u8, msg: ClientMsg) !ClientMsg {
+ const bytes = try encodeClient(buf, msg);
+ const f = (try framed(bytes)).?;
+ try testing.expectEqual(bytes.len, f.total);
+ return decodeClient(f.tag, f.payload);
+}
+
+test "detached wire: every Event variant round-trips" {
+ var buf: [4096]u8 = undefined;
+
+ // The tag space is the protocol's own, so assert the numbers themselves:
+ // a renumbering here breaks every deployed frontend and must be a diff
+ // somebody reads, not a silent change.
+ try testing.expectEqual(@as(u8, 0x01), @backingInt(ClientTag.hello));
+ try testing.expectEqual(@as(u8, 0x10), @backingInt(ClientTag.key));
+ try testing.expectEqual(@as(u8, 0x1d), @backingInt(ClientTag.pointer_leave));
+
+ {
+ const got = try roundClient(&buf, .{ .hello = .{ .session = "work" } });
+ try testing.expectEqual(version, got.hello.version);
+ try testing.expectEqual(semantics, got.hello.semantics);
+ try testing.expectEqualStrings("work", got.hello.session);
+ }
+ try testing.expect((try roundClient(&buf, .{ .bye = .{ .again = true } })).bye.again);
+ try testing.expectEqual(@as(?u8, 2), (try roundClient(&buf, .{ .hello = .{ .session = "work", .view = 2 } })).hello.view);
+ try testing.expectEqual(@as(u64, 0xfeed_beef_0000_0001), (try roundClient(&buf, .{ .ping = 0xfeed_beef_0000_0001 })).ping);
+ {
+ // The other way: framed the same, its tag the ServerTag's number.
+ const bytes = try encodeServer(&buf, .{ .welcome = .{ .pid = 42, .session = "work" } });
+ const f = (try framed(bytes)).?;
+ try testing.expectEqual(@as(u8, 0x01), f.tag);
+ try testing.expectEqualSlices(u8, &.{ 42, 0, 0, 0, 4, 0, 'w', 'o', 'r', 'k', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, f.payload);
+ const back = (try decodeServer(f.tag, f.payload)).welcome;
+ try testing.expectEqualStrings("work", back.session);
+ try testing.expectEqual(@as(u32, 42), back.pid);
+ try testing.expectEqual(@as(u8, 0x03), (try framed(try encodeServer(&buf, .{ .pong = 7 }))).?.tag);
+ }
+
+ {
+ const key: pardes.Key = .{ .cp = pardes.Key.page_down, .text = "ü", .ctrl = true, .alt = false, .shift = true };
+ const got = (try roundClient(&buf, .{ .event = .{ .key = key } })).event.key;
+ try testing.expectEqual(key.cp, got.cp);
+ try testing.expectEqualStrings(key.text, got.text);
+ try testing.expectEqual(key.ctrl, got.ctrl);
+ try testing.expectEqual(key.alt, got.alt);
+ try testing.expectEqual(key.shift, got.shift);
+ }
+ {
+ // Every button and every kind, because the two mapping switches are
+ // the only place a value can be mistranslated and still decode.
+ for (std.enums.values(pardes.Mouse.Button)) |button| {
+ for (std.enums.values(pardes.Mouse.Kind)) |kind| {
+ const m: pardes.Mouse = .{ .button = button, .kind = kind, .col = 4200, .row = 7, .ctrl = true, .shift = true, .alt = true };
+ const got = (try roundClient(&buf, .{ .event = .{ .mouse = m } })).event.mouse;
+ try testing.expectEqual(m.button, got.button);
+ try testing.expectEqual(m.kind, got.kind);
+ try testing.expectEqual(m.col, got.col);
+ try testing.expectEqual(m.row, got.row);
+ try testing.expectEqual(m.ctrl, got.ctrl);
+ try testing.expectEqual(m.shift, got.shift);
+ try testing.expectEqual(m.alt, got.alt);
+ }
+ }
+ }
+ {
+ const got = (try roundClient(&buf, .{ .event = .{ .resize = .{ .cols = 56, .rows = 14 } } })).event.resize;
+ try testing.expectEqual(@as(u16, 56), got.cols);
+ try testing.expectEqual(@as(u16, 14), got.rows);
+ // The conventional 1:2 default survives the trip.
+ try testing.expectEqual(@as(u16, 8), got.cell_pixels.w);
+ try testing.expectEqual(@as(u16, 16), got.cell_pixels.h);
+ }
+ try testing.expectEqualStrings("clip", (try roundClient(&buf, .{ .event = .{ .paste = "clip" } })).event.paste);
+ try testing.expectEqualStrings("Look /x", (try roundClient(&buf, .{ .event = .{ .command = "Look /x" } })).event.command);
+ try testing.expectEqual(
+ std.meta.Tag(pardes.Event).pointer_leave,
+ (try roundClient(&buf, .{ .event = .pointer_leave })).event,
+ );
+}
+
+test "detached wire: a session is never told to do a frontend's remembering" {
+ // What may reach the SESSION from a client.
+ //
+ // Adding a name here is meant to be an ARGUMENT, not a formality, and the
+ // bar is one sentence: A HUMAN DID IT. A keystroke, a click, a
+ // window resized, a paste, a command line executed, a pointer leaving the
+ // window, the window's focus — plus the session words that say who is speaking, time the link and end it. A pty's
+ // output, a worker's answer, a watched file's new bytes and an animation
+ // tick all fail that bar the same way: nobody did them, a machine reported
+ // them, and the machine that reports them is the one already holding the
+ // core.
+ const allowed = [_][]const u8{
+ // Who this connection is, its round trip, and that it is finished,
+ // and which terminal state its replica holds (a protocol's word,
+ // as a ping is).
+ "hello", "bye", "ping", "screen_ack", "check",
+ // ...and how far it is, and which of the join's blobs it lacks.
+ "far", "want",
+ // ...and when its next input was, by the session's clocks.
+ "stamp",
+ // ...and everything a person can do to a window.
+ "key", "mouse", "resize",
+ "paste", "command", "pointer_leave", "focus",
+ // ...and which of its frontends the person sits at: a window, or a
+ // terminal (what the view draws, and the words it takes).
+ "frontend",
+ };
+
+ // One: the tag set is exactly that, named rather than counted, so
+ // re-adding `output` fails with the name in the failure.
+ inline for (std.enums.values(ClientTag)) |t| {
+ for (allowed) |ok| {
+ if (std.mem.eql(u8, @tagName(t), ok)) break;
+ } else {
+ std.debug.print("ClientTag.{s} is not something a human did\n", .{@tagName(t)});
+ return error.MachineLocalReportOnTheWire;
+ }
+ }
+ try testing.expectEqual(allowed.len, std.enums.values(ClientTag).len);
+
+ // Two: and no tag BYTE outside them decodes either — the check above is
+ // about this build's enum, this one is about the bytes on the socket.
+ var accepted: usize = 0;
+ for (0..256) |i| {
+ const tag: u8 = @intCast(i);
+ // Empty payloads on purpose: what is asked is whether the TAG is known.
+ // A known one fails later (`EndOfStream`) or succeeds, never with
+ // `BadTag`.
+ if (decodeClient(tag, &.{})) |_| accepted += 1 else |err| switch (err) {
+ error.BadTag => continue,
+ else => accepted += 1,
+ }
+ const named = for (allowed) |ok| {
+ const want = std.meta.stringToEnum(ClientTag, ok).?;
+ if (@backingInt(want) == tag) break true;
+ } else false;
+ if (!named) {
+ std.debug.print("tag 0x{x:0>2} is decodable by a session and is not something a human did\n", .{tag});
+ return error.MachineLocalReportOnTheWire;
+ }
+ }
+ try testing.expectEqual(allowed.len, accepted);
+}
+
+test "detached wire: a truncated message is refused at every length" {
+ var buf: [4096]u8 = undefined;
+
+ // Every prefix of a real message. The framing must say "not yet" for the
+ // ones that are short, and the decoder must say "truncated" for a payload
+ // whose header lies about its length — never read past the slice.
+ const whole = try encodeClient(&buf, .{ .event = .{ .key = .{ .cp = 'a', .text = "a" } } });
+ var copy: [64]u8 = undefined;
+ @memcpy(copy[0..whole.len], whole);
+ for (header_len + 1..whole.len) |cut| {
+ try testing.expectEqual(@as(?Framed, null), try framed(copy[0..cut]));
+ // ...and the same bytes handed to the decoder with the header's length
+ // left claiming the whole message, which is how a decoder is walked
+ // off the end of its buffer.
+ try testing.expectError(error.EndOfStream, decodeClient(copy[0], copy[header_len..cut]));
+ }
+ // Shorter than the header itself is not yet a message at all.
+ for (0..header_len + 1) |cut|
+ try testing.expectEqual(@as(?Framed, null), try framed(copy[0..cut]));
+ // A payload with bytes LEFT OVER is refused too: it is not this message.
+ try testing.expectError(error.Trailing, decodeClient(@backingInt(ClientTag.pointer_leave), "x"));
+}
+
+test "detached wire: an unknown tag is refused, never guessed" {
+ // 0x00 and 0xff have never been assigned, and 0x0f sits in the gap between
+ // the session tags and the input tags. All three are the same answer.
+ for ([_]u8{ 0x00, 0x0f, 0x1f, 0xff }) |tag| {
+ try testing.expectError(error.BadTag, decodeClient(tag, ""));
+ }
+ // A tag NESTED in a payload gets the same treatment: a mouse button.
+ try testing.expectError(error.BadTag, decodeClient(
+ @backingInt(ClientTag.mouse),
+ &.{ 0xff, 0x00, 0, 0, 0, 0, 0 },
+ ));
+}
+
+test "detached wire: an over-long length prefix is refused before it is believed" {
+ // The prefix a hostile or corrupt peer sends to make the receiver allocate
+ // or index by it. `framed` must refuse rather than wait for 4 GiB.
+ var head: [header_len]u8 = .{ @backingInt(ClientTag.paste), 0, 0, 0, 0 };
+ std.mem.writeInt(u32, head[1..5], max_payload + 1, .little);
+ try testing.expectError(error.Overlong, framed(&head));
+ std.mem.writeInt(u32, head[1..5], std.math.maxInt(u32), .little);
+ try testing.expectError(error.Overlong, framed(&head));
+ // At the boundary it is a legal prefix and simply has not all arrived.
+ std.mem.writeInt(u32, head[1..5], max_payload, .little);
+ try testing.expectEqual(@as(?Framed, null), try framed(&head));
+
+ // An INNER length prefix, past the payload it sits in but inside the
+ // protocol's cap — the one an outer-frame check cannot catch.
+ var paste: [8]u8 = undefined;
+ std.mem.writeInt(u32, paste[0..4], 4096, .little);
+ @memcpy(paste[4..8], "abcd");
+ try testing.expectError(error.EndOfStream, decodeClient(@backingInt(ClientTag.paste), &paste));
+ // ...and past the cap, which is refused rather than read.
+ std.mem.writeInt(u32, paste[0..4], max_payload + 1, .little);
+ try testing.expectError(error.Overlong, decodeClient(@backingInt(ClientTag.paste), &paste));
+}
+
+test "detached wire: values a field cannot mean are refused" {
+ // A bool is 0 or 1. `2` used to be "true" in every hand-written codec that
+ // ever silently accepted a corrupt stream.
+ try testing.expectError(error.BadValue, decodeClient(
+ @backingInt(ClientTag.key),
+ &.{ 'a', 0, 0, 0, 0, 0, 2, 0, 0 },
+ ));
+ // A codepoint past Unicode's last: @intCast into Key.cp's u21 would panic.
+ try testing.expectError(error.BadValue, decodeClient(
+ @backingInt(ClientTag.key),
+ &.{ 0x00, 0x00, 0x11, 0x00, 0, 0, 0, 0, 0 },
+ ));
+ // A session name longer than the daemon keeps one: refused, never cut
+ // to another session's name.
+ {
+ var hello: [12 + max_name + 1]u8 = @splat('x');
+ std.mem.writeInt(u16, hello[0..2], version, .little);
+ std.mem.writeInt(u16, hello[10..12], max_name + 1, .little);
+ try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.hello), &hello));
+ std.mem.writeInt(u16, hello[10..12], max_name, .little);
+ hello[hello.len - 1] = 0xff;
+ try testing.expectEqual(@as(usize, max_name), (try decodeClient(@backingInt(ClientTag.hello), &hello)).hello.session.len);
+ try testing.expect(header_len + hello.len == hello_max);
+ }
+}
+
+test "detached wire: max_payload bounds every message this protocol can build" {
+ // A 4 MiB paste, which is the tty's own cap, fits.
+ try testing.expect((4 << 20) + header_len + 4 <= max_payload);
+ // A slice past the width of its own length prefix is refused by the
+ // ENCODER, rather than written and rejected at the far end. A command line
+ // is u16-prefixed because nothing legitimately types 64 KiB of one.
+ const gpa = testing.allocator;
+ const huge = try gpa.alloc(u8, std.math.maxInt(u16) + 1);
+ defer gpa.free(huge);
+ @memset(huge, 'x');
+ const room = try gpa.alloc(u8, huge.len + header_len + 2);
+ defer gpa.free(room);
+ try testing.expectError(error.Overlong, encodeClient(room, .{ .event = .{ .command = huge } }));
+ // ...and a buffer the caller sized too small is WriteFailed, which is the
+ // server's signal to drop that one message rather than the client.
+ var small: [8]u8 = undefined;
+ try testing.expectError(error.WriteFailed, encodeClient(&small, .{ .event = .{ .paste = "0123456789" } }));
+}
+
+test "detached wire carries exact pointer metrics" {
+ var logical: [12]pardes.Cell = @splat(.{});
+ var layer: pardes.Layer = .{ .id = 0, .serial = 42, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 4 }, .cols = 2, .rows = 6, .context_rows = 2, .cells = &logical, .cursor = .{ .x = 0, .y = 5, .bar = true } };
+ layer.context_separators.set(0);
+ var tag_cells: [3]pardes.Cell = @splat(.{});
+ const tag: pardes.Layer = .{ .kind = .column, .id = 1, .viewport = .{ .x = 0, .y = 0, .w = 2, .h = 1 }, .cols = 3, .rows = 1, .bg = .{ 11, 22, 33 }, .cells = &tag_cells, .cursor = .{ .x = 2, .y = 0, .bar = true } };
+ const pointer = layer.bodyHit(4, 27, 8, 16, 6, 8).?;
+ const tag_pointer = tag.tagHit(11, 8, 8, 16, 4, 8).?;
+ const message: ClientMsg = .{ .event = .{ .mouse = .{ .col = 0, .row = 1, .button = .left, .kind = .press, .body_hit = pointer, .tag_hit = tag_pointer } } };
+ var mouse_bytes: [256]u8 = undefined;
+ const mouse_encoded = try encodeClient(&mouse_bytes, message);
+ const mouse_packet = (try framed(mouse_encoded)).?;
+ const mouse = (try decodeClient(mouse_packet.tag, mouse_packet.payload)).event.mouse;
+ try std.testing.expectEqualDeep(pointer, mouse.body_hit.?);
+ try std.testing.expectEqualDeep(tag_pointer, mouse.tag_hit.?);
+ try std.testing.expect(mouse_encoded.len <= clientBound(message));
+}