summaryrefslogtreecommitdiff
path: root/core/Kind.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-18 22:03:14 -0300
committerGabriel Schneider <[email protected]>2026-11-18 22:23:51 -0300
commit99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch)
tree813596ea84318a7bae4fd7416ba463de8e3b7107 /core/Kind.zig
parent92d553123673376adf6126ab90d49a22c5b833d2 (diff)
downloadpardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.tar.gz
pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.zip
core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), 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 'core/Kind.zig')
-rw-r--r--core/Kind.zig1369
1 files changed, 1369 insertions, 0 deletions
diff --git a/core/Kind.zig b/core/Kind.zig
new file mode 100644
index 00000000..a624d7c6
--- /dev/null
+++ b/core/Kind.zig
@@ -0,0 +1,1369 @@
+//! A kind of pane that is neither text nor a terminal: a picture, a game,
+//! anything an addon (a library, Addon.zig) brings. Its records and
+//! functions are the C ABI of abi/pardes_addon.h (translated, the
+//! one copy); this file is the core's side of it: the kinds a core has
+//! (`Registry`, what libraries brought, with their words and extensions),
+//! and a pane's `Slot`, the state the core keeps round the kind's own.
+//!
+//! The core is deterministic and a kind is the authority's: a replica's
+//! core has the same registry (its words, its extensions) but no code for a
+//! kind a library brought, and shows its panes as a line saying so; but a
+//! PA_PLAIN kind, whose state is one plain block the core keeps
+//! (`Slot.plain`), runs in a client that has it, as the session runs it. So every call into a kind whose answer the core
+//! acts on is made at a place both cores reach, and its `Outcome` (the
+//! answer, what it said, a Look, a plain kind's state's hash) is taped: a
+//! replica takes it off the tape. Paint and the reads (body, ctl, a dump)
+//! change nothing and are not taped.
+const std = @import("std");
+const builtin = @import("builtin");
+pub const c = @import("pardes_addon");
+const pardes = @import("root.zig");
+const walk = @import("walk.zig");
+const tape = @import("tape.zig");
+const surface = @import("surface.zig");
+const views = @import("views.zig");
+const Addon = @import("Addon.zig");
+const host_io = @import("dev").host_io;
+pub const Loaded = Addon.Loaded;
+pub const LoadedWord = Addon.LoadedWord;
+pub const loadedOf = Addon.loadedOf;
+const Placement = surface.Placement;
+const Pardes = pardes.Pardes;
+const Pane = pardes.panes.Pane;
+
+pub const Ops = c.pa_ops;
+pub const abi_major: u32 = c.PA_ABI_MAJOR;
+pub const abi: u32 = c.PA_ABI;
+
+// The header's own sizes (its _Static_asserts), seen from here: the
+// records the core reads are the ones addons are built to.
+comptime {
+ if (@sizeOf(usize) == 8) for (.{
+ .{ c.pa_cell, 20 }, .{ c.pa_window, 24 }, .{ c.pa_rect, 16 }, .{ c.pa_cells, 8 },
+ .{ c.pa_placement, 80 }, .{ c.pa_paint, 48 }, .{ c.pa_key, 8 }, .{ c.pa_mouse, 16 },
+ .{ c.pa_api, 120 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 },
+ .{ c.pa_ops, 208 }, .{ c.pa_view, 32 }, .{ c.pa_tick, 128 },
+ }) |r| if (@sizeOf(r[0]) != r[1]) @compileError(std.fmt.comptimePrint("{s} is {d} bytes, the header says {d}", .{ @typeName(r[0]), @sizeOf(r[0]), r[1] }));
+}
+
+// ---- the kinds a core has ----
+
+pub const max_kinds = 16;
+
+/// Which of its functions a kind has: what both cores decide by.
+pub const Caps = packed struct(u16) {
+ tick: bool = false,
+ key: bool = false,
+ mouse: bool = false,
+ ctl: bool = false,
+ jobs: bool = false,
+ load: bool = false,
+ search: bool = false,
+ address: bool = false,
+ view: bool = false,
+ /// PA_PICTURES: its tag says how its pictures show, from the first frame.
+ pictures: bool = false,
+ /// PA_PLAIN: its state is its block, which the core keeps (`Slot.plain`).
+ plain: bool = false,
+ pad: u5 = 0,
+};
+
+pub const Entry = struct {
+ name: [16]u8 = @splat(0),
+ version: u32 = 0,
+ abi: u32 = 0,
+ hash: [32]u8 = @splat(0),
+ /// One more at each reload: a job's answer of another is dropped.
+ gen: u32 = 0,
+ caps: Caps = .{},
+ path: Buf(256) = .{},
+ /// A library refused, listed with `why`.
+ refused: bool = false,
+ why: Buf(128) = .{},
+
+ pub fn nameOf(e: *const Entry) []const u8 {
+ return std.mem.sliceTo(&e.name, 0);
+ }
+};
+
+pub const Word = struct { kind: u8, name: Buf(32) = .{}, leader: Buf(8) = .{}, arg: u8 = 0, opens: u8 = 0, doc: Buf(96) = .{} };
+pub const Ext = struct { kind: u8, ext: Buf(16) = .{} };
+
+/// A core's kinds: what libraries brought (Addon.zig), as data both cores
+/// hold alike; and each one's code here, which a replica has none of.
+pub const Registry = struct {
+ pub const replica = .{
+ .local = .{"ops"},
+ .len = .{ .{ "kinds", "n" }, .{ "words", "nwords" }, .{ "exts", "nexts" } },
+ };
+ kinds: [max_kinds]Entry = undefined,
+ n: u8 = 0,
+ words: [64]Word = undefined,
+ nwords: u8 = 0,
+ exts: [32]Ext = undefined,
+ nexts: u8 = 0,
+ ops: [max_kinds]?*const Ops = @splat(null),
+
+ /// What the scan at start found.
+ pub fn started(found: []const Loaded) Registry {
+ var r: Registry = .{};
+ for (found) |l| _ = r.take(l, "");
+ return r;
+ }
+
+ pub fn byName(r: *const Registry, name: []const u8) ?u8 {
+ for (r.kinds[0..r.n], 0..) |*e, i| if (!e.refused and std.mem.eql(u8, e.nameOf(), name)) return @intCast(i);
+ return null;
+ }
+
+ // What libraries bring, the loader's (Addon.zig).
+ pub const forPath = Addon.forPath;
+ pub const word = Addon.word;
+ pub const leader = Addon.leader;
+ pub const take = Addon.take;
+ pub const collides = Addon.collides;
+ pub const drop = Addon.drop;
+};
+
+// ---- a pane of a kind ----
+
+/// What the core keeps of a pane of a kind, round the kind's own state.
+/// A rollback copy leaves it be, as a terminal's emulator; a dump writes
+/// its record by hand (dump.zig). A digest walks every field a step reads
+/// (17.2), which a dump carries and test/panes.zig's parity walk checks.
+pub const Slot = struct {
+ pub const replica = .{
+ // The kind's own and the authority's (its code and memory, its
+ // jobs' inputs, its file's hash, a placeholder's record), and what
+ // a frame makes (the thumb, the pointer, whether one was drawn: a
+ // view's, never a step's).
+ .local = .{ "ops", "st", "gpa", "arena", "plain", "file", "opened", "reloads", "jobs", "record", "thumb_at", "thumb_span", "pointer", "painted", "over", "used" },
+ };
+ /// Its kind's code here; null in a placeholder (`live` false: its kind
+ /// not in the registry, its record kept for the day it comes) or a
+ /// replica's pane of a kind with no code there.
+ ops: ?*const Ops = null,
+ live: bool = false,
+ st: ?*anyopaque = null,
+ /// A PA_PLAIN kind's whole state, the one block its open allocated
+ /// (empty until it has): the core's memory (a client's rollback copy
+ /// saves it), whose hash is `state`. Null for another kind.
+ plain: ?[]align(16) u8 = null,
+ /// The hash of `plain` after the kind's last call, as the session's
+ /// was (the call's outcome, on the tape): in the digest, so a client
+ /// whose block came out otherwise is caught at that call.
+ state: u64 = 0,
+ /// The kind's allocations are its arena's, freed at the close.
+ gpa: std.mem.Allocator,
+ arena: std.heap.ArenaAllocator,
+ name: [16]u8 = @splat(0),
+ version: u32 = 0,
+ /// The hash of the file's bytes it was opened from, 0 for none (a
+ /// record's): whether the file a watch arms on is still those.
+ opened: u64 = 0,
+ /// Times its file changed under it (fileChanged): its pictures' keys
+ /// carry it, since its kind numbers them afresh from each open, and a
+ /// frontend keeps what it uploaded by key.
+ reloads: u32 = 0,
+ /// Its kind's generation when it was opened (Entry.gen).
+ gen: u32 = 0,
+ path: []u8 = &.{},
+ /// Petscii, Palette and Ascii: how a frontend shows its placements.
+ art: Placement.Art = .{},
+ /// When `tick` is next due; 0, never; 1, at the next step.
+ next_tick: u64 = 0,
+ /// PA_FOCUSED as `tick` was last told.
+ focused: bool = false,
+ /// Its jobs' inputs, until the host takes them (Effect.job); and the
+ /// last token it gave one, which every core gives alike (dumped: a
+ /// client joined later numbers its next job as the session does).
+ jobs: [4]?Job = @splat(null),
+ tokens: u32 = 0,
+ /// A placeholder's: the kind's record, kept whole.
+ record: ?[]u8 = null,
+ /// Its `where` as its kind's last call left it (the call's outcome, on
+ /// the tape): the place a step reads (a jump, Recent) on every core.
+ where_text: Buf(32) = .{},
+ /// What the kind said refusing its open (or a load), or `<path> is not here`.
+ refused: Buf(160) = .{},
+ /// Its words' last values, a `Word arg` line each, which a kind with
+ /// no `dump` is given again when its pane comes back.
+ values: Buf(256) = .{},
+ /// Its prefix as its last tick set it (the tick's outcome, on the
+ /// tape: a replica's is the authority's); where its window is in its
+ /// whole (the rail's thumb), 0 and 0 for none, as its last frame says.
+ prefix: Buf(96) = .{},
+ thumb_at: f32 = 0,
+ thumb_span: f32 = 0,
+ /// The pointer its last frame asked for over it (PA_POINTER_*), and
+ /// whether a frame was painted since its last tick.
+ pointer: u8 = 0,
+ painted: bool = false,
+ /// Each view's facts (a hash of its pa_view) as `view` was last told
+ /// them, 0 for none: a change tells it again.
+ views: [views.max]u64 = @splat(0),
+ /// The jobs whose answers it cancelled (`api.cancel`), dropped as they come.
+ cancelled: [4]u32 = @splat(0),
+ /// Debug: the sites a call over budget (or a raster over the bound) was said at.
+ over: u32 = 0,
+ /// What it has selected (`api.select`): a yank's, a chord's, a
+ /// keyboard Look's.
+ selection: []u8 = &.{},
+ /// Its tag's default words: Term, its kind's words for its panes,
+ /// Collapse Del.
+ tail: Buf(160) = .{},
+ /// A client's join: its plain kind's file, until the pane is opened
+ /// from it (dump.plainHere).
+ file: ?[]u8 = null,
+ /// Debug: the kind's allocations, which paint must leave as they are.
+ /// The slot's allocator's, as the slot is: a client's rollback puts
+ /// the list back with the slot that holds it (on the page allocator,
+ /// the list put back was one a speculation had grown and freed).
+ used: if (checked) std.ArrayList([]u8) else void = if (checked) .empty else {},
+
+ pub const Job = struct { token: u32, in: []u8 };
+
+ pub const dumpWrite = @import("dump.zig").slotWrite;
+ pub const dumpRead = @import("dump.zig").slotRead;
+ pub const dumpFree = @import("dump.zig").slotFree;
+
+ pub fn nameOf(s: *const Slot) []const u8 {
+ return std.mem.sliceTo(&s.name, 0);
+ }
+
+ pub fn is(s: *const Slot, name: []const u8) bool {
+ return std.mem.eql(u8, s.nameOf(), name);
+ }
+
+ pub fn free(s: *Slot) void {
+ for (&s.jobs) |*j| if (j.*) |job| s.gpa.free(job.in);
+ s.gpa.free(s.selection);
+ if (checked) s.used.deinit(s.gpa);
+ if (s.plain) |b| if (b.len > 0) s.gpa.free(b);
+ s.arena.deinit();
+ s.gpa.free(s.path);
+ if (s.record) |r| s.gpa.free(r);
+ if (s.file) |f| s.gpa.free(f);
+ s.* = undefined;
+ }
+};
+
+const checked = builtin.mode == .debug;
+
+fn caps(p: *const Pardes, s: *const Slot) Caps {
+ const k = p.kinds.byName(s.nameOf()) orelse return .{};
+ return if (s.live) p.kinds.kinds[k].caps else .{};
+}
+
+/// A new slot of kind `k` for pane `id`, showing `path` (null for one a
+/// word opened) from `bytes`: made whatever the kind says, with what it
+/// refused in `slot.refused` for the caller to say.
+pub fn open(p: *Pardes, id: usize, k: u8, path: ?[]const u8, bytes: ?[]const u8) !*Pane {
+ const e = &p.kinds.kinds[k];
+ // A plain kind's slot and block are the core's (a client's epoch).
+ const gpa = if (e.caps.plain) p.gpa else p.image_gpa;
+ const s = try gpa.create(Slot);
+ s.* = .{ .ops = p.kinds.ops[k], .live = true, .gpa = gpa, .arena = .init(gpa), .version = e.version, .gen = e.gen, .name = e.name };
+ errdefer {
+ s.free();
+ gpa.destroy(s);
+ }
+ s.path = try gpa.dupe(u8, path orelse "");
+ const pane = try p.newDocPane(id);
+ pane.addon = s;
+ _ = reopen(p, id, s, bytes);
+ // Its file watched, as a text's is: changed on disk, it opens again
+ // from it (fileChanged); retirePane lets the watch go.
+ if (s.path.len > 0 and @import("fs.zig").localPath(s.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } });
+ return pane;
+}
+
+/// `open` of the file at `path`, read here (a file that cannot be read
+/// is no bytes: its kind may refuse it). The slot stays ours across the
+/// read: another request may make a pane meanwhile.
+pub fn openFile(p: *Pardes, id: usize, k: u8, path: []const u8) !*Pane {
+ p.reserved_slots[id] = true;
+ const bytes: ?[]u8 = @import("fs.zig").read(p, path) catch null;
+ p.reserved_slots[id] = false;
+ defer if (bytes) |b| p.gpa.free(b);
+ return open(p, id, k, path, bytes orelse "");
+}
+
+/// The slot's kind state made (`open`, then `load` with its record, or
+/// `address` with its place and its words' last values): its refusal,
+/// if the kind refused, in `slot.refused`. One call for both cores.
+pub fn reopen(p: ?*Pardes, id: usize, s: *Slot, bytes: ?[]const u8) bool {
+ // A replica has no kind's code: what the open says is the authority's.
+ if (tape.authorityOnly("a kind's open")) return false;
+ var cl: Call = .{ .p = p, .id = id, .slot = s };
+ const prev = cl.begin("open");
+ if (p) |core| if (core.kinds.byName(s.nameOf())) |k| {
+ // Its code: its library loaded at the first pane of its kind.
+ if (s.ops == null) s.ops = Addon.need(&core.kinds, k, &cl.refused);
+ // Its block made afresh by this open.
+ if (core.kinds.kinds[k].caps.plain) {
+ if (s.plain) |b| if (b.len > 0) s.gpa.free(b);
+ s.plain = &.{};
+ }
+ var w: std.Io.Writer = .fixed(&s.tail.bytes);
+ w.writeAll(" Term") catch {};
+ for (core.kinds.words[0..core.kinds.nwords]) |*kw| if (kw.kind == k and kw.opens == 0) w.print(" {s}", .{kw.name.slice()}) catch {};
+ w.writeAll(" Collapse Del") catch {};
+ s.tail.len = @intCast(w.buffered().len);
+ };
+ s.opened = if (bytes) |b| std.hash.Wyhash.hash(0, b) else 0;
+ // Its file not read (not here): it waits for it, a placeholder.
+ if (s.ops != null and bytes == null and s.path.len > 0) _ = cl.refused.print("{s} is not here", .{s.path}) else if (s.ops) |ops| {
+ const path_z = s.arena.allocator().dupeSentinel(u8, s.path, 0) catch "";
+ // (the budget's from here: the file's hash and the tag are the core's)
+ if (checked) cl.began = @import("FrameStats.zig").nowNs();
+ cl.opening = true;
+ if (ops.open) |f| s.st = f(if (s.path.len > 0) path_z.ptr else null, if (bytes) |b| b.ptr else null, if (bytes) |b| b.len else 0);
+ cl.opening = false;
+ if (cl.refused.len == 0) if (s.record) |rec| if (ops.load) |f| if (f(s.st, rec.ptr, @intCast(rec.len), s.version) != c.PA_OK) {
+ cl.refused.set("its load refused the record");
+ };
+ if (cl.refused.len == 0 and s.record == null) {
+ if (s.where_text.len > 0) if (ops.address) |f| {
+ _ = f(s.st, s.where_text.slice().ptr, @intCast(s.where_text.len));
+ };
+ var lines = std.mem.tokenizeScalar(u8, s.values.slice(), '\n');
+ var reply: [160]u8 = undefined;
+ if (ops.ctl) |f| while (lines.next()) |line| {
+ _ = f(s.st, line.ptr, @intCast(line.len), &reply, reply.len);
+ };
+ }
+ if (cl.refused.len > 0) if (ops.close) |f| f(s.st);
+ }
+ const o = cl.end(prev);
+ s.refused.set(o.text);
+ if (o.text.len > 0) return false;
+ if (s.record) |r| s.gpa.free(r);
+ s.record = null;
+ s.live = true;
+ if (p) |core| poke(core, s);
+ return true;
+}
+
+/// Tick at the next step, once (16.2's rule 2).
+fn poke(p: *const Pardes, s: *Slot) void {
+ if (caps(p, s).tick) s.next_tick = 1;
+}
+
+/// Its file changed on disk: the pane opened again from the file as it is
+/// now, its record kept for its `load` (a PDF's place, fit and tint: the
+/// state `open` made from the new bytes takes them) or else its place and
+/// its words. The authority's: a replica with no code for it, its tape.
+pub fn fileChanged(p: *Pardes, id: usize, _: []const u8) bool {
+ const pane = p.panes[id] orelse return false;
+ const s = pane.addon orelse return false;
+ if (s.path.len == 0) return false;
+ // A placeholder waiting for its file: here now, it opens.
+ if (!s.live) {
+ @import("dump.zig").reviveSlot(p, id, s);
+ return s.live;
+ }
+ // Both cores read it and reopen it alike (the read and its open's
+ // outcome on the tape); the kind's record only the authority has.
+ const bytes: ?[]u8 = @import("fs.zig").read(p, s.path) catch null;
+ defer if (bytes) |b| p.gpa.free(b);
+ const record = @import("dump.zig").slotRecord(s) catch null;
+ var place: [32]u8 = undefined;
+ s.where_text.set(where(s, &place));
+ if (s.ops) |o| if (o.close) |f| {
+ var cl: Call = .{ .p = null, .id = 0, .slot = s, .quiet = true };
+ const prev = cl.begin("close");
+ f(s.st);
+ _ = cl.end(prev);
+ };
+ s.st = null;
+ s.arena.deinit();
+ s.arena = .init(s.gpa);
+ if (checked) s.used.clearRetainingCapacity();
+ if (s.record) |r| s.gpa.free(r);
+ s.record = record;
+ s.reloads +%= 1;
+ return reopen(p, id, s, bytes orelse "");
+}
+
+/// Its kind's close, then everything it had.
+pub fn close(p: *Pardes, pane: *Pane) void {
+ const s = pane.addon orelse return;
+ // A client's pane of a plain kind closed in a speculation: its kind's
+ // own memory (its pictures) is left be, as the rollback brings the pane
+ // back; the session's order closes it.
+ const kept = s.plain != null and s.ops != null and s.ops.?.close != null and tape.authorityOnly("a kind's close");
+ if (!kept) {
+ var i: usize = 0;
+ while (i < ready.items.len) if (ready.items[i].draw == p and ready.items[i].serial == pane.serial) ready.orderedRemove(i).drop() else {
+ i += 1;
+ };
+ if (ready.items.len == 0) ready.clearAndFree(heap);
+ }
+ if (s.ops) |ops| if (ops.close) |f| if (!kept) {
+ var cl: Call = .{ .p = null, .id = 0, .slot = s, .quiet = true };
+ const prev = cl.begin("close");
+ f(s.st);
+ _ = cl.end(prev);
+ };
+ const gpa = s.gpa;
+ s.free();
+ gpa.destroy(s);
+ pane.addon = null;
+}
+
+/// The pane's body painted over the `cols` x `rows` cells at (x, y):
+/// its cells into `s`, its placements after the frame's others. A pane
+/// whose kind has no code here, or a placeholder, says why in a line.
+pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pane, id: usize, x: u16, y: u16, cols: u16, rows: u16) void {
+ const slot = pane.addon orelse return;
+ if (cols == 0 or rows == 0) return;
+ const th = p.theme();
+ const fg: surface.Color = if (th.fg) |f| .{ .rgb = f } else .default;
+ const bg: surface.Color = if (th.bg) |b| .{ .rgb = b } else .default;
+ var frame: Frame = .{ .cols = cols, .rows = rows };
+ if (slot.ops == null and slot.live) {
+ // A client: a plain kind runs where it is shown, and this one lacks
+ // it; any other runs in its session alone.
+ const why = if (caps(p, slot).plain) "it is not in its addons, or it broke its promise here" else "its state is not plain (PA_PLAIN), so it runs in the session alone";
+ var line: [200]u8 = undefined;
+ _ = s.print(x, y, cols, std.fmt.bufPrint(&line, "addon {s} {d} does not run in this client: {s}", .{ slot.nameOf(), slot.version, why }) catch &line, .{ .fg = fg, .bg = bg });
+ return;
+ } else if (slot.ops == null) {
+ var line: [160]u8 = undefined;
+ const why = if (slot.refused.len > 0) slot.refused.slice() else "Addon load <path>";
+ // Its kind here, it waits for its file (`<path> is not here`).
+ const text = if (p.kinds.byName(slot.nameOf()) != null) why else std.fmt.bufPrint(&line, "addon {s} {d} is not loaded: {s}", .{ slot.nameOf(), slot.version, why }) catch &line;
+ _ = s.print(x, y, cols, text, .{ .fg = fg, .bg = bg });
+ return;
+ } else for (0..8) |_| {
+ if (ready.items.len > 0) deliver(p, slot, pane, id);
+ frame.cells = (paint(p, slot, id, arena, cols, rows, &frame) orelse return);
+ // No workers here (a test's, a bench's core): a draw that paint
+ // asked was done at once, and is this frame's, painted again.
+ if (drawer != null) break;
+ for (ready.items) |j| {
+ if (j.draw == p and j.pane == id) break;
+ } else break;
+ }
+ if (frame.gpu.len != 0) s.gpu_frames[id] = .{ .bytes = frame.gpu, .serial = pane.serial, .dst = .{ .x = x, .y = y, .w = cols, .h = rows } };
+ for (0..@min(rows, frame.rows)) |r| for (0..@min(cols, frame.cols)) |col| {
+ const cell = &frame.cells[r * frame.cols + col];
+ if (cell.flags & c.PA_PAINTED == 0) continue;
+ const len = @min(cell.len, 7);
+ s.set(x + @as(u16, @intCast(col)), y + @as(u16, @intCast(r)), if (len == 0) " " else cell.text[0..len], styleOf(cell, fg, bg));
+ };
+ for (frame.places[0..frame.n]) |pl| {
+ if (pl.rgba == null or pl.w == 0 or pl.h == 0) continue;
+ const dx = @min(pl.dst.x, cols);
+ const dy = @min(pl.dst.y, rows);
+ _ = p.appendPlacement(.{
+ .pane = @intCast(id),
+ .raster = .{ .ptr = pl.rgba, .w = pl.w, .h = pl.h, .stride = pl.w * 4 },
+ .src = .{ .x = pl.src.x, .y = pl.src.y, .w = pl.src.w, .h = pl.src.h },
+ .dst = .{ .x = x + dx, .y = y + dy, .w = @min(pl.dst.w, cols - dx), .h = @min(pl.dst.h, rows - dy) },
+ .at = if (pl.at.w == 0) null else .{ .x = pl.at.x, .y = pl.at.y, .w = pl.at.w, .h = pl.at.h },
+ .key = Placement.keyOf(pane.serial, @truncate(pl.key >> 32), @truncate(pl.key)),
+ .dirty = if (pl.from == 0) null else .{ .from = Placement.keyOf(pane.serial, @truncate(pl.from >> 32), @truncate(pl.from)), .y = pl.dirty_y, .h = pl.dirty_h },
+ .art = slot.art,
+ });
+ }
+}
+
+/// A frame of a kind's pane: its cells, `cols` a row, and its placements.
+pub const Frame = struct {
+ gpu: []const u8 = &.{},
+ cells: []c.pa_cell = &.{},
+ cols: u16,
+ rows: u16,
+ places: []c.pa_placement = &.{},
+ n: u32 = 0,
+ buf: [64]c.pa_placement = undefined,
+};
+
+/// The one paint of a frame in the live view: its cells (in `arena`) and
+/// placements into `frame`, its thumb and pointer into the slot. Debug
+/// checks it changed none of the kind's memory.
+pub fn paint(p: *const Pardes, slot: *Slot, id: usize, arena: std.mem.Allocator, cols: u16, rows: u16, frame: *Frame) ?[]c.pa_cell {
+ const ops = slot.ops orelse return null;
+ const cells = arena.alloc(c.pa_cell, @as(usize, cols) * rows) catch return null;
+ @memset(std.mem.sliceAsBytes(cells), 0);
+ var gpu: GpuPaint = .{ .arena = arena, .frame = frame };
+ var out: c.pa_paint = std.mem.zeroInit(c.pa_paint, .{ .placements = &frame.buf, .cap = frame.buf.len, .gpu = GpuPaint.emit, .gpu_ctx = &gpu });
+ const px = p.view().cell_pixels;
+ const win = std.mem.zeroInit(c.pa_window, .{ .cells = cells.ptr, .stride = cols, .rows = rows, .cols = cols, .cell_w = px.w, .cell_h = px.h, .focused = @intFromBool(focusedAnywhere(p, id)), .view = p.live + 1, .glyphs = @intFromBool(!p.view().frontend.native_images) });
+ var cl: Call = .{ .p = null, .id = id, .slot = slot, .quiet = true, .core = p };
+ const prev = cl.begin("paint");
+ const before = if (checked) usedHash(slot) else {};
+ ops.paint.?(slot.st, &win, &out);
+ if (checked and usedHash(slot) != before) std.debug.panic("addon {s}: paint changed its state (paint must be pure)", .{slot.nameOf()});
+ _ = cl.end(prev);
+ frame.places = &frame.buf;
+ // A picture over the bound is dropped, said once a pane (17.3).
+ frame.n = 0;
+ for (frame.buf[0..@min(out.n, frame.buf.len)]) |pl| {
+ if (@as(u64, pl.w) * pl.h * 4 > c.PA_RASTER_MAX) {
+ if (slot.over & 1 << 31 == 0) std.log.warn("{s}: a picture of {d} MB, over {d} MiB", .{ slot.nameOf(), @as(u64, pl.w) * pl.h * 4 >> 20, c.PA_RASTER_MAX >> 20 });
+ slot.over |= 1 << 31;
+ continue;
+ }
+ frame.buf[frame.n] = pl;
+ if (slot.reloads != 0) {
+ frame.buf[frame.n].key = std.hash.Wyhash.hash(slot.reloads, std.mem.asBytes(&pl.key));
+ if (pl.from != 0) frame.buf[frame.n].from = std.hash.Wyhash.hash(slot.reloads, std.mem.asBytes(&pl.from));
+ }
+ frame.n += 1;
+ }
+ slot.thumb_at = std.math.clamp(out.at, 0, 1);
+ slot.thumb_span = std.math.clamp(out.span, 0, 1);
+ slot.pointer = @intCast(@min(out.pointer, 255));
+ slot.painted = true;
+ return cells;
+}
+
+fn usedHash(slot: *const Slot) u64 {
+ var h = std.hash.Wyhash.init(0);
+ for (slot.used.items) |m| h.update(m);
+ return h.final();
+}
+
+fn styleOf(cell: *const c.pa_cell, fg: surface.Color, bg: surface.Color) surface.CellStyle {
+ const a = cell.attrs;
+ return .{
+ .fg = colorOf(cell.fg, fg),
+ .bg = colorOf(cell.bg, bg),
+ .bold = a & c.PA_BOLD != 0,
+ .dim = a & c.PA_DIM != 0,
+ .italic = a & c.PA_ITALIC != 0,
+ .reverse = a & c.PA_REVERSE != 0,
+ .ul = if (a & c.PA_UNDERLINE != 0) .single else .off,
+ };
+}
+
+fn colorOf(v: u32, default: surface.Color) surface.Color {
+ return switch (v & 0xff000000) {
+ c.PA_DEFAULT => default,
+ 0x02000000 => .{ .index = @truncate(v) },
+ else => .{ .rgb = .{ @truncate(v >> 16), @truncate(v >> 8), @truncate(v) } },
+ };
+}
+
+/// The start of its tag: its kind's prefix from its last tick (else the
+/// kind's name), the core's art words for a kind of PA_PICTURES, and its
+/// path. The authority's: a step reads it off the tape on a replica.
+pub fn prefix(p: *const Pardes, arena: std.mem.Allocator, pane: *const Pane) ![]const u8 {
+ const slot = pane.addon.?;
+ var buf: [400]u8 = undefined;
+ return arena.dupe(u8, tape.value(.addon, prefixOf, .{ p, slot, &buf }));
+}
+
+fn prefixOf(p: *const Pardes, slot: *const Slot, buf: *[400]u8) []const u8 {
+ if (!slot.live) return if (slot.path.len > 0) slot.path else slot.nameOf();
+ const own = slot.prefix.slice();
+ var w: std.Io.Writer = .fixed(buf);
+ w.writeAll(if (own.len > 0) own else slot.nameOf()) catch {};
+ // The same bytes whichever view's step lays the tag out (17.2): glyph
+ // art when Petscii says or the session's first view shows no pictures.
+ const first = &p.views[@min(@ctz(p.views_open), views.max - 1)].?;
+ if (caps(p, slot).pictures) w.print(" petscii:{s} palette:{t} ascii:{s}", .{
+ if (slot.art.glyph or !first.frontend.native_images) "on" else "off",
+ slot.art.palette,
+ if (slot.art.ascii) "on" else "off",
+ }) catch {};
+ if (slot.path.len > 0) w.print(" {s}", .{slot.path}) catch {};
+ return w.buffered();
+}
+
+/// A key at a pane whose kind takes keys: whether it did. A replica's
+/// speculation leaves it to the authority.
+pub fn key(p: *Pardes, id: usize, k: pardes.Key) bool {
+ const slot = (p.panes[id] orelse return false).addon orelse return false;
+ if (!caps(p, slot).key) return false;
+ if (!runsHere(slot) and tape.authorityOnly("a key into a kind's pane")) return true;
+ const pk: c.pa_key = .{ .cp = k.cp, .ctrl = @intFromBool(k.ctrl), .alt = @intFromBool(k.alt), .shift = @intFromBool(k.shift), .view = p.live + 1 };
+ var cl: Call = .{ .p = p, .id = id, .slot = slot };
+ const prev = cl.begin("key");
+ if (slot.ops) |o| cl.ret = o.key.?(slot.st, &pk);
+ return taken(p, slot, cl.end(prev));
+}
+
+fn taken(p: *Pardes, slot: *Slot, o: Outcome) bool {
+ if (o.ret == 0) return false;
+ poke(p, slot);
+ return true;
+}
+
+pub fn takesKeys(p: *const Pardes, s: *const Slot) bool {
+ return caps(p, s).key;
+}
+
+/// The kind's own rows for the core's `/`, those it found in the call
+/// (`api.found`; later ones go to its +Search as they come); null for a
+/// kind with no search.
+pub fn search(p: *Pardes, id: usize, pat: []const u8) ?[]const u8 {
+ const slot = (p.panes[id] orelse return null).addon orelse return null;
+ if (!caps(p, slot).search) return null;
+ if (tape.authorityOnly("a kind's search")) return null;
+ var cl: Call = .{ .p = p, .id = id, .slot = slot };
+ const prev = cl.begin("search");
+ if (slot.ops) |o| o.search.?(slot.st, pat.ptr, @intCast(pat.len));
+ // The rows are the authority's, on the tape: a replica's are those.
+ const o = cl.end(prev);
+ poke(p, slot);
+ return o.rows;
+}
+
+/// A place in it (`address`): taken, or null and what the kind said of
+/// the miss (empty when it said nothing).
+pub fn address(p: *Pardes, id: usize, text: []const u8, said: *Buf(160)) bool {
+ const slot = (p.panes[id] orelse return false).addon orelse return false;
+ // By its caps, not its code: a replica without it calls as the authority does.
+ if (!caps(p, slot).address) return false;
+ if (tape.authorityOnly("a kind's address")) return true;
+ var cl: Call = .{ .p = p, .id = id, .slot = slot, .missing = said };
+ const prev = cl.begin("address");
+ if (slot.ops) |o| cl.ret = o.address.?(slot.st, text.ptr, @intCast(text.len));
+ const o = cl.end(prev);
+ poke(p, slot);
+ return o.ret != 0;
+}
+
+pub fn takesMouse(p: *const Pardes, s: *const Slot) bool {
+ return caps(p, s).mouse;
+}
+
+/// The pointer at (col, row) of its body.
+pub fn mouse(p: *Pardes, id: usize, m: pardes.Mouse, col: u16, row: u16) bool {
+ const slot = (p.panes[id] orelse return false).addon orelse return false;
+ if (!caps(p, slot).mouse) return false;
+ if (!runsHere(slot) and tape.authorityOnly("the mouse in a kind's pane")) return true;
+ const pm: c.pa_mouse = .{
+ .button = switch (m.button) {
+ .left => c.PA_LEFT,
+ .middle => c.PA_MIDDLE,
+ .right => c.PA_RIGHT,
+ .wheel_up => c.PA_WHEEL_UP,
+ .wheel_down => c.PA_WHEEL_DOWN,
+ .wheel_left => c.PA_WHEEL_LEFT,
+ .wheel_right => c.PA_WHEEL_RIGHT,
+ else => 255,
+ },
+ .action = switch (m.kind) {
+ .press => c.PA_PRESS,
+ .release => c.PA_RELEASE,
+ .motion => c.PA_MOTION,
+ .drag => c.PA_DRAG,
+ },
+ .ctrl = @intFromBool(m.ctrl),
+ .shift = @intFromBool(m.shift),
+ .alt = @intFromBool(m.alt),
+ .view = p.live + 1,
+ .col = col,
+ .row = row,
+ .amount = m.amount,
+ };
+ var cl: Call = .{ .p = p, .id = id, .slot = slot };
+ const prev = cl.begin("mouse");
+ if (slot.ops) |o| cl.ret = o.mouse.?(slot.st, &pm);
+ return taken(p, slot, cl.end(prev));
+}
+
+/// The end of a step: each pane of a kind ticked that a call into it in
+/// the step asked for (16.2's rule 2). At a step of the session's own
+/// (`due`: a tick, a job's answer, a 9P request; never a client's input,
+/// which a replica guesses), also each told of each view whose facts
+/// changed (17.1), and ticked when its focus changed or its time came:
+/// units of the session's origin, which a replica replays (17.2).
+pub fn step(p: *Pardes, due: bool) void {
+ const now = p.clock.stepped_ns;
+ // A kind's call is the authority's alone but a plain kind's here: a
+ // speculation's tick after a call into the pane waits with that call's
+ // input (it stopped there).
+ const speculating = tape.speculating();
+ if (speculating) for (p.panes) |pslot| if (pslot) |pane| if (pane.addon) |slot| if (slot.next_tick == 1 and !runsHere(slot)) return tape.poison("a kind's tick");
+ for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |slot| {
+ if (speculating and !runsHere(slot)) continue;
+ if (due and caps(p, slot).view) for (0..views.max) |k| {
+ var v = viewOf(p, @intCast(k), id);
+ if (seen(&v) == slot.views[k]) continue;
+ slot.views[k] = seen(&v);
+ var cl: Call = .{ .p = p, .id = id, .slot = slot };
+ const prev = cl.begin("view");
+ if (slot.ops) |o| o.view.?(slot.st, &v);
+ _ = cl.end(prev);
+ poke(p, slot);
+ p.needs_frame = true;
+ };
+ if (!caps(p, slot).tick) continue;
+ const focused = focusedAnywhere(p, id);
+ if (due and focused != slot.focused) slot.next_tick = 1;
+ // 1 is the next step, whatever the clock says (a session whose
+ // clock has not moved yet reads 0).
+ if (slot.next_tick == 0 or (slot.next_tick > 1 and (!due or now < slot.next_tick))) continue;
+ slot.focused = focused;
+ var cl: Call = .{ .p = p, .id = id, .slot = slot };
+ const prev = cl.begin("tick");
+ // A frame drawn since its last tick: a fling's frames are counted by them.
+ const flags = (if (focused) c.PA_FOCUSED else 0) | (if (slot.painted and slot.plain == null) c.PA_FRAMED else 0);
+ slot.painted = false;
+ // The clock's now for a tick after an event (a key, a focus): the
+ // stepped frame lags it while the next wake is still to come.
+ var t = std.mem.zeroInit(c.pa_tick, .{ .now = if (slot.next_tick == 1) @max(now, p.clock.now_ns) else now, .flags = flags });
+ if (slot.ops) |o| {
+ o.tick.?(slot.st, &t);
+ cl.ret = @bitCast(t.next);
+ cl.prefix = t.prefix[0..@min(t.prefix_len, t.prefix.len)];
+ }
+ const o = cl.end(prev);
+ slot.next_tick = @bitCast(o.ret);
+ slot.prefix.set(o.prefix);
+ p.needs_frame = true;
+ };
+}
+
+/// A plain kind with its code here: a client runs it as the session does,
+/// its calls speculated as the text's are.
+fn runsHere(slot: *const Slot) bool {
+ return slot.plain != null and slot.ops != null;
+}
+
+/// Whether some view's facts are not what its kind was told.
+pub fn viewOwed(p: *const Pardes, slot: *const Slot, id: usize) bool {
+ if (caps(p, slot).view) for (0..views.max) |k| if (seen(&viewOf(p, @intCast(k), id)) != slot.views[k]) return true;
+ return false;
+}
+
+/// A view's facts as `view` is told them: 0 for one that shows it not.
+fn seen(v: *const c.pa_view) u64 {
+ return if (v.cols == 0) 0 else std.hash.Wyhash.hash(0, std.mem.asBytes(v));
+}
+
+/// The raster a frontend wants a kind's picture at (Kind.viewOf, a
+/// `pa_view`): a terminal's kitty images go down a wire, so smaller; a
+/// window rasterizes for its display.
+const RasterPolicy = struct { dpi: u16, max_dimension: u16, match_viewport: bool };
+/// A view's: a window's denser than a terminal's. By the view's frontend,
+/// never the build's, so every core of a session asks a kind alike.
+fn rasterPolicy(windowed: bool) RasterPolicy {
+ return if (windowed) .{ .dpi = 192, .max_dimension = 4096, .match_viewport = true } else .{ .dpi = 96, .max_dimension = 1200, .match_viewport = false };
+}
+
+/// Pane `id` as view `k` shows it (its id k + 1): its body below its
+/// notices, as draw.zig paints it, a cell's pixels, the theme's colours and
+/// the raster that view's frontend wants a picture at; no cells when the
+/// view is closed or shows it not.
+pub fn viewOf(p: *const Pardes, k: u8, id: usize) c.pa_view {
+ var out = std.mem.zeroes(c.pa_view);
+ out.id = k + 1;
+ const v = if (views.isOpen(p, k)) &(p.views[k] orelse return out) else return out;
+ const pane = p.panes[id] orelse return out;
+ const r = v.rects[id];
+ // The live view's share of the pane is in its own fields, another's parked.
+ const collapsed, const tag_rows = if (k == p.live) .{ pane.collapsed, pane.tag_rows } else .{ pane.pv[k].collapsed, pane.pv[k].tag_rows };
+ if (collapsed) return out;
+ // Its bands made again, never the copy a step or a park left: they are
+ // derived, so a client joined from a dump has none.
+ const notices = pardes.Messages.bands(p, v, pane, tag_rows, r, id).span();
+ const th = p.theme();
+ const rgb = struct {
+ fn f(x: [3]u8) u32 {
+ return @as(u32, x[0]) << 16 | @as(u32, x[1]) << 8 | x[2];
+ }
+ }.f;
+ const policy = rasterPolicy(v.frontend.windowed);
+ return .{
+ .cols = r.w -| pardes.config.GUTTER,
+ .rows = (r.h -| tag_rows) -| notices,
+ .cell_w = v.cell_pixels.w,
+ .cell_h = v.cell_pixels.h,
+ .fg = rgb(th.fg orelse th.tag_fg),
+ .bg = rgb(th.bg orelse th.tag_bg),
+ .sel = rgb(th.sel_bg),
+ .link = rgb(th.box),
+ .dpi = policy.dpi,
+ .max_px = policy.max_dimension,
+ .fill = @intFromBool(policy.match_viewport),
+ .glyphs = @intFromBool(!v.frontend.native_images),
+ .id = k + 1,
+ .pad = 0,
+ };
+}
+
+/// Whether pane `id` has the keyboard in some view (its window focused).
+fn focusedAnywhere(p: *const Pardes, id: usize) bool {
+ for (&p.views) |*v| if (v.*) |*vw| if (vw.active == id and vw.window_focused) return true;
+ return false;
+}
+
+/// When the kinds next want a step of the session's own: the soonest
+/// deadline (now, for a view whose facts changed after the kind was told
+/// them, or a focus), or null.
+pub fn wake(p: *const Pardes) ?u64 {
+ var soonest: ?u64 = null;
+ for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |slot| {
+ const moved = viewOwed(p, slot, id) or (caps(p, slot).tick and focusedAnywhere(p, id) != slot.focused);
+ const due = if (moved) @max(1, p.clock.stepped_ns) else slot.next_tick;
+ if (due != 0) soonest = @min(soonest orelse due, due);
+ };
+ return soonest;
+}
+
+/// A job's answer (Event.job): to its kind, unless its pane or its
+/// kind's generation is another's since it was asked.
+pub fn jobDone(p: *Pardes, pane_id: u8, serial: u32, token: u32, gen: u32, bytes: []const u8) void {
+ const pane = p.panes[pane_id] orelse return;
+ const slot = pane.addon orelse return;
+ if (pane.serial != serial or slot.gen != gen or !caps(p, slot).jobs) return;
+ // Cancelled: dropped, on every core (the cancel was on the tape).
+ if (std.mem.indexOfScalar(u32, &slot.cancelled, token)) |i| {
+ slot.cancelled[i] = 0;
+ return;
+ }
+ var cl: Call = .{ .p = p, .id = pane_id, .slot = slot };
+ const prev = cl.begin("job_done");
+ if (slot.ops) |o| o.job_done.?(slot.st, token, bytes.ptr, @intCast(bytes.len));
+ _ = cl.end(prev);
+ poke(p, slot);
+ p.needs_frame = true;
+}
+
+/// The pane's body as text (its 9P body), from the kind's `body`.
+pub fn body(pane: *const Pane, gpa: std.mem.Allocator) ![]u8 {
+ const slot = pane.addon orelse return gpa.alloc(u8, 0);
+ const ops = slot.ops orelse return gpa.alloc(u8, 0);
+ const len_f = ops.body_len orelse return gpa.alloc(u8, 0);
+ const read = ops.body orelse return gpa.alloc(u8, 0);
+ var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
+ const prev = cl.begin("body");
+ defer _ = cl.end(prev);
+ const n: usize = @intCast(@min(len_f(slot.st), 64 << 20));
+ const buf = try gpa.alloc(u8, n);
+ var off: usize = 0;
+ while (off < n) {
+ const got = read(slot.st, off, buf[off..].ptr, @intCast(@min(n - off, 1 << 20)));
+ if (got == 0) break;
+ off += got;
+ }
+ return buf[0..off];
+}
+
+/// The kind's `dump` into `buf`, a quiet call.
+pub fn dumpCall(slot: *Slot, f: anytype, buf: []u8) u32 {
+ var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
+ const prev = cl.begin("dump");
+ defer _ = cl.end(prev);
+ return f(slot.st, buf.ptr, @intCast(buf.len));
+}
+
+/// Where in it the pane is, as a text its `address` takes back.
+pub fn where(slot: *Slot, buf: *[32]u8) []const u8 {
+ const ops = slot.ops orelse return slot.where_text.slice();
+ const f = ops.where orelse return "";
+ var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
+ const prev = cl.begin("where");
+ defer _ = cl.end(prev);
+ return buf[0..@min(buf.len, f(slot.st, buf, buf.len))];
+}
+
+/// A kind's word as written to its pane: null taken, else why not.
+pub fn ctl(p: *Pardes, id: usize, line: []const u8, reply: *[160]u8) ?[]const u8 {
+ const slot = (p.panes[id] orelse return "no such pane").addon orelse return "not a kind's pane";
+ if (!slot.live) return "its addon is not loaded";
+ if (!caps(p, slot).ctl) return "its kind takes no words";
+ if (tape.authorityOnly("a kind's word")) return null;
+ var cl: Call = .{ .p = p, .id = id, .slot = slot };
+ const prev = cl.begin("ctl");
+ @memset(reply, 0);
+ if (slot.ops) |o| if (o.ctl.?(slot.st, line.ptr, @intCast(line.len), reply, reply.len) != c.PA_OK) {
+ const said = std.mem.sliceTo(reply, 0);
+ cl.refused.set(if (said.len > 0) said else "refused");
+ };
+ const o = cl.end(prev);
+ poke(p, slot);
+ if (o.text.len == 0) return null;
+ const n = @min(o.text.len, reply.len);
+ @memcpy(reply[0..n], o.text[0..n]);
+ return reply[0..n];
+}
+
+/// What its ctl file reads after the core's fields.
+pub fn ctlRead(pane: *const Pane, buf: []u8) []const u8 {
+ const slot = pane.addon orelse return "";
+ const f = (slot.ops orelse return "").ctl_read orelse return "";
+ var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true };
+ const prev = cl.begin("ctl_read");
+ defer _ = cl.end(prev);
+ return buf[0..@min(buf.len, f(slot.st, buf.ptr, @intCast(buf.len)))];
+}
+
+// ---- a call into a kind ----
+
+/// What a call into a kind did that the core takes on: its answer, a
+/// refusal or reply, what it said, a Look, a text pane. The authority's
+/// is taped; a replica's core takes it off the tape, kind or none.
+pub const Outcome = struct {
+ ret: i64 = 0,
+ text: []const u8 = "",
+ said: []const u8 = "",
+ err: bool = false,
+ look: []const u8 = "",
+ pane_name: []const u8 = "",
+ pane_text: []const u8 = "",
+ exec: []const u8 = "",
+ selected: ?[]const u8 = null,
+ rows: []const u8 = "",
+ /// A tick's: the start of its tag (pa_tick.prefix).
+ prefix: []const u8 = "",
+ /// A plain kind's block's hash after the call (Slot.state).
+ state: u64 = 0,
+ /// Its `where` after the call (a key, a view, a job's answer may move
+ /// it); null for a refused call.
+ where: ?[]const u8 = null,
+ /// The jobs it asked for (their tokens, 0 past the last): every core
+ /// emits them, so a replica's effects are the authority's; and those
+ /// it cancelled, every core drops.
+ jobs: [8]u32 = @splat(0),
+ cancels: [4]u32 = @splat(0),
+};
+
+/// The call under way: what `api` acts on, and what it gathers.
+const Call = struct {
+ p: ?*Pardes,
+ id: usize,
+ slot: *Slot,
+ /// Paint and the reads: what the kind asks of `api` is dropped, and
+ /// nothing is taped.
+ quiet: bool = false,
+ opening: bool = false,
+ /// An address's: what it says of a miss is the Look's to say.
+ missing: ?*Buf(160) = null,
+ /// Paint's core (its `p` is null: it asks nothing of the step), whose
+ /// pane `id` a draw is for.
+ core: ?*const Pardes = null,
+ name: []const u8 = "",
+ ret: i64 = 0,
+ refused: Buf(160) = .{},
+ said: Buf(160) = .{},
+ err: bool = false,
+ look: Buf(256) = .{},
+ pane_name: Buf(64) = .{},
+ pane_text: []const u8 = "",
+ exec: Buf(256) = .{},
+ selected: ?[]const u8 = null,
+ rows: []const u8 = "",
+ prefix: []const u8 = "",
+ jobs: [8]u32 = @splat(0),
+ cancels: [4]u32 = @splat(0),
+ /// Debug: when it began, for the budget.
+ began: u64 = 0,
+
+ fn begin(cl: *Call, comptime name: []const u8) ?*Call {
+ cl.name = name;
+ if (checked) cl.began = @import("FrameStats.zig").nowNs();
+ const prev = current;
+ current = cl;
+ return prev;
+ }
+
+ /// The call's outcome, as the authority's took it, done.
+ fn end(cl: *Call, prev: ?*Call) Outcome {
+ current = prev;
+ if (checked) overBudget(cl);
+ if (cl.quiet) return .{};
+ var place: [32]u8 = undefined;
+ // A refused open closed its state: no `where` to ask.
+ const at: ?[]const u8 = if (cl.refused.len == 0) where(cl.slot, &place) else null;
+ // Hashed while it records or replays: no client, no cost.
+ const state: u64 = if (tape.on == null) 0 else if (cl.slot.plain) |b| std.hash.Wyhash.hash(0, b) else 0;
+ const o = tape.value(.addon, same, .{Outcome{ .state = state, .ret = cl.ret, .text = cl.refused.slice(), .said = cl.said.slice(), .err = cl.err, .look = cl.look.slice(), .pane_name = cl.pane_name.slice(), .pane_text = cl.pane_text, .exec = cl.exec.slice(), .selected = cl.selected, .rows = cl.rows, .prefix = cl.prefix, .where = at, .jobs = cl.jobs, .cancels = cl.cancels }});
+ if (o.where) |w| cl.slot.where_text.set(w);
+ // Run here, it came out otherwise than the session's: it broke its
+ // promise (PA_PLAIN), and the client joins again without it.
+ if (cl.slot.ops != null and cl.slot.plain != null and tape.replaying() and o.state != state) {
+ pardes.Addon.distrust(cl.slot.nameOf());
+ var why: Buf(160) = .{};
+ tape.diverged(why.print("addon {s}: its state after {s} is not the session's (it breaks PA_PLAIN): the session's alone now", .{ cl.slot.nameOf(), cl.name }));
+ }
+ cl.slot.state = o.state;
+ // Its last job's token the session's, on a core whose kind asked
+ // none here (one with no code for it).
+ for (o.jobs) |token| if (token != 0) {
+ cl.slot.tokens = token;
+ };
+ if (cl.p) |p| if (p.panes[cl.id]) |pane| for (o.jobs) |token| if (token != 0) p.emit(.{ .job = .{ .pane = @intCast(cl.id), .serial = pane.serial, .token = token } });
+ for (o.cancels) |token| if (token != 0) {
+ for (&cl.slot.jobs) |*j| if (j.*) |job| if (job.token == token) {
+ cl.slot.gpa.free(job.in);
+ j.* = null;
+ };
+ std.mem.copyForwards(u32, cl.slot.cancelled[1..], cl.slot.cancelled[0..3]);
+ cl.slot.cancelled[0] = token;
+ };
+ if (o.selected) |sel| {
+ cl.slot.gpa.free(cl.slot.selection);
+ cl.slot.selection = cl.slot.gpa.dupe(u8, sel) catch &.{};
+ }
+ if (cl.missing) |m| if (o.err and o.ret == 0) {
+ m.set(o.said);
+ return o;
+ };
+ const p = cl.p orelse return o;
+ if (o.said.len > 0) if (o.err) p.reportFailure(cl.id, o.said) else p.setMessage(cl.id, o.said);
+ if (o.pane_name.len > 0) textPane(p, cl.id, cl.slot, o.pane_name, o.pane_text);
+ if (o.look.len > 0) @import("look.zig").lookAt(p, cl.id, o.look);
+ if (o.exec.len > 0) @import("mouse.zig").dispatchPointerBuiltin(p, cl.id, pardes.config.exec_cmd, o.exec, null);
+ // Rows found after its search (a job's): onto its +Search.
+ if (o.rows.len > 0 and !std.mem.eql(u8, cl.name, "search")) moreFound(p, cl.id, o.rows);
+ return o;
+ }
+};
+/// (The loop's: a job on a worker is in none.)
+threadlocal var current: ?*Call = null;
+
+/// A call's budget, in Debug: a frame (17.4; 2 ms in ReleaseFast, which
+/// Debug's kinds run three to four times slower than).
+const budget_ns = 16 * std.time.ns_per_ms;
+const sites = [_][]const u8{ "open", "close", "tick", "paint", "view", "key", "mouse", "body", "address", "where", "ctl", "ctl_read", "job_done", "dump", "search" };
+/// The first call over budget, `pdf: search took 118 ms, over 16 ms`:
+/// what `--addon-test` fails on.
+pub var breach: Buf(96) = .{};
+
+fn overBudget(cl: *Call) void {
+ const took = @import("FrameStats.zig").nowNs() -| cl.began;
+ const site = for (sites, 0..) |n, i| {
+ if (std.mem.eql(u8, n, cl.name)) break i;
+ } else return;
+ if (took <= budget_ns or cl.slot.over & @as(u32, 1) << @intCast(site) != 0) return;
+ cl.slot.over |= @as(u32, 1) << @intCast(site);
+ var line: Buf(96) = .{};
+ std.log.warn("{s}", .{line.print("{s}: {s} took {d} ms, over {d} ms", .{ cl.slot.nameOf(), cl.name, took / std.time.ns_per_ms, budget_ns / std.time.ns_per_ms })});
+ if (breach.len == 0) breach = line;
+}
+
+/// Rows a kind found after its search answered, appended to the pane's
+/// +Search (the list its last `/` made), as a file search's stream in.
+fn moreFound(p: *Pardes, id: usize, rows: []const u8) void {
+ const pane = p.panes[id] orelse return;
+ const rp = p.panes[pane.search_pane orelse return] orelse return;
+ const rf = if (rp.file) |*f| f else return;
+ const o = if (rf.output) |*x| x else return;
+ const content = std.mem.concat(p.gpa, u8, &.{ rf.content, rows }) catch |err| return p.reportError(id, "found", err);
+ pardes.panes.Output.fillResults(p, id, std.Io.Dir.path.dirname(rf.path) orelse p.sessionDir(), .search, o.arg(), content, null) catch |err| p.reportError(id, "found", err);
+}
+
+fn same(o: Outcome) Outcome {
+ return o;
+}
+
+/// The call into an addon under way, for a crash record: `in addon
+/// fake, paint`. Null outside one.
+pub fn calling(buf: []u8) ?[]const u8 {
+ const cl = current orelse return null;
+ return std.fmt.bufPrint(buf, "in addon {s}, {s}", .{ cl.slot.nameOf(), cl.name }) catch null;
+}
+
+pub const api: c.pa_api = .{
+ .size = @sizeOf(c.pa_api),
+ .abi = c.PA_ABI,
+ .pad = 0,
+ .alloc = struct {
+ fn f(n: usize) callconv(.c) ?*anyopaque {
+ const cl = current orelse return null;
+ // Its time the core's, not the kind's budget's (a region's
+ // first allocation is slow in Debug), as a job's copy is.
+ const t0 = if (checked) @import("FrameStats.zig").nowNs();
+ defer if (checked) {
+ cl.began += @import("FrameStats.zig").nowNs() -| t0;
+ };
+ // A plain kind's one block, the core's; no other.
+ const mem = mem: {
+ if (cl.slot.plain) |b| {
+ if (b.len > 0) return null;
+ cl.slot.plain = cl.slot.gpa.alignedAlloc(u8, .@"16", @max(n, 1)) catch return null;
+ break :mem cl.slot.plain.?;
+ }
+ break :mem cl.slot.arena.allocator().alignedAlloc(u8, .@"16", @max(n, 1)) catch return null;
+ };
+ @memset(mem, 0);
+ if (checked) cl.slot.used.append(cl.slot.gpa, mem) catch {};
+ return mem.ptr;
+ }
+ }.f,
+ .free = struct {
+ fn f(ptr: ?*anyopaque, n: usize) callconv(.c) void {
+ const cl = current orelse return;
+ const at: [*]align(16) u8 = @ptrCast(@alignCast(ptr orelse return));
+ // A plain kind's block goes with its pane.
+ if (cl.slot.plain) |b| if (b.ptr == at) return;
+ if (checked) for (cl.slot.used.items, 0..) |m, i| if (m.ptr == at) {
+ _ = cl.slot.used.swapRemove(i);
+ break;
+ };
+ cl.slot.arena.allocator().free(at[0..@max(n, 1)]);
+ }
+ }.f,
+ .job = struct {
+ /// Its input kept for the host, which runs it (Effect.job).
+ fn f(in: ?*const anyopaque, n: u32) callconv(.c) u32 {
+ const cl = current orelse return 0;
+ if (cl.p == null or cl.quiet) return 0;
+ const t0 = if (checked) @import("FrameStats.zig").nowNs();
+ defer if (checked) {
+ cl.began += @import("FrameStats.zig").nowNs() -| t0;
+ };
+ const s = cl.slot;
+ const asked = std.mem.indexOfScalar(u32, &cl.jobs, 0) orelse return 0;
+ // A client's (a plain kind's code here) runs none: its token
+ // alone, as the session's; the answer comes on the tape.
+ const free = if (tape.replaying()) null else for (&s.jobs) |*j| {
+ if (j.* == null) break j;
+ } else return 0;
+ const copy = if (free != null) s.gpa.dupe(u8, if (in) |b| @as([*]const u8, @ptrCast(b))[0..n] else "") catch return 0 else "";
+ s.tokens +%= 1;
+ if (s.tokens == 0) s.tokens = 1;
+ if (free) |slot| slot.* = .{ .token = s.tokens, .in = @constCast(copy) };
+ // Emitted as the call ends (Call.end), on every core.
+ cl.jobs[asked] = s.tokens;
+ return s.tokens;
+ }
+ }.f,
+ .look = struct {
+ fn f(text: [*c]const u8, n: u32) callconv(.c) void {
+ const cl = current orelse return;
+ if (!cl.quiet and text != null) cl.look.set(text[0..n]);
+ }
+ }.f,
+ .say = struct {
+ fn f(text: [*c]const u8, n: u32, err: c_int) callconv(.c) void {
+ const cl = current orelse return;
+ if (cl.quiet or text == null) return;
+ // Refusing its open: the opener says why.
+ if (err != 0 and cl.opening) return cl.refused.set(text[0..n]);
+ cl.said.set(text[0..n]);
+ cl.err = err != 0;
+ }
+ }.f,
+ .text = struct {
+ /// The pane is made as the call ends; its serial is the next.
+ fn f(name: [*c]const u8, name_len: u32, bytes: [*c]const u8, n: u32) callconv(.c) u32 {
+ const cl = current orelse return 0;
+ const p = cl.p orelse return 0;
+ if (cl.quiet or name == null or cl.pane_name.len > 0) return 0;
+ cl.pane_name.set(name[0..name_len]);
+ cl.pane_text = p.scratch.allocator().dupe(u8, if (bytes == null) "" else bytes[0..n]) catch "";
+ return p.next_serial + 1;
+ }
+ }.f,
+ .seed = struct {
+ /// The same pane seeds the same on every machine.
+ fn f() callconv(.c) u64 {
+ const cl = current orelse return seed_base;
+ const serial: u32 = if (cl.p) |p| (if (p.panes[cl.id]) |pane| pane.serial else 0) else 0;
+ return std.hash.Wyhash.hash(seed_base, std.mem.asBytes(&serial));
+ }
+ }.f,
+ .heap = struct {
+ /// `heap`'s, any thread: realloc's, n 0 a free.
+ fn f(ptr: ?*anyopaque, n: usize) callconv(.c) ?*anyopaque {
+ // Its time the core's, as an arena's is (a region's first
+ // allocation in Debug took 23 ms of a PDF's open).
+ const t0 = if (checked) @import("FrameStats.zig").nowNs();
+ defer if (checked) if (current) |cl| {
+ cl.began += @import("FrameStats.zig").nowNs() -| t0;
+ };
+ if (n == 0) {
+ kind_heap.free(ptr);
+ return null;
+ }
+ return kind_heap.realloc(ptr, n);
+ }
+ }.f,
+ .exec = struct {
+ fn f(text: [*c]const u8, n: u32) callconv(.c) void {
+ const cl = current orelse return;
+ if (!cl.quiet and text != null) cl.exec.set(text[0..n]);
+ }
+ }.f,
+ .select = struct {
+ fn f(text: [*c]const u8, n: u32) callconv(.c) void {
+ const cl = current orelse return;
+ if (cl.quiet) return;
+ const p = cl.p orelse return;
+ cl.selected = p.scratch.allocator().dupe(u8, if (text == null) "" else text[0..n]) catch return;
+ }
+ }.f,
+ .cancel = struct {
+ fn f(token: u32) callconv(.c) void {
+ const cl = current orelse return;
+ if (cl.quiet or token == 0) return;
+ const free = std.mem.indexOfScalar(u32, &cl.cancels, 0) orelse return;
+ cl.cancels[free] = token;
+ }
+ }.f,
+ .draw = struct {
+ /// A picture's job, of this process alone: on the frontend's
+ /// workers (`drawer`), else here at once; its answer to job_done at
+ /// the pane's next paint (`deliver`), never through the step.
+ fn f(in: ?*const anyopaque, n: u32) callconv(.c) u32 {
+ const cl = current orelse return 0;
+ const p: *const Pardes = cl.p orelse cl.core orelse return 0;
+ const pane = p.panes[cl.id] orelse return 0;
+ const ops = cl.slot.ops orelse return 0;
+ if (ops.job_run == null or ops.job_done == null) return 0;
+ const copy = heap.dupe(u8, if (in) |b| @as([*]const u8, @ptrCast(b))[0..n] else "") catch return 0;
+ const j = heap.create(host_io.KindJob) catch {
+ heap.free(copy);
+ return 0;
+ };
+ draw_tokens = (draw_tokens +% 1) & ~c.PA_DRAWN;
+ const token = c.PA_DRAWN | draw_tokens;
+ j.* = .{ .gpa = heap, .pane = @intCast(cl.id), .serial = pane.serial, .token = token, .gen = cl.slot.gen, .ops = ops, .in = copy, .arena = .init(heap), .draw = p };
+ Addon.holdJob(ops, true);
+ if (drawer) |d| if (d.go(d.ctx, j)) return token;
+ // Here, as a worker would run it: its time is not the call's.
+ const t0 = if (checked) @import("FrameStats.zig").nowNs();
+ j.run();
+ if (checked) cl.began += @import("FrameStats.zig").nowNs() -| t0;
+ ready.append(heap, j) catch j.drop();
+ return token;
+ }
+ }.f,
+ .found = struct {
+ /// Gathered in the call: the search's answer, or onto its +Search after.
+ fn f(rows: [*c]const u8, n: u32) callconv(.c) void {
+ const cl = current orelse return;
+ const p = cl.p orelse return;
+ if (cl.quiet or rows == null) return;
+ cl.rows = std.mem.concat(p.scratch.allocator(), u8, &.{ cl.rows, rows[0..n] }) catch return;
+ }
+ }.f,
+};
+
+/// Where this process's draws run (api.draw): its frontend's workers,
+/// which post each back to its loop to land (host_io.KindJob.land); false,
+/// or none (a test's core), and it runs here at once.
+pub var drawer: ?struct { ctx: ?*anyopaque, go: *const fn (ctx: ?*anyopaque, j: *host_io.KindJob) bool } = null;
+var draw_tokens: u32 = 0;
+/// Draws done, each kept for its pane's next paint (the loop's alone).
+var ready: std.ArrayListUnmanaged(*host_io.KindJob) = .empty;
+
+/// A draw done on a worker, back on the loop: kept for its pane's next
+/// paint, a frame owed. One of another core's (a client joined again
+/// since) is dropped: the new core's pane asked its own.
+pub fn landDraw(p: *Pardes, j: *host_io.KindJob) void {
+ if (j.draw != p) return j.drop();
+ ready.append(heap, j) catch return j.drop();
+ p.needs_frame = true;
+}
+
+/// The draws done for pane `id`, to its kind's job_done before it paints:
+/// pictures only, so a plain kind's block is as it was (Debug checks).
+fn deliver(p: *const Pardes, slot: *Slot, pane: *const Pane, id: usize) void {
+ var i: usize = 0;
+ while (i < ready.items.len) {
+ const j = ready.items[i];
+ if (j.draw != p or j.pane != id) {
+ i += 1;
+ continue;
+ }
+ _ = ready.orderedRemove(i);
+ defer j.drop();
+ if (pane.serial != j.serial or slot.gen != j.gen or slot.ops != j.ops) continue;
+ var cl: Call = .{ .p = null, .id = id, .slot = slot, .quiet = true, .core = p };
+ const prev = cl.begin("job_done");
+ const before = if (checked) usedHash(slot);
+ j.ops.job_done.?(slot.st, j.token, j.out.ptr, @intCast(j.out.len));
+ if (checked and slot.plain != null and usedHash(slot) != before) std.debug.panic("addon {s}: a draw's answer changed its state (a draw is pictures alone)", .{slot.nameOf()});
+ _ = cl.end(prev);
+ }
+}
+
+/// What `api.heap` hands out: memory that outlives a call, from any
+/// thread (a document a kind keeps, its pixels, MuPDF's own). A host sets
+/// it to its region for kinds (memory.zig); the C heap otherwise.
+pub var heap: std.mem.Allocator = std.heap.c_allocator;
+const kind_heap = @import("c_heap").Heap(&heap);
+
+/// What every pane's seed is made from: 0, or `--addon-test`'s `seed N`.
+pub var seed_base: u64 = 0;
+
+/// A kind's list (`api.text`): a pane named `name` in its file's
+/// directory, refilled when one is there, whose rows n and N walk from the
+/// kind's pane, a Look of one going to its kind (look.zig lookKind).
+fn textPane(p: *Pardes, id: usize, slot: *const Slot, name: []const u8, text: []const u8) void {
+ const dir = std.Io.Dir.path.dirname(slot.path) orelse p.sessionDir();
+ const content = p.gpa.dupe(u8, text) catch |err| return p.reportError(id, name, err);
+ pardes.panes.Output.fillResults(p, id, dir, .kind, name, content, null) catch |err| p.reportError(id, name, err);
+}
+
+/// A kind for tests of the core's side of a kind's pane, no library: a
+/// picture of one pixel over its body.
+pub const test_kind = struct {
+ const pixel = [4]u8{ 255, 0, 0, 255 };
+ fn picture(_: ?*anyopaque, win: [*c]const c.pa_window, out: [*c]c.pa_paint) callconv(.c) void {
+ out.*.placements[0] = std.mem.zeroInit(c.pa_placement, .{ .rgba = &pixel, .w = 1, .h = 1, .src = .{ .x = 0, .y = 0, .w = 1, .h = 1 }, .dst = .{ .x = 0, .y = 0, .w = win.*.cols, .h = win.*.rows } });
+ out.*.n = 1;
+ }
+ const ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .name = "test".* ++ @as([12]u8, @splat(0)), .version = 1, .flags = c.PA_PICTURES }), .paint = picture });
+
+ /// Its index in `p`'s kinds, taken in at the first ask.
+ pub fn of(p: *Pardes) u8 {
+ if (p.kinds.byName("test")) |k| return k;
+ var words: [64]LoadedWord = undefined;
+ _ = p.kinds.take(loadedOf(&ops, "", @splat(0), &words), "");
+ return p.kinds.n - 1;
+ }
+};
+
+// ---- small things ----
+
+pub fn Buf(comptime n: usize) type {
+ return struct {
+ pub const replica = .{ .len = .{.{ "bytes", "len" }} };
+ bytes: [n]u8 = undefined,
+ len: u16 = 0,
+
+ const Self = @This();
+ pub fn set(b: *Self, s: []const u8) void {
+ const k = @min(s.len, n);
+ std.mem.copyForwards(u8, b.bytes[0..k], s[0..k]);
+ b.len = @intCast(k);
+ }
+ pub fn slice(b: *const Self) []const u8 {
+ return b.bytes[0..b.len];
+ }
+ pub fn print(b: *Self, comptime fmt: []const u8, args: anytype) []const u8 {
+ const s = std.fmt.bufPrint(&b.bytes, fmt, args) catch &b.bytes;
+ b.len = @intCast(s.len);
+ return b.slice();
+ }
+ };
+}
+
+test "a kind's head is checked before a core takes it, and a core's kinds are its own" {
+ const Fake = struct {
+ fn paint(_: ?*anyopaque, _: [*c]const c.pa_window, _: [*c]c.pa_paint) callconv(.c) void {}
+ };
+ var ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .version = 3 }), .paint = Fake.paint });
+ @memcpy(ops.head.name[0..5], "zzzab");
+ var a: Registry = .{};
+ var b: Registry = .{};
+ var words: [64]LoadedWord = undefined;
+ try std.testing.expect(a.take(loadedOf(&ops, "", @splat(1), &words), "") == null);
+ try std.testing.expect(a.byName("zzzab") != null);
+ try std.testing.expect(b.byName("zzzab") == null);
+ try std.testing.expectEqualStrings("refused: kind zzzab is here already", a.take(loadedOf(&ops, "", @splat(1), &words), "").?);
+ a.drop(a.byName("zzzab").?);
+ try std.testing.expect(a.byName("zzzab") == null);
+}
+
+const GpuPaint = struct {
+ arena: std.mem.Allocator,
+ frame: *Frame,
+ fn emit(ctx: ?*anyopaque, bytes: [*c]const u8, n: u32) callconv(.c) c_int {
+ const self: *GpuPaint = @ptrCast(@alignCast(ctx orelse return 1));
+ if (bytes == null or n > 4 << 20) return 1;
+ self.frame.gpu = self.arena.dupe(u8, bytes[0..n]) catch return 1;
+ return 0;
+ }
+};