//! 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 `open`, `paint` (required), `tick`, //! `key`, `body`, `ctlRead`, `jobRun`, `jobDone`, `dump` and `load`, each //! over a `*T` that `open` is handed zeroed (its defaults set) in the //! pane's arena; pa_ops's others (mouse, ctl, address, where, search, //! close) no kind here has needed yet: //! //! export const pardes_addon = addon.ops(Snake); //! //! 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 = 0x20002; comptime { if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 2.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 = "" }; pub const Head = struct { name: []const u8, version: u32, exts: [:0]const u8 = "", words: []const Word = &.{} }; /// 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)); } /// 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)); } 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 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 as `paint` sees it, every cell unpainted. pub const Window = struct { cells: [*]c.pa_cell, stride: u32, cols: u16, rows: u16, focused: bool, /// `text` (UTF-8) from column x of row y on, a character a cell, cut at the edge. 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. pub const Paint = struct { out: *c.pa_paint, /// The start of the pane's tag; the kind's name when none. pub fn prefix(p: Paint, comptime fmt: []const u8, args: anytype) void { const t: []const u8 = std.fmt.bufPrint(&p.out.prefix, fmt, args) catch &p.out.prefix; p.out.prefix_len = @intCast(t.len); } /// 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 key: a codepoint (`char('h')`), or one of these. 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 = struct { code: Code, ctrl: bool = false, alt: bool = false, shift: bool = false }; pub fn char(comptime ch: u21) Code { return @fromBackingInt(@intCast(ch)); } /// 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) @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; } /// 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)); } fn init(a: [*c]const c.pa_api) callconv(.c) c_int { api = a; return c.PA_OK; } fn open(_: [*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 (bytes == null) null else bytes[0..len]); return s; } fn tick(st: ?*anyopaque, now: u64, flags: u32) callconv(.c) u64 { return T.tick(self(st) orelse return 0, now, @bitCast(flags)); } 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, .focused = w.*.focused != 0 }, .{ .out = out }); } fn key(st: ?*anyopaque, k: [*c]const c.pa_key) callconv(.c) c_int { return @intFromBool(T.key(self(st) orelse return 0, .{ .code = @fromBackingInt(@intCast(k.*.cp)), .ctrl = k.*.ctrl != 0, .alt = k.*.alt != 0, .shift = k.*.shift != 0 })); } /// The body (at most 4 KiB), written whole and read in pieces. fn text(st: ?*anyopaque, buf: *[4096]u8) []const u8 { var w: std.Io.Writer = .fixed(buf); T.body(self(st) orelse return "", &w) catch {}; return w.buffered(); } fn body_len(st: ?*anyopaque) callconv(.c) u64 { var buf: [4096]u8 = undefined; return text(st, &buf).len; } fn body(st: ?*anyopaque, off: u64, out: [*c]u8, n: u32) callconv(.c) u32 { var buf: [4096]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 ctl_read(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 { var w: std.Io.Writer = .fixed(buf[0..n]); T.ctlRead(self(st) orelse return 0, &w) catch {}; return @intCast(w.end); } 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(in[0..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, out[0..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, buf[0..n], version)); } }; 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, .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 = .{ .{ "tick", "tick" }, .{ "key", "key" }, .{ "body", "body_len" }, .{ "body", "body" }, .{ "ctlRead", "ctl_read" }, .{ "jobRun", "job_run" }, .{ "jobDone", "job_done" }, .{ "dump", "dump" }, .{ "load", "load" } }; 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`, which this file does not make. for (T.head.words) |w| if (!w.opens) @compileError(@typeName(T) ++ "'s word " ++ w.name ++ " opens no pane, and addon.zig makes no ctl to take it"); // A public function of another name (a typo) would be left out unsaid. const names = [_][]const u8{ "open", "paint", "tick", "key", "body", "ctlRead", "jobRun", "jobDone", "dump", "load" }; 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; }