//! 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`, `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 = 0x30000; comptime { if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 3.0 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. pub const Head = struct { name: []const u8, version: u32, exts: [:0]const u8 = "", words: []const Word = &.{}, pictures: 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 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, /// 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, .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; }