diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/CHANGELOG.md | 5 | ||||
| -rw-r--r-- | src/kinds/addon.zig | 228 | ||||
| -rw-r--r-- | src/kinds/pardes_addon.h | 12 |
3 files changed, 240 insertions, 5 deletions
diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 1ce7a3bf..fb47ac8e 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- Addons in Zig: `src/kinds/addon.zig` (over the same header, nothing of + the core) makes a kind's `pa_ops` from a struct of its functions, with + the pane's arena as an Allocator, typed keys, a window to `put` text in, + a deadline for `tick`, a struct's bytes as its record and its own `zig + test`; the snake and image addons are Zig now (`snake.zig`, `image.zig`). - The addons are build steps: `zig build image`, `zig build pdf`, or `zig build addons` for both, install them in `lib/pardes/addons`; the default install is the binaries alone, and `-Dmupdf` is gone. diff --git a/src/kinds/addon.zig b/src/kinds/addon.zig new file mode 100644 index 00000000..afb59337 --- /dev/null +++ b/src/kinds/addon.zig @@ -0,0 +1,228 @@ +//! 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 whichever of pa_ops's it has, each over a +//! `*T` that `open` is handed zeroed (its defaults set) in the pane's arena: +//! +//! export const pardes_addon = addon.ops(Snake); +//! +//! addons/snake/snake.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 `period` after now, unless it is still ahead: its time. + pub fn every(d: *Deadline, now: u64, period: u64) u64 { + if (d.at == 0 or now >= d.at) d.at = now + 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 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; +} diff --git a/src/kinds/pardes_addon.h b/src/kinds/pardes_addon.h index 072f2447..0870aa6f 100644 --- a/src/kinds/pardes_addon.h +++ b/src/kinds/pardes_addon.h @@ -20,8 +20,9 @@ * pa_paint and pa_ops: 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, and - * addons/snake/snake.c a game in it. + * 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 @@ -305,9 +306,10 @@ typedef struct pa_ops { 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: at most `n` bytes, n at least 1 MiB; 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. */ + /* The pane's record for a dump: its length, written in `n` bytes (n at + * least 1 MiB), or a length past n, unwritten, to be called again with that + * many; 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) returned, with the writer's * head.version: PA_OK, or nonzero to refuse (the pane waits as a |
