diff options
Diffstat (limited to 'src/Kind.zig')
| -rw-r--r-- | src/Kind.zig | 1388 |
1 files changed, 499 insertions, 889 deletions
diff --git a/src/Kind.zig b/src/Kind.zig index 7f9284c0..e5332831 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -1,16 +1,18 @@ //! A kind of pane that is neither text nor a terminal: a picture, a game, //! anything an addon (a library, Addon.zig) brings. Its records and //! functions are the C ABI of src/kinds/pardes_addon.h (translated, the -//! one copy); this file is the core's side of it: the kinds this process -//! has (compiled in, or an addon's, with the words and extensions they -//! bring), and a pane's `Slot`, the state the core keeps round the kind's -//! own (its path, its art bytes, its jobs, the record of one whose addon -//! is not here). +//! one copy); this file is the core's side of it: the kinds a core has +//! (`Registry`, compiled in or brought, with their words and extensions), +//! and a pane's `Slot`, the state the core keeps round the kind's own. //! -//! The core calls a kind at these places alone: Look and a word open a -//! pane (`open`), the frame paints it (`draw`), its tag asks its prefix, -//! keys and the mouse go to it, a tick steps it, a job's answer lands, -//! 9P reads its body and writes its words, a dump keeps it, and its close. +//! The core is deterministic and a kind is only the authority's: a +//! replica's core has the same registry (its words, its extensions) but no +//! code for a kind a library brought, and draws its panes from the +//! authority's frames (a Shadow, screen_state.zig). So every call into a +//! kind whose answer the core acts on is made at a place both cores reach, +//! and its `Outcome` (the answer, what it said, a Look) is taped: a replica +//! takes it off the tape. Paint and the reads (body, ctl, a dump) change +//! nothing and are not taped. const std = @import("std"); const builtin = @import("builtin"); pub const c = @import("pardes_addon"); @@ -18,323 +20,170 @@ const pardes = @import("pardes.zig"); const walk = @import("walk.zig"); const tape = @import("tape.zig"); const surface = @import("surface.zig"); +const views = @import("views.zig"); +const Addon = @import("Addon.zig"); +pub const Loaded = Addon.Loaded; +pub const LoadedWord = Addon.LoadedWord; +pub const loadedOf = Addon.loadedOf; const Placement = surface.Placement; const Pardes = pardes.Pardes; const Pane = pardes.panes.Pane; -const Kind = @This(); 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. +// The header's own sizes (its _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_placement, 80 }, .{ c.pa_paint, 120 }, .{ c.pa_key, 8 }, .{ c.pa_mouse, 10 }, + .{ c.pa_api, 64 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ 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 ---- +// ---- the kinds a core has ---- -/// A kind as /addons lists it: an addon's loaded, one compiled in, or an -/// addon refused and why. -pub const Listed = struct { +pub const max_kinds = 16; +/// The kinds compiled in come first in every core: the image is kind 0. +pub const image: u8 = 0; + +/// Which of its functions a kind has: what both cores decide by. +pub const Caps = packed struct(u8) { + tick: bool = false, + key: bool = false, + mouse: bool = false, + ctl: bool = false, + jobs: bool = false, + load: bool = false, + pad: u2 = 0, +}; + +pub const Entry = struct { name: [16]u8 = @splat(0), version: u32 = 0, abi: u32 = 0, - /// Null: refused. - ops: ?*const Ops = null, - /// Its addon's handle (Addon.zig), none for one compiled in. - lib: ?*anyopaque = null, + hash: [32]u8 = @splat(0), + /// One more at each reload: a job's answer of another is dropped. + gen: u32 = 0, + caps: Caps = .{}, path: Buf(256) = .{}, - /// The library file's BLAKE3, as it was loaded. - hash: ?[32]u8 = null, + /// A library refused, listed with `why`. + refused: bool = false, why: Buf(128) = .{}, - pub fn nameOf(l: *const Listed) []const u8 { - return std.mem.sliceTo(&l.name, 0); + pub fn nameOf(e: *const Entry) []const u8 { + return std.mem.sliceTo(&e.name, 0); } -}; - -pub const max_kinds = 16; -var listed: [max_kinds]Listed = undefined; -var nlisted: usize = 0; - -/// The run-time tail of the builtin registry (builtins.zig keeps the -/// comptime part): each kind's words, found after the comptime map misses. -pub const Word = struct { ops: *const Ops, w: *const c.pa_word }; -var words: [64]Word = undefined; -var nwords: usize = 0; -var exts: [32]struct { ext: []const u8, ops: *const Ops } = undefined; -var nexts: usize = 0; - -/// The kinds compiled in, registered before any lookup. -var statics_done = false; -fn statics() void { - if (statics_done) return; - statics_done = true; - _ = register(&@import("image.zig").kind, "", null); -} - -pub fn kinds() []const Listed { - statics(); - return listed[0..nlisted]; -} - -/// 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 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 (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 (w.ops != skipping and std.mem.eql(u8, std.mem.span(w.w.name), name)) return w; - return null; -} - -pub fn wordsOf() []const Word { - statics(); - return words[0..nwords]; -} - -/// The kind of the word whose leader path is `keys`, or whether one has -/// a path `keys` begins (`prefix`). -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 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; + pub fn compiledIn(e: *const Entry) bool { + return std.mem.allEqual(u8, &e.hash, 0); } - return if (begun) .prefix else .none; -} - -fn headWords(ops: *const Ops) []const c.pa_word { - return if (ops.head.nwords == 0 or ops.head.words == null) &.{} else ops.head.words[0..ops.head.nwords]; -} - -fn extsOf(ops: *const Ops) []const u8 { - return if (ops.head.exts == null) "" else std.mem.span(ops.head.exts); -} - -pub fn headName(ops: *const Ops) []const u8 { - return std.mem.sliceTo(&ops.head.name, 0); -} +}; -/// `ops` taken in, its words and extensions with it, or refused in -/// words: a head this pardes cannot read, another ABI, no paint, a name, -/// a word, a leader path or an extension already someone's, or its init -/// failing. Listed either way (/addons), the refusal's words returned. -/// `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 const Word = struct { kind: u8, name: Buf(32) = .{}, leader: Buf(8) = .{}, arg: u8 = 0, opens: u8 = 0, doc: Buf(96) = .{} }; +pub const Ext = struct { kind: u8, ext: Buf(16) = .{} }; -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, .hash = hash }; - l.path.set(path); - const why = check(ops, l) orelse { - l.name = ops.head.name; - l.name[15] = 0; - l.version = ops.head.version; - l.abi = ops.head.abi; - if (ops.init) |init| if (init(&api) != 0) { - l.why.set("refused: its init failed"); - nlisted += 1; - return l.why.slice(); - }; - l.ops = ops; - addTail(ops); - l.why.set(if (lib == null) "static" else "loaded"); - nlisted += 1; - return null; +/// A core's kinds: the compiled-in ones every core starts with, then what +/// libraries brought (Addon.zig), as data both cores hold alike; and each +/// one's code here, which a replica has none of for a library's. +pub const Registry = struct { + pub const replica = .{ + .local = .{"ops"}, + .len = .{ .{ "kinds", "n" }, .{ "words", "nwords" }, .{ "exts", "nexts" } }, }; - if (ops.head.size >= @sizeOf(c.pa_head)) { - l.name = ops.head.name; - l.name[15] = 0; - l.version = ops.head.version; - l.abi = ops.head.abi; - } - l.why.set(why); - nlisted += 1; - return l.why.slice(); -} + kinds: [max_kinds]Entry = undefined, + n: u8 = 0, + words: [64]Word = undefined, + nwords: u8 = 0, + exts: [32]Ext = undefined, + nexts: u8 = 0, + ops: [max_kinds]?*const Ops = @splat(null), -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; + /// The kinds compiled in. + pub fn init() Registry { + var r: Registry = .{}; + var words: [64]LoadedWord = undefined; + _ = r.take(loadedOf(&@import("image.zig").kind, "", @splat(0), &words), ""); + return r; } -} - -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"; - if (h.abi >> 16 != abi_major) return l.why.print("refused: wants abi {d}, this pardes speaks {d}", .{ h.abi >> 16, abi_major }); - if (ops.paint == null) return "refused: it has no paint"; - const name = std.mem.sliceTo(&h.name, 0); - if (name.len == 0 or name.len > 15) return "refused: its name is empty or longer than 15 bytes"; - for (name) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '_' and ch != '-') return "refused: its name is not a word"; - if (byName(name) != null) return l.why.print("refused: kind {s} is here already", .{name}); - if (h.nwords > 0 and ops.ctl == null) return "refused: it has words and no ctl"; - if ((ops.job_run == null) != (ops.job_done == null)) return "refused: a job needs job_run and job_done"; - if (nwords + h.nwords > words.len) return "refused: no room for its words"; - for (headWords(ops), 0..) |*w, i| { - if (w.size < @sizeOf(c.pa_word) or w.name == null) return "refused: a word it brings is malformed"; - const wn = std.mem.span(w.name); - if (wn.len == 0 or wn.len > 32) return "refused: a word's name is empty or longer than 32 bytes"; - if (coreWord(wn)) return l.why.print("refused: word {s} is the core's", .{wn}); - if (word(wn)) |other| return l.why.print("refused: word {s} is {s}'s", .{ wn, headName(other.ops) }); - for (headWords(ops)[0..i]) |*before| if (std.mem.eql(u8, std.mem.span(before.name), wn)) return l.why.print("refused: word {s} twice", .{wn}); - 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.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), ' '); - var n: usize = 0; - while (it.next()) |ext| : (n += 1) { - if (ext.len < 2 or ext[0] != '.') return l.why.print("refused: extension {s} has no dot", .{ext}); - if (forPath(ext)) |other| return l.why.print("refused: extension {s} is {s}'s", .{ ext, headName(other) }); + /// The kinds compiled in and what the scan at start found. + pub fn started(found: []const Loaded) Registry { + var r: Registry = .init(); + for (found) |l| _ = r.take(l, ""); + return r; } - if (nexts + n > exts.len) return "refused: no room for its extensions"; - return null; -} - -fn coreWord(name: []const u8) bool { - const builtins = @import("builtins.zig"); - return std.meta.stringToEnum(builtins.registry.Builtin(), name) != null or builtins.absentWhy(name) != null; -} - -fn coreLeader(keys: []const u8) bool { - return @import("keys.zig").leaderTaken(keys); -} -/// `name` out of the list, its words and extensions with it: its -/// library's handle, to close, or null when no such kind is loaded. -/// The caller sees no pane of it is open. -pub fn unregister(name: []const u8) ?Listed { - statics(); - const at = for (listed[0..nlisted], 0..) |*l, i| { - if (l.ops != null and std.mem.eql(u8, l.nameOf(), name)) break i; - } else return null; - const gone = listed[at]; - dropTail(gone.ops.?); - std.mem.copyForwards(Listed, listed[at .. nlisted - 1], listed[at + 1 .. nlisted]); - nlisted -= 1; - return gone; -} + pub fn byName(r: *const Registry, name: []const u8) ?u8 { + for (r.kinds[0..r.n], 0..) |*e, i| if (!e.refused and std.mem.eql(u8, e.nameOf(), name)) return @intCast(i); + return null; + } -/// An addon at `path` that brought no kind, listed with why. -pub fn note(path: []const u8, why: []const u8) void { - statics(); - if (nlisted == max_kinds) return; - listed[nlisted] = .{}; - listed[nlisted].path.set(path); - listed[nlisted].why.set(why); - nlisted += 1; -} + // What libraries bring, the loader's (Addon.zig). + pub const forPath = Addon.forPath; + pub const word = Addon.word; + pub const leader = Addon.leader; + pub const take = Addon.take; + pub const collides = Addon.collides; + pub const drop = Addon.drop; -/// The refused ones forgotten, as a load of the same path tries again. -pub fn forgetRefused(path: []const u8) void { - var n: usize = 0; - for (listed[0..nlisted]) |l| if (l.ops != null or !std.mem.eql(u8, l.path.slice(), path)) { - listed[n] = l; - n += 1; - }; - nlisted = n; -} - -/// /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} {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()}); - } -} +}; // ---- a pane of a kind ---- /// What the core keeps of a pane of a kind, round the kind's own state. -/// The walker sees none of it (it is the kind's): a dump writes its -/// record by hand (`dumpWrite`), a digest takes its name and path, and a -/// rollback copy leaves it be, as a terminal's emulator. +/// A rollback copy leaves it be, as a terminal's emulator; a dump writes +/// its record by hand (dump.zig). pub const Slot = struct { - /// Null: a placeholder, its kind not here (a dump's, loaded without - /// it), which keeps its record for the day it comes. - ops: ?*const Ops, + /// Its kind's code here; null in a placeholder (`live` false: its kind + /// not in the registry, its record kept for the day it comes) or a + /// Shadow (a replica's pane of a library's kind). + ops: ?*const Ops = null, + live: bool = false, st: ?*anyopaque = null, - /// What the slot's memory comes from; the kind's allocations are its - /// arena's, freed at the close. + /// The kind's allocations are its arena's, freed at the close. gpa: std.mem.Allocator, arena: std.heap.ArenaAllocator, name: [16]u8 = @splat(0), version: u32 = 0, + /// Its kind's generation when it was opened (Entry.gen). + gen: u32 = 0, path: []u8 = &.{}, /// Petscii, Palette and Ascii: how a frontend shows its placements. art: Placement.Art = .{}, - /// When `tick` asked to be called next; 0, never. + /// When `tick` is next due; 0, never; 1, at the next step. next_tick: u64 = 0, - jobs: [4]?*Job = @splat(null), + /// PA_FOCUSED as `tick` was last told. + focused: bool = false, + /// Its jobs' inputs, until the host takes them (Effect.job). + jobs: [4]?Job = @splat(null), tokens: u32 = 0, /// A placeholder's: the kind's record and its `where`, kept whole. record: ?[]u8 = null, where_text: Buf(32) = .{}, - /// An error the kind said while opening: the open refused. + /// What the kind said refusing its open (or a load). 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) = .{}, + /// Its last frame's prefix, and whether it placed a picture. + prefix: Buf(96) = .{}, + placed: bool = false, + /// Its last frame changed its tag: a step is owed to lay the tag out + /// again (the tag is laid out before the body paints). + retag: bool = false, + /// A replica's frame of it, as the authority painted it. + shadow: ?*@import("screen_state.zig").Shadow = null, + /// Debug: the kind's allocations, which paint must leave as they are. + used: if (checked) std.ArrayList([]u8) else void = if (checked) .empty else {}, + + pub const Job = struct { token: u32, in: []u8 }; + + pub const dumpWrite = @import("dump.zig").slotWrite; + pub const dumpRead = @import("dump.zig").slotRead; + pub const dumpFree = @import("dump.zig").slotFree; pub fn nameOf(s: *const Slot) []const u8 { return std.mem.sliceTo(&s.name, 0); @@ -344,92 +193,17 @@ pub const Slot = struct { return std.mem.eql(u8, s.nameOf(), name); } - /// The core's words of a pane: a kind's with keys is raw, as a raw - /// terminal is. - pub fn takesKeys(s: *const Slot) bool { - return if (s.ops) |o| o.key != null else false; - } - - pub fn takesMouse(s: *const Slot) bool { - return if (s.ops) |o| o.mouse != null else false; - } - pub fn digest(s: *const Slot, h: *walk.Hasher) void { h.update(s.nameOf()); h.update(s.path); h.update(std.mem.asBytes(&s.art)); - h.update(&.{@intFromBool(s.ops != null)}); + h.update(std.mem.asBytes(&.{ s.next_tick, s.gen, @intFromBool(s.live), @intFromBool(s.focused) })); } - /// What a dump keeps of it: the kind, its path, its place, the art - /// bytes, and the kind's own record when it has one. - const Record = struct { - name: []const u8 = "", - version: u32 = 0, - path: []const u8 = "", - 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(), .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), "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| { - var cap: usize = 64 << 10; - while (true) { - const buf = try gpa.alloc(u8, cap); - const n = f(s.st, buf.ptr, @intCast(cap)); - if (n <= cap) { - owned = buf; - r.record = buf[0..n]; - break; - } - gpa.free(buf); - cap = n; - } - } - } - const bytes = try walk.save(Record, gpa, &r); - defer gpa.free(bytes); - try w.writeAll(bytes); - } - - pub fn dumpFree(s: *Slot, gpa: std.mem.Allocator) void { - _ = gpa; - s.free(); - } - - /// The pane back from its record: through its kind's `open` and - /// `load` (or `address` with its place) when this process has it, - /// else a placeholder holding the record. - pub fn dumpRead(out: *Slot, gpa: std.mem.Allocator, bytes: []const u8) !void { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const r = try walk.load(Record, arena.allocator(), bytes, null); - out.* = .{ .ops = null, .gpa = gpa, .arena = .init(gpa), .version = r.version, .art = r.art }; - errdefer out.free(); - @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); - } - - fn free(s: *Slot) void { - for (&s.jobs) |*j| if (j.*) |job| { - job.wait(); - job.destroy(); - j.* = null; - }; + pub fn free(s: *Slot) void { + for (&s.jobs) |*j| if (j.*) |job| s.gpa.free(job.in); + if (checked) s.used.deinit(s.gpa); + if (s.shadow) |sh| sh.deinit(s.gpa); s.arena.deinit(); s.gpa.free(s.path); if (s.record) |r| s.gpa.free(r); @@ -437,168 +211,21 @@ pub const Slot = struct { } }; -/// A placeholder made whole by its kind: `open` from its path, then -/// `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, "open"); - defer leave(prev); - const path_z = s.arena.allocator().dupeSentinel(u8, s.path, 0) catch return; - current.?.opening = true; - const st = if (ops.open) |f| f(if (s.path.len > 0) path_z.ptr else null, null, 0) else null; - current.?.opening = false; - if (s.refused.len > 0) { - if (ops.close) |f| f(st); - return; - } - if (s.record) |rec| if (ops.load) |f| if (f(st, rec.ptr, @intCast(rec.len), s.version) != 0) { - if (ops.close) |cl| cl(st); - s.refused.set("its load refused the record"); - return; - }; - 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; -} - -/// The panes of kind `name` that waited for it (placeholders), opened. -pub fn reopenWaiting(p: *Pardes, name: []const u8) usize { - const ops = byName(name) orelse return 0; - var n: usize = 0; - for (p.panes, 0..) |slot, id| if (slot) |pane| if (pane.addon) |s| if (s.ops == null and s.is(name)) { - s.refused = .{}; - reopen(p, id, s, ops); - if (s.ops != null) n += 1; - }; - return 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; - }; - 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; - } -} +const checked = builtin.mode == .debug; -pub fn openPanes(p: *const Pardes, name: []const u8) usize { - var n: usize = 0; - for (p.panes) |slot| if (slot) |pane| if (pane.addon) |s| if (s.ops != null and s.is(name)) { - n += 1; - }; - return n; +fn caps(p: *const Pardes, s: *const Slot) Caps { + const k = p.kinds.byName(s.nameOf()) orelse return .{}; + return if (s.live) p.kinds.kinds[k].caps else .{}; } -/// A new pane of kind `ops` in slot `id`, showing `path` (null for one a +/// A new slot of kind `k` for pane `id`, showing `path` (null for one a /// word opened) from `bytes`: made whatever the kind says, with what it /// refused in `slot.refused` for the caller to say. -pub fn open(p: *Pardes, id: usize, ops: *const Ops, path: ?[]const u8, bytes: ?[]const u8) !*Pane { +pub fn open(p: *Pardes, id: usize, k: u8, path: ?[]const u8, bytes: ?[]const u8) !*Pane { const gpa = p.image_gpa; + const e = &p.kinds.kinds[k]; const s = try gpa.create(Slot); - s.* = .{ .ops = ops, .gpa = gpa, .arena = .init(gpa), .version = ops.head.version, .name = ops.head.name }; - s.name[15] = 0; + s.* = .{ .ops = p.kinds.ops[k], .live = true, .gpa = gpa, .arena = .init(gpa), .version = e.version, .gen = e.gen, .name = e.name }; errdefer { s.free(); gpa.destroy(s); @@ -606,34 +233,72 @@ 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; - 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; - if (ops.open) |f| s.st = f(if (path != null) path_z.ptr else null, if (bytes) |b| b.ptr else null, if (bytes) |b| b.len else 0); + _ = reopen(p, id, s, bytes); return pane; } /// `open` of the file at `path`, read here (a file that cannot be read /// is no bytes: its kind may refuse it). The slot stays ours across the /// read: another request may make a pane meanwhile. -pub fn openFile(p: *Pardes, id: usize, ops: *const Ops, path: []const u8) !*Pane { +pub fn openFile(p: *Pardes, id: usize, k: u8, path: []const u8) !*Pane { p.reserved_slots[id] = true; const bytes: ?[]u8 = @import("fs.zig").read(p, path) catch null; p.reserved_slots[id] = false; defer if (bytes) |b| p.gpa.free(b); - return open(p, id, ops, path, bytes orelse ""); + return open(p, id, k, path, bytes orelse ""); +} + +/// The slot's kind state made (`open`, then `load` with its record, or +/// `address` with its place and its words' last values): its refusal, +/// if the kind refused, in `slot.refused`. One call for both cores. +pub fn reopen(p: ?*Pardes, id: usize, s: *Slot, bytes: ?[]const u8) bool { + var cl: Call = .{ .p = p, .id = id, .slot = s }; + const prev = cl.begin("open"); + if (s.ops) |ops| { + const path_z = s.arena.allocator().dupeSentinel(u8, s.path, 0) catch ""; + cl.opening = true; + if (ops.open) |f| s.st = f(if (s.path.len > 0) path_z.ptr else null, if (bytes) |b| b.ptr else null, if (bytes) |b| b.len else 0); + cl.opening = false; + if (cl.refused.len == 0) if (s.record) |rec| if (ops.load) |f| if (f(s.st, rec.ptr, @intCast(rec.len), s.version) != c.PA_OK) { + cl.refused.set("its load refused the record"); + }; + if (cl.refused.len == 0 and s.record == null) { + if (s.where_text.len > 0) if (ops.address) |f| { + _ = f(s.st, s.where_text.slice().ptr, @intCast(s.where_text.len)); + }; + var lines = std.mem.tokenizeScalar(u8, s.values.slice(), '\n'); + var reply: [160]u8 = undefined; + if (ops.ctl) |f| while (lines.next()) |line| { + _ = f(s.st, line.ptr, @intCast(line.len), &reply, reply.len); + }; + } + if (cl.refused.len > 0) if (ops.close) |f| f(s.st); + } + const o = cl.end(prev); + s.refused.set(o.text); + if (o.text.len > 0) return false; + if (s.record) |r| s.gpa.free(r); + s.record = null; + s.live = true; + if (p) |core| poke(core, s); + return true; +} + +/// Tick at the next step, once (16.2's rule 2). +fn poke(p: *const Pardes, s: *Slot) void { + if (caps(p, s).tick) s.next_tick = 1; } /// Its kind's close, then everything it had. 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, "close"); - defer leave(prev); + var cl: Call = .{ .p = null, .id = 0, .slot = s, .quiet = true }; + const prev = cl.begin("close"); f(s.st); + _ = cl.end(prev); }; + _ = p; const gpa = s.gpa; s.free(); gpa.destroy(s); @@ -641,68 +306,90 @@ pub fn close(p: *Pardes, pane: *Pane) void { } /// The pane's body painted over the `cols` x `rows` cells at (x, y): -/// its cells into `s`, its placements after the frame's others. A -/// placeholder says what it waits for. +/// its cells into `s`, its placements after the frame's others. A Shadow +/// draws the authority's frame of it; a placeholder says what it waits for. pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pane, id: usize, x: u16, y: u16, cols: u16, rows: u16) void { const slot = pane.addon orelse return; if (cols == 0 or rows == 0) return; const th = p.theme(); const fg: surface.Color = if (th.fg) |f| .{ .rgb = f } else .default; const bg: surface.Color = if (th.bg) |b| .{ .rgb = b } else .default; - const ops = slot.ops orelse { + var frame: Frame = .{ .cols = cols, .rows = rows }; + if (slot.ops == null and slot.live) { + const sh = slot.shadow orelse return; + frame = .{ .cells = sh.cells, .cols = sh.cols, .rows = sh.rows, .places = sh.places.items, .n = @intCast(sh.places.items.len) }; + } else if (slot.ops == null) { var line: [160]u8 = undefined; const why = if (slot.refused.len > 0) slot.refused.slice() else "Addon load <path>"; const text = std.fmt.bufPrint(&line, "addon {s} {d} is not loaded: {s}", .{ slot.nameOf(), slot.version, why }) catch &line; _ = s.print(x, y, cols, text, .{ .fg = fg, .bg = bg }); return; - }; - const cells = arena.alloc(c.pa_cell, @as(usize, cols) * rows) catch return; - @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, "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]; + } else frame.cells = (paint(p, slot, id, arena, cols, rows, &frame) orelse return); + for (0..@min(rows, frame.rows)) |r| for (0..@min(cols, frame.cols)) |col| { + const cell = &frame.cells[r * frame.cols + col]; 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)); }; - for (places[0..@min(out.n, places.len)]) |pl| { + for (frame.places[0..frame.n]) |pl| { if (pl.rgba == null or pl.w == 0 or pl.h == 0) continue; const dx = @min(pl.dst.x, cols); const dy = @min(pl.dst.y, rows); _ = p.appendPlacement(.{ .pane = @intCast(id), - .raster = .{ .ptr = pl.rgba, .w = pl.w, .h = pl.h, .stride = pl.stride }, + .raster = .{ .ptr = pl.rgba, .w = pl.w, .h = pl.h, .stride = pl.w * 4 }, .src = .{ .x = pl.src.x, .y = pl.src.y, .w = pl.src.w, .h = pl.src.h }, .dst = .{ .x = x + dx, .y = y + dy, .w = @min(pl.dst.w, cols - dx), .h = @min(pl.dst.h, rows - dy) }, .at = if (pl.at.w == 0) null else .{ .x = pl.at.x, .y = pl.at.y, .w = pl.at.w, .h = pl.at.h }, .key = Placement.keyOf(pane.serial, @truncate(pl.key >> 32), @truncate(pl.key)), + .dirty = if (pl.from == 0) null else .{ .from = Placement.keyOf(pane.serial, @truncate(pl.from >> 32), @truncate(pl.from)), .y = pl.dirty_y, .h = pl.dirty_h }, .art = slot.art, }); } } -fn window(p: *const Pardes, slot: *const Slot, pane: *const Pane, cells: [*]c.pa_cell, cols: u16, rows: u16) c.pa_window { +/// A frame of a kind's pane: its cells, `cols` a row, and its placements. +pub const Frame = struct { + cells: []c.pa_cell = &.{}, + cols: u16, + rows: u16, + places: []c.pa_placement = &.{}, + n: u32 = 0, + buf: [64]c.pa_placement = undefined, +}; + +/// The one paint of a frame: its cells (in `arena`) and placements into +/// `frame`, its prefix and whether it placed a picture into the slot. +/// Debug checks it changed none of the kind's memory. +pub fn paint(p: *const Pardes, slot: *Slot, id: usize, arena: std.mem.Allocator, cols: u16, rows: u16, frame: *Frame) ?[]c.pa_cell { + const ops = slot.ops orelse return null; + const cells = arena.alloc(c.pa_cell, @as(usize, cols) * rows) catch return null; + @memset(std.mem.sliceAsBytes(cells), 0); + var out: c.pa_paint = std.mem.zeroInit(c.pa_paint, .{ .placements = &frame.buf, .cap = frame.buf.len }); const px = if (comptime pardes.pdf_enabled) p.cell_pixels else struct { w: u16 = 8, h: u16 = 16 }{}; - return std.mem.zeroInit(c.pa_window, .{ - .cells = cells, - .stride = cols, - .rows = rows, - .cols = cols, - .cell_w = px.w, - .cell_h = px.h, - .focused = @intFromBool(p.panes[p.active] == pane), - .glyphs = @intFromBool(slot.art.glyph or !p.frontend.native_images), - .palette = @intFromEnum(slot.art.palette), - .ascii = @intFromBool(slot.art.ascii), - }); + const win = std.mem.zeroInit(c.pa_window, .{ .cells = cells.ptr, .stride = cols, .rows = rows, .cols = cols, .cell_w = px.w, .cell_h = px.h, .focused = @intFromBool(focusedAnywhere(p, id)) }); + var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true }; + const prev = cl.begin("paint"); + const before = if (checked) usedHash(slot) else {}; + ops.paint.?(slot.st, &win, &out); + if (checked and usedHash(slot) != before) std.debug.panic("addon {s}: paint changed its state (paint must be pure)", .{slot.nameOf()}); + _ = cl.end(prev); + frame.places = &frame.buf; + frame.n = @min(out.n, frame.buf.len); + const own = out.prefix[0..@min(out.prefix_len, out.prefix.len)]; + const placed = for (frame.buf[0..frame.n]) |pl| { + if (pl.rgba != null and pl.w > 0 and pl.h > 0) break true; + } else false; + if (placed != slot.placed or !std.mem.eql(u8, own, slot.prefix.slice())) slot.retag = true; + slot.prefix.set(own); + slot.placed = placed; + return cells; +} + +fn usedHash(slot: *const Slot) u64 { + var h = std.hash.Wyhash.init(0); + for (slot.used.items) |m| h.update(m); + return h.final(); } fn styleOf(cell: *const c.pa_cell, fg: surface.Color, bg: surface.Color) surface.CellStyle { @@ -726,41 +413,62 @@ fn colorOf(v: u32, default: surface.Color) surface.Color { }; } -/// The start of its tag: what its kind's paint says over no cells, else -/// its path (a word's pane: the kind's name). +/// The start of its tag: its kind's prefix from its last frame (else the +/// kind's name), the core's art words when that frame placed a picture, +/// and its path. The authority's: a step reads it off the tape on a replica. pub fn prefix(p: *const Pardes, arena: std.mem.Allocator, pane: *const Pane) ![]const u8 { const slot = pane.addon.?; - const fallback = if (slot.path.len > 0) slot.path else slot.nameOf(); - const ops = slot.ops orelse return fallback; - 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, "paint"); - defer leave(prev); - current.?.painting = true; - ops.paint.?(slot.st, &win, &out); - } - if (out.prefix_len == 0) return fallback; - return arena.dupe(u8, out.prefix[0..@min(out.prefix_len, out.prefix.len)]); + var buf: [400]u8 = undefined; + const made = tape.value(.addon, prefixOf, .{ p, slot, &buf }); + return arena.dupe(u8, made); +} + +fn prefixOf(p: *const Pardes, slot: *const Slot, buf: *[400]u8) []const u8 { + if (!slot.live) return if (slot.path.len > 0) slot.path else slot.nameOf(); + const own = if (slot.shadow) |sh| sh.prefix.slice() else slot.prefix.slice(); + const placed = if (slot.shadow) |sh| sh.placed else slot.placed; + var w: std.Io.Writer = .fixed(buf); + w.writeAll(if (own.len > 0) own else slot.nameOf()) catch {}; + if (placed) w.print(" petscii:{s} palette:{t} ascii:{s}", .{ + if (slot.art.glyph or !p.frontend.native_images) "on" else "off", + slot.art.palette, + if (slot.art.ascii) "on" else "off", + }) catch {}; + if (slot.path.len > 0) w.print(" {s}", .{slot.path}) catch {}; + return w.buffered(); } /// A key at a pane whose kind takes keys: whether it did. A replica's -/// speculation leaves it to the authority (the kind's state is not in -/// the rollback copy). +/// speculation leaves it to the authority. pub fn key(p: *Pardes, id: usize, k: pardes.Key) bool { const slot = (p.panes[id] orelse return false).addon orelse return false; - const f = (slot.ops orelse return false).key orelse return false; + if (!caps(p, slot).key) 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, "key"); - defer leave(prev); - return f(slot.st, &pk) != 0; + var cl: Call = .{ .p = p, .id = id, .slot = slot }; + const prev = cl.begin("key"); + if (slot.ops) |o| cl.ret = o.key.?(slot.st, &pk); + return taken(p, slot, cl.end(prev)); +} + +fn taken(p: *Pardes, slot: *Slot, o: Outcome) bool { + if (o.ret == 0) return false; + poke(p, slot); + return true; +} + +pub fn takesKeys(p: *const Pardes, s: *const Slot) bool { + return caps(p, s).key; +} + +pub fn takesMouse(p: *const Pardes, s: *const Slot) bool { + return caps(p, s).mouse; } /// The pointer at (col, row) of its body. pub fn mouse(p: *Pardes, id: usize, m: pardes.Mouse, col: u16, row: u16) bool { const slot = (p.panes[id] orelse return false).addon orelse return false; - const f = (slot.ops orelse return false).mouse orelse return false; + if (!caps(p, slot).mouse) return false; if (authorityOnly("the mouse in a kind's pane")) return true; const pm: c.pa_mouse = .{ .button = switch (m.button) { @@ -784,55 +492,77 @@ 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, "mouse"); - defer leave(prev); - return f(slot.st, &pm) != 0; + var cl: Call = .{ .p = p, .id = id, .slot = slot }; + const prev = cl.begin("mouse"); + if (slot.ops) |o| cl.ret = o.mouse.?(slot.st, &pm); + return taken(p, slot, cl.end(prev)); } -/// A step of the session's clock: each kind whose time has come ticks, -/// and each job's answer lands. +/// The end of a step: each pane of a kind whose focus changed, or whose +/// time has come, ticks (16.2). pub fn step(p: *Pardes) void { if (tape.speculating()) return; const now = p.clock.stepped_ns; for (p.panes, 0..) |pslot, id| if (pslot) |pane| if (pane.addon) |slot| { - const ops = slot.ops orelse continue; - 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, "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, "tick"); - slot.next_tick = f(slot.st, now); - leave(prev); - p.needs_frame = true; - }; + // Its tag laid out again by this step's sync, and drawn. + if (slot.retag) p.needs_frame = true; + slot.retag = false; + if (!caps(p, slot).tick) continue; + const focused = focusedAnywhere(p, id); + if (focused != slot.focused) { + slot.focused = focused; + slot.next_tick = 1; + } + if (slot.next_tick == 0 or now < slot.next_tick) continue; + var cl: Call = .{ .p = p, .id = id, .slot = slot }; + const prev = cl.begin("tick"); + if (slot.ops) |o| cl.ret = @bitCast(o.tick.?(slot.st, now, if (focused) c.PA_FOCUSED else 0)); + slot.next_tick = @bitCast(cl.end(prev).ret); + p.needs_frame = true; }; } -/// When the kinds next want a step: `0` a frame from now (a job under -/// way), a time, or null. +/// Whether pane `id` has the keyboard in some view (its window focused). +fn focusedAnywhere(p: *const Pardes, id: usize) bool { + if (p.active == id and p.window_focused) return true; + for (p.parked, 0..) |v, k| if (v) |pv| if (k != p.view and views.isOpen(p, @intCast(k)) and pv.view.active == id and pv.view.window_focused) return true; + return false; +} + +/// When the kinds next want a step: the soonest deadline (now, for a +/// tag to lay out again), or null. pub fn wake(p: *const Pardes) ?u64 { var soonest: ?u64 = null; for (p.panes) |pslot| if (pslot) |pane| if (pane.addon) |slot| { - for (slot.jobs) |j| if (j != null) return 0; - if (slot.next_tick != 0) soonest = @min(soonest orelse slot.next_tick, slot.next_tick); + const due = if (slot.retag) @max(1, p.clock.stepped_ns) else slot.next_tick; + if (due != 0) soonest = @min(soonest orelse due, due); }; return soonest; } +/// A job's answer (Event.job): to its kind, unless its pane or its +/// kind's generation is another's since it was asked. +pub fn jobDone(p: *Pardes, pane_id: u8, serial: u32, token: u32, gen: u32, bytes: []const u8) void { + const pane = p.panes[pane_id] orelse return; + const slot = pane.addon orelse return; + if (pane.serial != serial or slot.gen != gen or !caps(p, slot).jobs) return; + var cl: Call = .{ .p = p, .id = pane_id, .slot = slot }; + const prev = cl.begin("job_done"); + if (slot.ops) |o| o.job_done.?(slot.st, token, bytes.ptr, @intCast(bytes.len)); + _ = cl.end(prev); + poke(p, slot); + p.needs_frame = true; +} + /// 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, "body"); - defer leave(prev); + var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true }; + const prev = cl.begin("body"); + defer _ = cl.end(prev); const n: usize = @intCast(@min(len_f(slot.st), 64 << 20)); const buf = try gpa.alloc(u8, n); var off: usize = 0; @@ -844,45 +574,52 @@ pub fn body(pane: *const Pane, gpa: std.mem.Allocator) ![]u8 { return buf[0..off]; } +/// The kind's `dump` into `buf`, a quiet call. +pub fn dumpCall(slot: *Slot, f: anytype, buf: []u8) u32 { + var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true }; + const prev = cl.begin("dump"); + defer _ = cl.end(prev); + return f(slot.st, buf.ptr, @intCast(buf.len)); +} + /// Where in it the pane is, as a text its `address` takes back. -pub fn where(pane: *const Pane, buf: *[32]u8) []const u8 { - const slot = pane.addon orelse return ""; +pub fn where(slot: *Slot, buf: *[32]u8) []const u8 { const ops = slot.ops orelse return slot.where_text.slice(); const f = ops.where orelse return ""; - const prev = enter(null, 0, slot, "where"); - defer leave(prev); + var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true }; + const prev = cl.begin("where"); + defer _ = cl.end(prev); return buf[0..@min(buf.len, f(slot.st, buf, buf.len))]; } -/// Go to `text` in it; false when the kind has no such place. -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, "address"); - defer leave(prev); - return f(slot.st, text.ptr, @intCast(text.len)) != 0; -} - /// A kind's word as written to its pane: null taken, else why not. 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 (!slot.live) return "its addon is not loaded"; + if (!caps(p, slot).ctl) return "its kind takes no words"; if (authorityOnly("a kind's word")) return null; - const prev = enter(p, id, slot, "ctl"); - defer leave(prev); + var cl: Call = .{ .p = p, .id = id, .slot = slot }; + const prev = cl.begin("ctl"); @memset(reply, 0); - if (f(slot.st, line.ptr, @intCast(line.len), reply, reply.len) == 0) return null; - const said = std.mem.sliceTo(reply, 0); - return if (said.len > 0) said else "refused"; + if (slot.ops) |o| if (o.ctl.?(slot.st, line.ptr, @intCast(line.len), reply, reply.len) != c.PA_OK) { + const said = std.mem.sliceTo(reply, 0); + cl.refused.set(if (said.len > 0) said else "refused"); + }; + const o = cl.end(prev); + poke(p, slot); + if (o.text.len == 0) return null; + const n = @min(o.text.len, reply.len); + @memcpy(reply[0..n], o.text[0..n]); + return reply[0..n]; } /// What its ctl file reads after the core's fields. 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, "ctl_read"); - defer leave(prev); + var cl: Call = .{ .p = null, .id = 0, .slot = slot, .quiet = true }; + const prev = cl.begin("ctl_read"); + defer _ = cl.end(prev); return buf[0..@min(buf.len, f(slot.st, buf.ptr, @intCast(buf.len)))]; } @@ -892,303 +629,178 @@ 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 call into a kind ---- -/// 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) ---- +/// What a call into a kind did that the core takes on: its answer, a +/// refusal or reply, what it said, a Look, a text pane. The authority's +/// is taped; a replica's core takes it off the tape, kind or none. +pub const Outcome = struct { + ret: i64 = 0, + text: []const u8 = "", + said: []const u8 = "", + err: bool = false, + look: []const u8 = "", + pane_name: []const u8 = "", + pane_text: []const u8 = "", +}; -/// The pane a call into a kind is for: what `api` acts on. -const Current = struct { +/// The call under way: what `api` acts on, and what it gathers. +const Call = struct { p: ?*Pardes, id: usize, slot: *Slot, - call: []const u8 = "", - painting: bool = false, - /// In `open`: an error said refuses the pane. + /// Paint and the reads: what the kind asks of `api` is dropped, and + /// nothing is taped. + quiet: bool = false, opening: bool = false, + name: []const u8 = "", + ret: i64 = 0, + refused: Buf(160) = .{}, + said: Buf(160) = .{}, + err: bool = false, look: Buf(256) = .{}, + pane_name: Buf(64) = .{}, + pane_text: []const u8 = "", + + fn begin(cl: *Call, comptime name: []const u8) ?*Call { + cl.name = name; + const prev = current; + current = cl; + return prev; + } + + /// The call's outcome, as the authority's took it, done. + fn end(cl: *Call, prev: ?*Call) Outcome { + current = prev; + if (cl.quiet) return .{}; + const o = tape.value(.addon, same, .{Outcome{ .ret = cl.ret, .text = cl.refused.slice(), .said = cl.said.slice(), .err = cl.err, .look = cl.look.slice(), .pane_name = cl.pane_name.slice(), .pane_text = cl.pane_text }}); + const p = cl.p orelse return o; + if (o.said.len > 0) if (o.err) p.reportFailure(cl.id, o.said) else p.setMessage(cl.id, o.said); + if (o.pane_name.len > 0) textPane(p, cl.id, cl.slot, o.pane_name, o.pane_text); + if (o.look.len > 0) @import("look.zig").lookAt(p, cl.id, o.look); + return o; + } }; -var current: ?Current = null; +var current: ?*Call = null; -fn enter(p: ?*Pardes, id: usize, slot: *Slot, comptime call: []const u8) ?Current { - const prev = current; - current = .{ .p = p, .id = id, .slot = slot, .call = call }; - return prev; +fn same(o: Outcome) Outcome { + return o; } /// 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. +/// fake, paint`. Null outside one. 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; - // A Look the kind asked for, once its call is over: it may change - // the panes the call was among. - if (done.look.len > 0) if (done.p) |p| @import("look.zig").lookAt(p, done.id, done.look.slice()); + const cl = current orelse return null; + return std.fmt.bufPrint(buf, "in addon {s}, {s}", .{ cl.slot.nameOf(), cl.name }) catch null; } pub const api: c.pa_api = .{ .size = @sizeOf(c.pa_api), - .alloc = apiAlloc, - .free = apiFree, - .job = apiJob, - .look = apiLook, - .say = apiSay, - .text = apiText, - .seed = apiSeed, + .alloc = struct { + fn f(n: usize) callconv(.c) ?*anyopaque { + const cl = current orelse return null; + const mem = cl.slot.arena.allocator().alignedAlloc(u8, .@"16", @max(n, 1)) catch return null; + @memset(mem, 0); + if (checked) cl.slot.used.append(cl.slot.gpa, mem) catch {}; + return mem.ptr; + } + }.f, + .free = struct { + fn f(ptr: ?*anyopaque, n: usize) callconv(.c) void { + const cl = current orelse return; + const at: [*]align(16) u8 = @ptrCast(@alignCast(ptr orelse return)); + if (checked) for (cl.slot.used.items, 0..) |m, i| if (m.ptr == at) { + _ = cl.slot.used.swapRemove(i); + break; + }; + cl.slot.arena.allocator().free(at[0..@max(n, 1)]); + } + }.f, + .job = struct { + /// Its input kept for the host, which runs it (Effect.job). + fn f(in: ?*const anyopaque, n: u32) callconv(.c) u32 { + const cl = current orelse return 0; + const p = cl.p orelse return 0; + if (cl.quiet) return 0; + const s = cl.slot; + const free = for (&s.jobs) |*j| { + if (j.* == null) break j; + } else return 0; + const copy = s.gpa.dupe(u8, if (in) |b| @as([*]const u8, @ptrCast(b))[0..n] else "") catch return 0; + s.tokens +%= 1; + if (s.tokens == 0) s.tokens = 1; + free.* = .{ .token = s.tokens, .in = copy }; + const pane = p.panes[cl.id] orelse return 0; + p.emit(.{ .job = .{ .pane = @intCast(cl.id), .serial = pane.serial, .token = s.tokens } }); + return s.tokens; + } + }.f, + .look = struct { + fn f(text: [*c]const u8, n: u32) callconv(.c) void { + const cl = current orelse return; + if (!cl.quiet and text != null) cl.look.set(text[0..n]); + } + }.f, + .say = struct { + fn f(text: [*c]const u8, n: u32, err: c_int) callconv(.c) void { + const cl = current orelse return; + if (cl.quiet or text == null) return; + // Refusing its open: the opener says why. + if (err != 0 and cl.opening) return cl.refused.set(text[0..n]); + cl.said.set(text[0..n]); + cl.err = err != 0; + } + }.f, + .text = struct { + /// The pane is made as the call ends; its serial is the next. + fn f(name: [*c]const u8, name_len: u32, bytes: [*c]const u8, n: u32) callconv(.c) u32 { + const cl = current orelse return 0; + const p = cl.p orelse return 0; + if (cl.quiet or name == null or cl.pane_name.len > 0) return 0; + cl.pane_name.set(name[0..name_len]); + cl.pane_text = p.scratch.allocator().dupe(u8, if (bytes == null) "" else bytes[0..n]) catch ""; + return p.next_serial + 1; + } + }.f, + .seed = struct { + /// The same pane seeds the same on every machine. + fn f() callconv(.c) u64 { + const cl = current orelse return seed_base; + const serial: u32 = if (cl.p) |p| (if (p.panes[cl.id]) |pane| pane.serial else 0) else 0; + return std.hash.Wyhash.hash(seed_base, std.mem.asBytes(&serial)); + } + }.f, }; /// 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; - @memset(mem, 0); - return mem.ptr; -} - -fn apiFree(ptr: ?*anyopaque, n: usize) callconv(.c) void { - const cur = current orelse return; - const at: [*]align(16) u8 = @ptrCast(@alignCast(ptr orelse return)); - cur.slot.arena.allocator().free(at[0..@max(n, 1)]); -} - -fn apiLook(text: [*c]const u8, n: u32) callconv(.c) void { - if (current == null or current.?.painting or text == null) return; - current.?.look.set(text[0..n]); -} - -fn apiSay(text: [*c]const u8, n: u32, err: c_int) callconv(.c) void { - const cur = current orelse return; - if (cur.painting or text == null) return; - const said = text[0..n]; - // Refusing its open: the opener says so, as it says why it could not. - if (err != 0 and cur.opening) return cur.slot.refused.set(said); - const p = cur.p orelse return; - if (err != 0) p.reportFailure(cur.id, said) else p.setMessage(cur.id, said); -} - -fn apiText(name: [*c]const u8, name_len: u32, bytes: [*c]const u8, n: u32) callconv(.c) u32 { - const cur = current orelse return 0; - if (cur.painting or name == null) return 0; - const p = cur.p orelse return 0; - const dir = std.fs.path.dirname(cur.slot.path) orelse p.sessionDir(); - const path = std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), name[0..name_len] }) catch return 0; - const content = p.gpa.dupe(u8, if (bytes == null) "" else bytes[0..n]) catch { - p.gpa.free(path); - return 0; - }; - const free = p.freeSlot() orelse { - p.gpa.free(path); - p.gpa.free(content); - return 0; - }; +fn textPane(p: *Pardes, id: usize, slot: *const Slot, name: []const u8, text: []const u8) void { + const dir = std.fs.path.dirname(slot.path) orelse p.sessionDir(); + const free = p.freeSlot() orelse return; + const path = std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), name }) catch return; + const content = p.gpa.dupe(u8, text) catch return p.gpa.free(path); const history = pardes.panes.File.History.create(p.gpa) catch { p.gpa.free(path); - p.gpa.free(content); - return 0; + return p.gpa.free(content); }; const pane = p.newDocPane(free) catch { p.gpa.destroy(history); p.gpa.free(path); - p.gpa.free(content); - return 0; + return p.gpa.free(content); }; pane.file = .{ .path = path, .content = content, .history = history }; pane.body.cur_pinned = true; - @import("exec.zig").placeNew(p, cur.id, cur.id, free, .doc); - return pane.serial; -} - -/// A kind's job: its input copied, run on a thread of its own (inline in -/// a test), its answer kept for `step` to hand back on the loop. -const Job = struct { - token: u32, - gpa: std.mem.Allocator, - run: *const fn ([*c]const u8, u32, [*c]c.pa_out) callconv(.c) u32, - in: []u8, - out: []u8 = &.{}, - thread: ?std.Thread = null, - done: std.atomic.Value(bool) = .init(false), - - fn work(j: *Job) void { - var out: c.pa_out = .{ .alloc = outAlloc, .ctx = j }; - const n = j.run(j.in.ptr, @intCast(j.in.len), &out); - j.out = j.out[0..@min(n, j.out.len)]; - j.done.store(true, .release); - } - - fn outAlloc(out: [*c]c.pa_out, n: usize) callconv(.c) ?*anyopaque { - const j: *Job = @ptrCast(@alignCast(out.*.ctx)); - if (j.out.len > 0) return null; - j.out = j.gpa.alloc(u8, n) catch return null; - return j.out.ptr; - } - - fn wait(j: *Job) void { - if (j.thread) |t| t.join(); - j.thread = null; - } - - fn destroy(j: *Job) void { - j.gpa.free(j.in); - j.gpa.free(j.out); - j.gpa.destroy(j); - } -}; - -/// 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; - const slot = cur.slot; - const run = (slot.ops orelse return 0).job_run orelse return 0; - const free_at = for (&slot.jobs) |*j| { - if (j.* == null) break j; - } else return 0; - const job = slot.gpa.create(Job) catch return 0; - slot.tokens +%= 1; - if (slot.tokens == 0) slot.tokens = 1; - job.* = .{ .token = slot.tokens, .gpa = slot.gpa, .run = run, .in = slot.gpa.dupe(u8, if (in) |b| @as([*]const u8, @ptrCast(b))[0..n] else "") catch { - slot.gpa.destroy(job); - return 0; - } }; - if (!inline_jobs) { - if (std.Thread.spawn(.{}, Job.work, .{job})) |t| job.thread = t else |_| job.work(); - } else job.work(); - free_at.* = job; - return job.token; + @import("exec.zig").placeNew(p, id, id, free, .doc); } // ---- small things ---- pub fn Buf(comptime n: usize) type { return struct { + pub const replica = .{ .len = .{.{ "bytes", "len" }} }; bytes: [n]u8 = undefined, - len: std.math.IntFittingRange(0, n) = 0, + len: u16 = 0, const Self = @This(); pub fn set(b: *Self, s: []const u8) void { @@ -1207,22 +819,20 @@ pub fn Buf(comptime n: usize) type { }; } -test "a kind's head is checked before it is taken" { +test "a kind's head is checked before a core takes it, and a core's kinds are its own" { const Fake = struct { fn paint(_: ?*anyopaque, _: [*c]const c.pa_window, _: [*c]c.pa_paint) callconv(.c) void {} }; var ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .version = 3 }), .paint = Fake.paint }); @memcpy(ops.head.name[0..5], "zzzab"); - var wrong = ops; - wrong.head.abi = (abi_major + 1) << 16; - @memcpy(wrong.head.name[0..5], "zzzac"); - try std.testing.expectEqualStrings("refused: wants abi 2, this pardes speaks 1", register(&wrong, "/x/wrong.so", null).?); - try std.testing.expect(register(&ops, "", null) == null); - try std.testing.expect(byName("zzzab") == &ops); - try std.testing.expectEqualStrings("refused: kind zzzab is here already", register(&ops, "", null).?); - _ = unregister("zzzab"); - try std.testing.expect(byName("zzzab") == null); - forgetRefused("/x/wrong.so"); - forgetRefused(""); - for (kinds()) |*l| try std.testing.expect(!std.mem.startsWith(u8, l.nameOf(), "zzza")); + var a: Registry = .init(); + var b: Registry = .init(); + var words: [64]LoadedWord = undefined; + try std.testing.expect(a.take(loadedOf(&ops, "", @splat(1), &words), "") == null); + try std.testing.expect(a.byName("zzzab") != null); + try std.testing.expect(b.byName("zzzab") == null); + try std.testing.expectEqualStrings("refused: kind zzzab is here already", a.take(loadedOf(&ops, "", @splat(1), &words), "").?); + try std.testing.expectEqualStrings("refused: kind image is here already", b.take(loadedOf(&@import("image.zig").kind, "", @splat(1), &words), "").?); + a.drop(a.byName("zzzab").?); + try std.testing.expect(a.byName("zzzab") == null); } |
