diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Addon.zig | 322 | ||||
| -rw-r--r-- | src/Core.zig | 4 | ||||
| -rw-r--r-- | src/Effect.zig | 6 | ||||
| -rw-r--r-- | src/Event.zig | 3 | ||||
| -rw-r--r-- | src/Kind.zig | 413 | ||||
| -rw-r--r-- | src/Output.zig | 17 | ||||
| -rw-r--r-- | src/builtins.zig | 10 | ||||
| -rw-r--r-- | src/config.zig | 1 | ||||
| -rw-r--r-- | src/crash.zig | 2 | ||||
| -rw-r--r-- | src/exec.zig | 2 | ||||
| -rw-r--r-- | src/fs-help.txt | 4 | ||||
| -rw-r--r-- | src/host_io.zig | 1 | ||||
| -rw-r--r-- | src/keys.zig | 13 | ||||
| -rw-r--r-- | src/kinds/pardes_addon.h | 27 | ||||
| -rw-r--r-- | src/look.zig | 1 | ||||
| -rw-r--r-- | src/mouse.zig | 19 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 17 | ||||
| -rw-r--r-- | src/ninep/pane.zig | 2 | ||||
| -rw-r--r-- | src/ninep/tree.zig | 27 | ||||
| -rw-r--r-- | src/pardes.zig | 2 | ||||
| -rw-r--r-- | src/wire.zig | 6 |
21 files changed, 786 insertions, 113 deletions
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 `<prefix>/lib/pardes/addons` at start, and `Addon load +//! <path>` 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/<n> 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 <name>`: 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: `<kind> <version> <abi> <panes open> <path> <blake3> +/// 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 <path>` (relative to the pane's directory), `Addon unload +/// <name>` (refused while a pane of its kind is open), `Addon reload +/// <name>` (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 <path>, unload <name> or reload <name>"; + 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 <path>`, +/// `Addon unload <name>`, `Addon reload <name>`; 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 <path> dumps the dumps the state file keeps, the newest first: <label> <date> <size> <panes> layout a line per column: serial index x width current|notcurrent empty|full pane-serials; then active <serial> diff --git a/src/host_io.zig b/src/host_io.zig index 86df754b..c00eb453 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -82,6 +82,7 @@ pub fn testClock() ?u64 { /// loop (pdf_view.workers). `stopWorkers` is its defer. pub fn startWorkers(io: std.Io, allocs: pardes.memory.Allocators) void { pardes.image.start(io, allocs.image); + pardes.Addon.scan(); if (comptime pardes.pdf_enabled) { pardes.pdf.start(allocs.pdf); pardes.panes.Pdf.workers = io; diff --git a/src/keys.zig b/src/keys.zig index 1329de0b..003f39b5 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -227,6 +227,13 @@ pub fn handleKey(p: *Pardes, key: Key) void { } return panes.terminal.forwardKey(p, p.active, key); } + // A kind's pane that takes keys takes them all, as a raw terminal + // does, but Esc, which leaves (and Shift-Esc, above). + if (header == null and pane.focus == .body and pane.prompt == .none) if (pane.addon) |slot| if (slot.takesKeys()) { + p.prefix = .none; + if (key.cp == Key.escape and !key.ctrl and !key.alt) return exec.runBuiltin(p, .Last, p.active, "", null); + if (pardes.Kind.key(p, p.active, key)) return; + }; if (p.prefix == .leader) return leaderKey(p, key); if (p.prefix == .window) { p.prefix = .none; @@ -465,6 +472,12 @@ fn leaderKey(p: *Pardes, key: Key) void { return; } } + // An addon's word, after the core's (a path the core has is no addon's). + switch (pardes.Kind.leader(pfx)) { + .word => |w| pardes.Kind.runWord(p, p.active, w, std.mem.span(w.w.name), ""), + .prefix => p.prefix = .leader, + .none => {}, + } } test "Esc back into a tty leaves its view at the prompt" { diff --git a/src/kinds/pardes_addon.h b/src/kinds/pardes_addon.h index 8a95d6d7..c3fbc097 100644 --- a/src/kinds/pardes_addon.h +++ b/src/kinds/pardes_addon.h @@ -39,8 +39,10 @@ #define PA_REVERSE 0x10u #define PA_UNDERLINE 0x100u -/* A cell: one character, `len` bytes of UTF-8 (at most 7). */ -#define PA_UNPAINTED 0x01u /* flags: the pane's background, nothing drawn */ +/* A cell: one character, `len` bytes of UTF-8 (at most 7), drawn only + * with PA_PAINTED in its flags (pa_put sets it); a zero cell is the pane's + * background. */ +#define PA_PAINTED 0x01u typedef struct pa_cell { uint8_t text[8]; uint32_t fg, bg; @@ -50,7 +52,7 @@ typedef struct pa_cell { } pa_cell; /* The pane's body, which `paint` writes: `rows` rows of `cols` cells, - * `stride` cells apart, every one PA_UNPAINTED when the call begins. */ + * `stride` cells apart, every one zero (unpainted) when the call begins. */ typedef struct pa_window { pa_cell *cells; uint32_t stride; @@ -146,6 +148,9 @@ typedef struct pa_api { void (*say)(const char *text, uint32_t n, int err); /* A new text pane named `name` holding `bytes`; its serial, 0 if none. */ uint32_t (*text)(const char *name, uint32_t name_len, const char *bytes, uint32_t n); + /* The pane's seed: the same pane, the same number, on every machine (a + * game's board), and what `pardes --addon-test`'s `seed N` sets. */ + uint64_t (*seed)(void); } pa_api; /* A job's answer buffer: `alloc` it once, write it, return its length. */ @@ -224,6 +229,20 @@ typedef struct pa_ops { int (*load)(void *st, const uint8_t *buf, uint32_t n, uint32_t version); } pa_ops; +/* The records' sizes on a 64-bit target: an addon built against another + * copy of this header that disagrees does not compile. */ +#if UINTPTR_MAX == 0xffffffffffffffffu +_Static_assert(sizeof(pa_cell) == 20, "pa_cell"); +_Static_assert(sizeof(pa_window) == 24, "pa_window"); +_Static_assert(sizeof(pa_rect) == 16 && sizeof(pa_cells) == 8, "pa_rect"); +_Static_assert(sizeof(pa_placement) == 72, "pa_placement"); +_Static_assert(sizeof(pa_paint) == 120, "pa_paint"); +_Static_assert(sizeof(pa_key) == 8 && sizeof(pa_mouse) == 10, "pa_key"); +_Static_assert(sizeof(pa_api) == 64 && sizeof(pa_out) == 16, "pa_api"); +_Static_assert(sizeof(pa_word) == 40 && sizeof(pa_head) == 56, "pa_head"); +_Static_assert(sizeof(pa_ops) == 192, "pa_ops"); +#endif + /* ---- helpers ---- */ static inline pa_cell *pa_at(const pa_window *w, unsigned row, unsigned col) { @@ -244,7 +263,7 @@ static inline unsigned pa_put(const pa_window *w, unsigned row, unsigned col, co c->fg = fg; c->bg = bg; c->attrs = 0; - c->flags = 0; + c->flags = PA_PAINTED; n++; } text += len; diff --git a/src/look.zig b/src/look.zig index 870209a3..d60ff3a9 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1891,7 +1891,6 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { var cut: [miss_path_cap + "…".len]u8 = undefined; return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: {s}", .{ missText(target.path, &cut), made.addon.?.refused.slice() }) catch "look: refused"); } - Kind.startTicking(p, made); exec.placeNew(p, id, id, free, .doc); }, } diff --git a/src/mouse.zig b/src/mouse.zig index 7905735c..0798b51f 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -381,6 +381,24 @@ fn tracksMouse(pane: *const Pane) bool { /// B2 and B3 are pardes's execute and look, and Shift-B2 and Shift-B3 the /// program's, reported without the Shift that chose it. True when the /// event was the program's. +/// The pointer over the body of a pane whose kind takes the mouse: the +/// kind's, a press focusing the pane first. +fn kindMouse(p: *Pardes, m: Mouse) bool { + if (p.drag != .none or p.header_drag or p.header_sweep != null) return false; + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const k = pane.addon orelse continue; + if (!k.takesMouse() or pane.collapsed) continue; + const r = p.rects[id]; + const top = p.bodyTop(pane, r) + pane.notices.span(); + const x0 = r.x + config.GUTTER; + if (m.col < x0 or m.col >= r.x + r.w or m.row < top or m.row >= r.y + r.h) continue; + if (m.kind == .press) p.active = id; + return pardes.Kind.mouse(p, id, m, m.col - x0, m.row - top); + } + return false; +} + fn programMouse(p: *Pardes, m: Mouse) bool { const button: ?panes.terminal.MouseButton = switch (m.button) { .left => .left, @@ -539,6 +557,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { } } p.pointer_inside = true; + if (kindMouse(p, m)) return; if (programMouse(p, m)) return; emulateButton(p, &m); if (m.button == .none and m.kind == .motion) { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 68fefbc5..a65b3562 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -408,7 +408,7 @@ fn writeQuoted(w: *std.Io.Writer, s: []const u8) !void { try w.writeByte('\''); } -pub const pane_text_cap = 9 * 12 + 2 * 256 + 4 + "notcurrent ".len + 48 + "collapsed fit:height tint:filtered mode:insert ".len; +pub const pane_text_cap = 9 * 12 + 2 * 256 + 4 + "notcurrent ".len + 48 + "collapsed fit:height tint:filtered mode:insert ".len + 129; /// acme's winctlprint (plan9port wind.c), field for field: serial, tag /// length, body length, isdir (1 for a directory pane), the dirty flag, @@ -444,6 +444,11 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { // PdfTint, in the words they take. if (pane.collapsed) w.writeAll("collapsed ") catch {}; if (comptime pardes.pdf_enabled) if (pane.pdf) |pv| w.print("fit:{s} tint:{s} ", .{ @tagName(pv.fit), @tagName(pv.tint) }) catch {}; + if (pane.addon != null) { + var fields: [128]u8 = undefined; + const kind_fields = pardes.Kind.ctlRead(pane, &fields); + if (kind_fields.len > 0) w.print("{s} ", .{kind_fields}) catch {}; + } // Last, the body's mode, which the tag shows as a box: helix's select // is normal mode extending. w.print("mode:{s} ", .{if (pane.body.mode == .normal and pane.body.select) "select" else @tagName(pane.body.mode)}) catch {}; @@ -521,6 +526,8 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? const arg = if (sp) |s| std.mem.trim(u8, line[s + 1 ..], " \t") else ""; const here = if (std.meta.stringToEnum(Builtin, word)) |b| builtins.registry.here(p, b) else false; const b = (if (here) std.meta.stringToEnum(Builtin, word) else null) orelse { + // An addon's word: its kind's to take or refuse as it runs. + if (pardes.Kind.word(word) != null) return null; // A setting this build's frontend cannot show (Lift, GripWidth on a // terminal, the window's own words in a terminal's view) is known, // and says so rather than sound misspelt. @@ -890,6 +897,14 @@ fn writeCommands(p: *const Pardes, w: *std.Io.Writer) !void { } try w.writeByte('\n'); } + // The addons' words, after the core's: `(addon <name>)` says whose. + for (pardes.Kind.wordsOf()) |kw| try w.print("{s}{s} {s} -- {s} (addon {s})\n", .{ + std.mem.span(kw.w.name), + if (kw.w.arg != pardes.Kind.c.PA_ARG_NONE) " arg" else "", + if (kw.w.opens != 0) "both" else "pane", + if (kw.w.doc == null) "" else std.mem.span(kw.w.doc), + pardes.Kind.headName(kw.ops), + }); } /// /commands' text (`writeCommands`), in the step's scratch. diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 49fa46c6..3b982803 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -454,7 +454,9 @@ fn readFlag(p: *Pardes, req: Req, on: bool) Reply { /// The text layer of the page a PDF pane shows (MuPDF's extraction, kept /// with the page), null for any other pane. +/// A document's text, read-only: a PDF's text layer, a kind's `body`. fn pdfText(p: *Pardes, pane: *Pane) ?[]const u8 { + if (pane.addon != null) return pardes.Kind.body(pane, p.scratch.allocator()) catch null; if (comptime !pardes.pdf_enabled) return null; const pv = pane.pdf orelse return null; return pv.ensureText(p.pdf_gpa); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 1b6c242e..9c3de708 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -265,6 +265,10 @@ pub const TopFile = enum(u5) { /// first: `<label> <date> <size> <panes>`; `Restore <label>` brings one /// back. dumps, + /// The kinds of pane this session has, compiled in or an addon's, and + /// the addons refused, a line each: `<kind> <version> <abi> + /// static|loaded|refused: why [path]`. + addons, pub fn fileName(f: TopFile) []const u8 { return if (f == .root) "/" else @tagName(f); @@ -274,7 +278,7 @@ pub const TopFile = enum(u5) { return switch (f) { .root, .pane, .col => 0o755, .look, .exec, .log, .focus, .ctl, .tag, .tagexec, .pager => 0o666, - .README, .index, .status, .screen, .listeners, .new, .commands, .layout, .recent, .dumps, .sessions => 0o444, + .README, .index, .status, .screen, .listeners, .new, .commands, .layout, .recent, .dumps, .sessions, .addons => 0o444, .kbdin, .mousein => 0o222, }; } @@ -675,7 +679,7 @@ fn topSize(p: *Pardes, f: TopFile) u64 { // frame, /pane/new until an open has a pane to name, and the index, // layout, recent list and listeners, which a stat would otherwise // have to build to count. - .root, .pane, .col, .screen, .new, .layout, .index, .recent, .dumps, .listeners, .sessions, .kbdin, .mousein => 0, + .root, .pane, .col, .screen, .new, .layout, .index, .recent, .dumps, .addons, .listeners, .sessions, .kbdin, .mousein => 0, .tag => cols.headerText(p, null).?.len, .README => fs.help.len, .status => ctl.statusText(p).len, @@ -759,7 +763,7 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { .root => { // The guide, then what describes the session, then the // files that act, then the directories. - inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.dumps, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.sessions, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.kbdin, TopFile.mousein, TopFile.pane, TopFile.col }) |t| { + inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.dumps, TopFile.addons, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.sessions, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.kbdin, TopFile.mousein, TopFile.pane, TopFile.col }) |t| { if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @backingInt(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); @@ -847,7 +851,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { }, .screen => .{ .snapshot = null }, .log => .{ .log = .{} }, - .index, .layout, .recent, .dumps, .commands, .status, .listeners, .sessions => .{ .frozen = &.{} }, + .index, .layout, .recent, .dumps, .addons, .commands, .status, .listeners, .sessions => .{ .frozen = &.{} }, // The root's ctl opened only to read: its settings, frozen. .ctl => if (linesOpen(target, req)) .lines else .{ .frozen = &.{} }, else => if (linesOpen(target, req)) .lines else return .{ .tag = req.tag }, @@ -1107,6 +1111,11 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { pardes.panes.Output.recentText(p, &text.writer, false) catch break :recent Reply.fail(req.tag, E.NOMEM); break :recent window(p, req, text.written()); }, + .addons => addons: { + var text: std.ArrayList(u8) = .empty; + pardes.Kind.list(p, &text, p.scratch.allocator()) catch break :addons Reply.fail(req.tag, E.NOMEM); + break :addons window(p, req, text.items); + }, .dumps => dumps: { // The state file read now, unless a step is out mid-syscall // (its database is the step's): then none. @@ -1546,13 +1555,13 @@ test "readdir lists the root and a pane directory without creating anything" { @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); try testing.expect(top.len >= 10); - for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "dumps", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "pane", "col", "os" }, 0..) |name, i| { + for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "dumps", "addons", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "pane", "col", "os" }, 0..) |name, i| { try testing.expectEqualStrings(name, top[i].name); - try testing.expectEqual(i >= 20, top[i].dir); + try testing.expectEqual(i >= 21, top[i].dir); } - try testing.expectEqual(@backingInt(TopFile.pane), top[20].node); - try testing.expectEqual(@backingInt(TopFile.col), top[21].node); - try testing.expectEqual(fs.os_root, top[22].node); + try testing.expectEqual(@backingInt(TopFile.pane), top[21].node); + try testing.expectEqual(@backingInt(TopFile.col), top[22].node); + try testing.expectEqual(fs.os_root, top[23].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); try testing.expect(th.nameAt(top, "self") == null); diff --git a/src/pardes.zig b/src/pardes.zig index ab2e706f..940e5c5d 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -79,6 +79,7 @@ pub const replica = @import("replica.zig"); pub const echo = @import("echo.zig"); pub const image = @import("image.zig"); pub const Kind = @import("Kind.zig"); +pub const Addon = @import("Addon.zig"); pub const dump = @import("dump.zig"); pub const lsp = @import("lsp/lsp.zig"); pub const host_io = @import("host_io.zig"); @@ -265,6 +266,7 @@ test "a compact tagline anchors at its own pane, and both shells step from the s } test { + _ = @import("Addon.zig"); _ = @import("rollback.zig"); _ = @import("Core.zig"); _ = @import("lsp/Ask.zig"); diff --git a/src/wire.zig b/src/wire.zig index 735fc37f..e2f85d18 100644 --- a/src/wire.zig +++ b/src/wire.zig @@ -393,7 +393,7 @@ fn clientTag(msg: ClientMsg) ClientTag { return switch (msg) { .event => |ev| switch (ev) { // Machine-local reports and 9P requests belong to the session owner. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .addon, .tick => unreachable, inline else => |_, t| @field(ClientTag, @tagName(t)), }, inline else => |_, t| @field(ClientTag, @tagName(t)), @@ -550,7 +550,7 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { try w.writeByte(@intFromBool(f.native_image_patches)); }, // See `clientTag`: no tag, so nothing to encode. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .addon, .tick => unreachable, }, } try finishMessage(&w, at); @@ -649,7 +649,7 @@ pub fn clientBound(msg: ClientMsg) usize { .paste => |b| b.len, .command => |line| line.len, // See `clientTag`: not on this wire in this direction. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .handed, .addon, .tick => unreachable, }, }; } |
