summaryrefslogtreecommitdiff
path: root/src/kinds
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 /src/kinds
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 'src/kinds')
-rw-r--r--src/kinds/addon.zig388
-rw-r--r--src/kinds/pardes_addon.h448
2 files changed, 0 insertions, 836 deletions
diff --git a/src/kinds/addon.zig b/src/kinds/addon.zig
deleted file mode 100644
index 1fa2279a..00000000
--- a/src/kinds/addon.zig
+++ /dev/null
@@ -1,388 +0,0 @@
-//! 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/src/kinds/pardes_addon.h b/src/kinds/pardes_addon.h
deleted file mode 100644
index 11dcec38..00000000
--- a/src/kinds/pardes_addon.h
+++ /dev/null
@@ -1,448 +0,0 @@
-/* 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