From e9b4f0e1c37c5c1f369d152d0a70b672433c94b5 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 6 Nov 2026 00:02:06 -0300 Subject: kinds #3, addons: src/Addon.zig loads a library that brings a kind (each *.so of $XDG_DATA_HOME/pardes/addons, then /lib/pardes/addons at start; `Addon load `, `Addon unload ` refused while a pane of the kind is open, `Addon reload `; bare, the kinds here), from a copy of its bytes in a memfd so a reload is the file as it is now, its BLAKE3 kept; a load is marked on disk while it runs and a start that finds the mark skips that library until `Addon load` asks again; the crash record says `in addon , `; Kind.zig checks a head before taking it (size, ABI major, a paint, a name, words, leader paths and extensions none else has, the core's or another addon's: refused whole, in words; ctl with words; jobs paired), and a reload checks the new library beside the old (the old kind's own names looked past), opens every pane of the kind again in a fresh arena from the old state's dump and the new load (or its place and its words' last values), and only then swaps, dropping the old library's jobs; any failure says why and leaves the old one running; /addons lists ` static|loaded|refused: why`; the tail: an addon's words join /commands and Help marked `(addon )`, run from exec, a ctl and a leader path after the core's, a word that opens its kind opens a pane of it from anywhere and any other goes to a pane of its kind, its ctl read ends with the kind's fields, its body is the kind's text over 9P, its keys (all but Esc, as a raw terminal's) and clicks go to it, a 9P request steps its ticks and jobs as an event does; the dump record keeps the words' last values; the size of every record is asserted in the header and seen again from Kind.zig; pa_api gains `seed` (a number the same for a pane on every machine, for a game's board), and a zero cell is an unpainted one (PA_PAINTED, which pa_put sets), so a window is cleared by one memset; the hook in the settings agent's files is one arm each: exec.zig executeBuiltinLine's miss goes to Kind.runLine, builtins.zig gains the Addon word, config.zig its leader path (none); the tree gains /addons (README and reference.typ's tree, and an Addons section), builtins-.json the Addon row; no golden changes; tests: a crash mark skipped at two starts and cleared by a load (Addon.zig), the tree listing tests (tree.zig and the process suite's) with /addons; the README keeps its 45 lines Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/Addon.zig | 322 ++++++++++++++++++++++++++++++++++++ src/Core.zig | 4 +- src/Effect.zig | 6 + src/Event.zig | 3 + src/Kind.zig | 413 ++++++++++++++++++++++++++++++++++++----------- src/Output.zig | 17 ++ src/builtins.zig | 10 ++ src/config.zig | 1 + src/crash.zig | 2 + src/exec.zig | 2 +- src/fs-help.txt | 4 +- src/host_io.zig | 1 + src/keys.zig | 13 ++ src/kinds/pardes_addon.h | 27 +++- src/look.zig | 1 - src/mouse.zig | 19 +++ src/ninep/ctl.zig | 17 +- src/ninep/pane.zig | 2 + src/ninep/tree.zig | 27 ++-- src/pardes.zig | 2 + src/wire.zig | 6 +- 21 files changed, 786 insertions(+), 113 deletions(-) create mode 100644 src/Addon.zig (limited to 'src') diff --git a/src/Addon.zig b/src/Addon.zig new file mode 100644 index 00000000..2a963cb2 --- /dev/null +++ b/src/Addon.zig @@ -0,0 +1,322 @@ +//! Addons: shared libraries that each bring a kind of pane (Kind.zig), +//! the host's side of it. Each `*.so` of `$XDG_DATA_HOME/pardes/addons` +//! and then `/lib/pardes/addons` at start, and `Addon load +//! ` after. An addon exports `pardes_addon`, a `pa_ops` +//! (src/kinds/pardes_addon.h); Kind.register checks it and takes it in. +//! +//! An addon runs in this process: one that crashes takes the session +//! with it. So a load is marked first (`addon-loading` in the data +//! directory, holding its path) and unmarked after; a start that finds +//! the mark moves it to `addon-crashed`, and skips that addon at every +//! start until `Addon load` asks for it by path again. +const std = @import("std"); +const Kind = @import("Kind.zig"); +const dump = @import("dump.zig"); +const pardes = @import("pardes.zig"); + +const Why = Kind.Buf(160); + +/// The core's `addon` effect performed, its answer the `addon` event: +/// `arg` a path to load (or reload), or the kind's name to let go. +pub fn perform(p: *pardes.Pardes, op: Kind.AddonOp, pane: u8, arg: []const u8) void { + var why: Why = .{}; + const ok = switch (op) { + .load => load(arg, &why), + .unload => ok: { + why.set(arg); + break :ok unload(arg); + }, + .reload => ok: { + if (!reload(p, arg, &why)) break :ok false; + why.set(arg); + break :ok true; + }, + }; + p.update(.{ .addon = .{ .op = op, .pane = pane, .ok = ok, .text = why.slice() } }); +} + +/// The addon at `path` loaded and its kind taken in: true, or false +/// with why not in `why`. +pub fn load(path: []const u8, why: *Why) bool { + var data_buf: [4096]u8 = undefined; + return loadMarked(dataDir(&data_buf), path, why); +} + +/// Where the crash mark goes: the data directory, none in a test (a +/// test's loads are no user's). +fn dataDir(buf: []u8) []const u8 { + if (@import("builtin").is_test) return ""; + return dump.defaultDirectory(buf) orelse ""; +} + +fn loadMarked(data: []const u8, path: []const u8, why: *Why) bool { + if (path.len >= 4096) return fail(why, "{s}: the path is too long", .{path}); + Kind.forgetRefused(path); + mark(data, path); + defer unmark(); + var hash: [32]u8 = undefined; + const lib = open(path, &hash, why) orelse { + Kind.note(path, why.slice()); + return false; + }; + const sym = std.c.dlsym(lib, "pardes_addon") orelse { + _ = std.c.dlclose(lib); + Kind.note(path, "refused: it has no pardes_addon"); + return fail(why, "{s}: refused: it has no pardes_addon", .{std.fs.path.basename(path)}); + }; + const ops: *const Kind.Ops = @ptrCast(@alignCast(sym)); + if (Kind.registerHashed(ops, path, lib, hash)) |refused| { + _ = std.c.dlclose(lib); + return fail(why, "{s}: {s}", .{ std.fs.path.basename(path), refused }); + } + why.set(Kind.headName(ops)); + return true; +} + +/// The library at `path` opened from a copy of its bytes in memory, so a +/// reload of a path already open is the file as it is now (dlopen hands +/// back the handle it has for a path it has), and their BLAKE3 in `hash`. +fn open(path: []const u8, hash: *[32]u8, why: *Why) ?*anyopaque { + var z: [4096]u8 = undefined; + const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return failNull(why, "the path is too long", .{}); + const f = std.c.fopen(path_z, "r") orelse return failNull(why, "cannot read it", .{}); + defer _ = std.c.fclose(f); + const gpa = std.heap.page_allocator; + var bytes: std.ArrayList(u8) = .empty; + defer bytes.deinit(gpa); + var chunk: [64 << 10]u8 = undefined; + while (true) { + const n = std.c.fread(&chunk, 1, chunk.len, f); + if (n == 0) break; + bytes.appendSlice(gpa, chunk[0..n]) catch return failNull(why, "out of memory", .{}); + if (bytes.items.len > 256 << 20) return failNull(why, "it is over 256 MiB", .{}); + } + std.crypto.hash.Blake3.hash(bytes.items, hash, .{}); + const fd = std.c.memfd_create("pardes-addon", 0); + if (fd < 0) return failNull(why, "no memfd for it", .{}); + // shortcut: the fd stays open while the process lives. dlopen hands + // back the library it has for a path it has, and /proc/self/fd/ of + // a closed fd is the next load's path too: an fd kept is a name kept + // (one an addon load; a dev loop of a hundred reloads is a hundred). + errdefer _ = std.c.close(fd); + var off: usize = 0; + while (off < bytes.items.len) { + const n = std.c.write(fd, bytes.items.ptr + off, bytes.items.len - off); + if (n <= 0) return failNull(why, "cannot copy it", .{}); + off += @intCast(n); + } + var proc: [64]u8 = undefined; + const at = std.fmt.bufPrintSentinel(&proc, "/proc/self/fd/{d}", .{fd}, 0) catch unreachable; + return std.c.dlopen(at, .{ .NOW = true }) orelse { + _ = std.c.close(fd); + return failNull(why, "{s}", .{if (std.c.dlerror()) |e| std.mem.span(e) else "cannot load it"}); + }; +} + +fn failNull(why: *Why, comptime fmt: []const u8, args: anytype) ?*anyopaque { + _ = why.print(fmt, args); + return null; +} + +/// `Addon reload `: its library loaded again from its path and +/// swapped in, or the old one left running and why not. +pub fn reload(p: *pardes.Pardes, name: []const u8, why: *Why) bool { + var path: [256]u8 = undefined; + const at = for (Kind.kinds()) |*l| { + if (l.ops != null and std.mem.eql(u8, l.nameOf(), name)) { + @memcpy(path[0..l.path.len], l.path.slice()); + break path[0..l.path.len]; + } + } else return fail(why, "no addon brought kind {s}", .{name}); + var data_buf: [4096]u8 = undefined; + mark(dataDir(&data_buf), at); + defer unmark(); + var hash: [32]u8 = undefined; + const lib = open(at, &hash, why) orelse return false; + const sym = std.c.dlsym(lib, "pardes_addon") orelse { + _ = std.c.dlclose(lib); + return fail(why, "refused: it has no pardes_addon", .{}); + }; + var old: ?*anyopaque = null; + if (!Kind.replace(p, name, @ptrCast(@alignCast(sym)), lib, hash, &old, why)) { + _ = std.c.dlclose(lib); + return false; + } + if (old) |o| _ = std.c.dlclose(o); + return true; +} + +/// Every addon let go, and the refused forgotten: the kinds a process +/// starts with (a test's session ends so, the kinds being the process's). +pub fn unloadAll() void { + for (0..Kind.max_kinds) |_| { + const l = for (Kind.kinds()) |*k| { + if (k.lib != null and k.ops != null) break k; + } else break; + var name: [16]u8 = l.name; + _ = unload(std.mem.sliceTo(&name, 0)); + } + for (0..Kind.max_kinds) |_| { + const l = for (Kind.kinds()) |*k| { + if (k.ops == null) break k; + } else break; + var path: [256]u8 = undefined; + @memcpy(path[0..l.path.len], l.path.slice()); + Kind.forgetRefused(path[0..l.path.len]); + } +} + +/// The kind `name` out, its library closed: false when none is loaded. +/// The caller has seen that no pane of it is open. +pub fn unload(name: []const u8) bool { + const gone = Kind.unregister(name) orelse return false; + if (gone.lib) |lib| _ = std.c.dlclose(lib); + return true; +} + +fn fail(why: *Why, comptime fmt: []const u8, args: anytype) bool { + _ = why.print(fmt, args); + return false; +} + +/// Every library of the two directories, in name order each, the user's +/// first (a kind of a name taken is refused, and listed so). A library +/// that crashed at its last load is listed, not loaded. +pub fn scan() void { + var data_buf: [4096]u8 = undefined; + const data = dataDir(&data_buf); + const crashed = crashedPath(data); + var dir_buf: [4096]u8 = undefined; + if (data.len > 0) scanDir(data, std.fmt.bufPrint(&dir_buf, "{s}/addons", .{data}) catch "", crashed.slice()); + var exe: [4096]u8 = undefined; + const n = std.c.readlink("/proc/self/exe", &exe, exe.len); + if (n > 0) { + const bin_dir = std.fs.path.dirname(exe[0..@intCast(n)]) orelse return; + const prefix = std.fs.path.dirname(bin_dir) orelse return; + scanDir(data, std.fmt.bufPrint(&dir_buf, "{s}/lib/pardes/addons", .{prefix}) catch "", crashed.slice()); + } +} + +fn scanDir(data: []const u8, dir: []const u8, crashed: []const u8) void { + if (dir.len == 0) return; + var z: [4096]u8 = undefined; + const dz = std.fmt.bufPrintSentinel(&z, "{s}", .{dir}, 0) catch return; + const d = std.c.opendir(dz) orelse return; + defer _ = std.c.closedir(d); + var names: [32][256]u8 = undefined; + var lens: [32]usize = undefined; + var count: usize = 0; + while (std.c.readdir(d)) |e| { + const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&e.name)), 0); + if (!std.mem.endsWith(u8, name, ".so") or name.len > 255 or count == names.len) continue; + @memcpy(names[count][0..name.len], name); + lens[count] = name.len; + count += 1; + } + var order: [32]usize = undefined; + for (0..count) |i| order[i] = i; + std.mem.sort(usize, order[0..count], Sort{ .names = &names, .lens = &lens }, Sort.lt); + for (order[0..count]) |i| { + var full: [4096]u8 = undefined; + const path = std.fmt.bufPrint(&full, "{s}/{s}", .{ dir, names[i][0..lens[i]] }) catch continue; + if (crashed.len > 0 and std.mem.eql(u8, path, crashed)) { + Kind.note(path, "skipped: it crashed its last load (Addon load asks for it again)"); + continue; + } + var why: Why = .{}; + _ = loadMarked(data, path, &why); + } +} + +const Sort = struct { + names: *const [32][256]u8, + lens: *const [32]usize, + fn lt(s: Sort, a: usize, b: usize) bool { + return std.mem.lessThan(u8, s.names[a][0..s.lens[a]], s.names[b][0..s.lens[b]]); + } +}; + +// ---- the crash mark ---- + +var marked: [4096]u8 = undefined; +var marked_len: usize = 0; + +fn markPath(buf: []u8, data: []const u8, comptime name: []const u8) ?[:0]const u8 { + return std.fmt.bufPrintSentinel(buf, "{s}/" ++ name, .{data}, 0) catch null; +} + +/// The load of `path` under way, on disk until `unmark`. +fn mark(data: []const u8, path: []const u8) void { + if (data.len == 0) return; + var buf: [4096]u8 = undefined; + const at = markPath(&buf, data, "addon-loading") orelse return; + const f = std.c.fopen(at, "w") orelse return; + _ = std.c.fwrite(path.ptr, 1, path.len, f); + _ = std.c.fclose(f); + @memcpy(marked[0..at.len], at); + marked_len = at.len; + // `Addon load` of the one that crashed asks for it again. + var cbuf: [4096]u8 = undefined; + const crashed = markPath(&cbuf, data, "addon-crashed") orelse return; + const was = readSmall(crashed); + if (std.mem.eql(u8, was.slice(), path)) _ = std.c.unlink(crashed); +} + +fn unmark() void { + if (marked_len == 0) return; + marked[marked_len] = 0; + _ = std.c.unlink(@ptrCast(&marked)); + marked_len = 0; +} + +/// The library that crashed its session's load: a mark left by a start +/// that never finished one becomes `kind-crashed`, which it stays. +fn crashedPath(data: []const u8) Kind.Buf(4096) { + var out: Kind.Buf(4096) = .{}; + if (data.len == 0) return out; + var lbuf: [4096]u8 = undefined; + var cbuf: [4096]u8 = undefined; + const loading = markPath(&lbuf, data, "addon-loading") orelse return out; + const crashed = markPath(&cbuf, data, "addon-crashed") orelse return out; + if (std.c.access(loading, 0) == 0) _ = std.c.rename(loading, crashed); + out.set(readSmall(crashed).slice()); + return out; +} + +fn readSmall(path: [*:0]const u8) Kind.Buf(4096) { + var out: Kind.Buf(4096) = .{}; + const f = std.c.fopen(path, "r") orelse return out; + defer _ = std.c.fclose(f); + const n = std.c.fread(&out.bytes, 1, out.bytes.len, f); + out.len = @intCast(n); + return out; +} + +test "a load that never finished is skipped at the next start, and every start after, until a load asks for it" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const data = buf[0..try tmp.dir.realPath(std.testing.io, &buf)]; + try tmp.dir.createDirPath(std.testing.io, "addons"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "addons/crashy.so", .data = "not a library" }); + var lib_buf: [4096]u8 = undefined; + const lib = try std.fmt.bufPrint(&lib_buf, "{s}/addons/crashy.so", .{data}); + // The mark a load leaves when its session dies in it. + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "addon-loading", .data = lib }); + var dir_buf: [4096]u8 = undefined; + const dir = try std.fmt.bufPrint(&dir_buf, "{s}/addons", .{data}); + for (0..2) |_| { + scanDir(data, dir, crashedPath(data).slice()); + const last = Kind.kinds()[Kind.kinds().len - 1]; + try std.testing.expectEqualStrings(lib, last.path.slice()); + try std.testing.expect(std.mem.startsWith(u8, last.why.slice(), "skipped: it crashed its last load")); + Kind.forgetRefused(lib); + } + // Asked for by name, it is tried again (and refused here for what it is). + var why: Why = .{}; + try std.testing.expect(!loadMarked(data, lib, &why)); + try std.testing.expect(std.mem.indexOf(u8, Kind.kinds()[Kind.kinds().len - 1].why.slice(), "skipped") == null); + try std.testing.expectError(error.FileNotFound, tmp.dir.access(std.testing.io, "addon-crashed", .{})); + try std.testing.expectError(error.FileNotFound, tmp.dir.access(std.testing.io, "addon-loading", .{})); + Kind.forgetRefused(lib); +} diff --git a/src/Core.zig b/src/Core.zig index 54f0233e..5c68a5af 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -1192,7 +1192,7 @@ pub fn dropPendingWrite(p: *Pardes, id: usize) void { pub fn postEvent(p: *Pardes, ev: Event) void { switch (ev) { .key => |k| std.debug.assert(k.text.len == 0), - .output, .paste, .lsp_resp, .pipe_resp, .search, .file_changed, .command => unreachable, + .output, .paste, .lsp_resp, .pipe_resp, .search, .file_changed, .command, .addon => unreachable, else => {}, } if (p.in_len == p.in_q.len) return; @@ -1483,6 +1483,7 @@ pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { // step does: the cursor and scroll reconciled, the scripted panes // told, and the panes it made announced to /log now rather than at // the end of whatever the editor does next. + pardes.Kind.step(p); p.sync(); p.fsReport(); // A /focus write moves the keyboard as a click does: the programs @@ -1622,6 +1623,7 @@ pub fn update(p: *Pardes, ev: Event) void { if (focused) if (p.host.vtable.newer_build) |f| if (f(p.host.ctx)) p.setMessage(p.active, newer_build_words); }, .handed => |h| p.handover.finish(p, h.seq, h.to, h.failure), + .addon => |a| pardes.Kind.landed(p, a.op, a.pane, a.ok, a.text), .frontend => |f| { p.frontend = f; }, diff --git a/src/Effect.zig b/src/Effect.zig index ba8e5d60..3ec87ff1 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -73,6 +73,10 @@ pub const Effect = union(enum) { /// The pane receives the completion/error message from the native host. dump_themes: struct { pane: u8 }, detach: struct { pane: u8 }, + /// An addon loaded, let go, or let go and loaded again (Addon.zig): + /// `arg` its path, or for unload its kind's name. Answered by an + /// `addon` event. + addon: struct { op: @import("Kind.zig").AddonOp, pane: u8, arg: Buf(effect_path_cap) }, quit, pub fn Buf(comptime n: usize) type { @@ -231,6 +235,8 @@ pub fn perform(p: *Pardes, e: Effect) void { f(p.host.ctx) else p.reportError(d.pane, "detach", error.NotAttached), + // dlopen is the same on every host, so none has a method of its own. + .addon => |a| @import("Addon.zig").perform(p, a.op, a.pane, a.arg.slice()), // the loop's own condition; a host tears down after its own loop .quit => p.quit = true, } diff --git a/src/Event.zig b/src/Event.zig index 6b2bb8a2..88407c9f 100644 --- a/src/Event.zig +++ b/src/Event.zig @@ -142,6 +142,9 @@ pub const Event = union(enum) { /// (docs/next-daemon.md, "Phase 6: GUI replica notes"): a window, which /// draws pictures itself and takes the GUI's own words, or a terminal. frontend: Frontend, + /// How the host's `addon` effect went: `text` the kind's name, or + /// why not (Kind.landed). Borrowed for the step. + addon: struct { op: @import("Kind.zig").AddonOp, pane: u8, ok: bool, text: []const u8 }, tick, }; diff --git a/src/Kind.zig b/src/Kind.zig index 24448aa5..7f9284c0 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -27,6 +27,17 @@ pub const Ops = c.pa_ops; pub const abi_major: u32 = c.PA_ABI_MAJOR; pub const abi: u32 = c.PA_ABI; +// The header's own sizes (src/kinds/pardes_addon.h's _Static_asserts), seen +// from here: the records the core reads are the ones addons are built to. +comptime { + if (@sizeOf(usize) == 8) for (.{ + .{ c.pa_cell, 20 }, .{ c.pa_window, 24 }, .{ c.pa_rect, 16 }, .{ c.pa_cells, 8 }, + .{ c.pa_placement, 72 }, .{ c.pa_paint, 120 }, .{ c.pa_key, 8 }, .{ c.pa_mouse, 10 }, + .{ c.pa_api, 64 }, .{ c.pa_out, 16 }, .{ c.pa_word, 40 }, .{ c.pa_head, 56 }, + .{ c.pa_ops, 192 }, + }) |r| if (@sizeOf(r[0]) != r[1]) @compileError(std.fmt.comptimePrint("{s} is {d} bytes, the header says {d}", .{ @typeName(r[0]), @sizeOf(r[0]), r[1] })); +} + // ---- the kinds this process has ---- /// A kind as /addons lists it: an addon's loaded, one compiled in, or an @@ -40,6 +51,8 @@ pub const Listed = struct { /// Its addon's handle (Addon.zig), none for one compiled in. lib: ?*anyopaque = null, path: Buf(256) = .{}, + /// The library file's BLAKE3, as it was loaded. + hash: ?[32]u8 = null, why: Buf(128) = .{}, pub fn nameOf(l: *const Listed) []const u8 { @@ -74,23 +87,26 @@ pub fn kinds() []const Listed { /// The kind named `name` (`image`), if this process has it. pub fn byName(name: []const u8) ?*const Ops { - for (kinds()) |*l| if (l.ops != null and std.mem.eql(u8, l.nameOf(), name)) return l.ops; + for (kinds()) |*l| if (l.ops != null and l.ops != skipping and std.mem.eql(u8, l.nameOf(), name)) return l.ops; return null; } +/// The kind a reload replaces, which its successor's checks look past. +var skipping: ?*const Ops = null; + /// The kind that opens `path`, by its extension (any case). pub fn forPath(path: []const u8) ?*const Ops { statics(); const dot = std.mem.lastIndexOfScalar(u8, path, '.') orelse return null; if (std.mem.indexOfScalarPos(u8, path, dot, '/') != null) return null; - for (exts[0..nexts]) |e| if (std.ascii.eqlIgnoreCase(e.ext, path[dot..])) return e.ops; + for (exts[0..nexts]) |e| if (e.ops != skipping and std.ascii.eqlIgnoreCase(e.ext, path[dot..])) return e.ops; return null; } /// A kind's word `name`, the tail's linear scan. pub fn word(name: []const u8) ?Word { statics(); - for (words[0..nwords]) |w| if (std.mem.eql(u8, std.mem.span(w.w.name), name)) return w; + for (words[0..nwords]) |w| if (w.ops != skipping and std.mem.eql(u8, std.mem.span(w.w.name), name)) return w; return null; } @@ -105,7 +121,7 @@ pub fn leader(keys: []const u8) union(enum) { none, prefix, word: Word } { statics(); var begun = false; for (words[0..nwords]) |w| { - if (w.w.leader == null) continue; + if (w.w.leader == null or w.ops == skipping) continue; const path = std.mem.span(w.w.leader); if (std.mem.eql(u8, path, keys)) return .{ .word = w }; if (std.mem.startsWith(u8, path, keys)) begun = true; @@ -132,9 +148,16 @@ pub fn headName(ops: *const Ops) []const u8 { /// `taken(word)` says whether the core has a word of that name, and /// `leader_taken(path)` a leader path that path begins or is begun by. pub fn register(ops: *const Ops, path: []const u8, lib: ?*anyopaque) ?[]const u8 { + return registerHashed(ops, path, lib, null); +} + +pub fn registerHashed(ops: *const Ops, path: []const u8, lib: ?*anyopaque, hash: ?[32]u8) ?[]const u8 { + // The kinds compiled in first: the checks below would list them under + // this one's entry. + statics(); if (nlisted == max_kinds) return "refused: no room for another kind"; const l = &listed[nlisted]; - l.* = .{ .lib = lib }; + l.* = .{ .lib = lib, .hash = hash }; l.path.set(path); const why = check(ops, l) orelse { l.name = ops.head.name; @@ -147,15 +170,7 @@ pub fn register(ops: *const Ops, path: []const u8, lib: ?*anyopaque) ?[]const u8 return l.why.slice(); }; l.ops = ops; - for (headWords(ops)) |*w| { - words[nwords] = .{ .ops = ops, .w = w }; - nwords += 1; - } - var it = std.mem.tokenizeScalar(u8, extsOf(ops), ' '); - while (it.next()) |ext| { - exts[nexts] = .{ .ext = ext, .ops = ops }; - nexts += 1; - } + addTail(ops); l.why.set(if (lib == null) "static" else "loaded"); nlisted += 1; return null; @@ -171,6 +186,33 @@ pub fn register(ops: *const Ops, path: []const u8, lib: ?*anyopaque) ?[]const u8 return l.why.slice(); } +fn addTail(ops: *const Ops) void { + for (headWords(ops)) |*w| { + words[nwords] = .{ .ops = ops, .w = w }; + nwords += 1; + } + var it = std.mem.tokenizeScalar(u8, extsOf(ops), ' '); + while (it.next()) |ext| { + exts[nexts] = .{ .ext = ext, .ops = ops }; + nexts += 1; + } +} + +fn dropTail(ops: *const Ops) void { + var n: usize = 0; + for (words[0..nwords]) |w| if (w.ops != ops) { + words[n] = w; + n += 1; + }; + nwords = n; + n = 0; + for (exts[0..nexts]) |e| if (e.ops != ops) { + exts[n] = e; + n += 1; + }; + nexts = n; +} + fn check(ops: *const Ops, l: *Listed) ?[]const u8 { const h = &ops.head; if (h.size < @sizeOf(c.pa_head)) return "refused: its head is too short for this pardes"; @@ -193,7 +235,7 @@ fn check(ops: *const Ops, l: *Listed) ?[]const u8 { if (w.leader != null) { const keys = std.mem.span(w.leader); if (keys.len == 0 or coreLeader(keys) or leader(keys) != .none) return l.why.print("refused: leader SPC {s} is taken", .{keys}); - for (words[0..nwords]) |o| if (o.w.leader != null and std.mem.startsWith(u8, keys, std.mem.span(o.w.leader))) return l.why.print("refused: leader SPC {s} is taken", .{keys}); + for (words[0..nwords]) |o| if (o.ops != skipping and o.w.leader != null and std.mem.startsWith(u8, keys, std.mem.span(o.w.leader))) return l.why.print("refused: leader SPC {s} is taken", .{keys}); } } var it = std.mem.tokenizeScalar(u8, extsOf(ops), ' '); @@ -224,19 +266,7 @@ pub fn unregister(name: []const u8) ?Listed { if (l.ops != null and std.mem.eql(u8, l.nameOf(), name)) break i; } else return null; const gone = listed[at]; - const ops = gone.ops.?; - var n: usize = 0; - for (words[0..nwords]) |w| if (w.ops != ops) { - words[n] = w; - n += 1; - }; - nwords = n; - n = 0; - for (exts[0..nexts]) |e| if (e.ops != ops) { - exts[n] = e; - n += 1; - }; - nexts = n; + dropTail(gone.ops.?); std.mem.copyForwards(Listed, listed[at .. nlisted - 1], listed[at + 1 .. nlisted]); nlisted -= 1; return gone; @@ -262,13 +292,14 @@ pub fn forgetRefused(path: []const u8) void { nlisted = n; } -/// /addons: `name version abi state [path]` a line. -pub fn list(out: *std.ArrayList(u8), gpa: std.mem.Allocator) !void { +/// /addons: ` +/// static|loaded|refused: why` a line (`-` for no path, no hash). +pub fn list(p: *const Pardes, out: *std.ArrayList(u8), gpa: std.mem.Allocator) !void { for (kinds()) |*l| { const name = if (l.nameOf().len > 0) l.nameOf() else std.fs.path.basename(l.path.slice()); - try out.print(gpa, "{s} {d} {d}.{d} {s}", .{ name, l.version, l.abi >> 16, l.abi & 0xffff, l.why.slice() }); - if (l.path.len > 0) try out.print(gpa, " {s}", .{l.path.slice()}); - try out.append(gpa, '\n'); + try out.print(gpa, "{s} {d} {d}.{d} {d} {s} ", .{ name, l.version, l.abi >> 16, l.abi & 0xffff, if (l.ops != null) openPanes(p, name) else 0, if (l.path.len > 0) l.path.slice() else "-" }); + if (l.hash) |h| try out.print(gpa, "{x}", .{h}) else try out.append(gpa, '-'); + try out.print(gpa, " {s}\n", .{l.why.slice()}); } } @@ -301,6 +332,9 @@ pub const Slot = struct { where_text: Buf(32) = .{}, /// An error the kind said while opening: the open refused. refused: Buf(96) = .{}, + /// Its words' last values, a `Word arg` line each, which a kind with + /// no `dump` is given again when its pane comes back. + values: Buf(256) = .{}, pub fn nameOf(s: *const Slot) []const u8 { return std.mem.sliceTo(&s.name, 0); @@ -336,15 +370,16 @@ pub const Slot = struct { where: []const u8 = "", art: Placement.Art = .{}, record: ?[]const u8 = null, + values: []const u8 = "", }; pub fn dumpWrite(s: *const Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { var place: [32]u8 = undefined; - var r: Record = .{ .name = s.nameOf(), .version = s.version, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice() }; + var r: Record = .{ .name = s.nameOf(), .version = s.version, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice(), .values = s.values.slice() }; var owned: ?[]u8 = null; defer if (owned) |o| gpa.free(o); if (s.ops) |ops| { - const prev = enter(null, 0, @constCast(s)); + const prev = enter(null, 0, @constCast(s), "dump"); defer leave(prev); if (ops.where) |f| r.where = place[0..@min(place.len, f(s.st, &place, place.len))]; if (ops.dump) |f| { @@ -384,6 +419,7 @@ pub const Slot = struct { @memcpy(out.name[0..@min(15, r.name.len)], r.name[0..@min(15, r.name.len)]); out.path = try gpa.dupe(u8, r.path); out.where_text.set(r.where); + out.values.set(r.values); if (r.record) |rec| out.record = try gpa.dupe(u8, rec); if (byName(out.nameOf())) |ops| reopen(null, 0, out, ops); } @@ -405,7 +441,7 @@ pub const Slot = struct { /// `load` with its record, or `address` with its place. A refused load /// keeps it a placeholder, its record kept. fn reopen(p: ?*Pardes, id: usize, s: *Slot, ops: *const Ops) void { - const prev = enter(p, id, s); + const prev = enter(p, id, s, "open"); defer leave(prev); const path_z = s.arena.allocator().dupeSentinel(u8, s.path, 0) catch return; current.?.opening = true; @@ -423,9 +459,16 @@ fn reopen(p: ?*Pardes, id: usize, s: *Slot, ops: *const Ops) void { if (s.record == null and s.where_text.len > 0) if (ops.address) |f| { _ = f(st, s.where_text.slice().ptr, @intCast(s.where_text.len)); }; + // ...and its words' last values, a kind with no record of its own. + if (s.record == null) if (ops.ctl) |f| { + var lines = std.mem.tokenizeScalar(u8, s.values.slice(), '\n'); + var reply: [160]u8 = undefined; + while (lines.next()) |line| _ = f(st, line.ptr, @intCast(line.len), &reply, reply.len); + }; s.ops = ops; s.st = st; s.version = ops.head.version; + if (ops.tick != null) s.next_tick = 1; if (s.record) |r| s.gpa.free(r); s.record = null; } @@ -442,39 +485,102 @@ pub fn reopenWaiting(p: *Pardes, name: []const u8) usize { return n; } -/// The panes of kind `name`, closed into placeholders (their records -/// kept by the kind's `dump`), so the kind can go. -pub fn makeWaiting(p: *Pardes, name: []const u8) void { - for (p.panes, 0..) |slot, id| if (slot) |pane| if (pane.addon) |s| if (s.ops != null and s.is(name)) { - const ops = s.ops.?; - const prev = enter(p, id, s); - defer leave(prev); - var place: [32]u8 = undefined; - if (ops.where) |f| s.where_text.set(place[0..@min(place.len, f(s.st, &place, place.len))]); - if (ops.dump) |f| keep: { - var cap: usize = 64 << 10; - while (true) { - const buf = s.gpa.alloc(u8, cap) catch break :keep; - const n = f(s.st, buf.ptr, @intCast(cap)); - if (n <= cap) { - s.record = s.gpa.realloc(buf, n) catch buf[0..n]; - break; - } - s.gpa.free(buf); - cap = n; - } +/// `Addon reload`: the kind `name` replaced by `ops` (a library loaded +/// beside the old one), or why not, nothing changed. Everything is +/// checked first: its head and collisions (the old kind's own looked +/// past), its name the same, and every open pane of the kind opened anew +/// in a fresh arena from the old state's `dump` (its `load`, else its +/// place and words); only then are the old states closed and the panes +/// swapped. A job the old library started is dropped, never handed to +/// the new one. The old library's handle comes back in `old_lib`. +pub fn replace(p: *Pardes, name: []const u8, ops: *const Ops, lib: *anyopaque, hash: [32]u8, old_lib: *?*anyopaque, why: *Buf(160)) bool { + const l = listedNamed(name) orelse return fail(why, "no addon brought kind {s}", .{name}); + const old = l.ops.?; + var trial: Listed = .{}; + skipping = old; + const refused = check(ops, &trial); + skipping = null; + if (refused) |r| return fail(why, "{s}", .{r}); + if (!std.mem.eql(u8, headName(ops), name)) return fail(why, "refused: its kind is now {s}, not {s}", .{ headName(ops), name }); + if (ops.init) |init| if (init(&api) != 0) return fail(why, "refused: its init failed", .{}); + var fresh: [pardes.MAX_PANES]?*Slot = @splat(null); + defer for (fresh) |f| if (f) |s| { + const gpa = s.gpa; + s.free(); + gpa.destroy(s); + }; + for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |s| if (s.ops == old) { + const n = s.gpa.create(Slot) catch return fail(why, "out of memory", .{}); + n.* = .{ .ops = null, .gpa = s.gpa, .arena = .init(s.gpa), .name = s.name, .version = s.version, .art = s.art, .values = s.values }; + fresh[id] = n; + n.path = s.gpa.dupe(u8, s.path) catch return fail(why, "out of memory", .{}); + // The old state's record, by the old library. + { + const prev = enter(p, id, s, "dump"); + defer leave(prev); + var place: [32]u8 = undefined; + if (old.where) |f| n.where_text.set(place[0..@min(place.len, f(s.st, &place, place.len))]); + if (old.dump != null and ops.load != null) n.record = dumpOf(s) catch return fail(why, "out of memory", .{}); } + reopen(p, id, n, ops); + if (n.ops == null) { + for (fresh) |f| if (f) |o| closeState(p, o); + return fail(why, "refused: a pane of it would not open again: {s}", .{if (n.refused.len > 0) n.refused.slice() else "its load refused the record"}); + } + }; + // Every pane opened: the old states go, the new take their slots. + for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |s| if (fresh[id]) |n| { for (&s.jobs) |*j| if (j.*) |job| { job.wait(); job.destroy(); j.* = null; }; - if (ops.close) |f| f(s.st); - _ = s.arena.reset(.free_all); - s.st = null; - s.ops = null; - s.next_tick = 0; + closeState(p, s); + s.arena.deinit(); + s.arena = n.arena; + n.arena = .init(n.gpa); + s.st = n.st; + s.ops = ops; + s.version = n.version; + s.next_tick = n.next_tick; + n.st = null; + n.ops = null; }; + dropTail(old); + addTail(ops); + old_lib.* = l.lib; + l.ops = ops; + l.lib = lib; + l.hash = hash; + l.version = ops.head.version; + l.abi = ops.head.abi; + return true; +} + +fn closeState(p: *Pardes, s: *Slot) void { + const ops = s.ops orelse return; + const f = ops.close orelse return; + const prev = enter(p, 0, s, "close"); + defer leave(prev); + f(s.st); +} + +fn fail(why: *Buf(160), comptime fmt: []const u8, args: anytype) bool { + _ = why.print(fmt, args); + return false; +} + +/// The kind's record of a slot's state, in `s.gpa`. +fn dumpOf(s: *Slot) ![]u8 { + const f = s.ops.?.dump.?; + var cap: usize = 64 << 10; + while (true) { + const buf = try s.gpa.alloc(u8, cap); + const n = f(s.st, buf.ptr, @intCast(cap)); + if (n <= cap) return s.gpa.realloc(buf, n) catch buf[0..n]; + s.gpa.free(buf); + cap = n; + } } pub fn openPanes(p: *const Pardes, name: []const u8) usize { @@ -500,7 +606,8 @@ pub fn open(p: *Pardes, id: usize, ops: *const Ops, path: ?[]const u8, bytes: ?[ s.path = try gpa.dupe(u8, path orelse ""); const pane = try p.newDocPane(id); pane.addon = s; - const prev = enter(p, id, s); + if (ops.tick != null) s.next_tick = 1; + const prev = enter(p, id, s, "open"); defer leave(prev); const path_z = try s.arena.allocator().dupeSentinel(u8, s.path, 0); current.?.opening = true; @@ -523,7 +630,7 @@ pub fn openFile(p: *Pardes, id: usize, ops: *const Ops, path: []const u8) !*Pane pub fn close(p: *Pardes, pane: *Pane) void { const s = pane.addon orelse return; if (s.ops) |ops| if (ops.close) |f| { - const prev = enter(p, 0, s); + const prev = enter(p, 0, s, "close"); defer leave(prev); f(s.st); }; @@ -550,19 +657,19 @@ pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pa return; }; const cells = arena.alloc(c.pa_cell, @as(usize, cols) * rows) catch return; - @memset(cells, std.mem.zeroInit(c.pa_cell, .{ .fg = c.PA_DEFAULT, .bg = c.PA_DEFAULT, .flags = c.PA_UNPAINTED })); + @memset(std.mem.sliceAsBytes(cells), 0); var places: [16]c.pa_placement = undefined; var out: c.pa_paint = std.mem.zeroInit(c.pa_paint, .{ .placements = &places, .cap = places.len }); const win = window(p, slot, pane, cells.ptr, cols, rows); { - const prev = enter(p, id, slot); + const prev = enter(p, id, slot, "paint"); defer leave(prev); current.?.painting = true; ops.paint.?(slot.st, &win, &out); } for (0..rows) |r| for (0..cols) |col| { const cell = &cells[r * cols + col]; - if (cell.flags & c.PA_UNPAINTED != 0) continue; + if (cell.flags & c.PA_PAINTED == 0) continue; const len = @min(cell.len, 7); s.set(x + @as(u16, @intCast(col)), y + @as(u16, @intCast(r)), if (len == 0) " " else cell.text[0..len], styleOf(cell, fg, bg)); }; @@ -628,7 +735,7 @@ pub fn prefix(p: *const Pardes, arena: std.mem.Allocator, pane: *const Pane) ![] var out: c.pa_paint = std.mem.zeroes(c.pa_paint); const win = window(p, slot, pane, undefined, 0, 0); { - const prev = enter(null, 0, slot); + const prev = enter(null, 0, slot, "paint"); defer leave(prev); current.?.painting = true; ops.paint.?(slot.st, &win, &out); @@ -645,7 +752,7 @@ pub fn key(p: *Pardes, id: usize, k: pardes.Key) bool { const f = (slot.ops orelse return false).key orelse return false; if (authorityOnly("a key into a kind's pane")) return true; const pk: c.pa_key = .{ .cp = k.cp, .ctrl = @intFromBool(k.ctrl), .alt = @intFromBool(k.alt), .shift = @intFromBool(k.shift), .pad = 0 }; - const prev = enter(p, id, slot); + const prev = enter(p, id, slot, "key"); defer leave(prev); return f(slot.st, &pk) != 0; } @@ -677,7 +784,7 @@ pub fn mouse(p: *Pardes, id: usize, m: pardes.Mouse, col: u16, row: u16) bool { .col = col, .row = row, }; - const prev = enter(p, id, slot); + const prev = enter(p, id, slot, "mouse"); defer leave(prev); return f(slot.st, &pm) != 0; } @@ -692,14 +799,14 @@ pub fn step(p: *Pardes) void { for (&slot.jobs) |*j| if (j.*) |job| if (job.done.load(.acquire)) { j.* = null; if (job.thread) |t| t.join(); - const prev = enter(p, id, slot); + const prev = enter(p, id, slot, "job_done"); ops.job_done.?(slot.st, job.token, job.out.ptr, @intCast(job.out.len)); leave(prev); job.destroy(); p.needs_frame = true; }; if (slot.next_tick != 0 and now >= slot.next_tick) if (ops.tick) |f| { - const prev = enter(p, id, slot); + const prev = enter(p, id, slot, "tick"); slot.next_tick = f(slot.st, now); leave(prev); p.needs_frame = true; @@ -718,20 +825,13 @@ pub fn wake(p: *const Pardes) ?u64 { return soonest; } -/// The pane's first tick, asked of a kind that has `tick` as it opens. -pub fn startTicking(p: *const Pardes, pane: *Pane) void { - const slot = pane.addon orelse return; - const ops = slot.ops orelse return; - if (ops.tick != null and slot.next_tick == 0) slot.next_tick = @max(1, p.clock.stepped_ns); -} - /// The pane's body as text (its 9P body), from the kind's `body`. pub fn body(pane: *const Pane, gpa: std.mem.Allocator) ![]u8 { const slot = pane.addon orelse return gpa.alloc(u8, 0); const ops = slot.ops orelse return gpa.alloc(u8, 0); const len_f = ops.body_len orelse return gpa.alloc(u8, 0); const read = ops.body orelse return gpa.alloc(u8, 0); - const prev = enter(null, 0, slot); + const prev = enter(null, 0, slot, "body"); defer leave(prev); const n: usize = @intCast(@min(len_f(slot.st), 64 << 20)); const buf = try gpa.alloc(u8, n); @@ -749,7 +849,7 @@ pub fn where(pane: *const Pane, buf: *[32]u8) []const u8 { const slot = pane.addon orelse return ""; const ops = slot.ops orelse return slot.where_text.slice(); const f = ops.where orelse return ""; - const prev = enter(null, 0, slot); + const prev = enter(null, 0, slot, "where"); defer leave(prev); return buf[0..@min(buf.len, f(slot.st, buf, buf.len))]; } @@ -759,7 +859,7 @@ pub fn address(p: *Pardes, id: usize, text: []const u8) bool { const slot = (p.panes[id] orelse return false).addon orelse return false; const f = (slot.ops orelse return false).address orelse return false; if (authorityOnly("an address in a kind's pane")) return true; - const prev = enter(p, id, slot); + const prev = enter(p, id, slot, "address"); defer leave(prev); return f(slot.st, text.ptr, @intCast(text.len)) != 0; } @@ -769,7 +869,7 @@ pub fn ctl(p: *Pardes, id: usize, line: []const u8, reply: *[160]u8) ?[]const u8 const slot = (p.panes[id] orelse return "no such pane").addon orelse return "not a kind's pane"; const f = (slot.ops orelse return "its addon is not loaded").ctl orelse return "its kind takes no words"; if (authorityOnly("a kind's word")) return null; - const prev = enter(p, id, slot); + const prev = enter(p, id, slot, "ctl"); defer leave(prev); @memset(reply, 0); if (f(slot.st, line.ptr, @intCast(line.len), reply, reply.len) == 0) return null; @@ -781,7 +881,7 @@ pub fn ctl(p: *Pardes, id: usize, line: []const u8, reply: *[160]u8) ?[]const u8 pub fn ctlRead(pane: *const Pane, buf: []u8) []const u8 { const slot = pane.addon orelse return ""; const f = (slot.ops orelse return "").ctl_read orelse return ""; - const prev = enter(null, 0, slot); + const prev = enter(null, 0, slot, "ctl_read"); defer leave(prev); return buf[0..@min(buf.len, f(slot.st, buf.ptr, @intCast(buf.len)))]; } @@ -792,6 +892,113 @@ fn authorityOnly(comptime why: []const u8) bool { return true; } +// ---- the Addon word, and the words addons bring ---- + +pub const AddonOp = enum { load, unload, reload }; + +fn listedNamed(name: []const u8) ?*Listed { + statics(); + for (listed[0..nlisted]) |*l| if (l.ops != null and std.mem.eql(u8, l.nameOf(), name)) return l; + return null; +} + +/// `Addon load ` (relative to the pane's directory), `Addon unload +/// ` (refused while a pane of its kind is open), `Addon reload +/// ` (its panes kept through it, as their dumps); bare, the kinds +/// this session has. The library is the host's to open: an effect, its +/// answer an `addon` event (`landed`). +pub fn addonWord(p: *Pardes, id: usize, arg: ?[]const u8) void { + const a = std.mem.trim(u8, arg orelse "", " \t"); + var said: [256]u8 = undefined; + if (a.len == 0) { + var w: std.Io.Writer = .fixed(&said); + w.writeAll("addons:") catch {}; + for (kinds()) |*l| if (l.ops != null) w.print(" {s} {d}{s}", .{ l.nameOf(), l.version, if (l.lib == null) " (compiled in)" else "" }) catch {}; + return p.setMessage(id, w.buffered()); + } + const takes = "Addon takes load , unload or reload "; + const sp = std.mem.indexOfAny(u8, a, " \t") orelse return p.reportFailure(id, takes); + const op = std.meta.stringToEnum(AddonOp, a[0..sp]) orelse return p.reportFailure(id, takes); + const rest = std.mem.trim(u8, a[sp..], " \t"); + var target: [pardes.effect_path_cap]u8 = undefined; + const what: []const u8 = switch (op) { + .load => if (std.fs.path.isAbsolute(rest)) rest else std.fmt.bufPrint(&target, "{s}/{s}", .{ std.mem.trimEnd(u8, if (p.panes[id]) |pane| Pardes.paneDir(pane) else p.sessionDir(), "/"), rest }) catch rest, + .unload, .reload => what: { + const l = listedNamed(rest) orelse return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon {t}: no addon brought kind {s}", .{ op, rest }) catch takes); + if (l.lib == null) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon {t}: {s} is compiled in", .{ op, rest }) catch takes); + const n = openPanes(p, rest); + if (op == .unload and n > 0) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon unload: {d} {s} pane{s} open", .{ n, rest, if (n == 1) " is" else "s are" }) catch takes); + break :what rest; + }, + }; + if (what.len > pardes.effect_path_cap) return p.reportFailure(id, "Addon: that path is too long"); + p.emit(.{ .addon = .{ .op = op, .pane = @intCast(id), .arg = .from(what) } }); +} + +/// How the host's load, unload or reload went: `text` the kind's name, +/// or why not. The panes that waited for that kind open. +pub fn landed(p: *Pardes, op: AddonOp, pane: u8, ok: bool, text: []const u8) void { + const id = if (pane < p.panes.len and p.panes[pane] != null) pane else p.active; + var said: [256]u8 = undefined; + if (!ok) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon {t}: {s}", .{ op, text }) catch "Addon: refused"); + if (op == .unload) return p.setMessage(id, std.fmt.bufPrint(&said, "Addon unload: {s} is gone", .{text}) catch "Addon unload"); + const n = reopenWaiting(p, text); + const version = if (byName(text)) |o| o.head.version else 0; + p.setMessage(id, std.fmt.bufPrint(&said, "Addon {t}: {s} {d}{s}", .{ op, text, version, if (n > 0) ", its panes back" else "" }) catch "Addon"); +} + +/// A line whose first word is an addon's: run, and true; false for one +/// that is no addon's word. +pub fn runLine(p: *Pardes, id: usize, line: []const u8) bool { + const end = std.mem.indexOfAny(u8, line, " \t") orelse line.len; + const w = word(line[0..end]) orelse return false; + runWord(p, id, w, line, std.mem.trim(u8, line[end..], " \t")); + return true; +} + +/// Word `w` from pane `id`: one that opens its kind opens a pane of it +/// (`arg` its path), any other goes to the pane's kind, which must be +/// the word's. +pub fn runWord(p: *Pardes, id: usize, w: Word, line: []const u8, arg: []const u8) void { + const name = std.mem.span(w.w.name); + const kind = headName(w.ops); + var said: [256]u8 = undefined; + if (w.w.arg == c.PA_ARG_NONE and arg.len > 0) return p.reportFailure(id, std.fmt.bufPrint(&said, "{s} takes no argument", .{name}) catch name); + if (w.w.arg == c.PA_ARG_REQUIRED and arg.len == 0) return p.reportFailure(id, std.fmt.bufPrint(&said, "{s} needs an argument", .{name}) catch name); + if (w.w.opens != 0) { + const free = p.freeSlot() orelse return p.reportError(id, name, error.NoPaneSlots); + var path_buf: [4096]u8 = undefined; + const path = if (arg.len == 0 or std.fs.path.isAbsolute(arg)) arg else std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ std.mem.trimEnd(u8, if (p.panes[id]) |pane| Pardes.paneDir(pane) else p.sessionDir(), "/"), arg }) catch arg; + const made = (if (path.len > 0) openFile(p, free, w.ops, path) else open(p, free, w.ops, null, null)) catch |err| return p.reportError(id, name, err); + if (made.addon.?.refused.len > 0) { + made.vweight = 0; + p.unplaced.set(free); + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: {s}", .{ name, made.addon.?.refused.slice() }) catch name); + } + @import("exec.zig").placeNew(p, id, id, free, .doc); + return; + } + const here = if (p.panes[id]) |pane| if (pane.addon) |s| s.ops == w.ops else false else false; + if (!here) return p.reportFailure(id, std.fmt.bufPrint(&said, "{s} is a {s} pane's word: run it in one", .{ name, kind }) catch name); + var reply: [160]u8 = undefined; + if (ctl(p, id, line, &reply)) |why| return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: {s}", .{ name, why }) catch name); + if (arg.len > 0) keepValue(p.panes[id].?.addon.?, name, arg); +} + +/// `Word arg` kept as the word's last value, one line a word. +fn keepValue(s: *Slot, name: []const u8, arg: []const u8) void { + var next: Buf(256) = .{}; + var w: std.Io.Writer = .fixed(&next.bytes); + var lines = std.mem.tokenizeScalar(u8, s.values.slice(), '\n'); + while (lines.next()) |line| { + const head = line[0 .. std.mem.indexOfScalar(u8, line, ' ') orelse line.len]; + if (!std.mem.eql(u8, head, name)) w.print("{s}\n", .{line}) catch return; + } + w.print("{s} {s}\n", .{ name, arg }) catch return; + next.len = @intCast(w.buffered().len); + s.values = next; +} + // ---- what the core does for a kind (pa_api) ---- /// The pane a call into a kind is for: what `api` acts on. @@ -799,6 +1006,7 @@ const Current = struct { p: ?*Pardes, id: usize, slot: *Slot, + call: []const u8 = "", painting: bool = false, /// In `open`: an error said refuses the pane. opening: bool = false, @@ -806,12 +1014,24 @@ const Current = struct { }; var current: ?Current = null; -fn enter(p: ?*Pardes, id: usize, slot: *Slot) ?Current { +fn enter(p: ?*Pardes, id: usize, slot: *Slot, comptime call: []const u8) ?Current { const prev = current; - current = .{ .p = p, .id = id, .slot = slot }; + current = .{ .p = p, .id = id, .slot = slot, .call = call }; return prev; } +/// The call into an addon under way, for a crash record: `in addon +/// fake.so, paint`. Null outside one, or in a kind compiled in. +pub fn calling(buf: []u8) ?[]const u8 { + const cur = current orelse return null; + const ops = cur.slot.ops orelse return null; + for (listed[0..nlisted]) |*l| if (l.ops == ops) { + if (l.lib == null) return null; + return std.fmt.bufPrint(buf, "in addon {s}, {s}", .{ std.fs.path.basename(l.path.slice()), cur.call }) catch null; + }; + return null; +} + fn leave(prev: ?Current) void { const done = current.?; current = prev; @@ -828,8 +1048,18 @@ pub const api: c.pa_api = .{ .look = apiLook, .say = apiSay, .text = apiText, + .seed = apiSeed, }; +/// What every pane's seed is made from: 0, or `--addon-test`'s `seed N`. +pub var seed_base: u64 = 0; + +fn apiSeed() callconv(.c) u64 { + const cur = current orelse return seed_base; + const serial: u32 = if (cur.p) |p| (if (p.panes[cur.id]) |pane| pane.serial else 0) else 0; + return std.hash.Wyhash.hash(seed_base, std.mem.asBytes(&serial)); +} + fn apiAlloc(n: usize) callconv(.c) ?*anyopaque { const cur = current orelse return null; const mem = cur.slot.arena.allocator().alignedAlloc(u8, .@"16", @max(n, 1)) catch return null; @@ -927,6 +1157,10 @@ const Job = struct { } }; +/// A test's jobs (and --addon-test's) run at once, their answers landing +/// at the step's end. +pub var inline_jobs = builtin.is_test; + fn apiJob(in: ?*const anyopaque, n: u32) callconv(.c) u32 { const cur = current orelse return 0; if (cur.painting) return 0; @@ -942,7 +1176,7 @@ fn apiJob(in: ?*const anyopaque, n: u32) callconv(.c) u32 { slot.gpa.destroy(job); return 0; } }; - if (comptime !builtin.is_test) { + if (!inline_jobs) { if (std.Thread.spawn(.{}, Job.work, .{job})) |t| job.thread = t else |_| job.work(); } else job.work(); free_at.* = job; @@ -990,8 +1224,5 @@ test "a kind's head is checked before it is taken" { try std.testing.expect(byName("zzzab") == null); forgetRefused("/x/wrong.so"); forgetRefused(""); - var it: std.ArrayList(u8) = .empty; - defer it.deinit(std.testing.allocator); - try list(&it, std.testing.allocator); - try std.testing.expect(std.mem.indexOf(u8, it.items, "zzza") == null); + for (kinds()) |*l| try std.testing.expect(!std.mem.startsWith(u8, l.nameOf(), "zzza")); } diff --git a/src/Output.zig b/src/Output.zig index bd8c79c0..37865fd8 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -898,6 +898,23 @@ fn helpContent(p: *const Pardes, gpa: std.mem.Allocator, prefix: []const u8) ![] if (!builtins.registry.here(p, row.cmd)) continue; try w.print("{s}\n", .{row.line}); } + // An addon's words, after the core's, each saying whose it is. + for (pardes.Kind.wordsOf()) |kw| { + const path = if (kw.w.leader == null) "" else std.mem.span(kw.w.leader); + if (!std.mem.startsWith(u8, path, prefix) or (prefix.len > 0 and path.len == 0)) continue; + var keys: [64]u8 = undefined; + var n: usize = 0; + if (path.len > 0) for ("SPC") |ch| { + keys[n] = ch; + n += 1; + }; + for (path) |ch| if (n + 2 <= keys.len) { + keys[n] = ' '; + keys[n + 1] = ch; + n += 2; + }; + try w.print("{s: <12}{s} {s} (addon {s})\n", .{ keys[0..n], std.mem.span(kw.w.name), if (kw.w.doc == null) "" else std.mem.span(kw.w.doc), pardes.Kind.headName(kw.ops) }); + } if (show_calls_help) try w.writeAll(calls_help); if (prefix.len == 0) try w.writeAll(language_footer); // The paths that run a builtin with a word (config.leader_args), and how diff --git a/src/builtins.zig b/src/builtins.zig index 92df2645..659e7cd5 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -989,6 +989,16 @@ pub const PdfSections = struct { } }; +/// Addons, the libraries that bring kinds of pane: `Addon load `, +/// `Addon unload `, `Addon reload `; bare, the kinds here. +pub const Addon = struct { + pub const scope: Scope = .session; + pub const takes_arg = true; + pub fn run(c: Ctx) void { + pardes.Kind.addonWord(c.p, c.id, c.arg); + } +}; + /// glyph art over the host's pixels: an image pane's picture, or the /// kitty graphics a terminal's program placed (yazi's previews) pub const Petscii = struct { diff --git a/src/config.zig b/src/config.zig index 3e05d7e1..2f72d332 100644 --- a/src/config.zig +++ b/src/config.zig @@ -64,6 +64,7 @@ pub const leader_path = paths: { .Lspwhy = "lw", .Callstack = "lb", .Index = null, + .Addon = null, .Callers = "lc", .Callees = "lC", .Supertypes = "lt", diff --git a/src/crash.zig b/src/crash.zig index 054feda3..998cc982 100644 --- a/src/crash.zig +++ b/src/crash.zig @@ -181,6 +181,8 @@ pub fn record(msg: []const u8) void { // without asking the process any questions: which build, when, where, and // what it said. That is the half a reporter cannot reconstruct afterwards. w.print("panic: {s}\n", .{msg}) catch {}; + var in_addon: [160]u8 = undefined; + if (@import("Kind.zig").calling(&in_addon)) |where| w.print("{s}\n", .{where}) catch {}; // One `write(2)`, and the loop is for a short write rather than for a // second record: `O_APPEND` puts it at the end whatever else is writing, diff --git a/src/exec.zig b/src/exec.zig index ca79a481..b3cbbdd9 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -918,7 +918,7 @@ pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { const head = std.meta.stringToEnum(Builtin, cmd[0 .. sp orelse break :blk null]) orelse break :blk null; break :blk if (builtins.registry.takesArg(head)) head else null; }; - const b = bi orelse return false; + const b = bi orelse return pardes.Kind.runLine(p, id, cmd); p.exec_depth += 1; defer p.exec_depth -= 1; const typed = if (sp) |s| std.mem.trim(u8, cmd[s + 1 ..], " \t") else ""; diff --git a/src/fs-help.txt b/src/fs-help.txt index d0c27c42..bc699418 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -1,7 +1,7 @@ Pardes virtual filesystem ========================= README this summary; the pardes book's Scripting and Reference chapters have the rest -index a line per pane: serial kind(text|term|cmd|pdf|image) dirty name column; names hold blanks: rsplit(maxsplit=1) +index a line per pane: serial kind(text|term|cmd|pdf|image|an addon's) dirty name column; names hold blanks: rsplit(maxsplit=1) status pid, version and pane count look write a line: a right click on it at the pane with the keyboard; read: the serials it touched (this open's) exec write a line: a middle click, a builtin or a shell line; read the same (every exec file) @@ -14,7 +14,7 @@ focus the serial of the pane with the keyboard (empty on a column tag); wr kbdin write runes: keys typed at the pane with the keyboard, done before the write answers (\x1b Esc, \n Enter) mousein write `m col row buttons` (1 left, 2 middle, 4 right): the mouse as it now is; m 10 5 4, m 10 5 0 is a right click ctl settings a line; or Newcol, Dump [export f], Restore [label|f], Exit (refuses once over unsaved panes), Kill [w], size C R -commands every builtin: word, arg, root|pane|both (the ctl that takes it), -- what it does +commands every builtin: word, arg, root|pane|both (the ctl that takes it), -- what it does; addons: the kinds of pane here recent files opened lately, closed ones too: open|closed dumps the dumps the state file keeps, the newest first: