summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--addons/image/image.c146
-rw-r--r--addons/image/image.zig124
-rw-r--r--addons/image/stb.c27
-rw-r--r--addons/snake/snake.c154
-rw-r--r--addons/snake/snake.zig147
-rw-r--r--build.zig25
-rw-r--r--docs/shared-libs.md2
-rw-r--r--docs/typ/reference.typ12
-rw-r--r--src/CHANGELOG.md5
-rw-r--r--src/kinds/addon.zig228
-rw-r--r--src/kinds/pardes_addon.h12
-rw-r--r--test/panes.zig2
-rw-r--r--test/session.zig2
13 files changed, 563 insertions, 323 deletions
diff --git a/addons/image/image.c b/addons/image/image.c
deleted file mode 100644
index 1aa34428..00000000
--- a/addons/image/image.c
+++ /dev/null
@@ -1,146 +0,0 @@
-/* image.c: pictures as a pardes addon (.png .jpg .gif .bmp .ppm .pgm .tga).
- * A pane keeps its file's bytes (its record in a dump) and decodes them on
- * a job with stb_image, at most MAX_DIM pixels a side; the core shows the
- * RGBA fitted to the pane (or as glyph art, its Petscii word). */
-#include <limits.h>
-#include "pardes_addon.h"
-
-#define MAX_DIM 1280u /* the longest side kept */
-#define MAX_PIXELS (64ull * 1024 * 1024) /* refused before decoding */
-
-static const pa_api *api;
-
-/* stb's memory: the job's on a worker (freed after its job_done), else
- * the pane's arena (a header read at open). Both are freed whole. */
-static _Thread_local pa_out *job;
-static void *mem(size_t n) { return job ? job->alloc(job, n) : api->alloc(n); }
-static void *remem(void *p, size_t old, size_t n) {
- void *q = mem(n);
- if (q && p) memcpy(q, p, old < n ? old : n);
- return q;
-}
-#define STBI_MALLOC(n) mem(n)
-#define STBI_REALLOC_SIZED(p, old, n) remem(p, old, n)
-#define STBI_FREE(p) ((void)(p))
-#define STBIR_MALLOC(n, c) ((void)(c), mem(n))
-#define STBIR_FREE(p, c) ((void)(p), (void)(c))
-#define STBI_NO_STDIO
-#define STBI_NO_HDR
-#define STB_IMAGE_IMPLEMENTATION
-#define STB_IMAGE_RESIZE_IMPLEMENTATION
-#define STB_IMAGE_STATIC
-#define STB_IMAGE_RESIZE_STATIC
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wunused-function"
-#include "stb_image.h"
-#include "stb_image_resize.h"
-#pragma GCC diagnostic pop
-
-typedef struct image {
- const uint8_t *raw; /* the file's bytes */
- uint32_t len, w, h;
- const uint8_t *rgba; /* w x h, once its job is done */
-} image;
-
-static int init(const pa_api *a) { api = a; return PA_OK; }
-
-/* The bytes kept, and decoded on a job. */
-static void keep(image *im, const uint8_t *bytes, uint32_t len) {
- uint8_t *copy = api->alloc(len);
- if (!copy) return;
- memcpy(copy, bytes, len);
- im->raw = copy, im->len = len;
- if (len > 0) api->job(copy, len);
-}
-
-static void *open(const char *path, const uint8_t *bytes, uint64_t len) {
- (void)path;
- image *im = api->alloc(sizeof *im);
- if (!im || !bytes) return im;
- int w, h, c;
- /* One it cannot read (corrupt, truncated, not what its name says) is
- * refused, rather than shown as a blank pane. */
- if (len == 0 || len > INT_MAX || !stbi_info_from_memory(bytes, (int)len, &w, &h, &c)) {
- static const char why[] = "not an image pardes can read";
- api->say(why, sizeof why - 1, 1);
- } else keep(im, bytes, (uint32_t)len);
- return im;
-}
-
-static void paint(void *st, const pa_window *win, pa_paint *out) {
- const image *im = st;
- memcpy(out->prefix, "img", 3); /* the core follows it with its art words and the path */
- out->prefix_len = 3;
- if (!im || !im->rgba) return;
- out->placements[0] = (pa_placement){ .rgba = im->rgba, .w = im->w, .h = im->h,
- .src = { 0, 0, im->w, im->h }, .dst = { 0, 0, win->cols, win->rows } };
- out->n = 1;
-}
-
-static void put32(uint8_t *at, uint32_t v) {
- for (int i = 0; i < 4; i++) at[i] = (uint8_t)(v >> (8 * i));
-}
-
-/* On a worker: width and height (little endian), then the RGBA. */
-static uint32_t decode(const uint8_t *in, uint32_t n) {
- int w, h, c;
- if (n == 0 || n > INT_MAX || !stbi_info_from_memory(in, (int)n, &w, &h, &c) || (uint64_t)w * (uint64_t)h > MAX_PIXELS) return 0;
- uint8_t *px = stbi_load_from_memory(in, (int)n, &w, &h, &c, 4);
- if (!px) return 0;
- uint32_t longest = (uint32_t)(w > h ? w : h), nw = (uint32_t)w, nh = (uint32_t)h;
- if (longest > MAX_DIM) {
- nw = (uint32_t)((uint64_t)w * MAX_DIM / longest), nh = (uint32_t)((uint64_t)h * MAX_DIM / longest);
- nw += !nw, nh += !nh;
- uint8_t *small = mem((size_t)nw * nh * 4);
- if (!small || !stbir_resize_uint8(px, w, h, 0, small, (int)nw, (int)nh, 0, 4)) return 0;
- px = small;
- }
- size_t len = 8 + (size_t)nw * nh * 4;
- uint8_t *a = job->alloc(job, len); /* the last: the answer */
- if (!a) return 0;
- put32(a, nw), put32(a + 4, nh);
- memcpy(a + 8, px, len - 8);
- return (uint32_t)len;
-}
-
-static uint32_t job_run(const uint8_t *in, uint32_t n, pa_out *out) {
- job = out;
- uint32_t got = decode(in, n);
- job = 0;
- return got;
-}
-
-static void job_done(void *st, uint32_t token, const uint8_t *out, uint32_t n) {
- image *im = st;
- (void)token;
- if (!im || n < 8) return;
- uint32_t w = out[0] | out[1] << 8 | out[2] << 16 | (uint32_t)out[3] << 24;
- uint32_t h = out[4] | out[5] << 8 | out[6] << 16 | (uint32_t)out[7] << 24;
- if ((uint64_t)w * h * 4 != n - 8) return;
- uint8_t *rgba = api->alloc(n - 8);
- if (!rgba) return;
- memcpy(rgba, out + 8, n - 8);
- im->rgba = rgba, im->w = w, im->h = h;
-}
-
-/* The record is the file's bytes. */
-static uint32_t dump(void *st, uint8_t *buf, uint32_t n) {
- const image *im = st;
- if (!im) return 0;
- if (im->len <= n) memcpy(buf, im->raw, im->len);
- return im->len;
-}
-
-/* On a state with no picture (a Restore's), the record's; one open made
- * from the file as it is now (it changed on disk) keeps that one. */
-static int load(void *st, const uint8_t *buf, uint32_t n, uint32_t version) {
- (void)version;
- if (!st) return 1;
- if (!((image *)st)->raw) keep(st, buf, n);
- return PA_OK;
-}
-
-const pa_ops pardes_addon = {
- .head = PA_ADDON("image", 1, ".png .jpg .jpeg .gif .bmp .ppm .pgm .tga", 0, 0),
- .init = init, .open = open, .paint = paint, .job_run = job_run, .job_done = job_done, .dump = dump, .load = load,
-};
diff --git a/addons/image/image.zig b/addons/image/image.zig
new file mode 100644
index 00000000..824d708f
--- /dev/null
+++ b/addons/image/image.zig
@@ -0,0 +1,124 @@
+//! image.zig: pictures as a pardes addon (.png .jpg .gif .bmp .ppm .pgm .tga).
+//! A pane keeps its file's bytes (its record in a dump) and decodes them on
+//! a job with stb_image (stb.c), at most max_dim pixels a side; the core
+//! shows the RGBA fitted to the pane (or as glyph art, its Petscii word).
+const std = @import("std");
+const addon = @import("addon");
+
+const max_dim = 1280; // the longest side kept
+const max_pixels = 64 << 20; // refused before decoding
+
+extern fn pa_image_info(bytes: [*]const u8, n: c_int, w: *c_int, h: *c_int) c_int;
+extern fn pa_image_load(bytes: [*]const u8, n: c_int, w: *c_int, h: *c_int) ?[*]const u8;
+extern fn pa_image_resize(in: [*]const u8, w: c_int, h: c_int, out: [*]u8, nw: c_int, nh: c_int) c_int;
+
+/// stb's memory (stb.c): the job's on a worker, else the pane's arena.
+threadlocal var job: ?std.mem.Allocator = null;
+export fn pa_image_mem(n: usize) ?*anyopaque {
+ return ((job orelse addon.arena).alignedAlloc(u8, .@"16", n) catch return null).ptr;
+}
+export fn pa_image_remem(p: ?*anyopaque, old: usize, n: usize) ?*anyopaque {
+ const q: [*]u8 = @ptrCast(pa_image_mem(n) orelse return null);
+ if (p) |from| @memcpy(q[0..@min(old, n)], @as([*]const u8, @ptrCast(from)));
+ return q;
+}
+
+/// Its width and height, if stb can read it.
+fn info(bytes: []const u8) ?[2]u32 {
+ var w: c_int, var h: c_int = .{ 0, 0 };
+ if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int) or pa_image_info(bytes.ptr, @intCast(bytes.len), &w, &h) == 0) return null;
+ return .{ @intCast(w), @intCast(h) };
+}
+
+pub const Image = struct {
+ raw: []const u8 = &.{}, // the file's bytes
+ w: u32 = 0,
+ h: u32 = 0,
+ rgba: ?[]const u8 = null, // w x h, once its job is done
+
+ pub const head: addon.Head = .{ .name = "image", .version = 1, .exts = ".png .jpg .jpeg .gif .bmp .ppm .pgm .tga" };
+
+ /// The bytes kept, and decoded on a job.
+ fn keep(im: *Image, bytes: []const u8) void {
+ im.raw = addon.arena.dupe(u8, bytes) catch return;
+ if (bytes.len > 0) _ = addon.job(im.raw);
+ }
+
+ /// One it cannot read (corrupt, truncated, not what its name says) is
+ /// refused, rather than shown as a blank pane.
+ pub fn open(im: *Image, bytes: ?[]const u8) void {
+ const b = bytes orelse return;
+ if (info(b) == null) return addon.say("not an image pardes can read", .err);
+ im.keep(b);
+ }
+
+ pub fn paint(im: *const Image, w: addon.Window, out: addon.Paint) void {
+ out.prefix("img", .{}); // the core follows it with its art words and the path
+ const rgba = im.rgba orelse return;
+ out.place(.{ .rgba = rgba.ptr, .w = im.w, .h = im.h, .src = .{ .w = im.w, .h = im.h }, .dst = .{ .w = w.cols, .h = w.rows } });
+ }
+
+ /// On a worker: width and height (little endian), then the RGBA.
+ pub fn jobRun(in: []const u8, gpa: std.mem.Allocator) ?[]u8 {
+ job = gpa;
+ defer job = null;
+ const wh = info(in) orelse return null;
+ if (@as(u64, wh[0]) * wh[1] > max_pixels) return null;
+ var w: c_int, var h: c_int = .{ 0, 0 };
+ var px = pa_image_load(in.ptr, @intCast(in.len), &w, &h) orelse return null;
+ const longest: u64 = @max(wh[0], wh[1]);
+ var nw, var nh = wh;
+ if (longest > max_dim) {
+ nw = @max(1, @as(u32, @intCast(@as(u64, wh[0]) * max_dim / longest)));
+ nh = @max(1, @as(u32, @intCast(@as(u64, wh[1]) * max_dim / longest)));
+ const small = gpa.alloc(u8, @as(usize, nw) * nh * 4) catch return null;
+ if (pa_image_resize(px, w, h, small.ptr, @intCast(nw), @intCast(nh)) == 0) return null;
+ px = small.ptr;
+ }
+ const a = gpa.alloc(u8, 8 + @as(usize, nw) * nh * 4) catch return null; // the last: the answer
+ std.mem.writeInt(u32, a[0..4], nw, .little);
+ std.mem.writeInt(u32, a[4..8], nh, .little);
+ @memcpy(a[8..], px[0 .. a.len - 8]);
+ return a;
+ }
+
+ pub fn jobDone(im: *Image, _: u32, out: []const u8) void {
+ if (out.len < 8) return;
+ const w = std.mem.readInt(u32, out[0..4], .little);
+ const h = std.mem.readInt(u32, out[4..8], .little);
+ if (@as(u64, w) * h * 4 != out.len - 8) return;
+ im.rgba = addon.arena.dupe(u8, out[8..]) catch return;
+ im.w, im.h = .{ w, h };
+ }
+
+ /// The record is the file's bytes.
+ pub fn dump(im: *const Image, buf: []u8) usize {
+ if (im.raw.len <= buf.len) @memcpy(buf[0..im.raw.len], im.raw);
+ return im.raw.len;
+ }
+
+ /// On a state with no picture (a Restore's), the record's; one open
+ /// made from the file as it is now (it changed on disk) keeps that one.
+ pub fn load(im: *Image, bytes: []const u8, _: u32) bool {
+ if (im.raw.len == 0) im.keep(bytes);
+ return true;
+ }
+};
+
+export const pardes_addon = addon.ops(Image);
+
+test "a job decodes a picture to its size and pixels, and one past max_dim is scaled to fit" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const png = "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\xcf\xc0\x00\x00\x03\x01\x01\x00\xc9\xfe\x92\xef\x00\x00\x00\x00IEND\xaeB`\x82";
+ const got = Image.jobRun(png, arena.allocator()).?;
+ try std.testing.expectEqualSlices(u8, &.{ 1, 0, 0, 0, 1, 0, 0, 0, 0xff, 0, 0, 0xff }, got);
+ // A PPM 2600x1: 1280x1 after.
+ var ppm: std.ArrayList(u8) = .empty;
+ try ppm.print(arena.allocator(), "P6\n2600 1\n255\n", .{});
+ try ppm.appendNTimes(arena.allocator(), 0x80, 2600 * 3);
+ const wide = Image.jobRun(ppm.items, arena.allocator()).?;
+ try std.testing.expectEqual(1280, std.mem.readInt(u32, wide[0..4], .little));
+ try std.testing.expectEqual(8 + 1280 * 4, wide.len);
+ try std.testing.expect(Image.jobRun("not a picture", arena.allocator()) == null);
+}
diff --git a/addons/image/stb.c b/addons/image/stb.c
new file mode 100644
index 00000000..5fba51bc
--- /dev/null
+++ b/addons/image/stb.c
@@ -0,0 +1,27 @@
+/* stb_image and its resize for image.zig, static here (a static pardes
+ * links a zstbi beside them), their memory image.zig's: the job's on a
+ * worker, else the pane's arena; both are freed whole. */
+#include <stddef.h>
+#include <string.h>
+void *pa_image_mem(size_t n);
+void *pa_image_remem(void *p, size_t old, size_t n);
+#define STBI_MALLOC(n) pa_image_mem(n)
+#define STBI_REALLOC_SIZED(p, old, n) pa_image_remem(p, old, n)
+#define STBI_FREE(p) ((void)(p))
+#define STBIR_MALLOC(n, c) ((void)(c), pa_image_mem(n))
+#define STBIR_FREE(p, c) ((void)(p), (void)(c))
+#define STBI_NO_STDIO
+#define STBI_NO_HDR
+#define STB_IMAGE_IMPLEMENTATION
+#define STB_IMAGE_RESIZE_IMPLEMENTATION
+#define STB_IMAGE_STATIC
+#define STB_IMAGE_RESIZE_STATIC
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-function"
+#include "stb_image.h"
+#include "stb_image_resize.h"
+#pragma GCC diagnostic pop
+
+int pa_image_info(const unsigned char *b, int n, int *w, int *h) { int c; return stbi_info_from_memory(b, n, w, h, &c); }
+unsigned char *pa_image_load(const unsigned char *b, int n, int *w, int *h) { int c; return stbi_load_from_memory(b, n, w, h, &c, 4); }
+int pa_image_resize(const unsigned char *in, int w, int h, unsigned char *out, int nw, int nh) { return stbir_resize_uint8(in, w, h, 0, out, nw, nh, 0, 4); }
diff --git a/addons/snake/snake.c b/addons/snake/snake.c
deleted file mode 100644
index ce9279dc..00000000
--- a/addons/snake/snake.c
+++ /dev/null
@@ -1,154 +0,0 @@
-/* snake.c: a snake game as a pardes addon.
- * cc -shared -fPIC -O2 -Wall -Wextra -Werror -I src/kinds -o snake.so addons/snake/snake.c
- * h j k l steer; once dead, any key starts again. It steps only while its
- * pane has the keyboard, and asks for nothing otherwise. */
-#include <stdio.h>
-#include "pardes_addon.h"
-
-#define W 20 /* the board, in cells, inside its wall */
-#define H 5
-#define PERIOD 150000000ull /* ns a step */
-#define VERSION 1
-
-typedef struct { uint8_t x, y; } pt;
-
-typedef struct snake {
- pt body[W * H]; /* body[0] is the head */
- uint16_t len;
- pt food;
- int8_t dx, dy; /* the direction last stepped */
- int8_t ndx, ndy; /* the direction the next step takes */
- uint8_t dead, pad[3];
- uint32_t score, steps;
- uint64_t rng, next; /* next: the deadline of the next step */
-} snake;
-
-static const pa_api *api;
-
-static uint64_t rnd(snake *s) {
- s->rng ^= s->rng << 13, s->rng ^= s->rng >> 7, s->rng ^= s->rng << 17;
- return s->rng;
-}
-
-/* Is (x, y) one of the snake's first n segments? */
-static int on_snake(const snake *s, int x, int y, unsigned n) {
- for (unsigned i = 0; i < n; i++)
- if (s->body[i].x == x && s->body[i].y == y) return 1;
- return 0;
-}
-
-static void place_food(snake *s) {
- unsigned free_cells = W * H - s->len;
- if (!free_cells) { s->dead = 1; return; } /* the board is full: a win, and over */
- unsigned k = (unsigned)(rnd(s) % free_cells);
- for (int y = 0; y < H; y++)
- for (int x = 0; x < W; x++)
- if (!on_snake(s, x, y, s->len) && k-- == 0) { s->food = (pt){(uint8_t)x, (uint8_t)y}; return; }
-}
-
-static void restart(snake *s) {
- s->len = 3;
- for (unsigned i = 0; i < 3; i++) s->body[i] = (pt){(uint8_t)(W / 2 - i), H / 2};
- s->dx = s->ndx = 1, s->dy = s->ndy = 0;
- s->dead = 0, s->score = 0, s->steps = 0;
- place_food(s);
-}
-
-static void step(snake *s) {
- s->dx = s->ndx, s->dy = s->ndy;
- int x = s->body[0].x + s->dx, y = s->body[0].y + s->dy;
- int eats = x == s->food.x && y == s->food.y;
- /* the tail moves away this step unless the snake grows */
- if (x < 0 || y < 0 || x >= W || y >= H || on_snake(s, x, y, eats ? s->len : s->len - 1u)) {
- s->dead = 1;
- return;
- }
- if (eats) s->len++;
- memmove(&s->body[1], &s->body[0], (s->len - 1) * sizeof(pt));
- s->body[0] = (pt){(uint8_t)x, (uint8_t)y};
- s->steps++;
- if (eats) s->score++, place_food(s);
-}
-
-/* ---- the contract ---- */
-
-static int init(const pa_api *a) { api = a; return PA_OK; }
-
-static void *open(const char *path, const uint8_t *bytes, uint64_t len) {
- (void)path, (void)bytes, (void)len;
- snake *s = api->alloc(sizeof *s);
- if (!s) return 0;
- s->rng = api->seed() | 1;
- restart(s);
- return s;
-}
-
-/* Unfocused or over, it stands still and asks for nothing: a key, or the
- * keyboard coming back, ticks it again. */
-static uint64_t tick(void *st, uint64_t now, uint32_t flags) {
- snake *s = st;
- if (!(flags & PA_FOCUSED) || s->dead) return s->next = 0;
- if (s->next && now >= s->next) step(s);
- if (s->dead) return s->next = 0;
- if (!s->next || now >= s->next) s->next = now + PERIOD;
- return s->next;
-}
-
-static void paint(void *st, const pa_window *w, pa_paint *out) {
- const snake *s = st;
- for (unsigned x = 0; x < W + 2; x++) pa_put(w, 0, x, "#", PA_INDEX(8), PA_DEFAULT, 0), pa_put(w, H + 1, x, "#", PA_INDEX(8), PA_DEFAULT, 0);
- for (unsigned y = 1; y <= H; y++) pa_put(w, y, 0, "#", PA_INDEX(8), PA_DEFAULT, 0), pa_put(w, y, W + 1, "#", PA_INDEX(8), PA_DEFAULT, 0);
- pa_put(w, 1 + s->food.y, 1 + s->food.x, "*", PA_INDEX(1), PA_DEFAULT, PA_BOLD);
- for (unsigned i = s->len; i-- > 0;)
- pa_put(w, 1 + s->body[i].y, 1 + s->body[i].x, i ? "o" : s->dead ? "x" : "@", PA_INDEX(2), PA_DEFAULT, i ? 0 : PA_BOLD);
- if (s->dead) pa_put(w, H + 2, 0, "game over: any key", PA_INDEX(1), PA_DEFAULT, 0);
- else if (!w->focused) pa_put(w, H + 2, 0, "paused", PA_INDEX(8), PA_DEFAULT, 0);
- int n = snprintf(out->prefix, sizeof out->prefix, "Snake %u%s", s->score, s->dead ? " over" : "");
- out->prefix_len = n < 0 ? 0 : (uint32_t)n;
-}
-
-static int key(void *st, const pa_key *k) {
- snake *s = st;
- if (k->cp == 0x1b) return 0; /* Esc leaves */
- if (s->dead) { restart(s); return 1; }
- int dx = 0, dy = 0;
- switch (k->cp) {
- case 'h': case PA_KEY_LEFT: dx = -1; break;
- case 'l': case PA_KEY_RIGHT: dx = 1; break;
- case 'k': case PA_KEY_UP: dy = -1; break;
- case 'j': case PA_KEY_DOWN: dy = 1; break;
- case 'r': restart(s); return 1;
- default: return 0;
- }
- if (dx != -s->dx || dy != -s->dy) s->ndx = (int8_t)dx, s->ndy = (int8_t)dy; /* no turning back */
- return 1;
-}
-
-static uint32_t text(const snake *s, char *buf, uint32_t n) {
- int r = snprintf(buf, n, "score %u\nlength %u\nsteps %u\n%s\n", s->score, s->len, s->steps, s->dead ? "over" : "alive");
- return r < 0 ? 0 : (uint32_t)r < n ? (uint32_t)r : n;
-}
-
-static uint64_t body_len(void *st) { char b[96]; return text(st, b, sizeof b); }
-
-static uint32_t body(void *st, uint64_t off, char *buf, uint32_t n) {
- char b[96];
- return pa_copy(b, text(st, b, sizeof b), off, buf, n);
-}
-
-static uint32_t ctl_read(void *st, char *buf, uint32_t n) {
- const snake *s = st;
- int r = snprintf(buf, n, "score %u\nlength %u\n", s->score, s->len);
- return r < 0 ? 0 : (uint32_t)r < n ? (uint32_t)r : n;
-}
-
-PA_POD(snake, VERSION)
-
-static const pa_word words[] = { PA_WORD("Snake", 0, PA_ARG_NONE, 1, "a game of snake: h j k l steer") };
-
-const pa_ops pardes_addon = {
- .head = PA_ADDON("snake", VERSION, "", words, 1),
- .init = init, .open = open, .tick = tick, .paint = paint, .key = key,
- .body_len = body_len, .body = body, .ctl_read = ctl_read,
- .dump = snake_dump, .load = snake_load,
-};
diff --git a/addons/snake/snake.zig b/addons/snake/snake.zig
new file mode 100644
index 00000000..badafc54
--- /dev/null
+++ b/addons/snake/snake.zig
@@ -0,0 +1,147 @@
+//! snake.zig: a snake game as a pardes addon, over src/kinds/addon.zig
+//! (`zig build addon-test` builds it as snake.so and runs snake.script).
+//! h j k l steer; once dead, any key starts again. It steps only while its
+//! pane has the keyboard, and asks for nothing otherwise.
+const std = @import("std");
+const addon = @import("addon");
+
+const W = 20; // the board, in cells, inside its wall
+const H = 5;
+const period = 150 * std.time.ns_per_ms;
+
+const Pt = extern struct { x: u8, y: u8 };
+
+pub const Snake = extern struct {
+ segs: [W * H]Pt, // segs[0] is the head
+ len: u16,
+ food: Pt,
+ dir: [2]i8, // the direction last stepped
+ turn: [2]i8, // the direction the next step takes
+ dead: bool,
+ score: u32,
+ steps: u32,
+ rng: u64,
+ next: addon.Deadline,
+
+ pub const head: addon.Head = .{ .name = "snake", .version = 1, .words = &.{
+ .{ .name = "Snake", .opens = true, .doc = "a game of snake: h j k l steer" },
+ } };
+
+ fn rnd(s: *Snake) u64 {
+ s.rng ^= s.rng << 13;
+ s.rng ^= s.rng >> 7;
+ s.rng ^= s.rng << 17;
+ return s.rng;
+ }
+
+ /// Is (x, y) one of the snake's first n segments?
+ fn on(s: *const Snake, x: i32, y: i32, n: usize) bool {
+ for (s.segs[0..n]) |q| if (q.x == x and q.y == y) return true;
+ return false;
+ }
+
+ fn placeFood(s: *Snake) void {
+ s.dead = s.len == W * H; // the board full: a win, and over
+ if (s.dead) return;
+ var k = s.rnd() % (W * H - s.len);
+ s.food = for (0..W * H) |i| {
+ const p: Pt = .{ .x = @intCast(i % W), .y = @intCast(i / W) };
+ if (s.on(p.x, p.y, s.len)) continue;
+ if (k == 0) break p;
+ k -= 1;
+ } else s.food;
+ }
+
+ fn restart(s: *Snake) void {
+ s.len = 3;
+ for (s.segs[0..3], 0..) |*p, i| p.* = .{ .x = @intCast(W / 2 - i), .y = H / 2 };
+ s.dir, s.turn, s.dead, s.score, s.steps = .{ .{ 1, 0 }, .{ 1, 0 }, false, 0, 0 };
+ s.placeFood();
+ }
+
+ fn step(s: *Snake) void {
+ s.dir = s.turn;
+ const x = @as(i32, s.segs[0].x) + s.dir[0];
+ const y = @as(i32, s.segs[0].y) + s.dir[1];
+ const eats = x == s.food.x and y == s.food.y;
+ // The tail moves away this step unless the snake grows.
+ s.dead = x < 0 or y < 0 or x >= W or y >= H or s.on(x, y, if (eats) s.len else s.len - 1);
+ if (s.dead) return;
+ if (eats) s.len += 1;
+ std.mem.copyBackwards(Pt, s.segs[1..s.len], s.segs[0 .. s.len - 1]);
+ s.segs[0] = .{ .x = @intCast(x), .y = @intCast(y) };
+ s.steps += 1;
+ if (!eats) return;
+ s.score += 1;
+ s.placeFood();
+ }
+
+ pub fn open(s: *Snake, _: ?[]const u8) void {
+ s.rng = addon.seed() | 1;
+ s.restart();
+ }
+
+ /// Unfocused or over, it stands still and asks for nothing: a key, or
+ /// the keyboard coming back, ticks it again.
+ pub fn tick(s: *Snake, now: u64, flags: addon.Flags) u64 {
+ if (s.next.due(now) and flags.focused and !s.dead) s.step();
+ return if (!flags.focused or s.dead) s.next.stop() else s.next.every(now, period);
+ }
+
+ pub fn paint(s: *const Snake, w: addon.Window, out: addon.Paint) void {
+ const wall: addon.Style = .{ .fg = .index(8) };
+ for (0..H + 2) |y| for (0..W + 2) |x| if (x % (W + 1) == 0 or y % (H + 1) == 0) w.put(x, y, "#", wall);
+ w.put(1 + s.food.x, 1 + s.food.y, "*", .{ .fg = .index(1), .attrs = .{ .bold = true } });
+ for (s.segs[0..s.len], 0..) |p, i|
+ w.put(1 + p.x, 1 + p.y, if (i > 0) "o" else if (s.dead) "x" else "@", .{ .fg = .index(2), .attrs = .{ .bold = i == 0 } });
+ if (s.dead) w.put(0, H + 2, "game over: any key", .{ .fg = .index(1) }) else if (!w.focused) w.put(0, H + 2, "paused", wall);
+ out.prefix("Snake {d}{s}", .{ s.score, if (s.dead) " over" else "" });
+ }
+
+ pub fn key(s: *Snake, k: addon.Key) bool {
+ if (k.code == .esc) return false; // Esc leaves
+ if (s.dead or k.code == addon.char('r')) {
+ s.restart();
+ return true;
+ }
+ const d: [2]i8 = switch (k.code) {
+ .left, addon.char('h') => .{ -1, 0 },
+ .right, addon.char('l') => .{ 1, 0 },
+ .up, addon.char('k') => .{ 0, -1 },
+ .down, addon.char('j') => .{ 0, 1 },
+ else => return false,
+ };
+ if (d[0] != -s.dir[0] or d[1] != -s.dir[1]) s.turn = d; // no turning back
+ return true;
+ }
+
+ pub fn body(s: *const Snake, w: *std.Io.Writer) !void {
+ try w.print("score {d}\nlength {d}\nsteps {d}\n{s}\n", .{ s.score, s.len, s.steps, if (s.dead) "over" else "alive" });
+ }
+
+ pub fn ctlRead(s: *const Snake, w: *std.Io.Writer) !void {
+ try w.print("score {d}\nlength {d}\n", .{ s.score, s.len });
+ }
+
+ pub const dump = addon.dumpBytes;
+ pub const load = addon.loadBytes;
+};
+
+export const pardes_addon = addon.ops(Snake);
+
+test "it eats, grows a segment and a point, dies on the wall, and its record is its state" {
+ var s = std.mem.zeroInit(Snake, .{ .rng = 3 });
+ s.restart();
+ s.food = .{ .x = s.segs[0].x + 1, .y = s.segs[0].y };
+ s.step();
+ try std.testing.expectEqual(4, s.len);
+ try std.testing.expectEqual(1, s.score);
+ _ = s.key(.{ .code = addon.char('k') });
+ while (!s.dead) s.step();
+ try std.testing.expectEqual(0, s.segs[0].y);
+ var record: [@sizeOf(Snake)]u8 = undefined;
+ var back = std.mem.zeroInit(Snake, .{});
+ try std.testing.expect(addon.loadBytes(&back, record[0..addon.dumpBytes(&s, &record)], 1));
+ try std.testing.expect(std.meta.eql(back, s));
+ try std.testing.expect(!addon.loadBytes(&back, &record, 2));
+}
diff --git a/build.zig b/build.zig
index 603857e7..2328d5df 100644
--- a/build.zig
+++ b/build.zig
@@ -341,14 +341,6 @@ pub fn build(b: *std.Build) void {
const zstbi_dep = b.dependency("zstbi", .{ .target = target, .optimize = c_optimize });
const zstbi_mod = zstbi_dep.module("root");
- // The image addon (addons/image/image.c over stb_image), installed where
- // the start scan finds it (<prefix>/lib/pardes/addons) and handed by
- // path to every test that opens a picture.
- const image_addon = b.addLibrary(.{ .name = "image", .linkage = .dynamic, .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }) });
- image_addon.root_module.addIncludePath(b.path("src/kinds"));
- image_addon.root_module.addIncludePath(zstbi_dep.path("libs/stbi"));
- image_addon.root_module.addCSourceFile(.{ .file = b.path("addons/image/image.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
-
// mvzr backtracks with no bound on its work (its own test "do not make
// this test any longer": `a?` n times is 2^n steps), and pardes searches
// with it holding the editor. Its matcher gets a step budget, patched into
@@ -817,6 +809,15 @@ pub fn build(b: *std.Build) void {
// The kinds' C ABI (src/kinds/pardes_addon.h), translated once: the core's
// records are the header's, never a mirror of it.
const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("src/kinds/pardes_addon.h"), .target = target, .optimize = optimize }).createModule();
+ // ...and what an addon in Zig imports over it (src/kinds/addon.zig).
+ const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} });
+ // The image addon (addons/image/image.zig over stb_image, stb.c),
+ // installed by its step and handed by path to every test that opens a
+ // picture.
+ const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = c_optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} });
+ image_mod.addIncludePath(zstbi_dep.path("libs/stbi"));
+ image_mod.addCSourceFile(.{ .file = b.path("addons/image/stb.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ const image_addon = b.addLibrary(.{ .name = "image", .linkage = .dynamic, .root_module = image_mod });
for (core_mods) |m| wireCore(m, .{
.kind = kind_mod,
.themes = themes_mod,
@@ -1585,10 +1586,10 @@ pub fn build(b: *std.Build) void {
// An addon's own test: `--addon-test` over the fake (the template)
// and the snake (a shipped example, built but not installed), each
// with its script, compared with what it printed when written.
- const addon_test_step = b.step("addon-test", "pardes --addon-test over the fake, snake and pdf addons, against addons/*/*.out");
- const snake_lib = b.addLibrary(.{ .name = "snake", .linkage = .dynamic, .root_module = b.createModule(.{ .target = target, .optimize = optimize, .link_libc = true }) });
- snake_lib.root_module.addIncludePath(b.path("src/kinds"));
- snake_lib.root_module.addCSourceFile(.{ .file = b.path("addons/snake/snake.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ const addon_test_step = b.step("addon-test", "pardes --addon-test over the fake, snake and pdf addons, against addons/*/*.out, and the Zig addons' own tests");
+ const snake_mod = b.createModule(.{ .root_source_file = b.path("addons/snake/snake.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "addon", .module = addon_mod }} });
+ const snake_lib = b.addLibrary(.{ .name = "snake", .linkage = .dynamic, .root_module = snake_mod });
+ for ([_]*std.Build.Module{ snake_mod, image_mod }) |m| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step);
// ...and the pdf addon's, which mupdf-check runs too (its script
// opens docs/design.pdf, from the build root).
const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ pdf_addon, "addons/pdf/pdf" } };
diff --git a/docs/shared-libs.md b/docs/shared-libs.md
index e730efbd..384dc2f1 100644
--- a/docs/shared-libs.md
+++ b/docs/shared-libs.md
@@ -45,7 +45,7 @@ are the binaries before both addons.
## Image panes became an addon (2026-11-06)
-`lib/pardes/addons/image.so` (addons/image/image.c) decodes image panes with
+`lib/pardes/addons/image.so` (addons/image/image.zig and stb.c) decodes image panes with
its own stb_image, PNG, JPEG and inflate included: the binaries keep none of
stb_image but its resize (a kitty PNG's downscale; the decoder and the writer
are patched out of zstbi.c), and a kitty `f=100` PNG is wuffs's alone. A
diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ
index ff035fac..c66de5ad 100644
--- a/docs/typ/reference.typ
+++ b/docs/typ/reference.typ
@@ -980,9 +980,15 @@ in C or anything that speaks C, and links nothing of pardes: the records
are the header's, and what pardes does for it (an allocation from the
pane's arena, memory that outlives a call, a job off the loop, a Look or an
Exec, a message, a new text pane, its selection) it is handed at load.
-`addons/fake/fake.c` uses every function and `addons/snake/snake.c` is a
-game in it; a kind with only a head and `paint` is a valid one. Pictures
-are an addon too, `addons/image/image.c` (PNG, JPEG, GIF, BMP, PPM, PGM and
+`addons/fake/fake.c` uses every function; a kind with only a head and
+`paint` is a valid one. In Zig, `src/kinds/addon.zig` (over the same
+header, and nothing of the core) makes the `pa_ops` from a struct of the
+functions a kind has (`export const pardes_addon = addon.ops(Snake);`),
+with the pane's arena as a `std.mem.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` (`zig build addon-test` runs them):
+`addons/snake/snake.zig` is a game in it. Pictures
+are an addon too, `addons/image/image.zig` (PNG, JPEG, GIF, BMP, PPM, PGM and
TGA through stb_image, at most 1280 pixels a side), which `zig build image`
installs as `<prefix>/lib/pardes/addons/image.so`, and so are PDFs,
`addons/pdf/pdf.c` over MuPDF (its pages rendered on jobs, two at once),
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
diff --git a/test/panes.zig b/test/panes.zig
index d16de109..d1c8af02 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -2245,7 +2245,7 @@ const OutputTests = struct {
}
};
-/// The image addon (addons/image/image.c), loaded as `Addon load` loads it.
+/// The image addon (addons/image/image.zig), loaded as `Addon load` loads it.
const ImageTests = struct {
fn load(p: *Pardes) u8 {
pardes.Addon.perform(p, .load, 0, @import("test_addons").image);
diff --git a/test/session.zig b/test/session.zig
index 7399ab0f..8c71cfb1 100644
--- a/test/session.zig
+++ b/test/session.zig
@@ -13,7 +13,7 @@ const Reply = pardes.ctlfs.Reply;
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
pub const Session = struct {
- /// The image addon (addons/image/image.c), as the build installs it.
+ /// The image addon (addons/image/image.zig), as the build installs it.
pub const image_addon = @import("session_options").image_addon;
/// The fake addon, and its copies built wrong (build.zig).
pub const fake_addons = struct {