diff options
Diffstat (limited to 'src/Kind.zig')
| -rw-r--r-- | src/Kind.zig | 413 |
1 files changed, 322 insertions, 91 deletions
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")); } |
